FragmentProtoAssembler.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  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. #include "FragmentProtoAssembler_tree.h"
  38. #include <structure/SAvl_impl.h>
  39. static void free_frame (FragmentProtoAssembler *o, struct FragmentProtoAssembler_frame *frame)
  40. {
  41. // remove from used list
  42. LinkedList1_Remove(&o->frames_used, &frame->list_node);
  43. // remove from used tree
  44. FPAFramesTree_Remove(&o->frames_used_tree, 0, frame);
  45. // append to free list
  46. LinkedList1_Append(&o->frames_free, &frame->list_node);
  47. }
  48. static void free_oldest_frame (FragmentProtoAssembler *o)
  49. {
  50. ASSERT(!LinkedList1_IsEmpty(&o->frames_used))
  51. // obtain oldest frame (first on the list)
  52. LinkedList1Node *list_node = LinkedList1_GetFirst(&o->frames_used);
  53. ASSERT(list_node)
  54. struct FragmentProtoAssembler_frame *frame = UPPER_OBJECT(list_node, struct FragmentProtoAssembler_frame, list_node);
  55. // free frame
  56. free_frame(o, frame);
  57. }
  58. static struct FragmentProtoAssembler_frame * allocate_new_frame (FragmentProtoAssembler *o, fragmentproto_frameid id)
  59. {
  60. ASSERT(!FPAFramesTree_LookupExact(&o->frames_used_tree, 0, id))
  61. // if there are no free entries, free the oldest used one
  62. if (LinkedList1_IsEmpty(&o->frames_free)) {
  63. PeerLog(o, BLOG_INFO, "freeing used frame");
  64. free_oldest_frame(o);
  65. }
  66. // obtain frame entry
  67. LinkedList1Node *list_node = LinkedList1_GetFirst(&o->frames_free);
  68. ASSERT(list_node)
  69. struct FragmentProtoAssembler_frame *frame = UPPER_OBJECT(list_node, struct FragmentProtoAssembler_frame, list_node);
  70. // remove from free list
  71. LinkedList1_Remove(&o->frames_free, &frame->list_node);
  72. // initialize values
  73. frame->id = id;
  74. frame->time = o->time;
  75. frame->num_chunks = 0;
  76. frame->sum = 0;
  77. frame->length = -1;
  78. frame->length_so_far = 0;
  79. // append to used list
  80. LinkedList1_Append(&o->frames_used, &frame->list_node);
  81. // insert to used tree
  82. int res = FPAFramesTree_Insert(&o->frames_used_tree, 0, frame, NULL);
  83. ASSERT_EXECUTE(res)
  84. return frame;
  85. }
  86. static int chunks_overlap (int c1_start, int c1_len, int c2_start, int c2_len)
  87. {
  88. return (c1_start + c1_len > c2_start && c2_start + c2_len > c1_start);
  89. }
  90. static int frame_is_timed_out (FragmentProtoAssembler *o, struct FragmentProtoAssembler_frame *frame)
  91. {
  92. ASSERT(frame->time <= o->time)
  93. return (o->time - frame->time > o->time_tolerance);
  94. }
  95. static void reduce_times (FragmentProtoAssembler *o)
  96. {
  97. // find the frame with minimal time, removing timed out frames
  98. struct FragmentProtoAssembler_frame *minframe = NULL;
  99. LinkedList1Node *list_node = LinkedList1_GetFirst(&o->frames_used);
  100. while (list_node) {
  101. LinkedList1Node *next = LinkedList1Node_Next(list_node);
  102. struct FragmentProtoAssembler_frame *frame = UPPER_OBJECT(list_node, struct FragmentProtoAssembler_frame, list_node);
  103. if (frame_is_timed_out(o, frame)) {
  104. PeerLog(o, BLOG_INFO, "freeing timed out frame (while reducing times)");
  105. free_frame(o, frame);
  106. } else {
  107. if (!minframe || frame->time < minframe->time) {
  108. minframe = frame;
  109. }
  110. }
  111. list_node = next;
  112. }
  113. if (!minframe) {
  114. // have no frames, set packet time to zero
  115. o->time = 0;
  116. return;
  117. }
  118. uint32_t min_time = minframe->time;
  119. // subtract minimal time from all frames
  120. for (list_node = LinkedList1_GetFirst(&o->frames_used); list_node; list_node = LinkedList1Node_Next(list_node)) {
  121. struct FragmentProtoAssembler_frame *frame = UPPER_OBJECT(list_node, struct FragmentProtoAssembler_frame, list_node);
  122. frame->time -= min_time;
  123. }
  124. // subtract minimal time from packet time
  125. o->time -= min_time;
  126. }
  127. static int process_chunk (FragmentProtoAssembler *o, fragmentproto_frameid frame_id, int chunk_start, int chunk_len, int is_last, uint8_t *payload)
  128. {
  129. ASSERT(chunk_start >= 0)
  130. ASSERT(chunk_len >= 0)
  131. ASSERT(is_last == 0 || is_last == 1)
  132. // verify chunk
  133. // check start
  134. if (chunk_start > o->output_mtu) {
  135. PeerLog(o, BLOG_INFO, "chunk starts outside");
  136. return 0;
  137. }
  138. // check frame size bound
  139. if (chunk_len > o->output_mtu - chunk_start) {
  140. PeerLog(o, BLOG_INFO, "chunk ends outside");
  141. return 0;
  142. }
  143. // calculate end
  144. int chunk_end = chunk_start + chunk_len;
  145. ASSERT(chunk_end >= 0)
  146. ASSERT(chunk_end <= o->output_mtu)
  147. // lookup frame
  148. struct FragmentProtoAssembler_frame *frame = FPAFramesTree_LookupExact(&o->frames_used_tree, 0, frame_id);
  149. if (!frame) {
  150. // frame not found, add a new one
  151. frame = allocate_new_frame(o, frame_id);
  152. } else {
  153. // have existing frame with that ID
  154. // check frame time
  155. if (frame_is_timed_out(o, frame)) {
  156. // frame is timed out, remove it and use a new one
  157. PeerLog(o, BLOG_INFO, "freeing timed out frame (while processing chunk)");
  158. free_frame(o, frame);
  159. frame = allocate_new_frame(o, frame_id);
  160. }
  161. }
  162. ASSERT(frame->num_chunks < o->num_chunks)
  163. // check if the chunk overlaps with any existing chunks
  164. for (int i = 0; i < frame->num_chunks; i++) {
  165. struct FragmentProtoAssembler_chunk *chunk = &frame->chunks[i];
  166. if (chunks_overlap(chunk->start, chunk->len, chunk_start, chunk_len)) {
  167. PeerLog(o, BLOG_INFO, "chunk overlaps with existing chunk");
  168. goto fail_frame;
  169. }
  170. }
  171. if (is_last) {
  172. // this chunk is marked as last
  173. if (frame->length >= 0) {
  174. PeerLog(o, BLOG_INFO, "got last chunk, but already have one");
  175. goto fail_frame;
  176. }
  177. // check if frame size according to this packet is consistent
  178. // with existing chunks
  179. if (frame->length_so_far > chunk_end) {
  180. PeerLog(o, BLOG_INFO, "got last chunk, but already have data over its bound");
  181. goto fail_frame;
  182. }
  183. } else {
  184. // if we have length, chunk must be in its bound
  185. if (frame->length >= 0) {
  186. if (chunk_end > frame->length) {
  187. PeerLog(o, BLOG_INFO, "chunk out of length bound");
  188. goto fail_frame;
  189. }
  190. }
  191. }
  192. // chunk is good, add it
  193. // update frame time
  194. frame->time = o->time;
  195. // add chunk entry
  196. struct FragmentProtoAssembler_chunk *chunk = &frame->chunks[frame->num_chunks];
  197. chunk->start = chunk_start;
  198. chunk->len = chunk_len;
  199. frame->num_chunks++;
  200. // update sum
  201. frame->sum += chunk_len;
  202. // update length
  203. if (is_last) {
  204. frame->length = chunk_end;
  205. } else {
  206. if (frame->length < 0) {
  207. if (frame->length_so_far < chunk_end) {
  208. frame->length_so_far = chunk_end;
  209. }
  210. }
  211. }
  212. // copy chunk payload to buffer
  213. memcpy(frame->buffer + chunk_start, payload, chunk_len);
  214. // is frame incomplete?
  215. if (frame->length < 0 || frame->sum < frame->length) {
  216. // if all chunks are used, fail it
  217. if (frame->num_chunks == o->num_chunks) {
  218. PeerLog(o, BLOG_INFO, "all chunks used, but frame not complete");
  219. goto fail_frame;
  220. }
  221. // wait for more chunks
  222. return 0;
  223. }
  224. ASSERT(frame->sum == frame->length)
  225. PeerLog(o, BLOG_DEBUG, "frame complete");
  226. // free frame entry
  227. free_frame(o, frame);
  228. // send frame
  229. PacketPassInterface_Sender_Send(o->output, frame->buffer, frame->length);
  230. return 1;
  231. fail_frame:
  232. free_frame(o, frame);
  233. return 0;
  234. }
  235. static void process_input (FragmentProtoAssembler *o)
  236. {
  237. ASSERT(o->in_len >= 0)
  238. // read chunks
  239. while (o->in_pos < o->in_len) {
  240. // obtain header
  241. if (o->in_len - o->in_pos < sizeof(struct fragmentproto_chunk_header)) {
  242. PeerLog(o, BLOG_INFO, "too little data for chunk header");
  243. break;
  244. }
  245. struct fragmentproto_chunk_header header;
  246. memcpy(&header, o->in + o->in_pos, sizeof(header));
  247. o->in_pos += sizeof(struct fragmentproto_chunk_header);
  248. fragmentproto_frameid frame_id = ltoh16(header.frame_id);
  249. int chunk_start = ltoh16(header.chunk_start);
  250. int chunk_len = ltoh16(header.chunk_len);
  251. int is_last = ltoh8(header.is_last);
  252. // check is_last field
  253. if (!(is_last == 0 || is_last == 1)) {
  254. PeerLog(o, BLOG_INFO, "chunk is_last wrong");
  255. break;
  256. }
  257. // obtain data
  258. if (o->in_len - o->in_pos < chunk_len) {
  259. PeerLog(o, BLOG_INFO, "too little data for chunk data");
  260. break;
  261. }
  262. // process chunk
  263. int res = process_chunk(o, frame_id, chunk_start, chunk_len, is_last, o->in + o->in_pos);
  264. o->in_pos += chunk_len;
  265. if (res) {
  266. // sending complete frame, stop processing input
  267. return;
  268. }
  269. }
  270. // increment packet time
  271. if (o->time == FPA_MAX_TIME) {
  272. reduce_times(o);
  273. if (!LinkedList1_IsEmpty(&o->frames_used)) {
  274. ASSERT(o->time < FPA_MAX_TIME) // If there was a frame with zero time, it was removed because
  275. // time_tolerance < FPA_MAX_TIME. So something >0 was subtracted.
  276. o->time++;
  277. } else {
  278. // it was set to zero by reduce_times
  279. ASSERT(o->time == 0)
  280. }
  281. } else {
  282. o->time++;
  283. }
  284. // set no input packet
  285. o->in_len = -1;
  286. // finish input
  287. PacketPassInterface_Done(&o->input);
  288. }
  289. static void input_handler_send (FragmentProtoAssembler *o, uint8_t *data, int data_len)
  290. {
  291. ASSERT(data_len >= 0)
  292. ASSERT(o->in_len == -1)
  293. DebugObject_Access(&o->d_obj);
  294. // save input packet
  295. o->in_len = data_len;
  296. o->in = data;
  297. o->in_pos = 0;
  298. process_input(o);
  299. }
  300. static void output_handler_done (FragmentProtoAssembler *o)
  301. {
  302. ASSERT(o->in_len >= 0)
  303. DebugObject_Access(&o->d_obj);
  304. process_input(o);
  305. }
  306. int FragmentProtoAssembler_Init (FragmentProtoAssembler *o, int input_mtu, PacketPassInterface *output, int num_frames, int num_chunks, BPendingGroup *pg, void *user, BLog_logfunc logfunc)
  307. {
  308. ASSERT(input_mtu >= 0)
  309. ASSERT(num_frames > 0)
  310. ASSERT(num_frames < FPA_MAX_TIME) // needed so we can always subtract times when packet time is maximum
  311. ASSERT(num_chunks > 0)
  312. // init arguments
  313. o->output = output;
  314. o->num_chunks = num_chunks;
  315. o->user = user;
  316. o->logfunc = logfunc;
  317. // init input
  318. PacketPassInterface_Init(&o->input, input_mtu, (PacketPassInterface_handler_send)input_handler_send, o, pg);
  319. // init output
  320. PacketPassInterface_Sender_Init(o->output, (PacketPassInterface_handler_done)output_handler_done, o);
  321. // remebmer output MTU
  322. o->output_mtu = PacketPassInterface_GetMTU(o->output);
  323. // set packet time to zero
  324. o->time = 0;
  325. // set time tolerance to num_frames
  326. o->time_tolerance = num_frames;
  327. // allocate frames
  328. if (!(o->frames_entries = (struct FragmentProtoAssembler_frame *)BAllocArray(num_frames, sizeof(o->frames_entries[0])))) {
  329. goto fail1;
  330. }
  331. // allocate chunks
  332. if (!(o->frames_chunks = (struct FragmentProtoAssembler_chunk *)BAllocArray2(num_frames, o->num_chunks, sizeof(o->frames_chunks[0])))) {
  333. goto fail2;
  334. }
  335. // allocate buffers
  336. if (!(o->frames_buffer = (uint8_t *)BAllocArray(num_frames, o->output_mtu))) {
  337. goto fail3;
  338. }
  339. // init frame lists
  340. LinkedList1_Init(&o->frames_free);
  341. LinkedList1_Init(&o->frames_used);
  342. // initialize frame entries
  343. for (int i = 0; i < num_frames; i++) {
  344. struct FragmentProtoAssembler_frame *frame = &o->frames_entries[i];
  345. // set chunks array pointer
  346. frame->chunks = o->frames_chunks + (size_t)i * o->num_chunks;
  347. // set buffer pointer
  348. frame->buffer = o->frames_buffer + (size_t)i * o->output_mtu;
  349. // add to free list
  350. LinkedList1_Append(&o->frames_free, &frame->list_node);
  351. }
  352. // init tree
  353. FPAFramesTree_Init(&o->frames_used_tree);
  354. // have no input packet
  355. o->in_len = -1;
  356. DebugObject_Init(&o->d_obj);
  357. return 1;
  358. fail3:
  359. BFree(o->frames_chunks);
  360. fail2:
  361. BFree(o->frames_entries);
  362. fail1:
  363. PacketPassInterface_Free(&o->input);
  364. return 0;
  365. }
  366. void FragmentProtoAssembler_Free (FragmentProtoAssembler *o)
  367. {
  368. DebugObject_Free(&o->d_obj);
  369. // free buffers
  370. BFree(o->frames_buffer);
  371. // free chunks
  372. BFree(o->frames_chunks);
  373. // free frames
  374. BFree(o->frames_entries);
  375. // free input
  376. PacketPassInterface_Free(&o->input);
  377. }
  378. PacketPassInterface * FragmentProtoAssembler_GetInput (FragmentProtoAssembler *o)
  379. {
  380. DebugObject_Access(&o->d_obj);
  381. return &o->input;
  382. }