FragmentProtoAssembler.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  1. /**
  2. * @file FragmentProtoAssembler.c
  3. * @author Ambroz Bizjak <ambrop7@gmail.com>
  4. *
  5. * @section LICENSE
  6. *
  7. * Redistribution and use in source and binary forms, with or without
  8. * modification, are permitted provided that the following conditions are met:
  9. * 1. Redistributions of source code must retain the above copyright
  10. * notice, this list of conditions and the following disclaimer.
  11. * 2. Redistributions in binary form must reproduce the above copyright
  12. * notice, this list of conditions and the following disclaimer in the
  13. * documentation and/or other materials provided with the distribution.
  14. * 3. Neither the name of the author nor the
  15. * names of its contributors may be used to endorse or promote products
  16. * derived from this software without specific prior written permission.
  17. *
  18. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  19. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  20. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  21. * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
  22. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  23. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  24. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  25. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  26. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  27. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. */
  29. #include <stdlib.h>
  30. #include <string.h>
  31. #include <misc/offset.h>
  32. #include <misc/byteorder.h>
  33. #include <misc/balloc.h>
  34. #include "FragmentProtoAssembler.h"
  35. #include <generated/blog_channel_FragmentProtoAssembler.h>
  36. #define PeerLog(_o, ...) BLog_LogViaFunc((_o)->logfunc, (_o)->user, BLOG_CURRENT_CHANNEL, __VA_ARGS__)
  37. static int frame_id_comparator (void *unused, fragmentproto_frameid *v1, fragmentproto_frameid *v2)
  38. {
  39. if (*v1 < *v2) {
  40. return -1;
  41. }
  42. if (*v1 > *v2) {
  43. return 1;
  44. }
  45. return 0;
  46. }
  47. static void free_frame (FragmentProtoAssembler *o, struct FragmentProtoAssembler_frame *frame)
  48. {
  49. // remove from used list
  50. LinkedList2_Remove(&o->frames_used, &frame->list_node);
  51. // remove from used tree
  52. BAVL_Remove(&o->frames_used_tree, &frame->tree_node);
  53. // append to free list
  54. LinkedList2_Append(&o->frames_free, &frame->list_node);
  55. }
  56. static void free_oldest_frame (FragmentProtoAssembler *o)
  57. {
  58. ASSERT(!LinkedList2_IsEmpty(&o->frames_used))
  59. // obtain oldest frame (first on the list)
  60. LinkedList2Node *list_node = LinkedList2_GetFirst(&o->frames_used);
  61. ASSERT(list_node)
  62. struct FragmentProtoAssembler_frame *frame = UPPER_OBJECT(list_node, struct FragmentProtoAssembler_frame, list_node);
  63. // free frame
  64. free_frame(o, frame);
  65. }
  66. static struct FragmentProtoAssembler_frame * allocate_new_frame (FragmentProtoAssembler *o, fragmentproto_frameid id)
  67. {
  68. ASSERT(!BAVL_LookupExact(&o->frames_used_tree, &id))
  69. // if there are no free entries, free the oldest used one
  70. if (LinkedList2_IsEmpty(&o->frames_free)) {
  71. PeerLog(o, BLOG_INFO, "freeing used frame");
  72. free_oldest_frame(o);
  73. }
  74. // obtain frame entry
  75. LinkedList2Node *list_node = LinkedList2_GetFirst(&o->frames_free);
  76. ASSERT(list_node)
  77. struct FragmentProtoAssembler_frame *frame = UPPER_OBJECT(list_node, struct FragmentProtoAssembler_frame, list_node);
  78. // remove from free list
  79. LinkedList2_Remove(&o->frames_free, &frame->list_node);
  80. // initialize values
  81. frame->id = id;
  82. frame->time = o->time;
  83. frame->num_chunks = 0;
  84. frame->sum = 0;
  85. frame->length = -1;
  86. frame->length_so_far = 0;
  87. // append to used list
  88. LinkedList2_Append(&o->frames_used, &frame->list_node);
  89. // insert to used tree
  90. ASSERT_EXECUTE(BAVL_Insert(&o->frames_used_tree, &frame->tree_node, NULL))
  91. return frame;
  92. }
  93. static int chunks_overlap (int c1_start, int c1_len, int c2_start, int c2_len)
  94. {
  95. return (c1_start + c1_len > c2_start && c2_start + c2_len > c1_start);
  96. }
  97. static int frame_is_timed_out (FragmentProtoAssembler *o, struct FragmentProtoAssembler_frame *frame)
  98. {
  99. ASSERT(frame->time <= o->time)
  100. return (o->time - frame->time > o->time_tolerance);
  101. }
  102. static void reduce_times (FragmentProtoAssembler *o)
  103. {
  104. // find the frame with minimal time, removing timed out frames
  105. struct FragmentProtoAssembler_frame *minframe = NULL;
  106. LinkedList2Iterator it;
  107. LinkedList2Iterator_InitForward(&it, &o->frames_used);
  108. LinkedList2Node *list_node;
  109. while (list_node = LinkedList2Iterator_Next(&it)) {
  110. struct FragmentProtoAssembler_frame *frame = UPPER_OBJECT(list_node, struct FragmentProtoAssembler_frame, list_node);
  111. if (frame_is_timed_out(o, frame)) {
  112. PeerLog(o, BLOG_INFO, "freeing timed out frame (while reducing times)");
  113. free_frame(o, frame);
  114. } else {
  115. if (!minframe || frame->time < minframe->time) {
  116. minframe = frame;
  117. }
  118. }
  119. }
  120. if (!minframe) {
  121. // have no frames, set packet time to zero
  122. o->time = 0;
  123. return;
  124. }
  125. uint32_t min_time = minframe->time;
  126. // subtract minimal time from all frames
  127. LinkedList2Iterator_InitForward(&it, &o->frames_used);
  128. while (list_node = LinkedList2Iterator_Next(&it)) {
  129. struct FragmentProtoAssembler_frame *frame = UPPER_OBJECT(list_node, struct FragmentProtoAssembler_frame, list_node);
  130. frame->time -= min_time;
  131. }
  132. // subtract minimal time from packet time
  133. o->time -= min_time;
  134. }
  135. static int process_chunk (FragmentProtoAssembler *o, fragmentproto_frameid frame_id, int chunk_start, int chunk_len, int is_last, uint8_t *payload)
  136. {
  137. ASSERT(chunk_start >= 0)
  138. ASSERT(chunk_len >= 0)
  139. ASSERT(is_last == 0 || is_last == 1)
  140. // verify chunk
  141. // check start
  142. if (chunk_start > o->output_mtu) {
  143. PeerLog(o, BLOG_INFO, "chunk starts outside");
  144. return 0;
  145. }
  146. // check frame size bound
  147. if (chunk_len > o->output_mtu - chunk_start) {
  148. PeerLog(o, BLOG_INFO, "chunk ends outside");
  149. return 0;
  150. }
  151. // calculate end
  152. int chunk_end = chunk_start + chunk_len;
  153. ASSERT(chunk_end >= 0)
  154. ASSERT(chunk_end <= o->output_mtu)
  155. // lookup frame
  156. struct FragmentProtoAssembler_frame *frame;
  157. BAVLNode *tree_node;
  158. if (!(tree_node = BAVL_LookupExact(&o->frames_used_tree, &frame_id))) {
  159. // frame not found, add a new one
  160. frame = allocate_new_frame(o, frame_id);
  161. } else {
  162. // have existing frame with that ID
  163. frame = UPPER_OBJECT(tree_node, struct FragmentProtoAssembler_frame, tree_node);
  164. // check frame time
  165. if (frame_is_timed_out(o, frame)) {
  166. // frame is timed out, remove it and use a new one
  167. PeerLog(o, BLOG_INFO, "freeing timed out frame (while processing chunk)");
  168. free_frame(o, frame);
  169. frame = allocate_new_frame(o, frame_id);
  170. }
  171. }
  172. ASSERT(frame->num_chunks < o->num_chunks)
  173. // check if the chunk overlaps with any existing chunks
  174. for (int i = 0; i < frame->num_chunks; i++) {
  175. struct FragmentProtoAssembler_chunk *chunk = &frame->chunks[i];
  176. if (chunks_overlap(chunk->start, chunk->len, chunk_start, chunk_len)) {
  177. PeerLog(o, BLOG_INFO, "chunk overlaps with existing chunk");
  178. goto fail_frame;
  179. }
  180. }
  181. if (is_last) {
  182. // this chunk is marked as last
  183. if (frame->length >= 0) {
  184. PeerLog(o, BLOG_INFO, "got last chunk, but already have one");
  185. goto fail_frame;
  186. }
  187. // check if frame size according to this packet is consistent
  188. // with existing chunks
  189. if (frame->length_so_far > chunk_end) {
  190. PeerLog(o, BLOG_INFO, "got last chunk, but already have data over its bound");
  191. goto fail_frame;
  192. }
  193. } else {
  194. // if we have length, chunk must be in its bound
  195. if (frame->length >= 0) {
  196. if (chunk_end > frame->length) {
  197. PeerLog(o, BLOG_INFO, "chunk out of length bound");
  198. goto fail_frame;
  199. }
  200. }
  201. }
  202. // chunk is good, add it
  203. // update frame time
  204. frame->time = o->time;
  205. // add chunk entry
  206. struct FragmentProtoAssembler_chunk *chunk = &frame->chunks[frame->num_chunks];
  207. chunk->start = chunk_start;
  208. chunk->len = chunk_len;
  209. frame->num_chunks++;
  210. // update sum
  211. frame->sum += chunk_len;
  212. // update length
  213. if (is_last) {
  214. frame->length = chunk_end;
  215. } else {
  216. if (frame->length < 0) {
  217. if (frame->length_so_far < chunk_end) {
  218. frame->length_so_far = chunk_end;
  219. }
  220. }
  221. }
  222. // copy chunk payload to buffer
  223. memcpy(frame->buffer + chunk_start, payload, chunk_len);
  224. // is frame incomplete?
  225. if (frame->length < 0 || frame->sum < frame->length) {
  226. // if all chunks are used, fail it
  227. if (frame->num_chunks == o->num_chunks) {
  228. PeerLog(o, BLOG_INFO, "all chunks used, but frame not complete");
  229. goto fail_frame;
  230. }
  231. // wait for more chunks
  232. return 0;
  233. }
  234. ASSERT(frame->sum == frame->length)
  235. PeerLog(o, BLOG_DEBUG, "frame complete");
  236. // free frame entry
  237. free_frame(o, frame);
  238. // send frame
  239. PacketPassInterface_Sender_Send(o->output, frame->buffer, frame->length);
  240. return 1;
  241. fail_frame:
  242. free_frame(o, frame);
  243. return 0;
  244. }
  245. static void process_input (FragmentProtoAssembler *o)
  246. {
  247. ASSERT(o->in_len >= 0)
  248. // read chunks
  249. while (o->in_pos < o->in_len) {
  250. // obtain header
  251. if (o->in_len - o->in_pos < sizeof(struct fragmentproto_chunk_header)) {
  252. PeerLog(o, BLOG_INFO, "too little data for chunk header");
  253. break;
  254. }
  255. struct fragmentproto_chunk_header *header = (struct fragmentproto_chunk_header *)(o->in + o->in_pos);
  256. o->in_pos += sizeof(struct fragmentproto_chunk_header);
  257. fragmentproto_frameid frame_id = ltoh16(header->frame_id);
  258. int chunk_start = ltoh16(header->chunk_start);
  259. int chunk_len = ltoh16(header->chunk_len);
  260. int is_last = ltoh8(header->is_last);
  261. // check is_last field
  262. if (!(is_last == 0 || is_last == 1)) {
  263. PeerLog(o, BLOG_INFO, "chunk is_last wrong");
  264. break;
  265. }
  266. // obtain data
  267. if (o->in_len - o->in_pos < chunk_len) {
  268. PeerLog(o, BLOG_INFO, "too little data for chunk data");
  269. break;
  270. }
  271. // process chunk
  272. int res = process_chunk(o, frame_id, chunk_start, chunk_len, is_last, o->in + o->in_pos);
  273. o->in_pos += chunk_len;
  274. if (res) {
  275. // sending complete frame, stop processing input
  276. return;
  277. }
  278. }
  279. // increment packet time
  280. if (o->time == FPA_MAX_TIME) {
  281. reduce_times(o);
  282. if (!LinkedList2_IsEmpty(&o->frames_used)) {
  283. ASSERT(o->time < FPA_MAX_TIME) // If there was a frame with zero time, it was removed because
  284. // time_tolerance < FPA_MAX_TIME. So something >0 was subtracted.
  285. o->time++;
  286. } else {
  287. // it was set to zero by reduce_times
  288. ASSERT(o->time == 0)
  289. }
  290. } else {
  291. o->time++;
  292. }
  293. // set no input packet
  294. o->in_len = -1;
  295. // finish input
  296. PacketPassInterface_Done(&o->input);
  297. }
  298. static void input_handler_send (FragmentProtoAssembler *o, uint8_t *data, int data_len)
  299. {
  300. ASSERT(data_len >= 0)
  301. ASSERT(o->in_len == -1)
  302. DebugObject_Access(&o->d_obj);
  303. // save input packet
  304. o->in_len = data_len;
  305. o->in = data;
  306. o->in_pos = 0;
  307. process_input(o);
  308. }
  309. static void output_handler_done (FragmentProtoAssembler *o)
  310. {
  311. ASSERT(o->in_len >= 0)
  312. DebugObject_Access(&o->d_obj);
  313. process_input(o);
  314. }
  315. int FragmentProtoAssembler_Init (FragmentProtoAssembler *o, int input_mtu, PacketPassInterface *output, int num_frames, int num_chunks, BPendingGroup *pg, void *user, BLog_logfunc logfunc)
  316. {
  317. ASSERT(input_mtu >= 0)
  318. ASSERT(num_frames > 0)
  319. ASSERT(num_frames < FPA_MAX_TIME) // needed so we can always subtract times when packet time is maximum
  320. ASSERT(num_chunks > 0)
  321. // init arguments
  322. o->output = output;
  323. o->num_chunks = num_chunks;
  324. o->user = user;
  325. o->logfunc = logfunc;
  326. // init input
  327. PacketPassInterface_Init(&o->input, input_mtu, (PacketPassInterface_handler_send)input_handler_send, o, pg);
  328. // init output
  329. PacketPassInterface_Sender_Init(o->output, (PacketPassInterface_handler_done)output_handler_done, o);
  330. // remebmer output MTU
  331. o->output_mtu = PacketPassInterface_GetMTU(o->output);
  332. // set packet time to zero
  333. o->time = 0;
  334. // set time tolerance to num_frames
  335. o->time_tolerance = num_frames;
  336. // allocate frames
  337. if (!(o->frames_entries = BAllocArray(num_frames, sizeof(o->frames_entries[0])))) {
  338. goto fail1;
  339. }
  340. // allocate chunks
  341. if (!(o->frames_chunks = BAllocArray2(num_frames, o->num_chunks, sizeof(o->frames_chunks[0])))) {
  342. goto fail2;
  343. }
  344. // allocate buffers
  345. if (!(o->frames_buffer = BAllocArray(num_frames, o->output_mtu))) {
  346. goto fail3;
  347. }
  348. // init frame lists
  349. LinkedList2_Init(&o->frames_free);
  350. LinkedList2_Init(&o->frames_used);
  351. // initialize frame entries
  352. for (int i = 0; i < num_frames; i++) {
  353. struct FragmentProtoAssembler_frame *frame = &o->frames_entries[i];
  354. // set chunks array pointer
  355. frame->chunks = o->frames_chunks + (size_t)i * o->num_chunks;
  356. // set buffer pointer
  357. frame->buffer = o->frames_buffer + (size_t)i * o->output_mtu;
  358. // add to free list
  359. LinkedList2_Append(&o->frames_free, &frame->list_node);
  360. }
  361. // init tree
  362. BAVL_Init(&o->frames_used_tree, OFFSET_DIFF(struct FragmentProtoAssembler_frame, id, tree_node), (BAVL_comparator)frame_id_comparator, NULL);
  363. // have no input packet
  364. o->in_len = -1;
  365. DebugObject_Init(&o->d_obj);
  366. return 1;
  367. fail3:
  368. BFree(o->frames_chunks);
  369. fail2:
  370. BFree(o->frames_entries);
  371. fail1:
  372. PacketPassInterface_Free(&o->input);
  373. return 0;
  374. }
  375. void FragmentProtoAssembler_Free (FragmentProtoAssembler *o)
  376. {
  377. DebugObject_Free(&o->d_obj);
  378. // free buffers
  379. BFree(o->frames_buffer);
  380. // free chunks
  381. BFree(o->frames_chunks);
  382. // free frames
  383. BFree(o->frames_entries);
  384. // free input
  385. PacketPassInterface_Free(&o->input);
  386. }
  387. PacketPassInterface * FragmentProtoAssembler_GetInput (FragmentProtoAssembler *o)
  388. {
  389. DebugObject_Access(&o->d_obj);
  390. return &o->input;
  391. }