8d09474c49ab82140661281d2b5a877a7eaed00d
[oweals/gnunet.git] / src / stream / stream_api.c
1 /*
2   This file is part of GNUnet.
3   (C) 2012 Christian Grothoff (and other contributing authors)
4
5   GNUnet is free software; you can redistribute it and/or modify
6   it under the terms of the GNU General Public License as published
7   by the Free Software Foundation; either version 3, or (at your
8   option) any later version.
9
10   GNUnet is distributed in the hope that it will be useful, but
11   WITHOUT ANY WARRANTY; without even the implied warranty of
12   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13   General Public License for more details.
14
15   You should have received a copy of the GNU General Public License
16   along with GNUnet; see the file COPYING.  If not, write to the
17   Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18   Boston, MA 02111-1307, USA.
19 */
20
21 /* TODO:
22  *
23  * Checks for matching the sender and socket->other_peer in server
24  * message handlers  
25  *
26  * Decrement PEER intern count during socket close and listen close to free the
27  * memory used for PEER interning
28  **/
29
30 /**
31  * @file stream/stream_api.c
32  * @brief Implementation of the stream library
33  * @author Sree Harsha Totakura
34  */
35 #include "platform.h"
36 #include "gnunet_common.h"
37 #include "gnunet_crypto_lib.h"
38 #include "gnunet_stream_lib.h"
39 #include "gnunet_testing_lib.h"
40 #include "stream_protocol.h"
41
42
43 /**
44  * The maximum packet size of a stream packet
45  */
46 #define MAX_PACKET_SIZE 64000
47
48 /**
49  * The maximum payload a data message packet can carry
50  */
51 static size_t max_payload_size = 
52   MAX_PACKET_SIZE - sizeof (struct GNUNET_STREAM_DataMessage);
53
54 /**
55  * Receive buffer
56  */
57 #define RECEIVE_BUFFER_SIZE 4096000
58
59 /**
60  * states in the Protocol
61  */
62 enum State
63   {
64     /**
65      * Client initialization state
66      */
67     STATE_INIT,
68
69     /**
70      * Listener initialization state 
71      */
72     STATE_LISTEN,
73
74     /**
75      * Pre-connection establishment state
76      */
77     STATE_HELLO_WAIT,
78
79     /**
80      * State where a connection has been established
81      */
82     STATE_ESTABLISHED,
83
84     /**
85      * State where the socket is closed on our side and waiting to be ACK'ed
86      */
87     STATE_RECEIVE_CLOSE_WAIT,
88
89     /**
90      * State where the socket is closed for reading
91      */
92     STATE_RECEIVE_CLOSED,
93
94     /**
95      * State where the socket is closed on our side and waiting to be ACK'ed
96      */
97     STATE_TRANSMIT_CLOSE_WAIT,
98
99     /**
100      * State where the socket is closed for writing
101      */
102     STATE_TRANSMIT_CLOSED,
103
104     /**
105      * State where the socket is closed on our side and waiting to be ACK'ed
106      */
107     STATE_CLOSE_WAIT,
108
109     /**
110      * State where the socket is closed
111      */
112     STATE_CLOSED 
113   };
114
115
116 /**
117  * Functions of this type are called when a message is written
118  *
119  * @param cls the closure from queue_message
120  * @param socket the socket the written message was bound to
121  */
122 typedef void (*SendFinishCallback) (void *cls,
123                                     struct GNUNET_STREAM_Socket *socket);
124
125
126 /**
127  * The send message queue
128  */
129 struct MessageQueue
130 {
131   /**
132    * The message
133    */
134   struct GNUNET_STREAM_MessageHeader *message;
135
136   /**
137    * Callback to be called when the message is sent
138    */
139   SendFinishCallback finish_cb;
140
141   /**
142    * The closure for finish_cb
143    */
144   void *finish_cb_cls;
145
146   /**
147    * The next message in queue. Should be NULL in the last message
148    */
149   struct MessageQueue *next;
150
151   /**
152    * The next message in queue. Should be NULL in the first message
153    */
154   struct MessageQueue *prev;
155 };
156
157
158 /**
159  * The STREAM Socket Handler
160  */
161 struct GNUNET_STREAM_Socket
162 {
163   /**
164    * Retransmission timeout
165    */
166   struct GNUNET_TIME_Relative retransmit_timeout;
167
168   /**
169    * The Acknowledgement Bitmap
170    */
171   GNUNET_STREAM_AckBitmap ack_bitmap;
172
173   /**
174    * Time when the Acknowledgement was queued
175    */
176   struct GNUNET_TIME_Absolute ack_time_registered;
177
178   /**
179    * Queued Acknowledgement deadline
180    */
181   struct GNUNET_TIME_Relative ack_time_deadline;
182
183   /**
184    * The mesh handle
185    */
186   struct GNUNET_MESH_Handle *mesh;
187
188   /**
189    * The mesh tunnel handle
190    */
191   struct GNUNET_MESH_Tunnel *tunnel;
192
193   /**
194    * Stream open closure
195    */
196   void *open_cls;
197
198   /**
199    * Stream open callback
200    */
201   GNUNET_STREAM_OpenCallback open_cb;
202
203   /**
204    * The current transmit handle (if a pending transmit request exists)
205    */
206   struct GNUNET_MESH_TransmitHandle *transmit_handle;
207
208   /**
209    * The current message associated with the transmit handle
210    */
211   struct MessageQueue *queue_head;
212
213   /**
214    * The queue tail, should always point to the last message in queue
215    */
216   struct MessageQueue *queue_tail;
217
218   /**
219    * The write IO_handle associated with this socket
220    */
221   struct GNUNET_STREAM_IOWriteHandle *write_handle;
222
223   /**
224    * The read IO_handle associated with this socket
225    */
226   struct GNUNET_STREAM_IOReadHandle *read_handle;
227
228   /**
229    * Buffer for storing received messages
230    */
231   void *receive_buffer;
232
233   /**
234    * Task identifier for the read io timeout task
235    */
236   GNUNET_SCHEDULER_TaskIdentifier read_io_timeout_task;
237
238   /**
239    * Task identifier for retransmission task after timeout
240    */
241   GNUNET_SCHEDULER_TaskIdentifier retransmission_timeout_task_id;
242
243   /**
244    * The task for sending timely Acks
245    */
246   GNUNET_SCHEDULER_TaskIdentifier ack_task_id;
247
248   /**
249    * Task scheduled to continue a read operation.
250    */
251   GNUNET_SCHEDULER_TaskIdentifier read_task_id;
252
253   /**
254    * The state of the protocol associated with this socket
255    */
256   enum State state;
257
258   /**
259    * The status of the socket
260    */
261   enum GNUNET_STREAM_Status status;
262
263   /**
264    * The number of previous timeouts; FIXME: currently not used
265    */
266   unsigned int retries;
267
268   /**
269    * Is this socket derived from listen socket?
270    */
271   unsigned int derived;
272   
273   /**
274    * The peer identity of the peer at the other end of the stream
275    */
276   GNUNET_PEER_Id other_peer;
277
278   /**
279    * Our Peer Identity (for debugging)
280    */
281   GNUNET_PEER_Id our_id;
282
283   /**
284    * The application port number (type: uint32_t)
285    */
286   GNUNET_MESH_ApplicationType app_port;
287
288   /**
289    * The session id associated with this stream connection
290    * FIXME: Not used currently, may be removed
291    */
292   uint32_t session_id;
293
294   /**
295    * Write sequence number. Set to random when sending HELLO(client) and
296    * HELLO_ACK(server) 
297    */
298   uint32_t write_sequence_number;
299
300   /**
301    * Read sequence number. This number's value is determined during handshake
302    */
303   uint32_t read_sequence_number;
304
305   /**
306    * The receiver buffer size
307    */
308   uint32_t receive_buffer_size;
309
310   /**
311    * The receiver buffer boundaries
312    */
313   uint32_t receive_buffer_boundaries[GNUNET_STREAM_ACK_BITMAP_BIT_LENGTH];
314
315   /**
316    * receiver's available buffer after the last acknowledged packet
317    */
318   uint32_t receive_window_available;
319
320   /**
321    * The offset pointer used during write operation
322    */
323   uint32_t write_offset;
324
325   /**
326    * The offset after which we are expecting data
327    */
328   uint32_t read_offset;
329
330   /**
331    * The offset upto which user has read from the received buffer
332    */
333   uint32_t copy_offset;
334 };
335
336
337 /**
338  * A socket for listening
339  */
340 struct GNUNET_STREAM_ListenSocket
341 {
342   /**
343    * The mesh handle
344    */
345   struct GNUNET_MESH_Handle *mesh;
346
347   /**
348    * The callback function which is called after successful opening socket
349    */
350   GNUNET_STREAM_ListenCallback listen_cb;
351
352   /**
353    * The call back closure
354    */
355   void *listen_cb_cls;
356
357   /**
358    * Our interned Peer's identity
359    */
360   GNUNET_PEER_Id our_id;
361
362   /**
363    * The service port
364    * FIXME: Remove if not required!
365    */
366   GNUNET_MESH_ApplicationType port;
367 };
368
369
370 /**
371  * The IO Write Handle
372  */
373 struct GNUNET_STREAM_IOWriteHandle
374 {
375   /**
376    * The packet_buffers associated with this Handle
377    */
378   struct GNUNET_STREAM_DataMessage *messages[64];
379
380   /**
381    * The write continuation callback
382    */
383   GNUNET_STREAM_CompletionContinuation write_cont;
384
385   /**
386    * Write continuation closure
387    */
388   void *write_cont_cls;
389
390   /**
391    * The bitmap of this IOHandle; Corresponding bit for a message is set when
392    * it has been acknowledged by the receiver
393    */
394   GNUNET_STREAM_AckBitmap ack_bitmap;
395
396   /**
397    * Number of bytes in this write handle
398    */
399   size_t size;
400
401   /**
402    * Number of packets sent before waiting for an ack
403    *
404    * FIXME: Do we need this?
405    */
406   unsigned int sent_packets;
407 };
408
409
410 /**
411  * The IO Read Handle
412  */
413 struct GNUNET_STREAM_IOReadHandle
414 {
415   /**
416    * Callback for the read processor
417    */
418   GNUNET_STREAM_DataProcessor proc;
419
420   /**
421    * The closure pointer for the read processor callback
422    */
423   void *proc_cls;
424 };
425
426
427 /**
428  * Default value in seconds for various timeouts
429  */
430 static unsigned int default_timeout = 10;
431
432 /**
433  * Callback function for sending hello message
434  *
435  * @param cls closure the socket
436  * @param size number of bytes available in buf
437  * @param buf where the callee should write the message
438  * @return number of bytes written to buf
439  */
440 static size_t
441 send_message_notify (void *cls, size_t size, void *buf)
442 {
443   struct GNUNET_STREAM_Socket *socket = cls;
444   struct GNUNET_PeerIdentity target;
445   struct MessageQueue *head;
446   size_t ret;
447
448   socket->transmit_handle = NULL; /* Remove the transmit handle */
449   head = socket->queue_head;
450   if (NULL == head)
451     return 0; /* just to be safe */
452   GNUNET_PEER_resolve (socket->other_peer, &target);
453   if (0 == size)                /* request timed out */
454     {
455       socket->retries++;
456       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
457                   "Message sending timed out. Retry %d \n",
458                   socket->retries);
459       socket->transmit_handle = 
460         GNUNET_MESH_notify_transmit_ready (socket->tunnel,
461                                            0, /* Corking */
462                                            1, /* Priority */
463                                            /* FIXME: exponential backoff */
464                                            socket->retransmit_timeout,
465                                            &target,
466                                            ntohs (head->message->header.size),
467                                            &send_message_notify,
468                                            socket);
469       return 0;
470     }
471
472   ret = ntohs (head->message->header.size);
473   GNUNET_assert (size >= ret);
474   memcpy (buf, head->message, ret);
475   if (NULL != head->finish_cb)
476     {
477       head->finish_cb (head->finish_cb_cls, socket);
478     }
479   GNUNET_CONTAINER_DLL_remove (socket->queue_head,
480                                socket->queue_tail,
481                                head);
482   GNUNET_free (head->message);
483   GNUNET_free (head);
484   head = socket->queue_head;
485   if (NULL != head)    /* more pending messages to send */
486     {
487       socket->retries = 0;
488       socket->transmit_handle = 
489         GNUNET_MESH_notify_transmit_ready (socket->tunnel,
490                                            0, /* Corking */
491                                            1, /* Priority */
492                                            /* FIXME: exponential backoff */
493                                            socket->retransmit_timeout,
494                                            &target,
495                                            ntohs (head->message->header.size),
496                                            &send_message_notify,
497                                            socket);
498     }
499   return ret;
500 }
501
502
503 /**
504  * Queues a message for sending using the mesh connection of a socket
505  *
506  * @param socket the socket whose mesh connection is used
507  * @param message the message to be sent
508  * @param finish_cb the callback to be called when the message is sent
509  * @param finish_cb_cls the closure for the callback
510  */
511 static void
512 queue_message (struct GNUNET_STREAM_Socket *socket,
513                struct GNUNET_STREAM_MessageHeader *message,
514                SendFinishCallback finish_cb,
515                void *finish_cb_cls)
516 {
517   struct MessageQueue *queue_entity;
518   struct GNUNET_PeerIdentity target;
519
520   GNUNET_assert 
521     ((ntohs (message->header.type) >= GNUNET_MESSAGE_TYPE_STREAM_DATA)
522      && (ntohs (message->header.type) <= GNUNET_MESSAGE_TYPE_STREAM_CLOSE_ACK));
523
524   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
525               "%x: Queueing message of type %d and size %d\n",
526               socket->our_id,
527               ntohs (message->header.type),
528               ntohs (message->header.size));
529   GNUNET_assert (NULL != message);
530   queue_entity = GNUNET_malloc (sizeof (struct MessageQueue));
531   queue_entity->message = message;
532   queue_entity->finish_cb = finish_cb;
533   queue_entity->finish_cb_cls = finish_cb_cls;
534   GNUNET_CONTAINER_DLL_insert_tail (socket->queue_head,
535                                     socket->queue_tail,
536                                     queue_entity);
537   if (NULL == socket->transmit_handle)
538   {
539     socket->retries = 0;
540     GNUNET_PEER_resolve (socket->other_peer, &target);
541     socket->transmit_handle = 
542       GNUNET_MESH_notify_transmit_ready (socket->tunnel,
543                                          0, /* Corking */
544                                          1, /* Priority */
545                                          socket->retransmit_timeout,
546                                          &target,
547                                          ntohs (message->header.size),
548                                          &send_message_notify,
549                                          socket);
550   }
551 }
552
553
554 /**
555  * Copies a message and queues it for sending using the mesh connection of
556  * given socket 
557  *
558  * @param socket the socket whose mesh connection is used
559  * @param message the message to be sent
560  * @param finish_cb the callback to be called when the message is sent
561  * @param finish_cb_cls the closure for the callback
562  */
563 static void
564 copy_and_queue_message (struct GNUNET_STREAM_Socket *socket,
565                         const struct GNUNET_STREAM_MessageHeader *message,
566                         SendFinishCallback finish_cb,
567                         void *finish_cb_cls)
568 {
569   struct GNUNET_STREAM_MessageHeader *msg_copy;
570   uint16_t size;
571   
572   size = ntohs (message->header.size);
573   msg_copy = GNUNET_malloc (size);
574   memcpy (msg_copy, message, size);
575   queue_message (socket, msg_copy, finish_cb, finish_cb_cls);
576 }
577
578
579 /**
580  * Callback function for sending ack message
581  *
582  * @param cls closure the ACK message created in ack_task
583  * @param size number of bytes available in buffer
584  * @param buf where the callee should write the message
585  * @return number of bytes written to buf
586  */
587 static size_t
588 send_ack_notify (void *cls, size_t size, void *buf)
589 {
590   struct GNUNET_STREAM_AckMessage *ack_msg = cls;
591
592   if (0 == size)
593     {
594       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
595                   "%s called with size 0\n", __func__);
596       return 0;
597     }
598   GNUNET_assert (ack_msg->header.header.size <= size);
599   
600   size = ack_msg->header.header.size;
601   memcpy (buf, ack_msg, size);
602   return size;
603 }
604
605 /**
606  * Writes data using the given socket. The amount of data written is limited by
607  * the receive_window_size
608  *
609  * @param socket the socket to use
610  */
611 static void 
612 write_data (struct GNUNET_STREAM_Socket *socket);
613
614 /**
615  * Task for retransmitting data messages if they aren't ACK before their ack
616  * deadline 
617  *
618  * @param cls the socket
619  * @param tc the Task context
620  */
621 static void
622 retransmission_timeout_task (void *cls,
623                              const struct GNUNET_SCHEDULER_TaskContext *tc)
624 {
625   struct GNUNET_STREAM_Socket *socket = cls;
626   
627   if (GNUNET_SCHEDULER_REASON_SHUTDOWN == tc->reason)
628     return;
629
630   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
631               "%x: Retransmitting DATA...\n", socket->our_id);
632   socket->retransmission_timeout_task_id = GNUNET_SCHEDULER_NO_TASK;
633   write_data (socket);
634 }
635
636
637 /**
638  * Task for sending ACK message
639  *
640  * @param cls the socket
641  * @param tc the Task context
642  */
643 static void
644 ack_task (void *cls,
645           const struct GNUNET_SCHEDULER_TaskContext *tc)
646 {
647   struct GNUNET_STREAM_Socket *socket = cls;
648   struct GNUNET_STREAM_AckMessage *ack_msg;
649   struct GNUNET_PeerIdentity target;
650
651   if (GNUNET_SCHEDULER_REASON_SHUTDOWN == tc->reason)
652     {
653       return;
654     }
655
656   socket->ack_task_id = 0;
657
658   /* Create the ACK Message */
659   ack_msg = GNUNET_malloc (sizeof (struct GNUNET_STREAM_AckMessage));
660   ack_msg->header.header.size = htons (sizeof (struct 
661                                                GNUNET_STREAM_AckMessage));
662   ack_msg->header.header.type = htons (GNUNET_MESSAGE_TYPE_STREAM_ACK);
663   ack_msg->bitmap = GNUNET_htonll (socket->ack_bitmap);
664   ack_msg->base_sequence_number = htonl (socket->read_sequence_number);
665   ack_msg->receive_window_remaining = 
666     htonl (RECEIVE_BUFFER_SIZE - socket->receive_buffer_size);
667
668   GNUNET_PEER_resolve (socket->other_peer, &target);
669   /* Request MESH for sending ACK */
670   GNUNET_MESH_notify_transmit_ready (socket->tunnel,
671                                      0, /* Corking */
672                                      1, /* Priority */
673                                      socket->retransmit_timeout,
674                                      &target,
675                                      ntohs (ack_msg->header.header.size),
676                                      &send_ack_notify,
677                                      ack_msg);
678
679   
680 }
681
682
683 /**
684  * Function to modify a bit in GNUNET_STREAM_AckBitmap
685  *
686  * @param bitmap the bitmap to modify
687  * @param bit the bit number to modify
688  * @param value GNUNET_YES to on, GNUNET_NO to off
689  */
690 static void
691 ackbitmap_modify_bit (GNUNET_STREAM_AckBitmap *bitmap,
692                       unsigned int bit, 
693                       int value)
694 {
695   GNUNET_assert (bit < 64);
696   if (GNUNET_YES == value)
697     *bitmap |= (1LL << bit);
698   else
699     *bitmap &= ~(1LL << bit);
700 }
701
702
703 /**
704  * Function to check if a bit is set in the GNUNET_STREAM_AckBitmap
705  *
706  * @param bitmap address of the bitmap that has to be checked
707  * @param bit the bit number to check
708  * @return GNUNET_YES if the bit is set; GNUNET_NO if not
709  */
710 static uint8_t
711 ackbitmap_is_bit_set (const GNUNET_STREAM_AckBitmap *bitmap,
712                       unsigned int bit)
713 {
714   GNUNET_assert (bit < 64);
715   return 0 != (*bitmap & (1LL << bit));
716 }
717
718
719
720 /**
721  * Function called when Data Message is sent
722  *
723  * @param cls the io_handle corresponding to the Data Message
724  * @param socket the socket which was used
725  */
726 static void
727 write_data_finish_cb (void *cls,
728                       struct GNUNET_STREAM_Socket *socket)
729 {
730   struct GNUNET_STREAM_IOWriteHandle *io_handle = cls;
731
732   io_handle->sent_packets++;
733 }
734
735
736 /**
737  * Writes data using the given socket. The amount of data written is limited by
738  * the receive_window_size
739  *
740  * @param socket the socket to use
741  */
742 static void 
743 write_data (struct GNUNET_STREAM_Socket *socket)
744 {
745   struct GNUNET_STREAM_IOWriteHandle *io_handle = socket->write_handle;
746   int packet;                   /* Although an int, should never be negative */
747   int ack_packet;
748
749   ack_packet = -1;
750   /* Find the last acknowledged packet */
751   for (packet=0; packet < 64; packet++)
752     {      
753       if (GNUNET_YES == ackbitmap_is_bit_set (&io_handle->ack_bitmap,
754                                               packet))
755         ack_packet = packet;        
756       else if (NULL == io_handle->messages[packet])
757         break;
758     }
759   /* Resend packets which weren't ack'ed */
760   for (packet=0; packet < ack_packet; packet++)
761     {
762       if (GNUNET_NO == ackbitmap_is_bit_set (&io_handle->ack_bitmap,
763                                              packet))
764         {
765           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
766                       "%x: Placing DATA message with sequence %u in send queue\n",
767                       socket->our_id,
768                       (unsigned int) 
769                       io_handle->messages[packet]->sequence_number);
770
771           copy_and_queue_message (socket,
772                                   &io_handle->messages[packet]->header,
773                                   NULL,
774                                   NULL);
775         }
776     }
777   packet = ack_packet + 1;
778   /* Now send new packets if there is enough buffer space */
779   while ( (NULL != io_handle->messages[packet]) &&
780           (socket->receive_window_available >= ntohs (io_handle->messages[packet]->header.header.size)) )
781     {
782       socket->receive_window_available -= 
783         ntohs (io_handle->messages[packet]->header.header.size);
784       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
785                   "%x: Placing DATA message with sequence %u in send queue\n",
786                   socket->our_id,
787                   (unsigned int) 
788                   io_handle->messages[packet]->sequence_number);
789       copy_and_queue_message (socket,
790                               &io_handle->messages[packet]->header,
791                               &write_data_finish_cb,
792                               io_handle);
793       packet++;
794     }
795
796   GNUNET_SCHEDULER_add_delayed
797     (GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5),
798      &retransmission_timeout_task,
799      socket);                                
800 }
801
802
803 /**
804  * Task for calling the read processor
805  *
806  * @param cls the socket
807  * @param tc the task context
808  */
809 static void
810 call_read_processor (void *cls,
811                           const struct GNUNET_SCHEDULER_TaskContext *tc)
812 {
813   struct GNUNET_STREAM_Socket *socket = cls;
814   size_t read_size;
815   size_t valid_read_size;
816   unsigned int packet;
817   uint32_t sequence_increase;
818   uint32_t offset_increase;
819
820   socket->read_task_id = GNUNET_SCHEDULER_NO_TASK;
821   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
822     return;
823
824   GNUNET_assert (NULL != socket->read_handle);
825   GNUNET_assert (NULL != socket->read_handle->proc);
826
827   /* Check the bitmap for any holes */
828   for (packet=0; packet < GNUNET_STREAM_ACK_BITMAP_BIT_LENGTH; packet++)
829     {
830       if (GNUNET_NO == ackbitmap_is_bit_set (&socket->ack_bitmap,
831                                              packet))
832         break;
833     }
834   /* We only call read processor if we have the first packet */
835   GNUNET_assert (0 < packet);
836
837   valid_read_size = 
838     socket->receive_buffer_boundaries[packet-1] - socket->copy_offset;
839
840   GNUNET_assert (0 != valid_read_size);
841
842   /* Cancel the read_io_timeout_task */
843   GNUNET_SCHEDULER_cancel (socket->read_io_timeout_task);
844   socket->read_io_timeout_task = GNUNET_SCHEDULER_NO_TASK;
845
846   /* Call the data processor */
847   read_size = 
848     socket->read_handle->proc (socket->read_handle->proc_cls,
849                                socket->status,
850                                socket->receive_buffer + socket->copy_offset,
851                                valid_read_size);
852   /* Free the read handle */
853   GNUNET_free (socket->read_handle);
854   socket->read_handle = NULL;
855
856   GNUNET_assert (read_size <= valid_read_size);
857   socket->copy_offset += read_size;
858
859   /* Determine upto which packet we can remove from the buffer */
860   for (packet = 0; packet < GNUNET_STREAM_ACK_BITMAP_BIT_LENGTH; packet++)
861     if (socket->copy_offset < socket->receive_buffer_boundaries[packet])
862       break;
863
864   /* If no packets can be removed we can't move the buffer */
865   if (0 == packet) return;
866
867   sequence_increase = packet;
868
869   /* Shift the data in the receive buffer */
870   memmove (socket->receive_buffer,
871            socket->receive_buffer 
872            + socket->receive_buffer_boundaries[sequence_increase-1],
873            socket->receive_buffer_size - socket->receive_buffer_boundaries[sequence_increase-1]);
874   
875   /* Shift the bitmap */
876   socket->ack_bitmap = socket->ack_bitmap >> sequence_increase;
877   
878   /* Set read_sequence_number */
879   socket->read_sequence_number += sequence_increase;
880   
881   /* Set read_offset */
882   offset_increase = socket->receive_buffer_boundaries[sequence_increase-1];
883   socket->read_offset += offset_increase;
884
885   /* Fix copy_offset */
886   GNUNET_assert (offset_increase <= socket->copy_offset);
887   socket->copy_offset -= offset_increase;
888   
889   /* Fix relative boundaries */
890   for (packet=0; packet < GNUNET_STREAM_ACK_BITMAP_BIT_LENGTH; packet++)
891     {
892       if (packet < GNUNET_STREAM_ACK_BITMAP_BIT_LENGTH - sequence_increase)
893         {
894           socket->receive_buffer_boundaries[packet] = 
895             socket->receive_buffer_boundaries[packet + sequence_increase] 
896             - offset_increase;
897         }
898       else
899         socket->receive_buffer_boundaries[packet] = 0;
900     }
901 }
902
903
904 /**
905  * Cancels the existing read io handle
906  *
907  * @param cls the closure from the SCHEDULER call
908  * @param tc the task context
909  */
910 static void
911 read_io_timeout (void *cls, 
912                 const struct GNUNET_SCHEDULER_TaskContext *tc)
913 {
914   struct GNUNET_STREAM_Socket *socket = cls;
915
916   socket->read_io_timeout_task = GNUNET_SCHEDULER_NO_TASK;
917   if (socket->read_task_id != GNUNET_SCHEDULER_NO_TASK)
918   {
919     GNUNET_SCHEDULER_cancel (socket->read_task_id);
920     socket->read_task_id = GNUNET_SCHEDULER_NO_TASK;
921   }
922   GNUNET_assert (NULL != socket->read_handle);
923   
924   GNUNET_free (socket->read_handle);
925   socket->read_handle = NULL;
926 }
927
928
929 /**
930  * Handler for DATA messages; Same for both client and server
931  *
932  * @param socket the socket through which the ack was received
933  * @param tunnel connection to the other end
934  * @param sender who sent the message
935  * @param msg the data message
936  * @param atsi performance data for the connection
937  * @return GNUNET_OK to keep the connection open,
938  *         GNUNET_SYSERR to close it (signal serious error)
939  */
940 static int
941 handle_data (struct GNUNET_STREAM_Socket *socket,
942              struct GNUNET_MESH_Tunnel *tunnel,
943              const struct GNUNET_PeerIdentity *sender,
944              const struct GNUNET_STREAM_DataMessage *msg,
945              const struct GNUNET_ATS_Information*atsi)
946 {
947   const void *payload;
948   uint32_t bytes_needed;
949   uint32_t relative_offset;
950   uint32_t relative_sequence_number;
951   uint16_t size;
952
953   size = htons (msg->header.header.size);
954   if (size < sizeof (struct GNUNET_STREAM_DataMessage))
955     {
956       GNUNET_break_op (0);
957       return GNUNET_SYSERR;
958     }
959
960   if (GNUNET_PEER_search (sender) != socket->other_peer)
961     {
962       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
963                   "%x: Received DATA from non-confirming peer\n",
964                   socket->our_id);
965       return GNUNET_YES;
966     }
967
968   switch (socket->state)
969     {
970     case STATE_ESTABLISHED:
971     case STATE_TRANSMIT_CLOSED:
972     case STATE_TRANSMIT_CLOSE_WAIT:
973       
974       /* check if the message's sequence number is in the range we are
975          expecting */
976       relative_sequence_number = 
977         ntohl (msg->sequence_number) - socket->read_sequence_number;
978       if ( relative_sequence_number > 64)
979         {
980           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
981                       "%x: Ignoring received message with sequence number %u\n",
982                       socket->our_id,
983                       ntohl (msg->sequence_number));
984           return GNUNET_YES;
985         }
986
987       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
988                   "%x: Receiving DATA with sequence number: %u and size: %d "
989                   "from %x\n",
990                   socket->our_id,
991                   ntohl (msg->sequence_number),
992                   ntohs (msg->header.header.size),
993                   socket->other_peer);
994
995       /* Check if we have to allocate the buffer */
996       size -= sizeof (struct GNUNET_STREAM_DataMessage);
997       relative_offset = ntohl (msg->offset) - socket->read_offset;
998       bytes_needed = relative_offset + size;
999       
1000       if (bytes_needed > socket->receive_buffer_size)
1001         {
1002           if (bytes_needed <= RECEIVE_BUFFER_SIZE)
1003             {
1004               socket->receive_buffer = GNUNET_realloc (socket->receive_buffer,
1005                                                        bytes_needed);
1006               socket->receive_buffer_size = bytes_needed;
1007             }
1008           else
1009             {
1010               GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1011                           "%x: Cannot accommodate packet %d as buffer is",
1012                           "full\n",
1013                           socket->our_id,
1014                           ntohl (msg->sequence_number));
1015               return GNUNET_YES;
1016             }
1017         }
1018       
1019       /* Copy Data to buffer */
1020       payload = &msg[1];
1021       GNUNET_assert (relative_offset + size <= socket->receive_buffer_size);
1022       memcpy (socket->receive_buffer + relative_offset,
1023               payload,
1024               size);
1025       socket->receive_buffer_boundaries[relative_sequence_number] = 
1026         relative_offset + size;
1027       
1028       /* Modify the ACK bitmap */
1029       ackbitmap_modify_bit (&socket->ack_bitmap,
1030                             relative_sequence_number,
1031                             GNUNET_YES);
1032
1033       /* Start ACK sending task if one is not already present */
1034       if (0 == socket->ack_task_id)
1035        {
1036          socket->ack_task_id = 
1037            GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_ntoh
1038                                          (msg->ack_deadline),
1039                                          &ack_task,
1040                                          socket);
1041        }
1042
1043       if ((NULL != socket->read_handle) /* A read handle is waiting */
1044           /* There is no current read task */
1045           && (GNUNET_SCHEDULER_NO_TASK == socket->read_task_id)
1046           /* We have the first packet */
1047           && (GNUNET_YES == ackbitmap_is_bit_set(&socket->ack_bitmap,
1048                                                  0)))
1049         {
1050           socket->read_task_id = 
1051             GNUNET_SCHEDULER_add_now (&call_read_processor,
1052                                       socket);
1053         }
1054       
1055       break;
1056
1057     default:
1058       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1059                   "%x: Received data message when it cannot be handled\n",
1060                   socket->our_id);
1061       break;
1062     }
1063   return GNUNET_YES;
1064 }
1065
1066 /**
1067  * Client's message Handler for GNUNET_MESSAGE_TYPE_STREAM_DATA
1068  *
1069  * @param cls the socket (set from GNUNET_MESH_connect)
1070  * @param tunnel connection to the other end
1071  * @param tunnel_ctx place to store local state associated with the tunnel
1072  * @param sender who sent the message
1073  * @param message the actual message
1074  * @param atsi performance data for the connection
1075  * @return GNUNET_OK to keep the connection open,
1076  *         GNUNET_SYSERR to close it (signal serious error)
1077  */
1078 static int
1079 client_handle_data (void *cls,
1080              struct GNUNET_MESH_Tunnel *tunnel,
1081              void **tunnel_ctx,
1082              const struct GNUNET_PeerIdentity *sender,
1083              const struct GNUNET_MessageHeader *message,
1084              const struct GNUNET_ATS_Information*atsi)
1085 {
1086   struct GNUNET_STREAM_Socket *socket = cls;
1087
1088   return handle_data (socket, 
1089                       tunnel, 
1090                       sender, 
1091                       (const struct GNUNET_STREAM_DataMessage *) message, 
1092                       atsi);
1093 }
1094
1095
1096 /**
1097  * Callback to set state to ESTABLISHED
1098  *
1099  * @param cls the closure from queue_message FIXME: document
1100  * @param socket the socket to requiring state change
1101  */
1102 static void
1103 set_state_established (void *cls,
1104                        struct GNUNET_STREAM_Socket *socket)
1105 {
1106   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
1107               "%x: Attaining ESTABLISHED state\n",
1108               socket->our_id);
1109   socket->write_offset = 0;
1110   socket->read_offset = 0;
1111   socket->state = STATE_ESTABLISHED;
1112   if (socket->open_cb)
1113     socket->open_cb (socket->open_cls, socket);
1114 }
1115
1116
1117 /**
1118  * Callback to set state to HELLO_WAIT
1119  *
1120  * @param cls the closure from queue_message
1121  * @param socket the socket to requiring state change
1122  */
1123 static void
1124 set_state_hello_wait (void *cls,
1125                       struct GNUNET_STREAM_Socket *socket)
1126 {
1127   GNUNET_assert (STATE_INIT == socket->state);
1128   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
1129               "%x: Attaining HELLO_WAIT state\n",
1130               socket->our_id);
1131   socket->state = STATE_HELLO_WAIT;
1132 }
1133
1134
1135 /**
1136  * Client's message handler for GNUNET_MESSAGE_TYPE_STREAM_HELLO_ACK
1137  *
1138  * @param cls the socket (set from GNUNET_MESH_connect)
1139  * @param tunnel connection to the other end
1140  * @param tunnel_ctx this is NULL
1141  * @param sender who sent the message
1142  * @param message the actual message
1143  * @param atsi performance data for the connection
1144  * @return GNUNET_OK to keep the connection open,
1145  *         GNUNET_SYSERR to close it (signal serious error)
1146  */
1147 static int
1148 client_handle_hello_ack (void *cls,
1149                          struct GNUNET_MESH_Tunnel *tunnel,
1150                          void **tunnel_ctx,
1151                          const struct GNUNET_PeerIdentity *sender,
1152                          const struct GNUNET_MessageHeader *message,
1153                          const struct GNUNET_ATS_Information*atsi)
1154 {
1155   struct GNUNET_STREAM_Socket *socket = cls;
1156   const struct GNUNET_STREAM_HelloAckMessage *ack_msg;
1157   struct GNUNET_STREAM_HelloAckMessage *reply;
1158
1159   if (GNUNET_PEER_search (sender) != socket->other_peer)
1160     {
1161       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1162                   "%x: Received HELLO_ACK from non-confirming peer\n",
1163                   socket->our_id);
1164       return GNUNET_YES;
1165     }
1166   ack_msg = (const struct GNUNET_STREAM_HelloAckMessage *) message;
1167   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1168               "%x: Received HELLO_ACK from %x\n",
1169               socket->our_id,
1170               socket->other_peer);
1171
1172   GNUNET_assert (socket->tunnel == tunnel);
1173   switch (socket->state)
1174   {
1175   case STATE_HELLO_WAIT:
1176     socket->read_sequence_number = ntohl (ack_msg->sequence_number);
1177     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1178                 "%x: Read sequence number %u\n",
1179                 socket->our_id,
1180                 (unsigned int) socket->read_sequence_number);
1181     socket->receive_window_available = ntohl (ack_msg->receive_window_size);
1182     /* Get the random sequence number */
1183     socket->write_sequence_number = 
1184       GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1185       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1186                   "%x: Generated write sequence number %u\n",
1187                   socket->our_id,
1188                   (unsigned int) socket->write_sequence_number);
1189     reply = 
1190       GNUNET_malloc (sizeof (struct GNUNET_STREAM_HelloAckMessage));
1191     reply->header.header.size = 
1192       htons (sizeof (struct GNUNET_STREAM_HelloAckMessage));
1193     reply->header.header.type = 
1194       htons (GNUNET_MESSAGE_TYPE_STREAM_HELLO_ACK);
1195     reply->sequence_number = htonl (socket->write_sequence_number);
1196     reply->receive_window_size = htonl (RECEIVE_BUFFER_SIZE);
1197     queue_message (socket, 
1198                    &reply->header, 
1199                    &set_state_established, 
1200                    NULL);      
1201     return GNUNET_OK;
1202   case STATE_ESTABLISHED:
1203   case STATE_RECEIVE_CLOSE_WAIT:
1204     // call statistics (# ACKs ignored++)
1205     return GNUNET_OK;
1206   case STATE_INIT:
1207   default:
1208     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1209                 "%x: Server %x sent HELLO_ACK when in state %d\n", 
1210                 socket->our_id,
1211                 socket->other_peer,
1212                 socket->state);
1213     socket->state = STATE_CLOSED; // introduce STATE_ERROR?
1214     return GNUNET_SYSERR;
1215   }
1216
1217 }
1218
1219
1220 /**
1221  * Client's message handler for GNUNET_MESSAGE_TYPE_STREAM_RESET
1222  *
1223  * @param cls the socket (set from GNUNET_MESH_connect)
1224  * @param tunnel connection to the other end
1225  * @param tunnel_ctx this is NULL
1226  * @param sender who sent the message
1227  * @param message the actual message
1228  * @param atsi performance data for the connection
1229  * @return GNUNET_OK to keep the connection open,
1230  *         GNUNET_SYSERR to close it (signal serious error)
1231  */
1232 static int
1233 client_handle_reset (void *cls,
1234                      struct GNUNET_MESH_Tunnel *tunnel,
1235                      void **tunnel_ctx,
1236                      const struct GNUNET_PeerIdentity *sender,
1237                      const struct GNUNET_MessageHeader *message,
1238                      const struct GNUNET_ATS_Information*atsi)
1239 {
1240   struct GNUNET_STREAM_Socket *socket = cls;
1241
1242   return GNUNET_OK;
1243 }
1244
1245
1246 /**
1247  * Common message handler for handling TRANSMIT_CLOSE messages
1248  *
1249  * @param socket the socket through which the ack was received
1250  * @param tunnel connection to the other end
1251  * @param sender who sent the message
1252  * @param msg the transmit close message
1253  * @param atsi performance data for the connection
1254  * @return GNUNET_OK to keep the connection open,
1255  *         GNUNET_SYSERR to close it (signal serious error)
1256  */
1257 static int
1258 handle_transmit_close (struct GNUNET_STREAM_Socket *socket,
1259                        struct GNUNET_MESH_Tunnel *tunnel,
1260                        const struct GNUNET_PeerIdentity *sender,
1261                        const struct GNUNET_STREAM_MessageHeader *msg,
1262                        const struct GNUNET_ATS_Information*atsi)
1263 {
1264   struct GNUNET_STREAM_MessageHeader *reply;
1265
1266   switch (socket->state)
1267     {
1268     case STATE_ESTABLISHED:
1269       socket->state = STATE_RECEIVE_CLOSED;
1270
1271       /* Send TRANSMIT_CLOSE_ACK */
1272       reply = GNUNET_malloc (sizeof (struct GNUNET_STREAM_MessageHeader));
1273       reply->header.type = 
1274         htons (GNUNET_MESSAGE_TYPE_STREAM_TRANSMIT_CLOSE_ACK);
1275       reply->header.size = htons (sizeof (struct GNUNET_STREAM_MessageHeader));
1276       queue_message (socket, reply, NULL, NULL);
1277       break;
1278
1279     default:
1280       /* FIXME: Call statistics? */
1281       break;
1282     }
1283   return GNUNET_YES;
1284 }
1285
1286
1287 /**
1288  * Client's message handler for GNUNET_MESSAGE_TYPE_STREAM_TRANSMIT_CLOSE
1289  *
1290  * @param cls the socket (set from GNUNET_MESH_connect)
1291  * @param tunnel connection to the other end
1292  * @param tunnel_ctx this is NULL
1293  * @param sender who sent the message
1294  * @param message the actual message
1295  * @param atsi performance data for the connection
1296  * @return GNUNET_OK to keep the connection open,
1297  *         GNUNET_SYSERR to close it (signal serious error)
1298  */
1299 static int
1300 client_handle_transmit_close (void *cls,
1301                               struct GNUNET_MESH_Tunnel *tunnel,
1302                               void **tunnel_ctx,
1303                               const struct GNUNET_PeerIdentity *sender,
1304                               const struct GNUNET_MessageHeader *message,
1305                               const struct GNUNET_ATS_Information*atsi)
1306 {
1307   struct GNUNET_STREAM_Socket *socket = cls;
1308   
1309   return handle_transmit_close (socket,
1310                                 tunnel,
1311                                 sender,
1312                                 (struct GNUNET_STREAM_MessageHeader *)message,
1313                                 atsi);
1314 }
1315
1316
1317 /**
1318  * Client's message handler for GNUNET_MESSAGE_TYPE_STREAM_TRANSMIT_CLOSE_ACK
1319  *
1320  * @param cls the socket (set from GNUNET_MESH_connect)
1321  * @param tunnel connection to the other end
1322  * @param tunnel_ctx this is NULL
1323  * @param sender who sent the message
1324  * @param message the actual message
1325  * @param atsi performance data for the connection
1326  * @return GNUNET_OK to keep the connection open,
1327  *         GNUNET_SYSERR to close it (signal serious error)
1328  */
1329 static int
1330 client_handle_transmit_close_ack (void *cls,
1331                                   struct GNUNET_MESH_Tunnel *tunnel,
1332                                   void **tunnel_ctx,
1333                                   const struct GNUNET_PeerIdentity *sender,
1334                                   const struct GNUNET_MessageHeader *message,
1335                                   const struct GNUNET_ATS_Information*atsi)
1336 {
1337   struct GNUNET_STREAM_Socket *socket = cls;
1338
1339   return GNUNET_OK;
1340 }
1341
1342
1343 /**
1344  * Client's message handler for GNUNET_MESSAGE_TYPE_STREAM_RECEIVE_CLOSE
1345  *
1346  * @param cls the socket (set from GNUNET_MESH_connect)
1347  * @param tunnel connection to the other end
1348  * @param tunnel_ctx this is NULL
1349  * @param sender who sent the message
1350  * @param message the actual message
1351  * @param atsi performance data for the connection
1352  * @return GNUNET_OK to keep the connection open,
1353  *         GNUNET_SYSERR to close it (signal serious error)
1354  */
1355 static int
1356 client_handle_receive_close (void *cls,
1357                              struct GNUNET_MESH_Tunnel *tunnel,
1358                              void **tunnel_ctx,
1359                              const struct GNUNET_PeerIdentity *sender,
1360                              const struct GNUNET_MessageHeader *message,
1361                              const struct GNUNET_ATS_Information*atsi)
1362 {
1363   struct GNUNET_STREAM_Socket *socket = cls;
1364
1365   return GNUNET_OK;
1366 }
1367
1368
1369 /**
1370  * Client's message handler for GNUNET_MESSAGE_TYPE_STREAM_RECEIVE_CLOSE_ACK
1371  *
1372  * @param cls the socket (set from GNUNET_MESH_connect)
1373  * @param tunnel connection to the other end
1374  * @param tunnel_ctx this is NULL
1375  * @param sender who sent the message
1376  * @param message the actual message
1377  * @param atsi performance data for the connection
1378  * @return GNUNET_OK to keep the connection open,
1379  *         GNUNET_SYSERR to close it (signal serious error)
1380  */
1381 static int
1382 client_handle_receive_close_ack (void *cls,
1383                                  struct GNUNET_MESH_Tunnel *tunnel,
1384                                  void **tunnel_ctx,
1385                                  const struct GNUNET_PeerIdentity *sender,
1386                                  const struct GNUNET_MessageHeader *message,
1387                                  const struct GNUNET_ATS_Information*atsi)
1388 {
1389   struct GNUNET_STREAM_Socket *socket = cls;
1390
1391   return GNUNET_OK;
1392 }
1393
1394
1395 /**
1396  * Client's message handler for GNUNET_MESSAGE_TYPE_STREAM_CLOSE
1397  *
1398  * @param cls the socket (set from GNUNET_MESH_connect)
1399  * @param tunnel connection to the other end
1400  * @param tunnel_ctx this is NULL
1401  * @param sender who sent the message
1402  * @param message the actual message
1403  * @param atsi performance data for the connection
1404  * @return GNUNET_OK to keep the connection open,
1405  *         GNUNET_SYSERR to close it (signal serious error)
1406  */
1407 static int
1408 client_handle_close (void *cls,
1409                      struct GNUNET_MESH_Tunnel *tunnel,
1410                      void **tunnel_ctx,
1411                      const struct GNUNET_PeerIdentity *sender,
1412                      const struct GNUNET_MessageHeader *message,
1413                      const struct GNUNET_ATS_Information*atsi)
1414 {
1415   struct GNUNET_STREAM_Socket *socket = cls;
1416
1417   return GNUNET_OK;
1418 }
1419
1420
1421 /**
1422  * Client's message handler for GNUNET_MESSAGE_TYPE_STREAM_CLOSE_ACK
1423  *
1424  * @param cls the socket (set from GNUNET_MESH_connect)
1425  * @param tunnel connection to the other end
1426  * @param tunnel_ctx this is NULL
1427  * @param sender who sent the message
1428  * @param message the actual message
1429  * @param atsi performance data for the connection
1430  * @return GNUNET_OK to keep the connection open,
1431  *         GNUNET_SYSERR to close it (signal serious error)
1432  */
1433 static int
1434 client_handle_close_ack (void *cls,
1435                          struct GNUNET_MESH_Tunnel *tunnel,
1436                          void **tunnel_ctx,
1437                          const struct GNUNET_PeerIdentity *sender,
1438                          const struct GNUNET_MessageHeader *message,
1439                          const struct GNUNET_ATS_Information*atsi)
1440 {
1441   struct GNUNET_STREAM_Socket *socket = cls;
1442
1443   return GNUNET_OK;
1444 }
1445
1446 /*****************************/
1447 /* Server's Message Handlers */
1448 /*****************************/
1449
1450 /**
1451  * Server's message Handler for GNUNET_MESSAGE_TYPE_STREAM_DATA
1452  *
1453  * @param cls the closure
1454  * @param tunnel connection to the other end
1455  * @param tunnel_ctx the socket
1456  * @param sender who sent the message
1457  * @param message the actual message
1458  * @param atsi performance data for the connection
1459  * @return GNUNET_OK to keep the connection open,
1460  *         GNUNET_SYSERR to close it (signal serious error)
1461  */
1462 static int
1463 server_handle_data (void *cls,
1464                     struct GNUNET_MESH_Tunnel *tunnel,
1465                     void **tunnel_ctx,
1466                     const struct GNUNET_PeerIdentity *sender,
1467                     const struct GNUNET_MessageHeader *message,
1468                     const struct GNUNET_ATS_Information*atsi)
1469 {
1470   struct GNUNET_STREAM_Socket *socket = *tunnel_ctx;
1471
1472   return handle_data (socket,
1473                       tunnel,
1474                       sender,
1475                       (const struct GNUNET_STREAM_DataMessage *)message,
1476                       atsi);
1477 }
1478
1479
1480 /**
1481  * Server's message handler for GNUNET_MESSAGE_TYPE_STREAM_HELLO
1482  *
1483  * @param cls the closure
1484  * @param tunnel connection to the other end
1485  * @param tunnel_ctx the socket
1486  * @param sender who sent the message
1487  * @param message the actual message
1488  * @param atsi performance data for the connection
1489  * @return GNUNET_OK to keep the connection open,
1490  *         GNUNET_SYSERR to close it (signal serious error)
1491  */
1492 static int
1493 server_handle_hello (void *cls,
1494                      struct GNUNET_MESH_Tunnel *tunnel,
1495                      void **tunnel_ctx,
1496                      const struct GNUNET_PeerIdentity *sender,
1497                      const struct GNUNET_MessageHeader *message,
1498                      const struct GNUNET_ATS_Information*atsi)
1499 {
1500   struct GNUNET_STREAM_Socket *socket = *tunnel_ctx;
1501   struct GNUNET_STREAM_HelloAckMessage *reply;
1502
1503   if (GNUNET_PEER_search (sender) != socket->other_peer)
1504     {
1505       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1506                   "%x: Received HELLO from non-confirming peer\n",
1507                   socket->our_id);
1508       return GNUNET_YES;
1509     }
1510
1511   GNUNET_assert (GNUNET_MESSAGE_TYPE_STREAM_HELLO == 
1512                  ntohs (message->type));
1513   GNUNET_assert (socket->tunnel == tunnel);
1514   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1515               "%x: Received HELLO from %x\n", 
1516               socket->our_id,
1517               socket->other_peer);
1518
1519   if (STATE_INIT == socket->state)
1520     {
1521       /* Get the random sequence number */
1522       socket->write_sequence_number = 
1523         GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1524       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1525                   "%x: Generated write sequence number %u\n",
1526                   socket->our_id,
1527                   (unsigned int) socket->write_sequence_number);
1528       reply = 
1529         GNUNET_malloc (sizeof (struct GNUNET_STREAM_HelloAckMessage));
1530       reply->header.header.size = 
1531         htons (sizeof (struct GNUNET_STREAM_HelloAckMessage));
1532       reply->header.header.type = 
1533         htons (GNUNET_MESSAGE_TYPE_STREAM_HELLO_ACK);
1534       reply->sequence_number = htonl (socket->write_sequence_number);
1535       queue_message (socket, 
1536                      &reply->header,
1537                      &set_state_hello_wait, 
1538                      NULL);
1539     }
1540   else
1541     {
1542       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1543                   "Client sent HELLO when in state %d\n", socket->state);
1544       /* FIXME: Send RESET? */
1545       
1546     }
1547   return GNUNET_OK;
1548 }
1549
1550
1551 /**
1552  * Server's message handler for GNUNET_MESSAGE_TYPE_STREAM_HELLO_ACK
1553  *
1554  * @param cls the closure
1555  * @param tunnel connection to the other end
1556  * @param tunnel_ctx the socket
1557  * @param sender who sent the message
1558  * @param message the actual message
1559  * @param atsi performance data for the connection
1560  * @return GNUNET_OK to keep the connection open,
1561  *         GNUNET_SYSERR to close it (signal serious error)
1562  */
1563 static int
1564 server_handle_hello_ack (void *cls,
1565                          struct GNUNET_MESH_Tunnel *tunnel,
1566                          void **tunnel_ctx,
1567                          const struct GNUNET_PeerIdentity *sender,
1568                          const struct GNUNET_MessageHeader *message,
1569                          const struct GNUNET_ATS_Information*atsi)
1570 {
1571   struct GNUNET_STREAM_Socket *socket = *tunnel_ctx;
1572   const struct GNUNET_STREAM_HelloAckMessage *ack_message;
1573
1574   GNUNET_assert (GNUNET_MESSAGE_TYPE_STREAM_HELLO_ACK ==
1575                  ntohs (message->type));
1576   GNUNET_assert (socket->tunnel == tunnel);
1577   ack_message = (struct GNUNET_STREAM_HelloAckMessage *) message;
1578   if (STATE_HELLO_WAIT == socket->state)
1579     {
1580       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1581                   "%x: Received HELLO_ACK from %x\n",
1582                   socket->our_id,
1583                   socket->other_peer);
1584       socket->read_sequence_number = ntohl (ack_message->sequence_number);
1585       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1586                   "%x: Read sequence number %u\n",
1587                   socket->our_id,
1588                   (unsigned int) socket->read_sequence_number);
1589       socket->receive_window_available = 
1590         ntohl (ack_message->receive_window_size);
1591       /* Attain ESTABLISHED state */
1592       set_state_established (NULL, socket);
1593     }
1594   else
1595     {
1596       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1597                   "Client sent HELLO_ACK when in state %d\n", socket->state);
1598       /* FIXME: Send RESET? */
1599       
1600     }
1601   return GNUNET_OK;
1602 }
1603
1604
1605 /**
1606  * Server's message handler for GNUNET_MESSAGE_TYPE_STREAM_RESET
1607  *
1608  * @param cls the closure
1609  * @param tunnel connection to the other end
1610  * @param tunnel_ctx the socket
1611  * @param sender who sent the message
1612  * @param message the actual message
1613  * @param atsi performance data for the connection
1614  * @return GNUNET_OK to keep the connection open,
1615  *         GNUNET_SYSERR to close it (signal serious error)
1616  */
1617 static int
1618 server_handle_reset (void *cls,
1619                      struct GNUNET_MESH_Tunnel *tunnel,
1620                      void **tunnel_ctx,
1621                      const struct GNUNET_PeerIdentity *sender,
1622                      const struct GNUNET_MessageHeader *message,
1623                      const struct GNUNET_ATS_Information*atsi)
1624 {
1625   struct GNUNET_STREAM_Socket *socket = *tunnel_ctx;
1626
1627   return GNUNET_OK;
1628 }
1629
1630
1631 /**
1632  * Server's message handler for GNUNET_MESSAGE_TYPE_STREAM_TRANSMIT_CLOSE
1633  *
1634  * @param cls the closure
1635  * @param tunnel connection to the other end
1636  * @param tunnel_ctx the socket
1637  * @param sender who sent the message
1638  * @param message the actual message
1639  * @param atsi performance data for the connection
1640  * @return GNUNET_OK to keep the connection open,
1641  *         GNUNET_SYSERR to close it (signal serious error)
1642  */
1643 static int
1644 server_handle_transmit_close (void *cls,
1645                               struct GNUNET_MESH_Tunnel *tunnel,
1646                               void **tunnel_ctx,
1647                               const struct GNUNET_PeerIdentity *sender,
1648                               const struct GNUNET_MessageHeader *message,
1649                               const struct GNUNET_ATS_Information*atsi)
1650 {
1651   struct GNUNET_STREAM_Socket *socket = *tunnel_ctx;
1652
1653   return handle_transmit_close (socket,
1654                                 tunnel,
1655                                 sender,
1656                                 (struct GNUNET_STREAM_MessageHeader *)message,
1657                                 atsi);
1658 }
1659
1660
1661 /**
1662  * Server's message handler for GNUNET_MESSAGE_TYPE_STREAM_TRANSMIT_CLOSE_ACK
1663  *
1664  * @param cls the closure
1665  * @param tunnel connection to the other end
1666  * @param tunnel_ctx the socket
1667  * @param sender who sent the message
1668  * @param message the actual message
1669  * @param atsi performance data for the connection
1670  * @return GNUNET_OK to keep the connection open,
1671  *         GNUNET_SYSERR to close it (signal serious error)
1672  */
1673 static int
1674 server_handle_transmit_close_ack (void *cls,
1675                                   struct GNUNET_MESH_Tunnel *tunnel,
1676                                   void **tunnel_ctx,
1677                                   const struct GNUNET_PeerIdentity *sender,
1678                                   const struct GNUNET_MessageHeader *message,
1679                                   const struct GNUNET_ATS_Information*atsi)
1680 {
1681   struct GNUNET_STREAM_Socket *socket = *tunnel_ctx;
1682
1683   return GNUNET_OK;
1684 }
1685
1686
1687 /**
1688  * Server's message handler for GNUNET_MESSAGE_TYPE_STREAM_RECEIVE_CLOSE
1689  *
1690  * @param cls the closure
1691  * @param tunnel connection to the other end
1692  * @param tunnel_ctx the socket
1693  * @param sender who sent the message
1694  * @param message the actual message
1695  * @param atsi performance data for the connection
1696  * @return GNUNET_OK to keep the connection open,
1697  *         GNUNET_SYSERR to close it (signal serious error)
1698  */
1699 static int
1700 server_handle_receive_close (void *cls,
1701                              struct GNUNET_MESH_Tunnel *tunnel,
1702                              void **tunnel_ctx,
1703                              const struct GNUNET_PeerIdentity *sender,
1704                              const struct GNUNET_MessageHeader *message,
1705                              const struct GNUNET_ATS_Information*atsi)
1706 {
1707   struct GNUNET_STREAM_Socket *socket = *tunnel_ctx;
1708
1709   return GNUNET_OK;
1710 }
1711
1712
1713 /**
1714  * Server's message handler for GNUNET_MESSAGE_TYPE_STREAM_RECEIVE_CLOSE_ACK
1715  *
1716  * @param cls the closure
1717  * @param tunnel connection to the other end
1718  * @param tunnel_ctx the socket
1719  * @param sender who sent the message
1720  * @param message the actual message
1721  * @param atsi performance data for the connection
1722  * @return GNUNET_OK to keep the connection open,
1723  *         GNUNET_SYSERR to close it (signal serious error)
1724  */
1725 static int
1726 server_handle_receive_close_ack (void *cls,
1727                                  struct GNUNET_MESH_Tunnel *tunnel,
1728                                  void **tunnel_ctx,
1729                                  const struct GNUNET_PeerIdentity *sender,
1730                                  const struct GNUNET_MessageHeader *message,
1731                                  const struct GNUNET_ATS_Information*atsi)
1732 {
1733   struct GNUNET_STREAM_Socket *socket = *tunnel_ctx;
1734
1735   return GNUNET_OK;
1736 }
1737
1738
1739 /**
1740  * Server's message handler for GNUNET_MESSAGE_TYPE_STREAM_CLOSE
1741  *
1742  * @param cls the closure
1743  * @param tunnel connection to the other end
1744  * @param tunnel_ctx the socket
1745  * @param sender who sent the message
1746  * @param message the actual message
1747  * @param atsi performance data for the connection
1748  * @return GNUNET_OK to keep the connection open,
1749  *         GNUNET_SYSERR to close it (signal serious error)
1750  */
1751 static int
1752 server_handle_close (void *cls,
1753                      struct GNUNET_MESH_Tunnel *tunnel,
1754                      void **tunnel_ctx,
1755                      const struct GNUNET_PeerIdentity *sender,
1756                      const struct GNUNET_MessageHeader *message,
1757                      const struct GNUNET_ATS_Information*atsi)
1758 {
1759   struct GNUNET_STREAM_Socket *socket = *tunnel_ctx;
1760
1761   return GNUNET_OK;
1762 }
1763
1764
1765 /**
1766  * Server's message handler for GNUNET_MESSAGE_TYPE_STREAM_CLOSE_ACK
1767  *
1768  * @param cls the closure
1769  * @param tunnel connection to the other end
1770  * @param tunnel_ctx the socket
1771  * @param sender who sent the message
1772  * @param message the actual message
1773  * @param atsi performance data for the connection
1774  * @return GNUNET_OK to keep the connection open,
1775  *         GNUNET_SYSERR to close it (signal serious error)
1776  */
1777 static int
1778 server_handle_close_ack (void *cls,
1779                          struct GNUNET_MESH_Tunnel *tunnel,
1780                          void **tunnel_ctx,
1781                          const struct GNUNET_PeerIdentity *sender,
1782                          const struct GNUNET_MessageHeader *message,
1783                          const struct GNUNET_ATS_Information*atsi)
1784 {
1785   struct GNUNET_STREAM_Socket *socket = *tunnel_ctx;
1786
1787   return GNUNET_OK;
1788 }
1789
1790
1791 /**
1792  * Message Handler for mesh
1793  *
1794  * @param socket the socket through which the ack was received
1795  * @param tunnel connection to the other end
1796  * @param sender who sent the message
1797  * @param ack the acknowledgment message
1798  * @param atsi performance data for the connection
1799  * @return GNUNET_OK to keep the connection open,
1800  *         GNUNET_SYSERR to close it (signal serious error)
1801  */
1802 static int
1803 handle_ack (struct GNUNET_STREAM_Socket *socket,
1804             struct GNUNET_MESH_Tunnel *tunnel,
1805             const struct GNUNET_PeerIdentity *sender,
1806             const struct GNUNET_STREAM_AckMessage *ack,
1807             const struct GNUNET_ATS_Information*atsi)
1808 {
1809   unsigned int packet;
1810   int need_retransmission;
1811
1812   if (GNUNET_PEER_search (sender) != socket->other_peer)
1813     {
1814       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1815                   "%x: Received ACK from non-confirming peer\n",
1816                   socket->our_id);
1817       return GNUNET_YES;
1818     }
1819
1820   switch (socket->state)
1821     {
1822     case (STATE_ESTABLISHED):
1823       if (NULL == socket->write_handle)
1824         {
1825           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1826                       "%x: Received DATA_ACK when write_handle is NULL\n",
1827                       socket->our_id);
1828           return GNUNET_OK;
1829         }
1830       
1831       if (!((socket->write_sequence_number 
1832              - htonl (ack->base_sequence_number)) < 64))
1833         {
1834           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1835                       "%x: Received DATA_ACK with unexpected base sequence",
1836                       "number\n",
1837                       socket->our_id);
1838           return GNUNET_OK;
1839         }
1840       /* FIXME: include the case when write_handle is cancelled - ignore the 
1841          acks */
1842       
1843       /* Cancel the retransmission task */
1844       if (GNUNET_SCHEDULER_NO_TASK != socket->retransmission_timeout_task_id)
1845         {
1846           GNUNET_SCHEDULER_cancel (socket->retransmission_timeout_task_id);
1847           socket->retransmission_timeout_task_id = 
1848             GNUNET_SCHEDULER_NO_TASK;
1849         }
1850          
1851       socket->write_handle->ack_bitmap = GNUNET_ntohll (ack->bitmap);
1852       socket->receive_window_available = 
1853         ntohl (ack->receive_window_remaining);
1854
1855       /* Check if we have received all acknowledgements */
1856       need_retransmission = GNUNET_NO;
1857       for (packet=0; packet < 64; packet++)
1858         {
1859           if (NULL == socket->write_handle->messages[packet]) break;
1860           if (GNUNET_YES != ackbitmap_is_bit_set 
1861               (&socket->write_handle->ack_bitmap,packet))
1862             {
1863               need_retransmission = GNUNET_YES;
1864               break;
1865             }
1866         }
1867       if (GNUNET_YES == need_retransmission)
1868         {
1869           write_data (socket);
1870         }
1871       else      /* We have to call the write continuation callback now */
1872         {
1873
1874           /* Free the packets */
1875           for (packet=0; packet < 64; packet++)
1876             {
1877               GNUNET_free_non_null (socket->write_handle->messages[packet]);
1878             }
1879           if (NULL != socket->write_handle->write_cont)
1880             socket->write_handle->write_cont
1881               (socket->write_handle->write_cont_cls,
1882                socket->status,
1883                socket->write_handle->size);
1884           /* We are done with the write handle - Freeing it */
1885           GNUNET_free (socket->write_handle);
1886           socket->write_handle = NULL;
1887         }
1888       break;
1889     default:
1890       break;
1891     }
1892   return GNUNET_OK;
1893 }
1894
1895
1896 /**
1897  * Message Handler for mesh
1898  *
1899  * @param cls the 'struct GNUNET_STREAM_Socket'
1900  * @param tunnel connection to the other end
1901  * @param tunnel_ctx unused
1902  * @param sender who sent the message
1903  * @param message the actual message
1904  * @param atsi performance data for the connection
1905  * @return GNUNET_OK to keep the connection open,
1906  *         GNUNET_SYSERR to close it (signal serious error)
1907  */
1908 static int
1909 client_handle_ack (void *cls,
1910                    struct GNUNET_MESH_Tunnel *tunnel,
1911                    void **tunnel_ctx,
1912                    const struct GNUNET_PeerIdentity *sender,
1913                    const struct GNUNET_MessageHeader *message,
1914                    const struct GNUNET_ATS_Information*atsi)
1915 {
1916   struct GNUNET_STREAM_Socket *socket = cls;
1917   const struct GNUNET_STREAM_AckMessage *ack = (const struct GNUNET_STREAM_AckMessage *) message;
1918  
1919   return handle_ack (socket, tunnel, sender, ack, atsi);
1920 }
1921
1922
1923 /**
1924  * Message Handler for mesh
1925  *
1926  * @param cls the server's listen socket
1927  * @param tunnel connection to the other end
1928  * @param tunnel_ctx pointer to the 'struct GNUNET_STREAM_Socket*'
1929  * @param sender who sent the message
1930  * @param message the actual message
1931  * @param atsi performance data for the connection
1932  * @return GNUNET_OK to keep the connection open,
1933  *         GNUNET_SYSERR to close it (signal serious error)
1934  */
1935 static int
1936 server_handle_ack (void *cls,
1937                    struct GNUNET_MESH_Tunnel *tunnel,
1938                    void **tunnel_ctx,
1939                    const struct GNUNET_PeerIdentity *sender,
1940                    const struct GNUNET_MessageHeader *message,
1941                    const struct GNUNET_ATS_Information*atsi)
1942 {
1943   struct GNUNET_STREAM_Socket *socket = *tunnel_ctx;
1944   const struct GNUNET_STREAM_AckMessage *ack = (const struct GNUNET_STREAM_AckMessage *) message;
1945  
1946   return handle_ack (socket, tunnel, sender, ack, atsi);
1947 }
1948
1949
1950 /**
1951  * For client message handlers, the stream socket is in the
1952  * closure argument.
1953  */
1954 static struct GNUNET_MESH_MessageHandler client_message_handlers[] = {
1955   {&client_handle_data, GNUNET_MESSAGE_TYPE_STREAM_DATA, 0},
1956   {&client_handle_ack, GNUNET_MESSAGE_TYPE_STREAM_ACK, 
1957    sizeof (struct GNUNET_STREAM_AckMessage) },
1958   {&client_handle_hello_ack, GNUNET_MESSAGE_TYPE_STREAM_HELLO_ACK,
1959    sizeof (struct GNUNET_STREAM_HelloAckMessage)},
1960   {&client_handle_reset, GNUNET_MESSAGE_TYPE_STREAM_RESET,
1961    sizeof (struct GNUNET_STREAM_MessageHeader)},
1962   {&client_handle_transmit_close, GNUNET_MESSAGE_TYPE_STREAM_TRANSMIT_CLOSE,
1963    sizeof (struct GNUNET_STREAM_MessageHeader)},
1964   {&client_handle_transmit_close_ack, GNUNET_MESSAGE_TYPE_STREAM_TRANSMIT_CLOSE_ACK,
1965    sizeof (struct GNUNET_STREAM_MessageHeader)},
1966   {&client_handle_receive_close, GNUNET_MESSAGE_TYPE_STREAM_RECEIVE_CLOSE,
1967    sizeof (struct GNUNET_STREAM_MessageHeader)},
1968   {&client_handle_receive_close_ack, GNUNET_MESSAGE_TYPE_STREAM_RECEIVE_CLOSE_ACK,
1969    sizeof (struct GNUNET_STREAM_MessageHeader)},
1970   {&client_handle_close, GNUNET_MESSAGE_TYPE_STREAM_CLOSE,
1971    sizeof (struct GNUNET_STREAM_MessageHeader)},
1972   {&client_handle_close_ack, GNUNET_MESSAGE_TYPE_STREAM_CLOSE_ACK,
1973    sizeof (struct GNUNET_STREAM_MessageHeader)},
1974   {NULL, 0, 0}
1975 };
1976
1977
1978 /**
1979  * For server message handlers, the stream socket is in the
1980  * tunnel context, and the listen socket in the closure argument.
1981  */
1982 static struct GNUNET_MESH_MessageHandler server_message_handlers[] = {
1983   {&server_handle_data, GNUNET_MESSAGE_TYPE_STREAM_DATA, 0},
1984   {&server_handle_ack, GNUNET_MESSAGE_TYPE_STREAM_ACK, 
1985    sizeof (struct GNUNET_STREAM_AckMessage) },
1986   {&server_handle_hello, GNUNET_MESSAGE_TYPE_STREAM_HELLO, 
1987    sizeof (struct GNUNET_STREAM_MessageHeader)},
1988   {&server_handle_hello_ack, GNUNET_MESSAGE_TYPE_STREAM_HELLO_ACK,
1989    sizeof (struct GNUNET_STREAM_HelloAckMessage)},
1990   {&server_handle_reset, GNUNET_MESSAGE_TYPE_STREAM_RESET,
1991    sizeof (struct GNUNET_STREAM_MessageHeader)},
1992   {&server_handle_transmit_close, GNUNET_MESSAGE_TYPE_STREAM_TRANSMIT_CLOSE,
1993    sizeof (struct GNUNET_STREAM_MessageHeader)},
1994   {&server_handle_transmit_close_ack, GNUNET_MESSAGE_TYPE_STREAM_TRANSMIT_CLOSE_ACK,
1995    sizeof (struct GNUNET_STREAM_MessageHeader)},
1996   {&server_handle_receive_close, GNUNET_MESSAGE_TYPE_STREAM_RECEIVE_CLOSE,
1997    sizeof (struct GNUNET_STREAM_MessageHeader)},
1998   {&server_handle_receive_close_ack, GNUNET_MESSAGE_TYPE_STREAM_RECEIVE_CLOSE_ACK,
1999    sizeof (struct GNUNET_STREAM_MessageHeader)},
2000   {&server_handle_close, GNUNET_MESSAGE_TYPE_STREAM_CLOSE,
2001    sizeof (struct GNUNET_STREAM_MessageHeader)},
2002   {&server_handle_close_ack, GNUNET_MESSAGE_TYPE_STREAM_CLOSE_ACK,
2003    sizeof (struct GNUNET_STREAM_MessageHeader)},
2004   {NULL, 0, 0}
2005 };
2006
2007
2008 /**
2009  * Function called when our target peer is connected to our tunnel
2010  *
2011  * @param cls the socket for which this tunnel is created
2012  * @param peer the peer identity of the target
2013  * @param atsi performance data for the connection
2014  */
2015 static void
2016 mesh_peer_connect_callback (void *cls,
2017                             const struct GNUNET_PeerIdentity *peer,
2018                             const struct GNUNET_ATS_Information * atsi)
2019 {
2020   struct GNUNET_STREAM_Socket *socket = cls;
2021   struct GNUNET_STREAM_MessageHeader *message;
2022   GNUNET_PEER_Id connected_peer;
2023
2024   connected_peer = GNUNET_PEER_search (peer);
2025   
2026   if (connected_peer != socket->other_peer)
2027     {
2028       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2029                   "%x: A peer which is not our target has connected",
2030                   "to our tunnel\n",
2031                   socket->our_id);
2032       return;
2033     }
2034   
2035   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2036               "%x: Target peer %x connected\n", 
2037               socket->our_id,
2038               connected_peer);
2039   
2040   /* Set state to INIT */
2041   socket->state = STATE_INIT;
2042
2043   /* Send HELLO message */
2044   message = GNUNET_malloc (sizeof (struct GNUNET_STREAM_MessageHeader));
2045   message->header.type = htons (GNUNET_MESSAGE_TYPE_STREAM_HELLO);
2046   message->header.size = htons (sizeof (struct GNUNET_STREAM_MessageHeader));
2047   queue_message (socket,
2048                  message,
2049                  &set_state_hello_wait,
2050                  NULL);
2051
2052   /* Call open callback */
2053   if (NULL == socket->open_cb)
2054     {
2055       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2056                   "STREAM_open callback is NULL\n");
2057     }
2058 }
2059
2060
2061 /**
2062  * Function called when our target peer is disconnected from our tunnel
2063  *
2064  * @param cls the socket associated which this tunnel
2065  * @param peer the peer identity of the target
2066  */
2067 static void
2068 mesh_peer_disconnect_callback (void *cls,
2069                                const struct GNUNET_PeerIdentity *peer)
2070 {
2071
2072 }
2073
2074
2075 /**
2076  * Method called whenever a peer creates a tunnel to us
2077  *
2078  * @param cls closure
2079  * @param tunnel new handle to the tunnel
2080  * @param initiator peer that started the tunnel
2081  * @param atsi performance information for the tunnel
2082  * @return initial tunnel context for the tunnel
2083  *         (can be NULL -- that's not an error)
2084  */
2085 static void *
2086 new_tunnel_notify (void *cls,
2087                    struct GNUNET_MESH_Tunnel *tunnel,
2088                    const struct GNUNET_PeerIdentity *initiator,
2089                    const struct GNUNET_ATS_Information *atsi)
2090 {
2091   struct GNUNET_STREAM_ListenSocket *lsocket = cls;
2092   struct GNUNET_STREAM_Socket *socket;
2093
2094   /* FIXME: If a tunnel is already created, we should not accept new tunnels
2095      from the same peer again until the socket is closed */
2096
2097   socket = GNUNET_malloc (sizeof (struct GNUNET_STREAM_Socket));
2098   socket->other_peer = GNUNET_PEER_intern (initiator);
2099   socket->tunnel = tunnel;
2100   socket->session_id = 0;       /* FIXME */
2101   socket->state = STATE_INIT;
2102   socket->derived = GNUNET_YES;
2103   socket->our_id = lsocket->our_id;
2104   
2105   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2106               "%x: Peer %x initiated tunnel to us\n", 
2107               socket->our_id,
2108               socket->other_peer);
2109   
2110   /* FIXME: Copy MESH handle from lsocket to socket */
2111   /* FIXME: What if listen_cb is NULL */
2112   if (GNUNET_SYSERR == lsocket->listen_cb (lsocket->listen_cb_cls,
2113                                            socket,
2114                                            initiator))
2115     {
2116       socket->state = STATE_CLOSED;
2117       /* FIXME: Send CLOSE message and then free */
2118       GNUNET_free (socket);
2119       GNUNET_MESH_tunnel_destroy (tunnel); /* Destroy the tunnel */
2120     }
2121   return socket;
2122 }
2123
2124
2125 /**
2126  * Function called whenever an inbound tunnel is destroyed.  Should clean up
2127  * any associated state.  This function is NOT called if the client has
2128  * explicitly asked for the tunnel to be destroyed using
2129  * GNUNET_MESH_tunnel_destroy. It must NOT call GNUNET_MESH_tunnel_destroy on
2130  * the tunnel.
2131  *
2132  * @param cls closure (set from GNUNET_MESH_connect)
2133  * @param tunnel connection to the other end (henceforth invalid)
2134  * @param tunnel_ctx place where local state associated
2135  *                   with the tunnel is stored
2136  */
2137 static void 
2138 tunnel_cleaner (void *cls,
2139                 const struct GNUNET_MESH_Tunnel *tunnel,
2140                 void *tunnel_ctx)
2141 {
2142   struct GNUNET_STREAM_Socket *socket = tunnel_ctx;
2143   
2144   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2145               "%x: Peer %x has terminated connection abruptly\n",
2146               socket->our_id,
2147               socket->other_peer);
2148
2149   socket->status = GNUNET_STREAM_SHUTDOWN;
2150
2151   /* Clear Transmit handles */
2152   if (NULL != socket->transmit_handle)
2153     {
2154       GNUNET_MESH_notify_transmit_ready_cancel (socket->transmit_handle);
2155       socket->transmit_handle = NULL;
2156     }
2157   socket->tunnel = NULL;
2158 }
2159
2160
2161 /*****************/
2162 /* API functions */
2163 /*****************/
2164
2165
2166 /**
2167  * Tries to open a stream to the target peer
2168  *
2169  * @param cfg configuration to use
2170  * @param target the target peer to which the stream has to be opened
2171  * @param app_port the application port number which uniquely identifies this
2172  *            stream
2173  * @param open_cb this function will be called after stream has be established 
2174  * @param open_cb_cls the closure for open_cb
2175  * @param ... options to the stream, terminated by GNUNET_STREAM_OPTION_END
2176  * @return if successful it returns the stream socket; NULL if stream cannot be
2177  *         opened 
2178  */
2179 struct GNUNET_STREAM_Socket *
2180 GNUNET_STREAM_open (const struct GNUNET_CONFIGURATION_Handle *cfg,
2181                     const struct GNUNET_PeerIdentity *target,
2182                     GNUNET_MESH_ApplicationType app_port,
2183                     GNUNET_STREAM_OpenCallback open_cb,
2184                     void *open_cb_cls,
2185                     ...)
2186 {
2187   struct GNUNET_STREAM_Socket *socket;
2188   struct GNUNET_PeerIdentity own_peer_id;
2189   enum GNUNET_STREAM_Option option;
2190   va_list vargs;                /* Variable arguments */
2191
2192   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2193               "%s\n", __func__);
2194
2195   socket = GNUNET_malloc (sizeof (struct GNUNET_STREAM_Socket));
2196   socket->other_peer = GNUNET_PEER_intern (target);
2197   socket->open_cb = open_cb;
2198   socket->open_cls = open_cb_cls;
2199   GNUNET_TESTING_get_peer_identity (cfg, &own_peer_id);
2200   socket->our_id = GNUNET_PEER_intern (&own_peer_id);
2201   
2202   /* Set defaults */
2203   socket->retransmit_timeout = 
2204     GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, default_timeout);
2205
2206   va_start (vargs, open_cb_cls); /* Parse variable args */
2207   do {
2208     option = va_arg (vargs, enum GNUNET_STREAM_Option);
2209     switch (option)
2210       {
2211       case GNUNET_STREAM_OPTION_INITIAL_RETRANSMIT_TIMEOUT:
2212         /* Expect struct GNUNET_TIME_Relative */
2213         socket->retransmit_timeout = va_arg (vargs,
2214                                              struct GNUNET_TIME_Relative);
2215         break;
2216       case GNUNET_STREAM_OPTION_END:
2217         break;
2218       }
2219   } while (GNUNET_STREAM_OPTION_END != option);
2220   va_end (vargs);               /* End of variable args parsing */
2221   socket->mesh = GNUNET_MESH_connect (cfg, /* the configuration handle */
2222                                       10,  /* QUEUE size as parameter? */
2223                                       socket, /* cls */
2224                                       NULL, /* No inbound tunnel handler */
2225                                       &tunnel_cleaner, /* FIXME: not required? */
2226                                       client_message_handlers,
2227                                       &app_port); /* We don't get inbound tunnels */
2228   if (NULL == socket->mesh)   /* Fail if we cannot connect to mesh */
2229     {
2230       GNUNET_free (socket);
2231       return NULL;
2232     }
2233
2234   /* Now create the mesh tunnel to target */
2235   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2236               "Creating MESH Tunnel\n");
2237   socket->tunnel = GNUNET_MESH_tunnel_create (socket->mesh,
2238                                               NULL, /* Tunnel context */
2239                                               &mesh_peer_connect_callback,
2240                                               &mesh_peer_disconnect_callback,
2241                                               socket);
2242   GNUNET_assert (NULL != socket->tunnel);
2243   GNUNET_MESH_peer_request_connect_add (socket->tunnel,
2244                                         target);
2245   
2246   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2247               "%s() END\n", __func__);
2248   return socket;
2249 }
2250
2251
2252 /**
2253  * Shutdown the stream for reading or writing (man 2 shutdown).
2254  *
2255  * @param socket the stream socket
2256  * @param how SHUT_RD, SHUT_WR or SHUT_RDWR 
2257  */
2258 void
2259 GNUNET_STREAM_shutdown (struct GNUNET_STREAM_Socket *socket,
2260                         int how)
2261 {
2262   return;
2263 }
2264
2265
2266 /**
2267  * Closes the stream
2268  *
2269  * @param socket the stream socket
2270  */
2271 void
2272 GNUNET_STREAM_close (struct GNUNET_STREAM_Socket *socket)
2273 {
2274   struct MessageQueue *head;
2275
2276   if (socket->read_task_id != GNUNET_SCHEDULER_NO_TASK)
2277   {
2278     /* socket closed with read task pending!? */
2279     GNUNET_break (0);
2280     GNUNET_SCHEDULER_cancel (socket->read_task_id);
2281     socket->read_task_id = GNUNET_SCHEDULER_NO_TASK;
2282   }
2283
2284   /* Clear Transmit handles */
2285   if (NULL != socket->transmit_handle)
2286     {
2287       GNUNET_MESH_notify_transmit_ready_cancel (socket->transmit_handle);
2288       socket->transmit_handle = NULL;
2289     }
2290
2291   /* Clear existing message queue */
2292   while (NULL != (head = socket->queue_head)) {
2293     GNUNET_CONTAINER_DLL_remove (socket->queue_head,
2294                                  socket->queue_tail,
2295                                  head);
2296     GNUNET_free (head->message);
2297     GNUNET_free (head);
2298   }
2299
2300   /* Close associated tunnel */
2301   if (NULL != socket->tunnel)
2302     {
2303       GNUNET_MESH_tunnel_destroy (socket->tunnel);
2304       socket->tunnel = NULL;
2305     }
2306
2307   /* Close mesh connection */
2308   if (NULL != socket->mesh && GNUNET_YES != socket->derived)
2309     {
2310       GNUNET_MESH_disconnect (socket->mesh);
2311       socket->mesh = NULL;
2312     }
2313   
2314   /* Release receive buffer */
2315   if (NULL != socket->receive_buffer)
2316     {
2317       GNUNET_free (socket->receive_buffer);
2318     }
2319
2320   GNUNET_free (socket);
2321 }
2322
2323
2324 /**
2325  * Listens for stream connections for a specific application ports
2326  *
2327  * @param cfg the configuration to use
2328  * @param app_port the application port for which new streams will be accepted
2329  * @param listen_cb this function will be called when a peer tries to establish
2330  *            a stream with us
2331  * @param listen_cb_cls closure for listen_cb
2332  * @return listen socket, NULL for any error
2333  */
2334 struct GNUNET_STREAM_ListenSocket *
2335 GNUNET_STREAM_listen (const struct GNUNET_CONFIGURATION_Handle *cfg,
2336                       GNUNET_MESH_ApplicationType app_port,
2337                       GNUNET_STREAM_ListenCallback listen_cb,
2338                       void *listen_cb_cls)
2339 {
2340   /* FIXME: Add variable args for passing configration options? */
2341   struct GNUNET_STREAM_ListenSocket *lsocket;
2342   struct GNUNET_PeerIdentity our_peer_id;
2343
2344   lsocket = GNUNET_malloc (sizeof (struct GNUNET_STREAM_ListenSocket));
2345   lsocket->port = app_port;
2346   lsocket->listen_cb = listen_cb;
2347   lsocket->listen_cb_cls = listen_cb_cls;
2348   GNUNET_TESTING_get_peer_identity (cfg, &our_peer_id);
2349   lsocket->our_id = GNUNET_PEER_intern (&our_peer_id);
2350   lsocket->mesh = GNUNET_MESH_connect (cfg,
2351                                        10, /* FIXME: QUEUE size as parameter? */
2352                                        lsocket, /* Closure */
2353                                        &new_tunnel_notify,
2354                                        &tunnel_cleaner,
2355                                        server_message_handlers,
2356                                        &app_port);
2357   GNUNET_assert (NULL != lsocket->mesh);
2358   return lsocket;
2359 }
2360
2361
2362 /**
2363  * Closes the listen socket
2364  *
2365  * @param lsocket the listen socket
2366  */
2367 void
2368 GNUNET_STREAM_listen_close (struct GNUNET_STREAM_ListenSocket *lsocket)
2369 {
2370   /* Close MESH connection */
2371   GNUNET_assert (NULL != lsocket->mesh);
2372   GNUNET_MESH_disconnect (lsocket->mesh);
2373   
2374   GNUNET_free (lsocket);
2375 }
2376
2377
2378 /**
2379  * Tries to write the given data to the stream
2380  *
2381  * @param socket the socket representing a stream
2382  * @param data the data buffer from where the data is written into the stream
2383  * @param size the number of bytes to be written from the data buffer
2384  * @param timeout the timeout period
2385  * @param write_cont the function to call upon writing some bytes into the stream
2386  * @param write_cont_cls the closure
2387  * @return handle to cancel the operation
2388  */
2389 struct GNUNET_STREAM_IOWriteHandle *
2390 GNUNET_STREAM_write (struct GNUNET_STREAM_Socket *socket,
2391                      const void *data,
2392                      size_t size,
2393                      struct GNUNET_TIME_Relative timeout,
2394                      GNUNET_STREAM_CompletionContinuation write_cont,
2395                      void *write_cont_cls)
2396 {
2397   unsigned int num_needed_packets;
2398   unsigned int packet;
2399   struct GNUNET_STREAM_IOWriteHandle *io_handle;
2400   uint32_t packet_size;
2401   uint32_t payload_size;
2402   struct GNUNET_STREAM_DataMessage *data_msg;
2403   const void *sweep;
2404   struct GNUNET_TIME_Relative ack_deadline;
2405
2406   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2407               "%s\n", __func__);
2408
2409   /* Return NULL if there is already a write request pending */
2410   if (NULL != socket->write_handle)
2411   {
2412     GNUNET_break (0);
2413     return NULL;
2414   }
2415   if (!((STATE_ESTABLISHED == socket->state)
2416         || (STATE_RECEIVE_CLOSE_WAIT == socket->state)
2417         || (STATE_RECEIVE_CLOSED == socket->state)))
2418     {
2419       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2420                   "%x: Attempting to write on a closed (OR) not-yet-established"
2421                   "stream\n",
2422                   socket->our_id);
2423       return NULL;
2424     } 
2425   if (GNUNET_STREAM_ACK_BITMAP_BIT_LENGTH * max_payload_size < size)
2426     size = GNUNET_STREAM_ACK_BITMAP_BIT_LENGTH  * max_payload_size;
2427   num_needed_packets = (size + (max_payload_size - 1)) / max_payload_size;
2428   io_handle = GNUNET_malloc (sizeof (struct GNUNET_STREAM_IOWriteHandle));
2429   io_handle->write_cont = write_cont;
2430   io_handle->write_cont_cls = write_cont_cls;
2431   io_handle->size = size;
2432   sweep = data;
2433   /* FIXME: Remove the fixed delay for ack deadline; Set it to the value
2434      determined from RTT */
2435   ack_deadline = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5);
2436   /* Divide the given buffer into packets for sending */
2437   for (packet=0; packet < num_needed_packets; packet++)
2438     {
2439       if ((packet + 1) * max_payload_size < size) 
2440         {
2441           payload_size = max_payload_size;
2442           packet_size = MAX_PACKET_SIZE;
2443         }
2444       else 
2445         {
2446           payload_size = size - packet * max_payload_size;
2447           packet_size =  payload_size + sizeof (struct
2448                                                 GNUNET_STREAM_DataMessage); 
2449         }
2450       io_handle->messages[packet] = GNUNET_malloc (packet_size);
2451       io_handle->messages[packet]->header.header.size = htons (packet_size);
2452       io_handle->messages[packet]->header.header.type =
2453         htons (GNUNET_MESSAGE_TYPE_STREAM_DATA);
2454       io_handle->messages[packet]->sequence_number =
2455         htons (socket->write_sequence_number++);
2456       io_handle->messages[packet]->offset = htons (socket->write_offset);
2457
2458       /* FIXME: Remove the fixed delay for ack deadline; Set it to the value
2459          determined from RTT */
2460       io_handle->messages[packet]->ack_deadline =
2461         GNUNET_TIME_relative_hton (ack_deadline);
2462       data_msg = io_handle->messages[packet];
2463       /* Copy data from given buffer to the packet */
2464       memcpy (&data_msg[1],
2465               sweep,
2466               payload_size);
2467       sweep += payload_size;
2468       socket->write_offset += payload_size;
2469     }
2470   socket->write_handle = io_handle;
2471   write_data (socket);
2472
2473   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2474               "%s() END\n", __func__);
2475
2476   return io_handle;
2477 }
2478
2479
2480 /**
2481  * Tries to read data from the stream
2482  *
2483  * @param socket the socket representing a stream
2484  * @param timeout the timeout period
2485  * @param proc function to call with data (once only)
2486  * @param proc_cls the closure for proc
2487  * @return handle to cancel the operation
2488  */
2489 struct GNUNET_STREAM_IOReadHandle *
2490 GNUNET_STREAM_read (struct GNUNET_STREAM_Socket *socket,
2491                     struct GNUNET_TIME_Relative timeout,
2492                     GNUNET_STREAM_DataProcessor proc,
2493                     void *proc_cls)
2494 {
2495   struct GNUNET_STREAM_IOReadHandle *read_handle;
2496   
2497   /* Return NULL if there is already a read handle; the user has to cancel that
2498   first before continuing or has to wait until it is completed */
2499   if (NULL != socket->read_handle) return NULL;
2500
2501   read_handle = GNUNET_malloc (sizeof (struct GNUNET_STREAM_IOReadHandle));
2502   read_handle->proc = proc;
2503   socket->read_handle = read_handle;
2504
2505   /* Check if we have a packet at bitmap 0 */
2506   if (GNUNET_YES == ackbitmap_is_bit_set (&socket->ack_bitmap,
2507                                           0))
2508     {
2509       socket->read_task_id = GNUNET_SCHEDULER_add_now (&call_read_processor,
2510                                                        socket);
2511    
2512     }
2513   
2514   /* Setup the read timeout task */
2515   socket->read_io_timeout_task = GNUNET_SCHEDULER_add_delayed (timeout,
2516                                                                &read_io_timeout,
2517                                                                socket);
2518   return read_handle;
2519 }
2520
2521
2522 /**
2523  * Cancel pending write operation.
2524  *
2525  * @param ioh handle to operation to cancel
2526  */
2527 void
2528 GNUNET_STREAM_io_write_cancel (struct GNUNET_STREAM_IOWriteHandle *ioh)
2529 {
2530   return;
2531 }
2532
2533
2534 /**
2535  * Cancel pending read operation.
2536  *
2537  * @param ioh handle to operation to cancel
2538  */
2539 void
2540 GNUNET_STREAM_io_read_cancel (struct GNUNET_STREAM_IOReadHandle *ioh)
2541 {
2542   return;
2543 }