- dead code
[oweals/gnunet.git] / src / mesh / gnunet-service-mesh-enc.c
1 /*
2      This file is part of GNUnet.
3      (C) 2001-2013 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 /**
22  * @file mesh/gnunet-service-mesh-enc.c
23  * @brief GNUnet MESH service with encryption
24  * @author Bartlomiej Polot
25  *
26  *  FIXME in progress:
27  * - when sending in-order buffered data, wait for client ACKs
28  * - add signatures
29  * - add encryption
30  *
31  * TODO:
32  * - relay corking down to core
33  * - set ttl relative to path length
34  * TODO END
35  * 
36  * Dictionary:
37  * - peer: other mesh instance. If there is direct connection it's a neighbor.
38  * - tunnel: encrypted connection to a peer, neighbor or not.
39  * - channel: connection between two clients, on the same or different peers.
40  *            have properties like reliability.
41  * - path: series of directly connected peer from one peer to another.
42  * - connection: path which is being used in a tunnel.
43  */
44
45 #include "platform.h"
46 #include "gnunet_crypto_lib.h"
47 #include "mesh_enc.h"
48 #include "mesh_protocol_enc.h"
49 #include "mesh_path.h"
50 #include "block_mesh.h"
51 #include "gnunet_dht_service.h"
52 #include "gnunet_statistics_service.h"
53
54 #define MESH_BLOOM_SIZE         128
55
56 #define MESH_DEBUG_DHT          GNUNET_NO
57 #define MESH_DEBUG_CONNECTION   GNUNET_NO
58 #define MESH_DEBUG_TIMING       __LINUX__ && GNUNET_NO
59
60 #define MESH_MAX_POLL_TIME      GNUNET_TIME_relative_multiply (\
61                                   GNUNET_TIME_UNIT_MINUTES,\
62                                   10)
63 #define MESH_RETRANSMIT_TIME    GNUNET_TIME_UNIT_SECONDS
64 #define MESH_RETRANSMIT_MARGIN  4
65
66 #if MESH_DEBUG_CONNECTION
67 #define DEBUG_CONN(...) GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__)
68 #else
69 #define DEBUG_CONN(...)
70 #endif
71
72 #if MESH_DEBUG_DHT
73 #define DEBUG_DHT(...) GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__)
74 #else
75 #define DEBUG_DHT(...)
76 #endif
77
78 #if MESH_DEBUG_TIMING
79 #include <time.h>
80 double __sum;
81 uint64_t __count;
82 struct timespec __mesh_start;
83 struct timespec __mesh_end;
84 #define INTERVAL_START clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &(__mesh_start))
85 #define INTERVAL_END \
86 do {\
87   clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &(__mesh_end));\
88   double __diff = __mesh_end.tv_nsec - __mesh_start.tv_nsec;\
89   if (__diff < 0) __diff += 1000000000;\
90   __sum += __diff;\
91   __count++;\
92 } while (0)
93 #define INTERVAL_SHOW \
94 if (0 < __count)\
95   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "AVG process time: %f ns\n", __sum/__count)
96 #else
97 #define INTERVAL_START
98 #define INTERVAL_END
99 #define INTERVAL_SHOW
100 #endif
101
102 /**
103  * All the states a tunnel can be in.
104  */
105 enum MeshTunnelState
106 {
107     /**
108      * Uninitialized status, should never appear in operation.
109      */
110   MESH_TUNNEL_NEW,
111
112     /**
113      * Path to the peer not known yet
114      */
115   MESH_TUNNEL_SEARCHING,
116
117     /**
118      * Request sent, not yet answered.
119      */
120   MESH_TUNNEL_WAITING,
121
122     /**
123      * Peer connected and ready to accept data
124      */
125   MESH_TUNNEL_READY,
126
127     /**
128      * Peer connected previosly but not responding
129      */
130   MESH_TUNNEL_RECONNECTING
131 };
132
133
134 /**
135  * All the states a connection can be in.
136  */
137 enum MeshConnectionState
138 {
139   /**
140    * Uninitialized status, should never appear in operation.
141    */
142   MESH_CONNECTION_NEW,
143
144   /**
145    * Connection created, waiting for ACK.
146    */
147   MESH_CONNECTION_SENT,
148
149   /**
150    * Connection confirmed, ready to carry traffic..
151    */
152   MESH_CONNECTION_READY,
153 };
154
155
156 /******************************************************************************/
157 /************************      DATA STRUCTURES     ****************************/
158 /******************************************************************************/
159
160 /** FWD declaration */
161 struct MeshClient;
162 struct MeshPeer;
163 struct MeshTunnel2;
164 struct MeshConnection;
165 struct MeshChannel;
166 struct MeshChannelReliability;
167
168
169 /**
170  * Struct containing info about a queued transmission to this peer
171  */
172 struct MeshPeerQueue
173 {
174     /**
175       * DLL next
176       */
177   struct MeshPeerQueue *next;
178
179     /**
180       * DLL previous
181       */
182   struct MeshPeerQueue *prev;
183
184     /**
185      * Peer this transmission is directed to.
186      */
187   struct MeshPeer *peer;
188
189     /**
190      * Connection this message belongs to.
191      */
192   struct MeshConnection *c;
193
194     /**
195      * Channel this message belongs to, if known.
196      */
197   struct MeshChannel *ch;
198
199     /**
200      * Pointer to info stucture used as cls.
201      */
202   void *cls;
203
204     /**
205      * Type of message
206      */
207   uint16_t type;
208
209     /**
210      * Size of the message
211      */
212   size_t size;
213 };
214
215
216 /**
217  * Struct to encapsulate all the Flow Control information to a peer to which
218  * we are directly connected (on a core level).
219  */
220 struct MeshFlowControl
221 {
222   /**
223    * Peer
224    */
225   struct MeshPeer *peer;
226
227   /**
228    * Transmission queue to core DLL head
229    */
230   struct MeshPeerQueue *queue_head;
231
232   /**
233    * Transmission queue to core DLL tail
234    */
235   struct MeshPeerQueue *queue_tail;
236
237   /**
238    * How many messages are in the queue to this peer.
239    */
240   unsigned int queue_n;
241
242   /**
243    * How many messages do we accept in the queue.
244    */
245   unsigned int queue_max;
246
247   /**
248    * Handle for queued transmissions
249    */
250   struct GNUNET_CORE_TransmitHandle *core_transmit;
251
252   /**
253    * ID of the last packet sent towards the peer.
254    */
255   uint32_t last_pid_sent;
256
257   /**
258    * ID of the last packet received from the peer.
259    */
260   uint32_t last_pid_recv;
261
262   /**
263    * Last ACK sent to the peer (peer can't send more than this PID).
264    */
265   uint32_t last_ack_sent;
266
267   /**
268    * Last ACK sent towards the origin (for traffic towards leaf node).
269    */
270   uint32_t last_ack_recv;
271
272   /**
273    * Task to poll the peer in case of a lost ACK causes stall.
274    */
275   GNUNET_SCHEDULER_TaskIdentifier poll_task;
276
277   /**
278    * How frequently to poll for ACKs.
279    */
280   struct GNUNET_TIME_Relative poll_time;
281 };
282
283
284 /**
285  * Struct containing all information regarding a given peer
286  */
287 struct MeshPeer
288 {
289     /**
290      * ID of the peer
291      */
292   GNUNET_PEER_Id id;
293
294     /**
295      * Last time we heard from this peer
296      */
297   struct GNUNET_TIME_Absolute last_contact;
298
299     /**
300      * Number of attempts to reconnect so far
301      */
302   int n_reconnect_attempts;
303
304     /**
305      * Paths to reach the peer, ordered by ascending hop count
306      */
307   struct MeshPeerPath *path_head;
308
309     /**
310      * Paths to reach the peer, ordered by ascending hop count
311      */
312   struct MeshPeerPath *path_tail;
313
314     /**
315      * Handle to stop the DHT search for paths to this peer
316      */
317   struct GNUNET_DHT_GetHandle *dhtget;
318
319     /**
320      * Tunnel to this peer, if any.
321      */
322   struct MeshTunnel2 *tunnel;
323
324     /**
325      * Flow control information for direct traffic.
326      */
327   struct MeshFlowControl *fc;
328
329 };
330
331
332 /**
333  * Info needed to retry a message in case it gets lost.
334  */
335 struct MeshReliableMessage
336 {
337     /**
338      * Double linked list, FIFO style
339      */
340   struct MeshReliableMessage    *next;
341   struct MeshReliableMessage    *prev;
342
343     /**
344      * Tunnel Reliability queue this message is in.
345      */
346   struct MeshChannelReliability  *rel;
347
348     /**
349      * ID of the message (ACK needed to free)
350      */
351   uint32_t                      mid;
352
353     /**
354      * When was this message issued (to calculate ACK delay)
355      */
356   struct GNUNET_TIME_Absolute   timestamp;
357
358   /* struct GNUNET_MESH_Data with payload */
359 };
360
361
362 struct MeshChannelReliability
363 {
364     /**
365      * Channel this is about.
366      */
367   struct MeshChannel *ch;
368
369     /**
370      * DLL of messages sent and not yet ACK'd.
371      */
372   struct MeshReliableMessage        *head_sent;
373   struct MeshReliableMessage        *tail_sent;
374
375     /**
376      * Messages pending
377      */
378   unsigned int                      n_sent;
379
380     /**
381      * Next MID to use.
382      */
383   uint32_t                          mid_sent;
384
385     /**
386      * DLL of messages received out of order.
387      */
388   struct MeshReliableMessage        *head_recv;
389   struct MeshReliableMessage        *tail_recv;
390
391     /**
392      * Next MID expected.
393      */
394   uint32_t                          mid_recv;
395
396     /**
397      * Task to resend/poll in case no ACK is received.
398      */
399   GNUNET_SCHEDULER_TaskIdentifier   retry_task;
400
401     /**
402      * Counter for exponential backoff.
403      */
404   struct GNUNET_TIME_Relative       retry_timer;
405
406     /**
407      * How long does it usually take to get an ACK.
408      */
409   struct GNUNET_TIME_Relative       expected_delay;
410 };
411
412
413 /**
414  * Struct containing all information regarding a channel to a remote client.
415  */
416 struct MeshChannel
417 {
418     /**
419      * Tunnel this channel is in.
420      */
421   struct MeshTunnel2 *t;
422
423     /**
424      * Double linked list.
425      */
426   struct MeshChannel    *next;
427   struct MeshChannel    *prev;
428
429     /**
430      * Destination port of the channel.
431      */
432   uint32_t port;
433
434     /**
435      * Local tunnel number ( >= GNUNET_MESH_LOCAL_CHANNEL_ID_CLI or 0 )
436      */
437   MESH_ChannelNumber id;
438
439     /**
440      * Local tunnel number for local destination clients (incoming number)
441      * ( >= GNUNET_MESH_LOCAL_CHANNEL_ID_SERV or 0). All clients share the same
442      * number.
443      */
444   MESH_ChannelNumber id_dest;
445
446     /**
447      * Is the tunnel bufferless (minimum latency)?
448      */
449   int nobuffer;
450
451     /**
452      * Is the tunnel reliable?
453      */
454   int reliable;
455
456     /**
457      * Last time the channel was used
458      */
459   struct GNUNET_TIME_Absolute timestamp;
460
461     /**
462      * Client owner of the tunnel, if any
463      */
464   struct MeshClient *owner;
465
466     /**
467      * Client destination of the tunnel, if any.
468      */
469   struct MeshClient *client;
470
471     /**
472      * Flag to signal the destruction of the channel.
473      * If this is set GNUNET_YES the channel will be destroyed
474      * when the queue is empty.
475      */
476   int destroy;
477
478     /**
479      * Total messages pending for this channel, payload or not.
480      */
481   unsigned int pending_messages;
482
483     /**
484      * Reliability data.
485      * Only present (non-NULL) at the owner of a tunnel.
486      */
487   struct MeshChannelReliability *fwd_rel;
488
489     /**
490      * Reliability data.
491      * Only present (non-NULL) at the destination of a tunnel.
492      */
493   struct MeshChannelReliability *bck_rel;
494 };
495
496
497 struct MeshConnection
498 {
499   /**
500    * DLL
501    */
502   struct MeshConnection *next;
503   struct MeshConnection *prev;
504
505   /**
506    * Tunnel this connection is part of.
507    */
508   struct MeshTunnel2 *t;
509
510   /**
511    * Connection number.
512    */
513   uint32_t id;
514
515   /**
516    * State of the connection.
517    */
518   enum MeshConnectionState state;
519
520   /**
521    * Path being used for the tunnel.
522    */
523   struct MeshPeerPath *path;
524
525   /**
526    * Position of the local peer in the path.
527    */
528   unsigned int own_pos;
529
530   /**
531    * Task to keep the used paths alive at the owner,
532    * time tunnel out on all the other peers.
533    */
534   GNUNET_SCHEDULER_TaskIdentifier fwd_maintenance_task;
535
536   /**
537    * Task to keep the used paths alive at the destination,
538    * time tunnel out on all the other peers.
539    */
540   GNUNET_SCHEDULER_TaskIdentifier bck_maintenance_task;
541
542   /**
543    * Pending message count.
544    */
545   int pending_messages;
546
547   /**
548    * Destroy flag: if true, destroy on last message.
549    */
550   int destroy;
551 };
552
553
554 /**
555  * Struct containing all information regarding a tunnel to a peer.
556  */
557 struct MeshTunnel2
558 {
559     /**
560      * Endpoint of the tunnel.
561      */
562   struct MeshPeer *peer;
563
564     /**
565      * ID of the tunnel.
566      */
567   struct GNUNET_HashCode id;
568
569     /**
570      * State of the tunnel.
571      */
572   enum MeshTunnelState state;
573
574   /**
575    * Local peer ephemeral private key
576    */
577   struct GNUNET_CRYPTO_EccPrivateKey *my_eph_key;
578
579   /**
580    * Local peer ephemeral public key
581    */
582   struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded *my_eph;
583
584   /**
585    * Remote peer's public key.
586    */
587   struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded *peers_eph;
588
589   /**
590    * Encryption ("our") key.
591    */
592   struct GNUNET_CRYPTO_AesSessionKey e_key;
593
594   /**
595    * Decryption ("their") key.
596    */
597   struct GNUNET_CRYPTO_AesSessionKey d_key;
598
599   /**
600    * Paths that are actively used to reach the destination peer.
601    */
602   struct MeshConnection *connection_head;
603   struct MeshConnection *connection_tail;
604
605   /**
606    * Next connection number.
607    */
608   uint32_t next_cid;
609
610   /**
611    * Channels inside this tunnel.
612    */
613   struct MeshChannel *channel_head;
614   struct MeshChannel *channel_tail;
615
616   /**
617    * Channel ID for the next created tunnel.
618    */
619   MESH_ChannelNumber next_chid;
620
621   /**
622    * Channel ID for the next incoming tunnel.
623    */
624   MESH_ChannelNumber next_local_chid;
625
626   /**
627    * Pending message count.
628    */
629   int pending_messages;
630
631   /**
632    * Destroy flag: if true, destroy on last message.
633    */
634   int destroy;
635 };
636
637
638
639 /**
640  * Struct containing information about a client of the service
641  * 
642  * TODO: add a list of 'waiting' ports
643  */
644 struct MeshClient
645 {
646     /**
647      * Linked list next
648      */
649   struct MeshClient *next;
650
651     /**
652      * Linked list prev
653      */
654   struct MeshClient *prev;
655
656     /**
657      * Tunnels that belong to this client, indexed by local id
658      */
659   struct GNUNET_CONTAINER_MultiHashMap32 *own_channels;
660
661    /**
662      * Tunnels this client has accepted, indexed by incoming local id
663      */
664   struct GNUNET_CONTAINER_MultiHashMap32 *incoming_channels;
665
666     /**
667      * Handle to communicate with the client
668      */
669   struct GNUNET_SERVER_Client *handle;
670
671     /**
672      * Ports that this client has declared interest in.
673      * Indexed by port, contains *Client.
674      */
675   struct GNUNET_CONTAINER_MultiHashMap32 *ports;
676
677     /**
678      * Whether the client is active or shutting down (don't send confirmations
679      * to a client that is shutting down.
680      */
681   int shutting_down;
682
683     /**
684      * ID of the client, mainly for debug messages
685      */
686   unsigned int id;
687 };
688
689
690 /******************************************************************************/
691 /************************      DEBUG FUNCTIONS     ****************************/
692 /******************************************************************************/
693
694 #if MESH_DEBUG
695 /**
696  * GNUNET_SCHEDULER_Task for printing a message after some operation is done
697  * @param cls string to print
698  * @param success  GNUNET_OK if the PUT was transmitted,
699  *                GNUNET_NO on timeout,
700  *                GNUNET_SYSERR on disconnect from service
701  *                after the PUT message was transmitted
702  *                (so we don't know if it was received or not)
703  */
704
705 #if 0
706 static void
707 mesh_debug (void *cls, int success)
708 {
709   char *s = cls;
710
711   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "%s (%d)\n", s, success);
712 }
713 #endif
714
715 #endif
716
717 /******************************************************************************/
718 /***********************      GLOBAL VARIABLES     ****************************/
719 /******************************************************************************/
720
721 /************************** Configuration parameters **************************/
722
723 /**
724  * How often to send path keepalives. Paths timeout after 4 missed.
725  */
726 static struct GNUNET_TIME_Relative refresh_connection_time;
727
728 /**
729  * How often to PUT own ID in the DHT.
730  */
731 static struct GNUNET_TIME_Relative id_announce_time;
732
733 /**
734  * Maximum time allowed to connect to a peer found by string.
735  */
736 static struct GNUNET_TIME_Relative connect_timeout;
737
738 /**
739  * Default TTL for payload packets.
740  */
741 static unsigned long long default_ttl;
742
743 /**
744  * DHT replication level, see DHT API: GNUNET_DHT_get_start, GNUNET_DHT_put.
745  */
746 static unsigned long long dht_replication_level;
747
748 /**
749  * How many tunnels are we willing to maintain.
750  * Local tunnels are always allowed, even if there are more tunnels than max.
751  */
752 static unsigned long long max_tunnels;
753
754 /**
755  * How many messages *in total* are we willing to queue, divided by number of 
756  * tunnels to get tunnel queue size.
757  */
758 static unsigned long long max_msgs_queue;
759
760 /**
761  * How many peers do we want to remember?
762  */
763 static unsigned long long max_peers;
764
765 /**
766  * Percentage of messages that will be dropped (for test purposes only).
767  */
768 static unsigned long long drop_percent;
769
770 /*************************** Static global variables **************************/
771
772 /**
773  * DLL with all the clients, head.
774  */
775 static struct MeshClient *clients_head;
776
777 /**
778  * DLL with all the clients, tail.
779  */
780 static struct MeshClient *clients_tail;
781
782 /**
783  * Tunnels known, indexed by MESH_TunnelID (MeshTunnel).
784  */
785 static struct GNUNET_CONTAINER_MultiHashMap *tunnels;
786
787 /**
788  * Peers known, indexed by PeerIdentity (MeshPeer).
789  */
790 static struct GNUNET_CONTAINER_MultiHashMap *peers;
791
792 /**
793  * Handle to communicate with core.
794  */
795 static struct GNUNET_CORE_Handle *core_handle;
796
797 /**
798  * Handle to use DHT.
799  */
800 static struct GNUNET_DHT_Handle *dht_handle;
801
802 /**
803  * Handle to server lib.
804  */
805 static struct GNUNET_SERVER_Handle *server_handle;
806
807 /**
808  * Handle to the statistics service.
809  */
810 static struct GNUNET_STATISTICS_Handle *stats;
811
812 /**
813  * Notification context, to send messages to local clients.
814  */
815 static struct GNUNET_SERVER_NotificationContext *nc;
816
817 /**
818  * Local peer own ID (memory efficient handle).
819  */
820 static GNUNET_PEER_Id myid;
821
822 /**
823  * Local peer own ID (full value).
824  */
825 static struct GNUNET_PeerIdentity my_full_id;
826
827 /**
828  * Own private key.
829  */
830 static struct GNUNET_CRYPTO_EccPrivateKey *my_private_key;
831
832 /**
833  * Own public key.
834  */
835 static struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded my_public_key;
836
837 /**
838  * All ports clients of this peer have opened.
839  */
840 static struct GNUNET_CONTAINER_MultiHashMap32 *ports;
841
842 /**
843  * Task to periodically announce itself in the network.
844  */
845 GNUNET_SCHEDULER_TaskIdentifier announce_id_task;
846
847 /**
848  * Next ID to assign to a client.
849  */
850 unsigned int next_client_id;
851
852
853 /******************************************************************************/
854 /***********************         DECLARATIONS        **************************/
855 /******************************************************************************/
856
857 /**
858  * Function to process paths received for a new peer addition. The recorded
859  * paths form the initial tunnel, which can be optimized later.
860  * Called on each result obtained for the DHT search.
861  *
862  * @param cls closure
863  * @param exp when will this value expire
864  * @param key key of the result
865  * @param type type of the result
866  * @param size number of bytes in data
867  * @param data pointer to the result data
868  */
869 static void
870 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
871                     const struct GNUNET_HashCode * key,
872                     const struct GNUNET_PeerIdentity *get_path,
873                     unsigned int get_path_length,
874                     const struct GNUNET_PeerIdentity *put_path,
875                     unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
876                     size_t size, const void *data);
877
878
879 /**
880  * Retrieve the MeshPeer stucture associated with the peer, create one
881  * and insert it in the appropriate structures if the peer is not known yet.
882  *
883  * @param peer Full identity of the peer.
884  *
885  * @return Existing or newly created peer info.
886  */
887 static struct MeshPeer *
888 peer_get (const struct GNUNET_PeerIdentity *peer);
889
890
891 /**
892  * Retrieve the MeshPeer stucture associated with the peer, create one
893  * and insert it in the appropriate structures if the peer is not known yet.
894  *
895  * @param peer Short identity of the peer.
896  *
897  * @return Existing or newly created peer info.
898  */
899 static struct MeshPeer *
900 peer_get_short (const GNUNET_PEER_Id peer);
901
902
903 /**
904  * Build a PeerPath from the paths returned from the DHT, reversing the paths
905  * to obtain a local peer -> destination path and interning the peer ids.
906  *
907  * @return Newly allocated and created path
908  */
909 static struct MeshPeerPath *
910 path_build_from_dht (const struct GNUNET_PeerIdentity *get_path,
911                      unsigned int get_path_length,
912                      const struct GNUNET_PeerIdentity *put_path,
913                      unsigned int put_path_length);
914
915
916 /**
917  * Adds a path to the data structs of all the peers in the path
918  *
919  * @param p Path to process.
920  * @param confirmed Whether we know if the path works or not.
921  */
922 static void
923 path_add_to_peers (struct MeshPeerPath *p, int confirmed);
924
925
926 /**
927  * Search for a channel by global ID using full PeerIdentities.
928  *
929  * @param oid owner of the tunnel.
930  * @param tid global tunnel number.
931  *
932  * @return tunnel handler, NULL if doesn't exist.
933  */
934 static struct MeshChannel *
935 channel_get (const struct GNUNET_PeerIdentity *oid, MESH_ChannelNumber tid);
936
937
938 /**
939  * Change the tunnel state.
940  *
941  * @param t Tunnel whose state to change.
942  * @param state New state.
943  */
944 static void
945 tunnel_change_state (struct MeshTunnel2 *t, enum MeshTunnelState state);
946
947
948 /**
949  * Notify a tunnel that a connection has broken that affects at least
950  * some of its peers.
951  *
952  * @param t Tunnel affected.
953  * @param p1 Peer that got disconnected from p2.
954  * @param p2 Peer that got disconnected from p1.
955  *
956  * @return Short ID of the peer disconnected (either p1 or p2).
957  *         0 if the tunnel remained unaffected.
958  */
959 static GNUNET_PEER_Id
960 tunnel_notify_connection_broken (struct MeshTunnel2 *t,
961                                  GNUNET_PEER_Id p1, GNUNET_PEER_Id p2);
962
963 /**
964  * @brief Use the given path for the tunnel.
965  * Update the next and prev hops (and RCs).
966  * (Re)start the path refresh in case the tunnel is locally owned.
967  * 
968  * @param t Tunnel to update.
969  * @param p Path to use.
970  *
971  * @return Connection created.
972  */
973 static struct MeshConnection *
974 tunnel_use_path (struct MeshTunnel2 *t, struct MeshPeerPath *p);
975
976 /**
977  * Tunnel is empty: destroy it.
978  * 
979  * Notifies all participants (peers, cleints) about the destruction.
980  * 
981  * @param t Tunnel to destroy. 
982  */
983 static void
984 tunnel_destroy_empty (struct MeshTunnel2 *t);
985
986 /**
987  * Destroy the tunnel.
988  *
989  * This function does not generate any warning traffic to clients or peers.
990  *
991  * Tasks:
992  * Cancel messages belonging to this tunnel queued to neighbors.
993  * Free any allocated resources linked to the tunnel.
994  *
995  * @param t The tunnel to destroy.
996  */
997 static void
998 tunnel_destroy (struct MeshTunnel2 *t);
999
1000 /**
1001  * Send FWD keepalive packets for a connection.
1002  *
1003  * @param cls Closure (connection for which to send the keepalive).
1004  * @param tc Notification context.
1005  */
1006 static void
1007 connection_fwd_keepalive (void *cls,
1008                           const struct GNUNET_SCHEDULER_TaskContext *tc);
1009
1010 /**
1011  * Send BCK keepalive packets for a connection.
1012  *
1013  * @param cls Closure (connection for which to send the keepalive).
1014  * @param tc Notification context.
1015  */
1016 static void
1017 connection_bck_keepalive (void *cls,
1018                           const struct GNUNET_SCHEDULER_TaskContext *tc);
1019
1020
1021 /**
1022  * Change the tunnel state.
1023  *
1024  * @param c Connection whose state to change.
1025  * @param state New state.
1026  */
1027 static void
1028 connection_change_state (struct MeshConnection* c,
1029                          enum MeshConnectionState state);
1030
1031
1032
1033 /**
1034  * @brief Queue and pass message to core when possible.
1035  *
1036  * @param cls Closure (@c type dependant). It will be used by queue_send to
1037  *            build the message to be sent if not already prebuilt.
1038  * @param type Type of the message, 0 for a raw message.
1039  * @param size Size of the message.
1040  * @param dst Neighbor to send message to.
1041  * @param c Connection this message belongs to, if any.
1042  * @param ch Channel this message belongs to, if applicable (otherwise NULL).
1043  */
1044 static void
1045 queue_add (void *cls, uint16_t type, size_t size,
1046            struct MeshPeer *dst,
1047            struct MeshConnection *c,
1048            struct MeshChannel *ch);
1049
1050
1051 /**
1052  * Free a transmission that was already queued with all resources
1053  * associated to the request.
1054  *
1055  * @param queue Queue handler to cancel.
1056  * @param clear_cls Is it necessary to free associated cls?
1057  */
1058 static void
1059 queue_destroy (struct MeshPeerQueue *queue, int clear_cls);
1060
1061
1062 /**
1063  * @brief Get the next transmittable message from the queue.
1064  *
1065  * This will be the head, except in the case of being a data packet
1066  * not allowed by the destination peer.
1067  *
1068  * @param peer Destination peer.
1069  *
1070  * @return The next viable MeshPeerQueue element to send to that peer.
1071  *         NULL when there are no transmittable messages.
1072  */
1073 struct MeshPeerQueue *
1074 queue_get_next (const struct MeshPeer *peer);
1075
1076
1077 /**
1078  * Core callback to write a queued packet to core buffer
1079  *
1080  * @param cls Closure (peer info).
1081  * @param size Number of bytes available in buf.
1082  * @param buf Where the to write the message.
1083  *
1084  * @return number of bytes written to buf
1085  */
1086 static size_t
1087 queue_send (void *cls, size_t size, void *buf);
1088
1089
1090 /**
1091  * Dummy function to separate declarations from definitions in function list.
1092  */
1093 void
1094 __mesh_divider______________________________________________________________();
1095
1096
1097 /**
1098  * Get string description for tunnel state.
1099  *
1100  * @param s Tunnel state.
1101  *
1102  * @return String representation. 
1103  */
1104 static const char *
1105 GNUNET_MESH_DEBUG_TS2S (enum MeshTunnelState s)
1106 {
1107   static char buf[128];
1108
1109   switch (s)
1110   {
1111     case MESH_TUNNEL_NEW:
1112       return "MESH_TUNNEL_NEW";
1113     case MESH_TUNNEL_SEARCHING:
1114       return "MESH_TUNNEL_SEARCHING";
1115     case MESH_TUNNEL_WAITING:
1116       return "MESH_TUNNEL_WAITING";
1117     case MESH_TUNNEL_READY:
1118       return "MESH_TUNNEL_READY";
1119     case MESH_TUNNEL_RECONNECTING:
1120       return "MESH_TUNNEL_RECONNECTING";
1121
1122     default:
1123       sprintf (buf, "%u (UNKNOWN STATE)", s);
1124       return buf;
1125   }
1126 }
1127
1128
1129 /**
1130  * Get string description for tunnel state.
1131  *
1132  * @param s Tunnel state.
1133  *
1134  * @return String representation. 
1135  */
1136 static const char *
1137 GNUNET_MESH_DEBUG_CS2S (enum MeshTunnelState s)
1138 {
1139   switch (s) 
1140   {
1141     case MESH_CONNECTION_NEW:
1142       return "MESH_CONNECTION_NEW";
1143     case MESH_CONNECTION_SENT:
1144       return "MESH_CONNECTION_SENT";
1145     case MESH_CONNECTION_READY:
1146       return "MESH_CONNECTION_READY";
1147     default:
1148       return "MESH_CONNECTION_STATE_ERROR";
1149   }
1150 }
1151
1152
1153
1154 /******************************************************************************/
1155 /************************    PERIODIC FUNCTIONS    ****************************/
1156 /******************************************************************************/
1157
1158 /**
1159  * Periodically announce self id in the DHT
1160  *
1161  * @param cls closure
1162  * @param tc task context
1163  */
1164 static void
1165 announce_id (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1166 {
1167   struct PBlock block;
1168
1169   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1170   {
1171     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
1172     return;
1173   }
1174   /* TODO
1175    * - Set data expiration in function of X
1176    * - Adapt X to churn
1177    */
1178   DEBUG_DHT ("DHT_put for ID %s started.\n", GNUNET_i2s (&my_full_id));
1179
1180   block.id = my_full_id;
1181   GNUNET_DHT_put (dht_handle,   /* DHT handle */
1182                   &my_full_id.hashPubKey,       /* Key to use */
1183                   dht_replication_level,     /* Replication level */
1184                   GNUNET_DHT_RO_RECORD_ROUTE | GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,    /* DHT options */
1185                   GNUNET_BLOCK_TYPE_MESH_PEER,       /* Block type */
1186                   sizeof (block),  /* Size of the data */
1187                   (const char *) &block, /* Data itself */
1188                   GNUNET_TIME_UNIT_FOREVER_ABS,  /* Data expiration */
1189                   GNUNET_TIME_UNIT_FOREVER_REL, /* Retry time */
1190                   NULL,         /* Continuation */
1191                   NULL);        /* Continuation closure */
1192   announce_id_task =
1193       GNUNET_SCHEDULER_add_delayed (id_announce_time, &announce_id, cls);
1194 }
1195
1196
1197 /******************************************************************************/
1198 /******************      GENERAL HELPER FUNCTIONS      ************************/
1199 /******************************************************************************/
1200
1201
1202 /**
1203  * Get the previous hop in a connection
1204  *
1205  * @param c Connection.
1206  *
1207  * @return Previous peer in the connection.
1208  */
1209 static struct MeshPeer *
1210 connection_get_prev_hop (struct MeshConnection *c)
1211 {
1212   GNUNET_PEER_Id id;
1213
1214   if (0 == c->own_pos || c->path->length < 2)
1215     id = c->path->peers[0];
1216   else
1217     id = c->path->peers[c->own_pos - 1];
1218
1219   return peer_get_short (id);
1220 }
1221
1222
1223 /**
1224  * Get the next hop in a connection
1225  *
1226  * @param c Connection.
1227  *
1228  * @return Next peer in the connection. 
1229  */
1230 static struct MeshPeer *
1231 connection_get_next_hop (struct MeshConnection *c)
1232 {
1233   GNUNET_PEER_Id id;
1234
1235   if ((c->path->length - 1) == c->own_pos || c->path->length < 2)
1236     id = c->path->peers[c->path->length - 1];
1237   else
1238     id = c->path->peers[c->own_pos + 1];
1239
1240   return peer_get_short (id);
1241 }
1242
1243
1244 /**
1245  * Check if client has registered with the service and has not disconnected
1246  *
1247  * @param client the client to check
1248  *
1249  * @return non-NULL if client exists in the global DLL
1250  */
1251 static struct MeshClient *
1252 client_get (struct GNUNET_SERVER_Client *client)
1253 {
1254   return GNUNET_SERVER_client_get_user_context (client, struct MeshClient);
1255 }
1256
1257
1258 /**
1259  * Deletes a tunnel from a client (either owner or destination). To be used on
1260  * tunnel destroy.
1261  *
1262  * @param c Client whose tunnel to delete.
1263  * @param ch Channel which should be deleted.
1264  */
1265 static void
1266 client_delete_channel (struct MeshClient *c, struct MeshChannel *ch)
1267 {
1268   int res;
1269
1270   if (c == ch->owner)
1271   {
1272     res = GNUNET_CONTAINER_multihashmap32_remove (c->own_channels,
1273                                                   ch->id, ch);
1274     if (GNUNET_YES != res)
1275       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client_delete_channel owner KO\n");
1276   }
1277   if (c == ch->client)
1278   {
1279     res = GNUNET_CONTAINER_multihashmap32_remove (c->incoming_channels,
1280                                                   ch->id_dest, ch);
1281     if (GNUNET_YES != res)
1282       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client_delete_tunnel client KO\n");
1283   }
1284 }
1285
1286
1287 /**
1288  * Notify the appropriate client that a new incoming channel was created.
1289  *
1290  * @param ch Channel that was created.
1291  */
1292 static void
1293 send_local_channel_create (struct MeshChannel *ch)
1294 {
1295   struct GNUNET_MESH_ChannelMessage msg;
1296   struct MeshTunnel2 *t = ch->t;
1297
1298   if (NULL == ch->client)
1299     return;
1300   msg.header.size = htons (sizeof (msg));
1301   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE);
1302   msg.channel_id = htonl (ch->id_dest);
1303   msg.port = htonl (ch->port);
1304   msg.opt = 0;
1305   msg.opt |= GNUNET_YES == ch->reliable ? GNUNET_MESH_OPTION_RELIABLE : 0;
1306   msg.opt |= GNUNET_YES == ch->nobuffer ? GNUNET_MESH_OPTION_NOBUFFER : 0;
1307   msg.opt = htonl (msg.opt);
1308   GNUNET_PEER_resolve (t->peer->id, &msg.peer);
1309   GNUNET_SERVER_notification_context_unicast (nc, ch->client->handle,
1310                                               &msg.header, GNUNET_NO);
1311 }
1312
1313
1314 /**
1315  * Notify a client that the incoming tunnel is no longer valid.
1316  *
1317  * @param ch Channel that is destroyed.
1318  * @param fwd Forward notification (owner->dest)?
1319  */
1320 static void
1321 send_local_channel_destroy (struct MeshChannel *ch, int fwd)
1322 {
1323   struct GNUNET_MESH_ChannelMessage msg;
1324   struct MeshClient *c;
1325
1326   c = fwd ? ch->client : ch->owner;
1327   if (NULL == c)
1328   {
1329     GNUNET_break (0);
1330     return;
1331   }
1332   msg.header.size = htons (sizeof (msg));
1333   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY);
1334   msg.channel_id = htonl (fwd ? ch->id_dest : ch->id);
1335   msg.port = htonl (0);
1336   memset (&msg.peer, 0, sizeof (msg.peer));
1337   msg.opt = htonl (0);
1338   GNUNET_SERVER_notification_context_unicast (nc, c->handle,
1339                                               &msg.header, GNUNET_NO);
1340 }
1341
1342
1343 /**
1344  * Build a local ACK message and send it to a local client.
1345  * 
1346  * @param ch Channel on which to send the ACK.
1347  * @param c Client to whom send the ACK.
1348  * @param is_fwd Set to GNUNET_YES for FWD ACK (dest->owner)
1349  */
1350 static void
1351 send_local_ack (struct MeshChannel *ch,
1352                 struct MeshClient *c,
1353                 int is_fwd)
1354 {
1355   struct GNUNET_MESH_LocalAck msg;
1356
1357   msg.header.size = htons (sizeof (msg));
1358   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
1359   msg.channel_id = htonl (is_fwd ? ch->id : ch->id_dest);
1360   GNUNET_SERVER_notification_context_unicast (nc,
1361                                               c->handle,
1362                                               &msg.header,
1363                                               GNUNET_NO);
1364 }
1365
1366
1367 /**
1368  * Pick a connection on which send the next data message.
1369  *
1370  * @param t Tunnel on which to send the message.
1371  * @param fwd Is this a fwd message?
1372  *
1373  * @return The connection on which to send the next message.
1374  */
1375 static struct MeshConnection *
1376 tunnel_get_connection (struct MeshTunnel2 *t, int fwd)
1377 {
1378   struct MeshConnection *c;
1379   struct MeshConnection *best;
1380   struct MeshPeer *peer;
1381   unsigned int lowest_q;
1382
1383
1384   peer = NULL;
1385   best = NULL;
1386   lowest_q = UINT_MAX;
1387   for (c = t->connection_head; NULL != c; c = c->next)
1388   {
1389     if (MESH_CONNECTION_READY == c->state)
1390     {
1391       peer = fwd ? connection_get_next_hop (c) : connection_get_prev_hop (c);
1392       if (NULL == peer->fc)
1393       {
1394         GNUNET_break (0);
1395         continue;
1396       }
1397       if (peer->fc->queue_n < lowest_q)
1398       {
1399         best = c;
1400         lowest_q = peer->fc->queue_n;
1401       }
1402     }
1403   }
1404   return best;
1405 }
1406
1407
1408 /**
1409  * FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME 
1410  * Encrypt data with the tunnel key.
1411  *
1412  * @param t Tunnel whose key to use.
1413  * @param dst Destination for the encrypted data.
1414  * @param src Source of the plaintext.
1415  * @param size Size of the plaintext.
1416  * @param iv Initialization Vector to use.
1417  * @param fwd Is this a fwd message?
1418  */
1419 static void
1420 tunnel_encrypt (struct MeshTunnel2 *t,
1421                 void *dst, const void *src,
1422                 size_t size, uint64_t iv, int fwd)
1423 {
1424   memcpy (dst, src, size);
1425 }
1426
1427
1428 /**
1429  * FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME 
1430  * Decrypt data with the tunnel key.
1431  *
1432  * @param t Tunnel whose key to use.
1433  * @param dst Destination for the plaintext.
1434  * @param src Source of the encrypted data.
1435  * @param size Size of the encrypted data.
1436  * @param iv Initialization Vector to use.
1437  * @param fwd Is this a fwd message?
1438  */
1439 static void
1440 tunnel_decrypt (struct MeshTunnel2 *t,
1441                 void *dst, const void *src,
1442                 size_t size, uint64_t iv, int fwd)
1443 {
1444   memcpy (dst, src, size);
1445 }
1446
1447
1448 /**
1449  * Sends an already built message on a connection, properly registering
1450  * all used resources.
1451  *
1452  * @param message Message to send. Function makes a copy of it.
1453  *                If message is not hop-by-hop, decrements TTL of copy.
1454  * @param c Connection on which this message is transmitted.
1455  * @param ch Channel on which this message is transmitted, or NULL.
1456  * @param fwd Is this a fwd message?
1457  */
1458 static void
1459 send_prebuilt_message_connection (const struct GNUNET_MessageHeader *message,
1460                                   struct MeshConnection *c,
1461                                   struct MeshChannel *ch,
1462                                   int fwd)
1463 {
1464   struct MeshPeer *neighbor;
1465   void *data;
1466   size_t size;
1467   uint16_t type;
1468
1469   neighbor = fwd ? connection_get_next_hop (c) : connection_get_prev_hop (c);
1470   if (NULL == neighbor)
1471   {
1472     GNUNET_break (0);
1473     return;
1474   }
1475
1476   size = ntohs (message->size);
1477   data = GNUNET_malloc (size);
1478   memcpy (data, message, size);
1479   type = ntohs(message->type);
1480
1481   if (GNUNET_MESSAGE_TYPE_MESH_FWD == type ||
1482       GNUNET_MESSAGE_TYPE_MESH_BCK == type)
1483   {
1484     struct GNUNET_MESH_Encrypted *msg;
1485     uint32_t ttl;
1486
1487     msg = (struct GNUNET_MESH_Encrypted *) data;
1488     ttl = ntohl (msg->ttl);
1489     if (0 == ttl)
1490     {
1491       GNUNET_break_op (0);
1492       return;
1493     }
1494     msg->ttl = htonl (ttl - 1);
1495   }
1496
1497   queue_add (data,
1498              type,
1499              size,
1500              neighbor,
1501              c,
1502              ch);
1503 }
1504
1505
1506 /**
1507  * Sends an already built message on a tunnel, choosing the best connection.
1508  *
1509  * @param message Message to send. Function modifies it.
1510  * @param t Tunnel on which this message is transmitted.
1511  * @param ch Channel on which this message is transmitted.
1512  * @param fwd Is this a fwd message?
1513  */
1514 static void
1515 send_prebuilt_message_tunnel (struct GNUNET_MESH_Encrypted *msg,
1516                               struct MeshTunnel2 *t,
1517                               struct MeshChannel *ch,
1518                               int fwd)
1519 {
1520   struct MeshConnection *c;
1521   uint16_t type;
1522
1523   c = tunnel_get_connection (t, fwd);
1524   if (NULL == c)
1525   {
1526     GNUNET_break (0);
1527     return;
1528   }
1529   type = ntohs (msg->header.size);
1530   switch (type)
1531   {
1532     case GNUNET_MESSAGE_TYPE_MESH_FWD:
1533     case GNUNET_MESSAGE_TYPE_MESH_BCK:
1534       msg->cid = htonl (c->id);
1535       msg->tid = t->id;
1536       msg->ttl = default_ttl;
1537       break;
1538     default:
1539       GNUNET_break (0);
1540   }
1541
1542   send_prebuilt_message_connection (&msg->header, c, ch, fwd);
1543 }
1544
1545
1546 /**
1547  * Sends an already built message on a channel, properly registering
1548  * all used resources and encrypting the message with the tunnel's key.
1549  *
1550  * @param message Message to send. Function makes a copy of it.
1551  * @param ch Channel on which this message is transmitted.
1552  * @param fwd Is this a fwd message?
1553  */
1554 static void
1555 send_prebuilt_message_channel (const struct GNUNET_MessageHeader *message,
1556                                struct MeshChannel *ch,
1557                                int fwd)
1558 {
1559   struct GNUNET_MESH_Encrypted *msg;
1560   size_t size = ntohs (message->size);
1561   char *cbuf[size + sizeof (struct GNUNET_MESH_Encrypted)];
1562   uint16_t type;
1563   uint64_t iv;
1564
1565   type = fwd ? GNUNET_MESSAGE_TYPE_MESH_FWD : GNUNET_MESSAGE_TYPE_MESH_BCK;
1566   iv = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX);
1567
1568   msg = (struct GNUNET_MESH_Encrypted *) cbuf;
1569   msg->header.type = htons (type);
1570   msg->header.size = htons (size);
1571   msg->iv = GNUNET_htonll (iv);
1572   tunnel_encrypt (ch->t, &msg[1], message, size, iv, fwd);
1573
1574   send_prebuilt_message_tunnel (msg, ch->t, ch, fwd);
1575 }
1576
1577
1578 /**
1579  * Sends an already built message directly to a peer.
1580  * Message does must not belong to a connection or channel.
1581  *
1582  * @param message Message to send. Function makes a copy of it.
1583  * @param peer Tunnel on which this message is transmitted.
1584  */
1585 static void
1586 send_prebuilt_message_peer (const struct GNUNET_MessageHeader *message,
1587                             struct MeshPeer *peer)
1588 {
1589   void *data;
1590   size_t size;
1591   uint16_t type;
1592
1593   if (NULL == peer)
1594   {
1595     GNUNET_break (0);
1596     return;
1597   }
1598
1599   size = ntohs (message->size);
1600   data = GNUNET_malloc (size);
1601   memcpy (data, message, size);
1602   type = ntohs(message->type);
1603
1604   queue_add (data,
1605              type,
1606              size,
1607              peer,
1608              NULL,
1609              NULL);
1610 }
1611
1612
1613 /**
1614  * Sends a CREATE CONNECTION message for a path to a peer.
1615  * Changes the connection and tunnel states if necessary.
1616  *
1617  * @param connection Connection to create.
1618  */
1619 static void
1620 send_connection_create (struct MeshConnection *connection)
1621 {
1622   struct MeshPeer *neighbor;
1623   struct MeshTunnel2 *t;
1624
1625   t = connection->t;
1626   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Send connection create\n");
1627   neighbor = connection_get_next_hop (connection);
1628   queue_add (connection,
1629              GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE,
1630              sizeof (struct GNUNET_MESH_ConnectionCreate) +
1631                 (connection->path->length *
1632                  sizeof (struct GNUNET_PeerIdentity)),
1633              neighbor,
1634              connection,
1635              NULL);
1636   if (MESH_TUNNEL_SEARCHING == t->state)
1637     tunnel_change_state (t, MESH_TUNNEL_WAITING);
1638   if (MESH_CONNECTION_NEW == connection->state)
1639     connection_change_state (connection, MESH_CONNECTION_SENT);
1640 }
1641
1642
1643 /**
1644  * Sends a CONNECTION ACK message in reponse to a received CONNECTION_CREATE
1645  * directed to us.
1646  *
1647  * @param connection Connection to confirm.
1648  */
1649 static void
1650 send_connection_ack (struct MeshConnection *connection) 
1651 {
1652   struct MeshPeer *neighbor;
1653   struct MeshTunnel2 *t;
1654
1655   t = connection->t;
1656   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Send connection ack\n");
1657   neighbor = connection_get_prev_hop (connection);
1658   queue_add (connection,
1659              GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK,
1660              sizeof (struct GNUNET_MESH_ConnectionACK),
1661              neighbor,
1662              connection,
1663              NULL);
1664   if (MESH_TUNNEL_NEW == t->state)
1665     tunnel_change_state (t, MESH_TUNNEL_WAITING);
1666 }
1667
1668
1669 /**
1670  * Build an ACK message and queue it to send to the given peer.
1671  * 
1672  * @param peer Peer to whom send the ACK.
1673  * @param ack Value of the ACK.
1674  */
1675 static void
1676 send_ack (struct MeshPeer *peer, uint32_t ack)
1677 {
1678   struct GNUNET_MESH_ACK msg;
1679
1680   msg.header.size = htons (sizeof (msg));
1681   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_ACK);
1682   msg.ack = htonl (ack);
1683
1684   send_prebuilt_message_peer (&msg.header, peer);
1685 }
1686
1687
1688 /**
1689   * Core callback to write a pre-constructed data packet to core buffer
1690   *
1691   * @param cls Closure (MeshTransmissionDescriptor with data in "data" member).
1692   * @param size Number of bytes available in buf.
1693   * @param buf Where the to write the message.
1694   *
1695   * @return number of bytes written to buf
1696   */
1697 static size_t
1698 send_core_data_raw (void *cls, size_t size, void *buf)
1699 {
1700   struct GNUNET_MessageHeader *msg = cls;
1701   size_t total_size;
1702
1703   GNUNET_assert (NULL != msg);
1704   total_size = ntohs (msg->size);
1705
1706   if (total_size > size)
1707   {
1708     GNUNET_break (0);
1709     return 0;
1710   }
1711   memcpy (buf, msg, total_size);
1712   GNUNET_free (cls);
1713   return total_size;
1714 }
1715
1716
1717 /**
1718  * Function to send a create path packet to a peer.
1719  *
1720  * @param cls closure
1721  * @param size number of bytes available in buf
1722  * @param buf where the callee should write the message
1723  * @return number of bytes written to buf
1724  */
1725 static size_t
1726 send_core_connection_create (void *cls, size_t size, void *buf)
1727 {
1728   struct MeshConnection *c = cls;
1729   struct GNUNET_MESH_ConnectionCreate *msg;
1730   struct GNUNET_PeerIdentity *peer_ptr;
1731   struct MeshPeerPath *p = c->path;
1732   size_t size_needed;
1733   int i;
1734
1735   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending CONNECTION CREATE...\n");
1736   size_needed =
1737       sizeof (struct GNUNET_MESH_ConnectionCreate) +
1738       p->length * sizeof (struct GNUNET_PeerIdentity);
1739
1740   if (size < size_needed || NULL == buf)
1741   {
1742     GNUNET_break (0);
1743     return 0;
1744   }
1745   msg = (struct GNUNET_MESH_ConnectionCreate *) buf;
1746   msg->header.size = htons (size_needed);
1747   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE);
1748   msg->cid = htonl (c->id);
1749
1750   peer_ptr = (struct GNUNET_PeerIdentity *) &msg[1];
1751   for (i = 0; i < p->length; i++)
1752   {
1753     GNUNET_PEER_resolve (p->peers[i], peer_ptr++);
1754   }
1755
1756   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1757               "CONNECTION CREATE (%u bytes long) sent!\n", size_needed);
1758   return size_needed;
1759 }
1760
1761
1762 /**
1763  * Creates a path ack message in buf and frees all unused resources.
1764  *
1765  * @param cls closure (MeshTransmissionDescriptor)
1766  * @param size number of bytes available in buf
1767  * @param buf where the callee should write the message
1768  * @return number of bytes written to buf
1769  */
1770 static size_t
1771 send_core_connection_ack (void *cls, size_t size, void *buf)
1772 {
1773   struct GNUNET_MESH_ConnectionACK *msg = buf;
1774   struct MeshConnection *c = cls;
1775   struct MeshTunnel2 *t = c->t;
1776
1777   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending CONNECTION ACK...\n");
1778   GNUNET_assert (NULL != t);
1779   if (sizeof (struct GNUNET_MESH_ConnectionACK) > size)
1780   {
1781     GNUNET_break (0);
1782     return 0;
1783   }
1784   msg->header.size = htons (sizeof (struct GNUNET_MESH_ConnectionACK));
1785   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK);
1786   GNUNET_CRYPTO_hash_xor (&GNUNET_PEER_resolve2 (t->peer->id)->hashPubKey,
1787                           &my_full_id.hashPubKey,
1788                           &msg->tid);
1789   msg->cid = htonl (c->id);
1790
1791   /* TODO add signature */
1792
1793   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CONNECTION ACK sent!\n");
1794   return sizeof (struct GNUNET_MESH_ConnectionACK);
1795 }
1796
1797
1798 /**
1799  * Iterator over all the peers to remove the oldest not-used entry.
1800  *
1801  * @param cls Closure (unsued).
1802  * @param key ID of the peer.
1803  * @param value Peer_Info of the peer.
1804  *
1805  * FIXME implement
1806  */
1807 static int
1808 peer_timeout (void *cls,
1809               const struct GNUNET_HashCode *key,
1810               void *value)
1811 {
1812   return GNUNET_YES;
1813 }
1814
1815
1816 /**
1817  * Retrieve the MeshPeer stucture associated with the peer, create one
1818  * and insert it in the appropriate structures if the peer is not known yet.
1819  *
1820  * @param peer Full identity of the peer.
1821  *
1822  * @return Existing or newly created peer info.
1823  */
1824 static struct MeshPeer *
1825 peer_get (const struct GNUNET_PeerIdentity *peer_id)
1826 {
1827   struct MeshPeer *peer;
1828
1829   peer = GNUNET_CONTAINER_multihashmap_get (peers, &peer_id->hashPubKey);
1830   if (NULL == peer)
1831   {
1832     peer = GNUNET_new (struct MeshPeer);
1833     if (GNUNET_CONTAINER_multihashmap_size (peers) > max_peers)
1834     {
1835       GNUNET_CONTAINER_multihashmap_iterate (peers,
1836                                              &peer_timeout,
1837                                              NULL);
1838     }
1839     GNUNET_CONTAINER_multihashmap_put (peers, &peer_id->hashPubKey, peer,
1840                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
1841     peer->id = GNUNET_PEER_intern (peer_id);
1842   }
1843   peer->last_contact = GNUNET_TIME_absolute_get();
1844
1845   return peer;
1846 }
1847
1848
1849 /**
1850  * Retrieve the MeshPeer stucture associated with the peer, create one
1851  * and insert it in the appropriate structures if the peer is not known yet.
1852  *
1853  * @param peer Short identity of the peer.
1854  *
1855  * @return Existing or newly created peer info.
1856  */
1857 static struct MeshPeer *
1858 peer_get_short (const GNUNET_PEER_Id peer)
1859 {
1860   return peer_get (GNUNET_PEER_resolve2 (peer));
1861 }
1862
1863
1864 /**
1865  * Get a cost of a path for a peer considering existing tunnel connections.
1866  *
1867  * @param peer Peer towards which the path is considered.
1868  * @param path Candidate path.
1869  *
1870  * @return Cost of the path (path length + number of overlapping nodes)
1871  */
1872 static unsigned int
1873 peer_get_path_cost (const struct MeshPeer *peer,
1874                     const struct MeshPeerPath *path)
1875 {
1876   struct MeshConnection *c;
1877   unsigned int overlap;
1878   unsigned int i;
1879   unsigned int j;
1880
1881   if (NULL == path)
1882     return 0;
1883
1884   overlap = 0;
1885   GNUNET_assert (NULL != peer->tunnel);
1886
1887   for (i = 0; i < path->length; i++)
1888   {
1889     for (c = peer->tunnel->connection_head; NULL != c; c = c->next)
1890     {
1891       for (j = 0; j < c->path->length; j++)
1892       {
1893         if (path->peers[i] == c->path->peers[j])
1894         {
1895           overlap++;
1896           break;
1897         }
1898       }
1899     }
1900   }
1901   return (path->length + overlap) * (path->score * -1);
1902 }
1903
1904
1905 /**
1906  * Choose the best path towards a peer considering the tunnel properties.
1907  *
1908  * @param peer The destination peer.
1909  *
1910  * @return Best current known path towards the peer, if any.
1911  */
1912 static struct MeshPeerPath *
1913 peer_get_best_path (const struct MeshPeer *peer)
1914 {
1915   struct MeshPeerPath *best_p;
1916   struct MeshPeerPath *p;
1917   struct MeshConnection *c;
1918   unsigned int best_cost;
1919   unsigned int cost;
1920
1921   best_cost = UINT_MAX;
1922   best_p = NULL;
1923   for (p = peer->path_head; NULL != p; p = p->next)
1924   {
1925     for (c = peer->tunnel->connection_head; NULL != c; c = c->next)
1926       if (c->path == p)
1927         break;
1928     if (NULL != p)
1929       continue; /* If path is in use in a connection, skip it. */
1930
1931     if ((cost = peer_get_path_cost (peer, p)) < best_cost)
1932     {
1933       best_cost = cost;
1934       best_p = p;
1935     }
1936   }
1937   return best_p;
1938 }
1939
1940
1941 /**
1942  * Try to establish a new connection to this peer in the given tunnel.
1943  * If the peer doesn't have any path to it yet, try to get one.
1944  * If the peer already has some path, send a CREATE CONNECTION towards it.
1945  *
1946  * @param peer PeerInfo of the peer.
1947  */
1948 static void
1949 peer_connect (struct MeshPeer *peer)
1950 {
1951   struct MeshTunnel2 *t;
1952   struct MeshPeerPath *p;
1953   struct MeshConnection *c;
1954
1955   t = peer->tunnel;
1956   if (NULL != peer->path_head)
1957   {
1958     p = peer_get_best_path (peer);
1959     if (NULL != p)
1960     {
1961       c = tunnel_use_path (t, p);
1962       send_connection_create (c);
1963     }
1964   }
1965   else if (NULL == peer->dhtget)
1966   {
1967     const struct GNUNET_PeerIdentity *id;
1968
1969     id = GNUNET_PEER_resolve2 (peer->id);
1970     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1971                 "  Starting DHT GET for peer %s\n", GNUNET_i2s (id));
1972     peer->dhtget = GNUNET_DHT_get_start (dht_handle,    /* handle */
1973                                          GNUNET_BLOCK_TYPE_MESH_PEER, /* type */
1974                                          &id->hashPubKey,     /* key to search */
1975                                          dht_replication_level, /* replication level */
1976                                          GNUNET_DHT_RO_RECORD_ROUTE |
1977                                          GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
1978                                          NULL,       /* xquery */
1979                                          0,     /* xquery bits */
1980                                          &dht_get_id_handler, peer);
1981     if (MESH_TUNNEL_NEW == t->state)
1982       tunnel_change_state (t, MESH_TUNNEL_SEARCHING);
1983   }
1984   else
1985   {
1986     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1987                 "There is no path but the DHT GET is already started.\n");
1988   }
1989 }
1990
1991
1992 /**
1993  * @brief Re-initiate traffic to this peer if necessary.
1994  *
1995  * Check if there is traffic queued towards this peer
1996  * and the core transmit handle is NULL (traffic was stalled).
1997  * If so, call core tmt rdy.
1998  *
1999  * @param peer_id Short ID of peer to which initiate traffic.
2000  */
2001 static void
2002 peer_unlock_queue (GNUNET_PEER_Id peer_id)
2003 {
2004   struct MeshPeer *peer;
2005   struct MeshPeerQueue *q;
2006   size_t size;
2007
2008   peer = peer_get_short (peer_id);
2009   if (NULL != peer->fc->core_transmit)
2010     return; /* Already unlocked */
2011
2012   q = queue_get_next (peer);
2013   if (NULL == q)
2014     return; /* Nothing to transmit */
2015
2016   size = q->size;
2017   peer->fc->core_transmit =
2018       GNUNET_CORE_notify_transmit_ready (core_handle,
2019                                          GNUNET_NO,
2020                                          0,
2021                                          GNUNET_TIME_UNIT_FOREVER_REL,
2022                                          GNUNET_PEER_resolve2 (peer->id),
2023                                          size,
2024                                          &queue_send,
2025                                          peer);
2026 }
2027
2028
2029 /**
2030  * Cancel all transmissions towards a neighbor that belong to
2031  * a certain connection.
2032  *
2033  * @param peer Neighbor to whom cancel the transmissions.
2034  * @param c Connection which to cancel.
2035  */
2036 static void
2037 peer_cancel_queues (struct MeshPeer *peer, struct MeshConnection *c)
2038 {
2039   struct MeshPeerQueue *q;
2040   struct MeshPeerQueue *next;
2041   struct MeshFlowControl *fc;
2042
2043   if (NULL == peer || NULL == peer->fc)
2044   {
2045     GNUNET_break (0);
2046     return;
2047   }
2048   fc = peer->fc;
2049   for (q = fc->queue_head; NULL != q; q = next)
2050   {
2051     next = q->next;
2052     if (q->c == c)
2053     {
2054       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2055                   "peer_cancel_queue %s\n",
2056                   GNUNET_MESH_DEBUG_M2S (q->type));
2057       queue_destroy (q, GNUNET_YES);
2058     }
2059   }
2060   if (NULL == fc->queue_head)
2061   {
2062     if (NULL != fc->core_transmit)
2063     {
2064       GNUNET_CORE_notify_transmit_ready_cancel (fc->core_transmit);
2065       fc->core_transmit = NULL;
2066     }
2067     if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task)
2068     {
2069       GNUNET_SCHEDULER_cancel (fc->poll_task);
2070       fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
2071     }
2072   }
2073 }
2074
2075
2076 /**
2077  * Destroy the peer_info and free any allocated resources linked to it
2078  *
2079  * @param peer The peer_info to destroy.
2080  *
2081  * @return GNUNET_OK on success
2082  */
2083 static int
2084 peer_destroy (struct MeshPeer *peer)
2085 {
2086   struct GNUNET_PeerIdentity id;
2087   struct MeshPeerPath *p;
2088   struct MeshPeerPath *nextp;
2089
2090   GNUNET_PEER_resolve (peer->id, &id);
2091   GNUNET_PEER_change_rc (peer->id, -1);
2092
2093   if (GNUNET_YES !=
2094       GNUNET_CONTAINER_multihashmap_remove (peers, &id.hashPubKey, peer))
2095   {
2096     GNUNET_break (0);
2097     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2098                 "removing peer %s, not in hashmap\n", GNUNET_i2s (&id));
2099   }
2100   if (NULL != peer->dhtget)
2101   {
2102     GNUNET_DHT_get_stop (peer->dhtget);
2103   }
2104   p = peer->path_head;
2105   while (NULL != p)
2106   {
2107     nextp = p->next;
2108     GNUNET_CONTAINER_DLL_remove (peer->path_head, peer->path_tail, p);
2109     path_destroy (p);
2110     p = nextp;
2111   }
2112   tunnel_destroy_empty (peer->tunnel);
2113   GNUNET_free (peer);
2114   return GNUNET_OK;
2115 }
2116
2117
2118 /**
2119  * Remove all paths that rely on a direct connection between p1 and p2
2120  * from the peer itself and notify all tunnels about it.
2121  *
2122  * @param peer PeerInfo of affected peer.
2123  * @param p1 GNUNET_PEER_Id of one peer.
2124  * @param p2 GNUNET_PEER_Id of another peer that was connected to the first and
2125  *           no longer is.
2126  *
2127  * TODO: optimize (see below)
2128  */
2129 static void
2130 peer_remove_path (struct MeshPeer *peer, GNUNET_PEER_Id p1,
2131                   GNUNET_PEER_Id p2)
2132 {
2133   struct MeshPeerPath *p;
2134   struct MeshPeerPath *next;
2135   struct MeshPeer *peer_d;
2136   GNUNET_PEER_Id d;
2137   unsigned int destroyed;
2138   unsigned int i;
2139
2140   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "peer_info_remove_path\n");
2141   destroyed = 0;
2142   for (p = peer->path_head; NULL != p; p = next)
2143   {
2144     next = p->next;
2145     for (i = 0; i < (p->length - 1); i++)
2146     {
2147       if ((p->peers[i] == p1 && p->peers[i + 1] == p2) ||
2148           (p->peers[i] == p2 && p->peers[i + 1] == p1))
2149       {
2150         GNUNET_CONTAINER_DLL_remove (peer->path_head, peer->path_tail, p);
2151         path_destroy (p);
2152         destroyed++;
2153         break;
2154       }
2155     }
2156   }
2157   if (0 == destroyed)
2158     return;
2159
2160
2161   d = tunnel_notify_connection_broken (peer->tunnel, p1, p2);
2162
2163   peer_d = peer_get_short (d); // FIXME
2164   next = peer_get_best_path (peer_d);
2165   tunnel_use_path (peer->tunnel, next);
2166   peer_connect (peer_d);
2167
2168   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "peer_info_remove_path END\n");
2169 }
2170
2171
2172 /**
2173  * Add the path to the peer and update the path used to reach it in case this
2174  * is the shortest.
2175  *
2176  * @param peer_info Destination peer to add the path to.
2177  * @param path New path to add. Last peer must be the peer in arg 1.
2178  *             Path will be either used of freed if already known.
2179  * @param trusted Do we trust that this path is real?
2180  */
2181 void
2182 peer_add_path (struct MeshPeer *peer_info, struct MeshPeerPath *path,
2183                     int trusted)
2184 {
2185   struct MeshPeerPath *aux;
2186   unsigned int l;
2187   unsigned int l2;
2188
2189   if ((NULL == peer_info) || (NULL == path))
2190   {
2191     GNUNET_break (0);
2192     path_destroy (path);
2193     return;
2194   }
2195   if (path->peers[path->length - 1] != peer_info->id)
2196   {
2197     GNUNET_break (0);
2198     path_destroy (path);
2199     return;
2200   }
2201   if (2 >= path->length && GNUNET_NO == trusted)
2202   {
2203     /* Only allow CORE to tell us about direct paths */
2204     path_destroy (path);
2205     return;
2206   }
2207   for (l = 1; l < path->length; l++)
2208   {
2209     if (path->peers[l] == myid)
2210     {
2211       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shortening path by %u\n", l);
2212       for (l2 = 0; l2 < path->length - l; l2++)
2213       {
2214         path->peers[l2] = path->peers[l + l2];
2215       }
2216       path->length -= l;
2217       l = 1;
2218       path->peers =
2219           GNUNET_realloc (path->peers, path->length * sizeof (GNUNET_PEER_Id));
2220     }
2221   }
2222 #if MESH_DEBUG
2223   {
2224     struct GNUNET_PeerIdentity id;
2225
2226     GNUNET_PEER_resolve (peer_info->id, &id);
2227     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "adding path [%u] to peer %s\n",
2228                 path->length, GNUNET_i2s (&id));
2229   }
2230 #endif
2231   l = path_get_length (path);
2232   if (0 == l)
2233   {
2234     path_destroy (path);
2235     return;
2236   }
2237
2238   GNUNET_assert (peer_info->id == path->peers[path->length - 1]);
2239   for (aux = peer_info->path_head; aux != NULL; aux = aux->next)
2240   {
2241     l2 = path_get_length (aux);
2242     if (l2 > l)
2243     {
2244       GNUNET_CONTAINER_DLL_insert_before (peer_info->path_head,
2245                                           peer_info->path_tail, aux, path);
2246       return;
2247     }
2248     else
2249     {
2250       if (l2 == l && memcmp (path->peers, aux->peers, l) == 0)
2251       {
2252         path_destroy (path);
2253         return;
2254       }
2255     }
2256   }
2257   GNUNET_CONTAINER_DLL_insert_tail (peer_info->path_head, peer_info->path_tail,
2258                                     path);
2259   return;
2260 }
2261
2262
2263 /**
2264  * Add the path to the origin peer and update the path used to reach it in case
2265  * this is the shortest.
2266  * The path is given in peer_info -> destination, therefore we turn the path
2267  * upside down first.
2268  *
2269  * @param peer_info Peer to add the path to, being the origin of the path.
2270  * @param path New path to add after being inversed.
2271  *             Path will be either used or freed.
2272  * @param trusted Do we trust that this path is real?
2273  */
2274 static void
2275 peer_add_path_to_origin (struct MeshPeer *peer_info,
2276                          struct MeshPeerPath *path, int trusted)
2277 {
2278   path_invert (path);
2279   peer_add_path (peer_info, path, trusted);
2280 }
2281
2282
2283
2284 /**
2285  * Function called if the connection to the peer has been stalled for a while,
2286  * possibly due to a missed ACK. Poll the peer about its ACK status.
2287  *
2288  * @param cls Closure (poll ctx).
2289  * @param tc TaskContext.
2290  */
2291 static void
2292 peer_poll (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2293 {
2294   struct MeshFlowControl *fc = cls;
2295   struct GNUNET_MESH_Poll msg;
2296   struct MeshPeer *peer;
2297
2298   fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
2299   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2300   {
2301     return;
2302   }
2303
2304   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " *** Polling!\n");
2305   peer = fc->peer;
2306
2307   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " *** peer: %s!\n", 
2308                 GNUNET_i2s (GNUNET_PEER_resolve2 (peer->id)));
2309
2310   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_POLL);
2311   msg.header.size = htons (sizeof (msg));
2312   msg.pid = htonl (fc->last_pid_sent);
2313   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " *** pid (%u)!\n", fc->last_pid_sent);
2314   send_prebuilt_message_peer (&msg.header, peer);
2315   fc->poll_time = GNUNET_TIME_STD_BACKOFF (fc->poll_time);
2316   fc->poll_task = GNUNET_SCHEDULER_add_delayed (fc->poll_time,
2317                                                 &peer_poll, fc);
2318 }
2319
2320
2321 /**
2322  * Build a PeerPath from the paths returned from the DHT, reversing the paths
2323  * to obtain a local peer -> destination path and interning the peer ids.
2324  *
2325  * @return Newly allocated and created path
2326  */
2327 static struct MeshPeerPath *
2328 path_build_from_dht (const struct GNUNET_PeerIdentity *get_path,
2329                      unsigned int get_path_length,
2330                      const struct GNUNET_PeerIdentity *put_path,
2331                      unsigned int put_path_length)
2332 {
2333   struct MeshPeerPath *p;
2334   GNUNET_PEER_Id id;
2335   int i;
2336
2337   p = path_new (1);
2338   p->peers[0] = myid;
2339   GNUNET_PEER_change_rc (myid, 1);
2340   i = get_path_length;
2341   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   GET has %d hops.\n", i);
2342   for (i--; i >= 0; i--)
2343   {
2344     id = GNUNET_PEER_intern (&get_path[i]);
2345     if (p->length > 0 && id == p->peers[p->length - 1])
2346     {
2347       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   Optimizing 1 hop out.\n");
2348       GNUNET_PEER_change_rc (id, -1);
2349     }
2350     else
2351     {
2352       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   Adding from GET: %s.\n",
2353                   GNUNET_i2s (&get_path[i]));
2354       p->length++;
2355       p->peers = GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * p->length);
2356       p->peers[p->length - 1] = id;
2357     }
2358   }
2359   i = put_path_length;
2360   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   PUT has %d hops.\n", i);
2361   for (i--; i >= 0; i--)
2362   {
2363     id = GNUNET_PEER_intern (&put_path[i]);
2364     if (id == myid)
2365     {
2366       /* PUT path went through us, so discard the path up until now and start
2367        * from here to get a much shorter (and loop-free) path.
2368        */
2369       path_destroy (p);
2370       p = path_new (0);
2371     }
2372     if (p->length > 0 && id == p->peers[p->length - 1])
2373     {
2374       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   Optimizing 1 hop out.\n");
2375       GNUNET_PEER_change_rc (id, -1);
2376     }
2377     else
2378     {
2379       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   Adding from PUT: %s.\n",
2380                   GNUNET_i2s (&put_path[i]));
2381       p->length++;
2382       p->peers = GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * p->length);
2383       p->peers[p->length - 1] = id;
2384     }
2385   }
2386 #if MESH_DEBUG
2387   if (get_path_length > 0)
2388     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   (first of GET: %s)\n",
2389                 GNUNET_i2s (&get_path[0]));
2390   if (put_path_length > 0)
2391     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   (first of PUT: %s)\n",
2392                 GNUNET_i2s (&put_path[0]));
2393   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   In total: %d hops\n",
2394               p->length);
2395   for (i = 0; i < p->length; i++)
2396   {
2397     struct GNUNET_PeerIdentity peer_id;
2398
2399     GNUNET_PEER_resolve (p->peers[i], &peer_id);
2400     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "       %u: %s\n", p->peers[i],
2401                 GNUNET_i2s (&peer_id));
2402   }
2403 #endif
2404   return p;
2405 }
2406
2407
2408 /**
2409  * Adds a path to the peer_infos of all the peers in the path
2410  *
2411  * @param p Path to process.
2412  * @param confirmed Whether we know if the path works or not.
2413  */
2414 static void
2415 path_add_to_peers (struct MeshPeerPath *p, int confirmed)
2416 {
2417   unsigned int i;
2418
2419   /* TODO: invert and add */
2420   for (i = 0; i < p->length && p->peers[i] != myid; i++) /* skip'em */ ;
2421   for (i++; i < p->length; i++)
2422   {
2423     struct MeshPeer *aux;
2424     struct MeshPeerPath *copy;
2425
2426     aux = peer_get_short (p->peers[i]);
2427     copy = path_duplicate (p);
2428     copy->length = i + 1;
2429     peer_add_path (aux, copy, p->length < 3 ? GNUNET_NO : confirmed);
2430   }
2431 }
2432
2433
2434 /**
2435  * Search for a channel among the channels for a client
2436  *
2437  * @param c the client whose channels to search in
2438  * @param chid the local id of the channel
2439  *
2440  * @return channel handler, NULL if doesn't exist
2441  */
2442 static struct MeshChannel *
2443 channel_get_by_local_id (struct MeshClient *c, MESH_ChannelNumber chid)
2444 {
2445   if (0 == (chid & GNUNET_MESH_LOCAL_CHANNEL_ID_CLI))
2446   {
2447     GNUNET_break_op (0);
2448     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CHID %X not a local chid\n", chid);
2449     return NULL;
2450   }
2451   if (chid >= GNUNET_MESH_LOCAL_CHANNEL_ID_SERV)
2452     return GNUNET_CONTAINER_multihashmap32_get (c->incoming_channels, chid);
2453   return GNUNET_CONTAINER_multihashmap32_get (c->own_channels, chid);
2454 }
2455
2456
2457 /**
2458  * Search for a tunnel by global ID using PEER_ID
2459  *
2460  * @param pi owner of the tunnel
2461  * @param tid global tunnel number
2462  *
2463  * @return tunnel handler, NULL if doesn't exist
2464  */
2465 static struct MeshChannel *
2466 channel_get_by_pi (GNUNET_PEER_Id pi, MESH_ChannelNumber tid)
2467 {
2468 //   struct GNUNET_HashCode hash;
2469
2470 //   return GNUNET_CONTAINER_multihashmap_get (tunnels, &hash); FIXME
2471   return NULL;
2472 }
2473
2474
2475 /**
2476  * Search for a tunnel by global ID using full PeerIdentities
2477  *
2478  * @param oid owner of the tunnel
2479  * @param tid global tunnel number
2480  *
2481  * @return tunnel handler, NULL if doesn't exist
2482  */
2483 static struct MeshChannel *
2484 channel_get (const struct GNUNET_PeerIdentity *oid, MESH_ChannelNumber tid)
2485 {
2486   return channel_get_by_pi (GNUNET_PEER_search (oid), tid);
2487 }
2488
2489
2490 /**
2491  * Change the tunnel state.
2492  *
2493  * @param t Tunnel whose state to change.
2494  * @param state New state.
2495  */
2496 static void
2497 tunnel_change_state (struct MeshTunnel2* t, enum MeshTunnelState state)
2498 {
2499   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2500               "Tunnel %s state was %s\n",
2501               GNUNET_i2s (GNUNET_PEER_resolve2 (t->peer->id)),
2502               GNUNET_MESH_DEBUG_TS2S (t->state));
2503   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2504               "Tunnel %s state is now %s\n",
2505               GNUNET_i2s (GNUNET_PEER_resolve2 (t->peer->id)),
2506               GNUNET_MESH_DEBUG_TS2S (state));
2507   t->state = state;
2508 }
2509
2510
2511 static void
2512 connection_change_state (struct MeshConnection* c,
2513                          enum MeshConnectionState state)
2514 {
2515   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2516               "Connection %s[%X] state was %s\n",
2517               GNUNET_i2s (GNUNET_PEER_resolve2 (c->t->peer->id)), c->id,
2518               GNUNET_MESH_DEBUG_CS2S (c->state));
2519   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2520               "Connection %s[%X] state is now %s\n",
2521               GNUNET_i2s (GNUNET_PEER_resolve2 (c->t->peer->id)), c->id,
2522               GNUNET_MESH_DEBUG_CS2S (state));
2523   c->state = state;
2524 }
2525
2526
2527 /**
2528  * Add a client to a channel, initializing all needed data structures.
2529  * 
2530  * @param ch Channel to which add the client.
2531  * @param c Client which to add to the channel.
2532  */
2533 static void
2534 channel_add_client (struct MeshChannel *ch, struct MeshClient *c)
2535 {
2536   if (NULL != ch->client)
2537   {
2538     GNUNET_break(0);
2539     return;
2540   }
2541   if (GNUNET_OK !=
2542       GNUNET_CONTAINER_multihashmap32_put (c->incoming_channels,
2543                                            ch->id_dest, ch,
2544                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
2545   {
2546     GNUNET_break (0);
2547     return;
2548   }
2549   ch->client = c;
2550 }
2551
2552
2553 static struct MeshConnection *
2554 tunnel_use_path (struct MeshTunnel2 *t, struct MeshPeerPath *p)
2555 {
2556   struct MeshConnection *c;
2557   unsigned int own_pos;
2558
2559   c = GNUNET_new (struct MeshConnection);
2560   for (own_pos = 0; own_pos < p->length; own_pos++)
2561   {
2562     if (p->peers[own_pos] == myid)
2563       break;
2564   }
2565   if (own_pos > p->length - 1)
2566   {
2567     GNUNET_break (0);
2568     return NULL;
2569   }
2570   c->own_pos = own_pos;
2571   c->path = p;
2572   c->id = t->next_cid++;
2573   c->t = t;
2574   GNUNET_CONTAINER_DLL_insert_tail (t->connection_head, t->connection_tail, c);
2575
2576   if (0 == own_pos)
2577   {
2578     c->fwd_maintenance_task =
2579         GNUNET_SCHEDULER_add_delayed (refresh_connection_time,
2580                                       &connection_fwd_keepalive, c);
2581   }
2582   return c;
2583 }
2584
2585
2586 /**
2587  * Notifies a tunnel that a connection has broken that affects at least
2588  * some of its peers. Sends a notification towards the root of the tree.
2589  * In case the peer is the owner of the tree, notifies the client that owns
2590  * the tunnel and tries to reconnect.
2591  *
2592  * @param t Tunnel affected.
2593  * @param p1 Peer that got disconnected from p2.
2594  * @param p2 Peer that got disconnected from p1.
2595  *
2596  * @return Short ID of the peer disconnected (either p1 or p2).
2597  *         0 if the tunnel remained unaffected.
2598  */
2599 static GNUNET_PEER_Id
2600 tunnel_notify_connection_broken (struct MeshTunnel2* t,
2601                                  GNUNET_PEER_Id p1, GNUNET_PEER_Id p2)
2602 {
2603 //   if (myid != p1 && myid != p2) FIXME
2604 //   {
2605 //     return;
2606 //   }
2607 // 
2608 //   if (tree_get_predecessor (t->tree) != 0)
2609 //   {
2610 //     /* We are the peer still connected, notify owner of the disconnection. */
2611 //     struct GNUNET_MESH_PathBroken msg;
2612 //     struct GNUNET_PeerIdentity neighbor;
2613 // 
2614 //     msg.header.size = htons (sizeof (msg));
2615 //     msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN);
2616 //     GNUNET_PEER_resolve (t->id.oid, &msg.oid);
2617 //     msg.tid = htonl (t->id.tid);
2618 //     msg.peer1 = my_full_id;
2619 //     GNUNET_PEER_resolve (pid, &msg.peer2);
2620 //     GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &neighbor);
2621 //     send_prebuilt_message (&msg.header, &neighbor, t);
2622 //   }
2623   return 0;
2624 }
2625
2626
2627 /**
2628  * Send an end-to-end FWD ACK message for the most recent in-sequence payload.
2629  * 
2630  * @param ch Channel this is about.
2631  * @param fwd Is for FWD traffic? (ACK dest->owner)
2632  */
2633 static void
2634 channel_send_data_ack (struct MeshChannel *ch, int fwd)
2635 {
2636   struct GNUNET_MESH_DataACK msg;
2637   struct MeshChannelReliability *rel;
2638   struct MeshReliableMessage *copy;
2639   uint64_t mask;
2640   unsigned int delta;
2641
2642   if (GNUNET_NO == ch->reliable)
2643   {
2644     GNUNET_break (0);
2645     return;
2646   }
2647   rel = fwd ? ch->bck_rel  : ch->fwd_rel;
2648   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2649               "send_data_ack for %u\n",
2650               rel->mid_recv - 1);
2651
2652   msg.header.type = htons (fwd ? GNUNET_MESSAGE_TYPE_MESH_UNICAST_ACK :
2653                                  GNUNET_MESSAGE_TYPE_MESH_TO_ORIG_ACK);
2654   msg.header.size = htons (sizeof (msg));
2655   msg.chid = htonl (ch->id);
2656   msg.mid = htonl (rel->mid_recv - 1);
2657   msg.futures = 0;
2658   for (copy = rel->head_recv; NULL != copy; copy = copy->next)
2659   {
2660     delta = copy->mid - rel->mid_recv;
2661     if (63 < delta)
2662       break;
2663     mask = 0x1LL << delta;
2664     msg.futures |= mask;
2665     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2666                 " setting bit for %u (delta %u) (%llX) -> %llX\n",
2667                 copy->mid, delta, mask, msg.futures);
2668   }
2669   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " final futures %llX\n", msg.futures);
2670
2671   send_prebuilt_message_channel (&msg.header, ch, fwd);
2672   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "send_data_ack END\n");
2673 }
2674
2675
2676 /**
2677  * Send an ACK informing the predecessor about the available buffer space.
2678  *
2679  * Note that although the name is fwd_ack, the FWD mean forward *traffic*,
2680  * the ACK itself goes "back" (towards root).
2681  *
2682  * @param c Connection on which to send the ACK.
2683  * @param fwd Is this FWD ACK? (Going dest->owner)
2684  */
2685 static void
2686 connection_send_ack (struct MeshConnection *c, int fwd)
2687 {
2688   struct MeshFlowControl *next_fc;
2689   struct MeshFlowControl *prev_fc;
2690   struct MeshPeer *next;
2691   struct MeshPeer *prev;
2692   uint32_t ack;
2693   int delta;
2694
2695   next    = fwd ? connection_get_next_hop (c) : connection_get_prev_hop (c);
2696   prev    = fwd ? connection_get_prev_hop (c) : connection_get_next_hop (c);
2697   next_fc = next->fc;
2698   prev_fc = prev->fc;
2699
2700   /* Check if we need to transmit the ACK */
2701   if (prev_fc->last_ack_sent - prev_fc->last_pid_recv > 3)
2702   {
2703     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending ACK, buffer > 3\n");
2704     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2705                 "  last pid recv: %u, last ack sent: %u\n",
2706                 prev_fc->last_pid_recv, prev_fc->last_ack_sent);
2707     return;
2708   }
2709
2710   /* Ok, ACK might be necessary, what PID to ACK? */
2711   delta = next_fc->queue_max - next_fc->queue_n;
2712   ack = prev_fc->last_pid_recv + delta;
2713   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ACK %u\n", ack);
2714   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2715               " last pid %u, last ack %u, qmax %u, q %u\n",
2716               prev_fc->last_pid_recv, prev_fc->last_ack_sent,
2717               next_fc->queue_max, next_fc->queue_n);
2718   if (ack == prev_fc->last_ack_sent)
2719   {
2720     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending FWD ACK, not needed\n");
2721     return;
2722   }
2723
2724   prev_fc->last_ack_sent = ack;
2725   send_ack (prev, ack);
2726 }
2727
2728
2729 /**
2730  * Send an ACK informing the client about available buffer space.
2731  *
2732  * Note that although the name is fwd_ack, the FWD mean forward *traffic*,
2733  * the ACK itself goes "back" (towards root).
2734  * 
2735  * @param ch Channel on which to send the ACK, NULL if unknown.
2736  * @param fwd Is this FWD ACK? (Going dest->owner)
2737  */
2738 // static void
2739 // channel_send_ack (struct MeshChannel *ch, uint16_t type, int fwd)
2740 // {
2741 //   struct MeshChannelReliability *rel;
2742 //   struct MeshFlowControl *next_fc;
2743 //   struct MeshFlowControl *prev_fc;
2744 //   struct MeshClient *c;
2745 //   struct MeshClient *o;
2746 //   GNUNET_PEER_Id hop;
2747 //   uint32_t delta_mid;
2748 //   uint32_t ack;
2749 //   int delta;
2750 // 
2751 //   rel     = fwd ? ch->fwd_rel : ch->bck_rel;
2752 //   c       = fwd ? ch->client  : ch->owner;
2753 //   o       = fwd ? ch->owner   : ch->client;
2754 //   hop     = fwd ? connection_get_prev_hop (cn) : connection_get_next_hop (cn);
2755 //   next_fc = fwd ? &t->next_fc : &t->prev_fc;
2756 //   prev_fc = fwd ? &t->prev_fc : &t->next_fc;
2757 // 
2758 //   switch (type)
2759 //   {
2760 //     case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
2761 //     case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
2762 //       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2763 //                   "ACK due to %s\n",
2764 //                   GNUNET_MESH_DEBUG_M2S (type));
2765 //       if (GNUNET_YES == t->nobuffer && (GNUNET_NO == t->reliable || NULL == c))
2766 //       {
2767 //         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending ACK, nobuffer\n");
2768 //         return;
2769 //       }
2770 //       if (GNUNET_YES == t->reliable && NULL != c)
2771 //         tunnel_send_data_ack (t, fwd);
2772 //       break;
2773 //     case GNUNET_MESSAGE_TYPE_MESH_UNICAST_ACK:
2774 //     case GNUNET_MESSAGE_TYPE_MESH_TO_ORIG_ACK:
2775 //     case GNUNET_MESSAGE_TYPE_MESH_ACK:
2776 //     case GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK:
2777 //       break;
2778 //     case GNUNET_MESSAGE_TYPE_MESH_POLL:
2779 //     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK:
2780 //       t->force_ack = GNUNET_YES;
2781 //       break;
2782 //     default:
2783 //       GNUNET_break (0);
2784 //   }
2785 // 
2786 //   /* Check if we need to transmit the ACK */
2787 //   if (NULL == o &&
2788 //       prev_fc->last_ack_sent - prev_fc->last_pid_recv > 3 &&
2789 //       GNUNET_NO == t->force_ack)
2790 //   {
2791 //     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending ACK, buffer free\n");
2792 //     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2793 //                 "  last pid recv: %u, last ack sent: %u\n",
2794 //                 prev_fc->last_pid_recv, prev_fc->last_ack_sent);
2795 //     return;
2796 //   }
2797 // 
2798 //   /* Ok, ACK might be necessary, what PID to ACK? */
2799 //   delta = t->queue_max - next_fc->queue_n;
2800 //   if (NULL != o && GNUNET_YES == t->reliable && NULL != rel->head_sent)
2801 //     delta_mid = rel->mid_sent - rel->head_sent->mid;
2802 //   else
2803 //     delta_mid = 0;
2804 //   if (0 > delta || (GNUNET_YES == t->reliable && 
2805 //                     NULL != o &&
2806 //                     (10 < rel->n_sent || 64 <= delta_mid)))
2807 //     delta = 0;
2808 //   if (NULL != o && delta > 1)
2809 //     delta = 1;
2810 //   ack = prev_fc->last_pid_recv + delta;
2811 //   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ACK %u\n", ack);
2812 //   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2813 //               " last pid %u, last ack %u, qmax %u, q %u\n",
2814 //               prev_fc->last_pid_recv, prev_fc->last_ack_sent,
2815 //               t->queue_max, next_fc->queue_n);
2816 //   if (ack == prev_fc->last_ack_sent && GNUNET_NO == t->force_ack)
2817 //   {
2818 //     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending FWD ACK, not needed\n");
2819 //     return;
2820 //   }
2821 // 
2822 //   prev_fc->last_ack_sent = ack;
2823 //   if (NULL != o)
2824 //     send_local_ack (t, o, fwd);
2825 //   else if (0 != hop)
2826 //     send_ack (t, hop, ack);
2827 //   else
2828 //     GNUNET_break (GNUNET_YES == t->destroy);
2829 //   t->force_ack = GNUNET_NO;
2830 // }
2831
2832
2833 /**
2834  * Modify the mesh message TID from global to local and send to client.
2835  * 
2836  * @param ch Channel on which to send the message.
2837  * @param msg Message to modify and send.
2838  * @param c Client to send to.
2839  * @param tid Tunnel ID to use (c can be both owner and client).
2840  */
2841 static void
2842 channel_send_client_to_tid (struct MeshChannel *ch,
2843                              const struct GNUNET_MESH_Data *msg,
2844                              struct MeshClient *c, MESH_ChannelNumber id)
2845 {
2846   struct GNUNET_MESH_LocalData *copy;
2847   uint16_t size = ntohs (msg->header.size) - sizeof (struct GNUNET_MESH_Data);
2848   char cbuf[size + sizeof (struct GNUNET_MESH_LocalData)];
2849
2850   if (size < sizeof (struct GNUNET_MessageHeader))
2851   {
2852     GNUNET_break_op (0);
2853     return;
2854   }
2855   if (NULL == c)
2856   {
2857     GNUNET_break (0);
2858     return;
2859   }
2860   copy = (struct GNUNET_MESH_LocalData *) cbuf;
2861   memcpy (&copy[1], &msg[1], size);
2862   copy->header.size = htons (sizeof (struct GNUNET_MESH_LocalData) + size);
2863   copy->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_DATA);
2864   copy->id = htonl (id);
2865   GNUNET_SERVER_notification_context_unicast (nc, c->handle,
2866                                               &copy->header, GNUNET_NO);
2867 }
2868
2869 /**
2870  * Modify the data message ID from global to local and send to client.
2871  * 
2872  * @param ch Channel on which to send the message.
2873  * @param msg Message to modify and send.
2874  * @param fwd Forward?
2875  */
2876 static void
2877 channel_send_client_data (struct MeshChannel *ch,
2878                           const struct GNUNET_MESH_Data *msg,
2879                           int fwd)
2880 {
2881   if (fwd)
2882     channel_send_client_to_tid (ch, msg, ch->client, ch->id_dest);
2883   else
2884     channel_send_client_to_tid (ch, msg, ch->owner, ch->id);
2885 }
2886
2887
2888 /**
2889  * Send up to 64 buffered messages to the client for in order delivery.
2890  *
2891  * @param ch Channel on which to empty the message buffer.
2892  * @param c Client to send to.
2893  * @param rel Reliability structure to corresponding peer.
2894  *            If rel == bck_rel, this is FWD data.
2895  */
2896 static void
2897 channel_send_client_buffered_data (struct MeshChannel *ch,
2898                                    struct MeshClient *c,
2899                                    struct MeshChannelReliability *rel)
2900 {
2901   struct MeshReliableMessage *copy;
2902   struct MeshReliableMessage *next;
2903
2904   if (GNUNET_NO == ch->reliable)
2905   {
2906     GNUNET_break (0);
2907     return;
2908   }
2909
2910   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "send_buffered_data\n");
2911   for (copy = rel->head_recv; NULL != copy; copy = next)
2912   {
2913     next = copy->next;
2914     if (copy->mid == rel->mid_recv)
2915     {
2916       struct GNUNET_MESH_Data *msg = (struct GNUNET_MESH_Data *) &copy[1];
2917
2918       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2919                   " have %u! now expecting %u\n",
2920                   copy->mid, rel->mid_recv + 1);
2921       channel_send_client_data (ch, msg, (rel == ch->bck_rel));
2922       rel->mid_recv++;
2923       GNUNET_CONTAINER_DLL_remove (rel->head_recv, rel->tail_recv, copy);
2924       GNUNET_free (copy);
2925     }
2926     else
2927     {
2928       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2929                   " don't have %u, next is %u\n",
2930                   rel->mid_recv,
2931                   copy->mid);
2932       return;
2933     }
2934   }
2935   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "send_buffered_data END\n");
2936 }
2937
2938
2939 /**
2940  * We have received a message out of order, buffer it until we receive
2941  * the missing one and we can feed the rest to the client.
2942  *
2943  * @param msg Message to buffer.
2944  * @param rel Reliability data to the corresponding direction.
2945  */
2946 static void
2947 channel_rel_add_buffered_data (const struct GNUNET_MESH_Data *msg,
2948                                struct MeshChannelReliability *rel)
2949 {
2950   struct MeshReliableMessage *copy;
2951   struct MeshReliableMessage *prev;
2952   uint32_t mid;
2953   uint16_t size;
2954
2955   size = ntohs (msg->header.size);
2956   mid = ntohl (msg->mid);
2957   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "add_buffered_data %u\n", mid);
2958
2959   copy = GNUNET_malloc (sizeof (*copy) + size);
2960   copy->mid = mid;
2961   copy->rel = rel;
2962   memcpy (&copy[1], msg, size);
2963
2964   // FIXME do something better than O(n), although n < 64...
2965   // FIXME start from the end (most messages are the latest ones)
2966   for (prev = rel->head_recv; NULL != prev; prev = prev->next)
2967   {
2968     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " prev %u\n", prev->mid);
2969     if (GMC_is_pid_bigger (prev->mid, mid))
2970     {
2971       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " bingo!\n");
2972       GNUNET_CONTAINER_DLL_insert_before (rel->head_recv, rel->tail_recv,
2973                                           prev, copy);
2974       return;
2975     }
2976   }
2977   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " insert at tail!\n");
2978   GNUNET_CONTAINER_DLL_insert_tail (rel->head_recv, rel->tail_recv, copy);
2979   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "add_buffered_data END\n");
2980 }
2981
2982
2983 /**
2984  * Destroy a reliable message after it has been acknowledged, either by
2985  * direct mid ACK or bitfield. Updates the appropriate data structures and
2986  * timers and frees all memory.
2987  * 
2988  * @param copy Message that is no longer needed: remote peer got it.
2989  */
2990 static void
2991 rel_message_free (struct MeshReliableMessage *copy)
2992 {
2993   struct MeshChannelReliability *rel;
2994   struct GNUNET_TIME_Relative time;
2995
2996   rel = copy->rel;
2997   time = GNUNET_TIME_absolute_get_duration (copy->timestamp);
2998   rel->expected_delay.rel_value *= 7;
2999   rel->expected_delay.rel_value += time.rel_value;
3000   rel->expected_delay.rel_value /= 8;
3001   rel->n_sent--;
3002   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! Freeing %u\n", copy->mid);
3003   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    n_sent %u\n", rel->n_sent);
3004   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!!  took %s\n",
3005               GNUNET_STRINGS_relative_time_to_string (time, GNUNET_NO));
3006   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!!  new expected delay %s\n",
3007               GNUNET_STRINGS_relative_time_to_string (rel->expected_delay,
3008                                                       GNUNET_NO));
3009   rel->retry_timer = rel->expected_delay;
3010   GNUNET_CONTAINER_DLL_remove (rel->head_sent, rel->tail_sent, copy);
3011   GNUNET_free (copy);
3012 }
3013
3014
3015 /**
3016  * Destroy all reliable messages queued for a channel,
3017  * during a channel destruction.
3018  * Frees the reliability structure itself.
3019  *
3020  * @param rel Reliability data for a channel.
3021  */
3022 static void
3023 channel_rel_free_all (struct MeshChannelReliability *rel)
3024 {
3025   struct MeshReliableMessage *copy;
3026   struct MeshReliableMessage *next;
3027
3028   if (NULL == rel)
3029     return;
3030
3031   for (copy = rel->head_recv; NULL != copy; copy = next)
3032   {
3033     next = copy->next;
3034     GNUNET_CONTAINER_DLL_remove (rel->head_recv, rel->tail_recv, copy);
3035     GNUNET_free (copy);
3036   }
3037   for (copy = rel->head_sent; NULL != copy; copy = next)
3038   {
3039     next = copy->next;
3040     GNUNET_CONTAINER_DLL_remove (rel->head_sent, rel->tail_sent, copy);
3041     GNUNET_free (copy);
3042   }
3043   if (GNUNET_SCHEDULER_NO_TASK != rel->retry_task)
3044     GNUNET_SCHEDULER_cancel (rel->retry_task);
3045   GNUNET_free (rel);
3046 }
3047
3048
3049 /**
3050  * Mark future messages as ACK'd.
3051  *
3052  * @param rel Reliability data.
3053  * @param msg DataACK message with a bitfield of future ACK'd messages.
3054  */
3055 static void
3056 channel_rel_free_sent (struct MeshChannelReliability *rel,
3057                        const struct GNUNET_MESH_DataACK *msg)
3058 {
3059   struct MeshReliableMessage *copy;
3060   struct MeshReliableMessage *next;
3061   uint64_t bitfield;
3062   uint64_t mask;
3063   uint32_t mid;
3064   uint32_t target;
3065   unsigned int i;
3066
3067   bitfield = msg->futures;
3068   mid = ntohl (msg->mid);
3069   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3070               "free_sent_reliable %u %llX\n",
3071               mid, bitfield);
3072   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3073               " rel %p, head %p\n",
3074               rel, rel->head_sent);
3075   for (i = 0, copy = rel->head_sent;
3076        i < 64 && NULL != copy && 0 != bitfield;
3077        i++)
3078   {
3079     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3080                 " trying bit %u (mid %u)\n",
3081                 i, mid + i + 1);
3082     mask = 0x1LL << i;
3083     if (0 == (bitfield & mask))
3084      continue;
3085
3086     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " set!\n");
3087     /* Bit was set, clear the bit from the bitfield */
3088     bitfield &= ~mask;
3089
3090     /* The i-th bit was set. Do we have that copy? */
3091     /* Skip copies with mid < target */
3092     target = mid + i + 1;
3093     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " target %u\n", target);
3094     while (NULL != copy && GMC_is_pid_bigger (target, copy->mid))
3095      copy = copy->next;
3096
3097     /* Did we run out of copies? (previously freed, it's ok) */
3098     if (NULL == copy)
3099     {
3100      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "run out of copies...\n");
3101      return;
3102     }
3103
3104     /* Did we overshoot the target? (previously freed, it's ok) */
3105     if (GMC_is_pid_bigger (copy->mid, target))
3106     {
3107      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " next copy %u\n", copy->mid);
3108      continue;
3109     }
3110
3111     /* Now copy->mid == target, free it */
3112     next = copy->next;
3113     rel_message_free (copy);
3114     copy = next;
3115   }
3116   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "free_sent_reliable END\n");
3117 }
3118
3119
3120 /**
3121  * We haven't received an ACK after a certain time: restransmit the message.
3122  *
3123  * @param cls Closure (MeshReliableMessage with the message to restransmit)
3124  * @param tc TaskContext.
3125  */
3126 static void
3127 channel_retransmit_message (void *cls,
3128                             const struct GNUNET_SCHEDULER_TaskContext *tc)
3129 {
3130   struct MeshChannelReliability *rel = cls;
3131   struct MeshReliableMessage *copy;
3132   struct MeshPeerQueue *q;
3133   struct MeshPeer *pi;
3134   struct MeshChannel *ch;
3135   struct MeshConnection *c;
3136   struct GNUNET_MESH_Data *payload;
3137   int fwd;
3138
3139   rel->retry_task = GNUNET_SCHEDULER_NO_TASK;
3140   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
3141     return;
3142
3143   ch = rel->ch;
3144   copy = rel->head_sent;
3145   if (NULL == copy)
3146   {
3147     GNUNET_break (0);
3148     return;
3149   }
3150
3151   /* Search the message to be retransmitted in the outgoing queue.
3152    * Check only the queue for the connection that is going to be used,
3153    * if the message is stuck in some other connection's queue we shouldn't
3154    * act upon it:
3155    * - cancelling it and sending the new one doesn't guarantee it's delivery,
3156    *   the old connection could be temporary stalled or the queue happened to
3157    *   be long at time of insertion.
3158    * - not sending the new one could cause terrible delays the old connection
3159    *   is stalled.
3160    */
3161   payload = (struct GNUNET_MESH_Data *) &copy[1];
3162   fwd = (rel == ch->fwd_rel);
3163   c = tunnel_get_connection(ch->t, fwd);
3164   pi = connection_get_next_hop (c);
3165   for (q = pi->fc->queue_head; NULL != q; q = q->next)
3166   {
3167     if (ntohs (payload->header.type) == q->type && ch == q->ch)
3168     {
3169       struct GNUNET_MESH_Data *queued_data = q->cls;
3170
3171       if (queued_data->mid == payload->mid)
3172         break;
3173     }
3174   }
3175
3176   /* Message not found in the queue that we are going to use. */
3177   if (NULL == q)
3178   {
3179     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! RETRANSMIT %u\n", copy->mid);
3180
3181     send_prebuilt_message_channel (&payload->header, ch, ch->fwd_rel == rel);
3182     GNUNET_STATISTICS_update (stats, "# data retransmitted", 1, GNUNET_NO);
3183   }
3184   else
3185   {
3186     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! ALREADY IN QUEUE %u\n", copy->mid);
3187   }
3188
3189   rel->retry_timer = GNUNET_TIME_STD_BACKOFF (rel->retry_timer);
3190   rel->retry_task = GNUNET_SCHEDULER_add_delayed (rel->retry_timer,
3191                                                   &channel_retransmit_message,
3192                                                   cls);
3193 }
3194
3195
3196 /**
3197  * Send keepalive packets for a connection.
3198  *
3199  * @param c Connection to keep alive..
3200  * @param fwd Is this a FWD keepalive? (owner -> dest).
3201  */
3202 static void
3203 connection_keepalive (struct MeshConnection *c, int fwd)
3204 {
3205   struct GNUNET_MESH_ConnectionKeepAlive *msg;
3206   size_t size = sizeof (struct GNUNET_MESH_ConnectionKeepAlive);
3207   char cbuf[size];
3208   uint16_t type;
3209
3210   type = fwd ? GNUNET_MESSAGE_TYPE_MESH_FWD_KEEPALIVE :
3211                GNUNET_MESSAGE_TYPE_MESH_BCK_KEEPALIVE;
3212
3213   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3214               "sending %s keepalive for connection %s[%d]\n",
3215               fwd ? "FWD" : "BCK",
3216               GNUNET_i2s (GNUNET_PEER_resolve2 (c->t->peer->id)),
3217               c->id);
3218
3219   msg = (struct GNUNET_MESH_ConnectionKeepAlive *) cbuf;
3220   msg->header.size = htons (size);
3221   msg->header.type = htons (type);
3222   msg->cid = htonl (c->id);
3223   msg->tid = c->t->id;
3224
3225   send_prebuilt_message_connection (&msg->header, c, NULL, fwd);
3226 }
3227
3228
3229 /**
3230  * Send CONNECTION_{CREATE/ACK} packets for a connection.
3231  *
3232  * @param c Connection for which to send the message.
3233  * @param fwd If GNUNET_YES, send CREATE, otherwise send ACK.
3234  */
3235 static void
3236 connection_recreate (struct MeshConnection *c, int fwd)
3237 {
3238   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "sending connection recreate\n");
3239   if (fwd)
3240     send_connection_create (c);
3241   else
3242     send_connection_ack (c);
3243 }
3244
3245
3246 /**
3247  * Generic connection timer management.
3248  * Depending on the role of the peer in the connection will send the
3249  * appropriate message (build or keepalive)
3250  *
3251  * @param c Conncetion to maintain.
3252  * @param fwd Is FWD?
3253  */
3254 static void
3255 connection_maintain (struct MeshConnection *c, int fwd)
3256 {
3257   if (MESH_TUNNEL_SEARCHING == c->t->state)
3258   {
3259     /* TODO DHT GET with RO_BART */
3260     return;
3261   }
3262   switch (c->state)
3263   {
3264     case MESH_CONNECTION_NEW:
3265       GNUNET_break (0);
3266     case MESH_CONNECTION_SENT:
3267       connection_recreate (c, fwd);
3268       break;
3269     case MESH_CONNECTION_READY:
3270       connection_keepalive (c, fwd);
3271       break;
3272     default:
3273       break;
3274   }
3275 }
3276
3277
3278 static void
3279 connection_fwd_keepalive (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3280 {
3281   struct MeshConnection *c = cls;
3282
3283   c->fwd_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
3284   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
3285     return;
3286
3287   connection_keepalive (c, GNUNET_YES);
3288   c->fwd_maintenance_task = GNUNET_SCHEDULER_add_delayed (refresh_connection_time,
3289                                                           &connection_fwd_keepalive,
3290                                                           c);
3291 }
3292
3293
3294 static void
3295 connection_bck_keepalive (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3296 {
3297   struct MeshConnection *c = cls;
3298
3299   c->bck_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
3300   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
3301     return;
3302
3303   connection_keepalive (c, GNUNET_NO);
3304   c->bck_maintenance_task = GNUNET_SCHEDULER_add_delayed (refresh_connection_time,
3305                                                           &connection_bck_keepalive,
3306                                                           c);
3307 }
3308
3309
3310 /**
3311  * Send a message to all peers in this connection that the connection
3312  * is no longer valid.
3313  *
3314  * If some peer should not receive the message, it should be zero'ed out
3315  * before calling this function.
3316  *
3317  * @param c The connection whose peers to notify.
3318  */
3319 static void
3320 connection_send_destroy (struct MeshConnection *c)
3321 {
3322   struct GNUNET_MESH_ConnectionDestroy msg;
3323
3324   msg.header.size = htons (sizeof (msg));
3325   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY);;
3326   msg.cid = htonl (c->id);
3327   msg.tid = c->t->id;
3328   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3329               "  sending tunnel destroy for connection %s[%X]\n",
3330               GNUNET_i2s (GNUNET_PEER_resolve2 (c->t->peer->id)),
3331               c->id);
3332
3333   send_prebuilt_message_connection (&msg.header, c, NULL, GNUNET_YES);
3334   send_prebuilt_message_connection (&msg.header, c, NULL, GNUNET_NO);
3335 }
3336
3337
3338 /**
3339  * Send a message to all clients (local and remote) of this channel
3340  * notifying that the channel is no longer valid.
3341  *
3342  * If some peer or client should not receive the message,
3343  * should be zero'ed out before calling this function.
3344  *
3345  * @param ch The channel whose clients to notify.
3346  */
3347 static void
3348 channel_send_destroy (struct MeshChannel *ch)
3349 {
3350   struct GNUNET_MESH_ChannelDestroy msg;
3351
3352   msg.header.size = htons (sizeof (msg));
3353   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY);
3354   msg.chid = htonl (ch->id);
3355   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3356               "  sending tunnel destroy for channel %s:%X\n",
3357               GNUNET_i2s (GNUNET_PEER_resolve2 (ch->t->peer->id)),
3358               ch->id);
3359
3360   if (NULL != ch->owner)
3361     send_local_channel_destroy (ch, GNUNET_NO);
3362   else
3363     send_prebuilt_message_channel (&msg.header, ch, GNUNET_NO);
3364
3365   if (NULL != ch->client)
3366     send_local_channel_destroy (ch, GNUNET_YES);
3367   else
3368     send_prebuilt_message_channel (&msg.header, ch, GNUNET_YES);
3369 }
3370
3371
3372 /**
3373  * Create a tunnel.
3374  *
3375  * @param tid Tunnel ID.
3376  */
3377 static struct MeshTunnel2 *
3378 tunnel_new (struct GNUNET_HashCode *tid)
3379 {
3380   struct MeshTunnel2 *t;
3381
3382   t = GNUNET_new (struct MeshTunnel2);
3383   t->id = *tid;
3384   if (GNUNET_OK !=
3385       GNUNET_CONTAINER_multihashmap_put (tunnels, tid, t,
3386                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
3387   {
3388     GNUNET_break (0);
3389     tunnel_destroy (t);
3390     return NULL;
3391   }
3392
3393   return t;
3394 }
3395
3396
3397 /**
3398  * Find a tunnel.
3399  *
3400  * @param tid Tunnel ID.
3401  */
3402 static struct MeshTunnel2 *
3403 tunnel_get (struct GNUNET_HashCode *tid)
3404 {
3405   return GNUNET_CONTAINER_multihashmap_get (tunnels, tid);
3406 }
3407
3408
3409 /**
3410  * Add a connection to a tunnel.
3411  *
3412  * @param t Tunnel.
3413  * @param c Connection.
3414  */
3415 static void
3416 tunnel_add_connection (struct MeshTunnel2 *t, struct MeshConnection *c)
3417 {
3418   c->t = t;
3419   GNUNET_CONTAINER_DLL_insert_tail (t->connection_head, t->connection_tail, c);
3420 }
3421
3422
3423 /**
3424  * Create a connection.
3425  *
3426  * @param tid Tunnel ID.
3427  * @param cid Connection ID.
3428  */
3429 static struct MeshConnection *
3430 connection_new (struct GNUNET_HashCode *tid, uint32_t cid)
3431 {
3432   struct MeshConnection *c;
3433   struct MeshTunnel2 *t;
3434
3435   t = tunnel_get (tid);
3436   if (NULL == t)
3437   {
3438     t = tunnel_new (tid);
3439     if (NULL == t)
3440     {
3441       GNUNET_break (0);
3442       return NULL;
3443     }
3444   }
3445
3446   c = GNUNET_new (struct MeshConnection);
3447   c->id = cid;
3448   tunnel_add_connection (t, c);
3449
3450   return c;
3451 }
3452
3453
3454 /**
3455  * Find a connection.
3456  *
3457  * @param tid Tunnel ID.
3458  * @param cid Connection ID.
3459  */
3460 static struct MeshConnection *
3461 connection_get (struct GNUNET_HashCode *tid, uint32_t cid)
3462 {
3463   struct MeshConnection *c;
3464   struct MeshTunnel2 *t;
3465
3466   t = tunnel_get (tid);
3467   for (c = t->connection_head; NULL != c; c = c->next)
3468     if (c->id == cid)
3469       return c;
3470
3471   return NULL;
3472 }
3473
3474
3475 /**
3476  * Connection is no longer needed: destroy it and remove from tunnel.
3477  *
3478  * @param c Connection to destroy.
3479  */
3480 static void
3481 connection_destroy (struct MeshConnection *c)
3482 {
3483   struct MeshPeer *peer;
3484
3485   if (NULL == c)
3486     return;
3487
3488   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "destroying connection %s[%X]\n",
3489               GNUNET_i2s (GNUNET_PEER_resolve2 (c->t->peer->id)),
3490               c->id);
3491
3492   peer = connection_get_next_hop (c);
3493   if (NULL != peer)
3494     peer_cancel_queues (peer, c);
3495   peer = connection_get_prev_hop (c);
3496   if (NULL != peer)
3497     peer_cancel_queues (peer, c);
3498
3499   if (GNUNET_SCHEDULER_NO_TASK != c->fwd_maintenance_task)
3500     GNUNET_SCHEDULER_cancel (c->fwd_maintenance_task);
3501   if (GNUNET_SCHEDULER_NO_TASK != c->bck_maintenance_task)
3502     GNUNET_SCHEDULER_cancel (c->bck_maintenance_task);
3503
3504   GNUNET_CONTAINER_DLL_remove (c->t->connection_head, c->t->connection_tail, c);
3505
3506   GNUNET_STATISTICS_update (stats, "# connections", -1, GNUNET_NO);
3507   GNUNET_free (c);
3508 }
3509
3510
3511 static void
3512 tunnel_destroy (struct MeshTunnel2 *t)
3513 {
3514   struct MeshConnection *c;
3515   struct MeshConnection *next;
3516
3517   if (NULL == t)
3518     return;
3519
3520   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s\n",
3521               GNUNET_i2s (GNUNET_PEER_resolve2 (c->t->peer->id)));
3522
3523   if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_remove (tunnels, &t->id, t))
3524     GNUNET_break (0);
3525
3526   for (c = t->connection_head; NULL != c; c = next)
3527   {
3528     next = c->next;
3529     connection_destroy (c);
3530   }
3531
3532   GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
3533
3534   GNUNET_free (t);
3535 }
3536
3537
3538 /**
3539  * Tunnel is empty: destroy it.
3540  *
3541  * Notifies all connections about the destruction.
3542  *
3543  * @param t Tunnel to destroy. 
3544  */
3545 static void
3546 tunnel_destroy_empty (struct MeshTunnel2 *t)
3547 {
3548   struct MeshConnection *c;
3549
3550   for (c = t->connection_head; NULL != c; c = c->next)
3551   {
3552     if (GNUNET_NO == c->destroy)
3553       connection_send_destroy (c);
3554   }
3555
3556   if (0 == t->pending_messages)
3557     tunnel_destroy (t);
3558   else
3559     t->destroy = GNUNET_YES;
3560 }
3561
3562
3563 /**
3564  * Destroy tunnel if empty (no more channels).
3565  *
3566  * @param t Tunnel to destroy if empty.
3567  */
3568 static void
3569 tunnel_destroy_if_empty (struct MeshTunnel2 *t)
3570 {
3571   if (NULL != t->channel_head)
3572     return;
3573
3574   tunnel_destroy_empty (t);
3575 }
3576
3577
3578 /**
3579  * Initialize a Flow Control structure to the initial state.
3580  * 
3581  * @param fc Flow Control structure to initialize.
3582  */
3583 static void
3584 fc_init (struct MeshFlowControl *fc)
3585 {
3586   fc->last_pid_sent = (uint32_t) -1; /* Next (expected) = 0 */
3587   fc->last_pid_recv = (uint32_t) -1;
3588   fc->last_ack_sent = (uint32_t) -1; /* No traffic allowed yet */
3589   fc->last_ack_recv = (uint32_t) -1;
3590   fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
3591   fc->poll_time = GNUNET_TIME_UNIT_SECONDS;
3592   fc->queue_n = 0;
3593 }
3594
3595
3596 /**
3597  * Destroy a channel and free all resources.
3598  * 
3599  * @param ch Channel to destroy.
3600  */
3601 static void
3602 channel_destroy (struct MeshChannel *ch)
3603 {
3604   struct MeshClient *c;
3605
3606   if (NULL == ch)
3607     return;
3608
3609   c = ch->owner;
3610   if (NULL != c)
3611   {
3612     if (GNUNET_YES != GNUNET_CONTAINER_multihashmap32_remove (c->own_channels,
3613                                                               c->id, ch))
3614     {
3615       GNUNET_break (0);
3616     }
3617   }
3618
3619   c = ch->client;
3620   if (NULL != c)
3621   {
3622     if (GNUNET_YES !=
3623         GNUNET_CONTAINER_multihashmap32_remove (c->incoming_channels,
3624                                                 ch->id_dest, ch))
3625     {
3626       GNUNET_break (0);
3627     }
3628   }
3629
3630   if (GNUNET_YES == ch->reliable)
3631   {
3632     channel_rel_free_all (ch->fwd_rel);
3633     channel_rel_free_all (ch->bck_rel);
3634   }
3635
3636   GNUNET_CONTAINER_DLL_remove (ch->t->channel_head, ch->t->channel_tail, ch);
3637   GNUNET_STATISTICS_update (stats, "# channels", -1, GNUNET_NO);
3638
3639   GNUNET_free (ch);
3640 }
3641
3642 /**
3643  * Create a new channel.
3644  * 
3645  * @param owner Clients that owns the channel, NULL for foreign channels.
3646  * @param id Channel Number for the channel, for the owner point of view.
3647  * 
3648  * @return A new initialized channel. NULL on error.
3649  */
3650 static struct MeshChannel *
3651 channel_new (struct MeshClient *owner,
3652              MESH_ChannelNumber id)
3653 {
3654   struct MeshChannel *ch;
3655
3656   if (NULL == owner)
3657     return NULL;
3658
3659   ch = GNUNET_new (struct MeshChannel);
3660   ch->owner = owner;
3661   ch->id = id;
3662
3663   GNUNET_STATISTICS_update (stats, "# channels", 1, GNUNET_NO);
3664
3665   if (GNUNET_OK !=
3666       GNUNET_CONTAINER_multihashmap32_put (owner->own_channels, id, ch,
3667                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
3668   {
3669     GNUNET_break (0);
3670     channel_destroy (ch);
3671     GNUNET_SERVER_receive_done (owner->handle, GNUNET_SYSERR);
3672     return NULL;
3673   }
3674
3675   return ch;
3676 }
3677
3678
3679 /**
3680  * Set options in a channel, extracted from a bit flag field
3681  * 
3682  * @param ch Channel to set options to.
3683  * @param options Bit array in host byte order.
3684  */
3685 static void
3686 channel_set_options (struct MeshChannel *ch, uint32_t options)
3687 {
3688   ch->nobuffer = (options & GNUNET_MESH_OPTION_NOBUFFER) != 0 ?
3689                  GNUNET_YES : GNUNET_NO;
3690   ch->reliable = (options & GNUNET_MESH_OPTION_RELIABLE) != 0 ?
3691                  GNUNET_YES : GNUNET_NO;
3692 }
3693
3694
3695 /**
3696  * Iterator for deleting each channel whose client endpoint disconnected.
3697  *
3698  * @param cls Closure (client that has disconnected).
3699  * @param key The local channel id (used to access the hashmap).
3700  * @param value The value stored at the key (channel to destroy).
3701  *
3702  * @return GNUNET_OK, keep iterating.
3703  */
3704 static int
3705 channel_destroy_iterator (void *cls,
3706                           uint32_t key,
3707                           void *value)
3708 {
3709   struct MeshChannel *ch = value;
3710   struct MeshClient *c = cls;
3711   struct MeshTunnel2 *t;
3712
3713   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3714               " Channel %X / %X destroy, due to client %u shutdown.\n",
3715               ch->id, ch->id_dest, c->id);
3716
3717   if (c == ch->client)
3718   {
3719     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Client %u is destination.\n", c->id);
3720     ch->client = NULL;
3721   }
3722   if (c == ch->owner)
3723   {
3724     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Client %u is owner.\n", c->id);
3725     ch->owner = NULL;
3726   }
3727
3728   t = ch->t;
3729   channel_send_destroy (ch);
3730   channel_destroy (ch);
3731   tunnel_destroy_if_empty (t);
3732
3733   return GNUNET_OK;
3734 }
3735
3736
3737 /**
3738  * Remove client's ports from the global hashmap on disconnect.
3739  *
3740  * @param cls Closure (unused).
3741  * @param key Port.
3742  * @param value Client structure.
3743  *
3744  * @return GNUNET_OK, keep iterating.
3745  */
3746 static int
3747 client_release_ports (void *cls,
3748                       uint32_t key,
3749                       void *value)
3750 {
3751   int res;
3752
3753   res = GNUNET_CONTAINER_multihashmap32_remove (ports, key, value);
3754   if (GNUNET_YES != res)
3755   {
3756     GNUNET_break (0);
3757     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3758                 "Port %u by client %p was not registered.\n",
3759                 key, value);
3760   }
3761   return GNUNET_OK;
3762 }
3763
3764
3765 /**
3766  * Timeout function due to lack of keepalive/traffic from the owner.
3767  * Destroys connection if called.
3768  *
3769  * @param cls Closure (connection to destroy).
3770  * @param tc TaskContext.
3771  */
3772 static void
3773 connection_fwd_timeout (void *cls,
3774                         const struct GNUNET_SCHEDULER_TaskContext *tc)
3775 {
3776   struct MeshConnection *c = cls;
3777
3778   c->fwd_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
3779   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
3780     return;
3781   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3782               "Connection %s[%X] FWD timed out. Destroying.\n",
3783               GNUNET_i2s(GNUNET_PEER_resolve2 (c->t->peer->id)),
3784               c->id);
3785
3786   if (NULL != c->t->channel_head) /* If local, leave TODO review */
3787     return;
3788
3789   connection_destroy (c);
3790 }
3791
3792
3793 /**
3794  * Timeout function due to lack of keepalive/traffic from the destination.
3795  * Destroys connection if called.
3796  *
3797  * @param cls Closure (connection to destroy).
3798  * @param tc TaskContext
3799  */
3800 static void
3801 connection_bck_timeout (void *cls,
3802                         const struct GNUNET_SCHEDULER_TaskContext *tc)
3803 {
3804   struct MeshConnection *c = cls;
3805
3806   c->bck_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
3807   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
3808     return;
3809
3810   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3811               "Connection %s[%X] FWD timed out. Destroying.\n",
3812               GNUNET_i2s(GNUNET_PEER_resolve2 (c->t->peer->id)),
3813               c->id);
3814
3815   if (NULL != c->t->channel_head) /* If local, leave TODO review */
3816     return;
3817
3818   connection_destroy (c);
3819 }
3820
3821
3822 /**
3823  * Resets the connection timeout task, some other message has done the
3824  * task's job.
3825  * - For the first peer on the direction this means to send
3826  *   a keepalive or a path confirmation message (either create or ACK).
3827  * - For all other peers, this means to destroy the connection,
3828  *   due to lack of activity.
3829  * Starts the tiemout if no timeout was running (connection just created).
3830  *
3831  * @param c Connection whose timeout to reset.
3832  * @param fwd Is this forward?
3833  *
3834  * TODO use heap to improve efficiency of scheduler.
3835  */
3836 static void
3837 connection_reset_timeout (struct MeshConnection *c, int fwd)
3838 {
3839   GNUNET_SCHEDULER_TaskIdentifier *ti;
3840   GNUNET_SCHEDULER_Task f;
3841
3842   ti = fwd ? &c->fwd_maintenance_task : &c->bck_maintenance_task;
3843
3844   if (GNUNET_SCHEDULER_NO_TASK != *ti)
3845     GNUNET_SCHEDULER_cancel (*ti);
3846
3847   if (NULL != c->t->channel_head) /* Endpoint */
3848   {
3849     f  = fwd ? &connection_fwd_keepalive : &connection_bck_keepalive;
3850     *ti = GNUNET_SCHEDULER_add_delayed (refresh_connection_time, f, c);
3851   }
3852   else /* Relay */
3853   {
3854     struct GNUNET_TIME_Relative delay;
3855
3856     delay = GNUNET_TIME_relative_multiply (refresh_connection_time, 4);
3857     f  = fwd ? &connection_fwd_timeout : &connection_bck_timeout;
3858     *ti = GNUNET_SCHEDULER_add_delayed (delay, f, c);
3859   }
3860 }
3861
3862
3863 /******************************************************************************/
3864 /****************      MESH NETWORK HANDLER HELPERS     ***********************/
3865 /******************************************************************************/
3866
3867 /**
3868  * Free a transmission that was already queued with all resources
3869  * associated to the request.
3870  *
3871  * @param queue Queue handler to cancel.
3872  * @param clear_cls Is it necessary to free associated cls?
3873  */
3874 static void
3875 queue_destroy (struct MeshPeerQueue *queue, int clear_cls)
3876 {
3877   struct MeshFlowControl *fc;
3878
3879   fc = queue->peer->fc;
3880   if (GNUNET_YES == clear_cls)
3881   {
3882     switch (queue->type)
3883     {
3884       case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_DESTROY:
3885         GNUNET_log (GNUNET_ERROR_TYPE_INFO, "destroying CONNECTION_DESTROY\n");
3886         GNUNET_break (GNUNET_YES == queue->c->destroy);
3887         /* fall through */
3888       case GNUNET_MESSAGE_TYPE_MESH_FWD:
3889       case GNUNET_MESSAGE_TYPE_MESH_BCK:
3890       case GNUNET_MESSAGE_TYPE_MESH_ACK:
3891       case GNUNET_MESSAGE_TYPE_MESH_POLL:
3892       case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK:
3893         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   prebuilt message\n");
3894         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   type %s\n",
3895                     GNUNET_MESH_DEBUG_M2S (queue->type));
3896         break;
3897
3898       case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE:
3899         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   type create path\n");
3900         break;
3901
3902       default:
3903         GNUNET_break (0);
3904         GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "   type %s unknown!\n",
3905                     GNUNET_MESH_DEBUG_M2S (queue->type));
3906     }
3907     GNUNET_free_non_null (queue->cls);
3908   }
3909   GNUNET_CONTAINER_DLL_remove (fc->queue_head, fc->queue_tail, queue);
3910
3911   fc->queue_n--;
3912
3913   GNUNET_free (queue);
3914 }
3915
3916 static size_t
3917 queue_send (void *cls, size_t size, void *buf)
3918 {
3919   struct MeshPeer *peer = cls;
3920   const struct GNUNET_PeerIdentity *dst_id;
3921   struct GNUNET_MessageHeader *msg;
3922   struct MeshPeerQueue *queue;
3923   struct MeshTunnel2 *t;
3924   struct MeshFlowControl *fc;
3925   struct MeshConnection *c;
3926   size_t data_size;
3927   uint32_t pid;
3928   uint16_t type;
3929   int fwd;
3930
3931   fc = peer->fc;
3932   if (NULL == fc)
3933   {
3934     GNUNET_break (0);
3935     return 0;
3936   }
3937   fc->core_transmit = NULL;
3938
3939   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* Queue send\n");
3940
3941   if (NULL == buf || 0 == size)
3942   {
3943     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "* Buffer size 0.\n");
3944     return 0;
3945   }
3946   queue = fc->queue_head;
3947
3948   /* Queue has no traffic */
3949   if (NULL == queue)
3950   {
3951     GNUNET_break (0); /* Core tmt_rdy should've been canceled */
3952     return 0;
3953   }
3954
3955   dst_id = GNUNET_PEER_resolve2 (peer->id);
3956   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*   towards %s\n", GNUNET_i2s (dst_id));
3957   /* Check if buffer size is enough for the message */
3958   if (queue->size > size)
3959   {
3960       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*   not enough room, reissue\n");
3961       fc->core_transmit =
3962           GNUNET_CORE_notify_transmit_ready (core_handle,
3963                                              GNUNET_NO,
3964                                              0,
3965                                              GNUNET_TIME_UNIT_FOREVER_REL,
3966                                              dst_id,
3967                                              queue->size,
3968                                              &queue_send,
3969                                              peer);
3970       return 0;
3971   }
3972   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*   size ok\n");
3973
3974   c = queue->c;
3975   t = (NULL != c) ? c->t : NULL;
3976   type = 0;
3977
3978   /* Fill buf */
3979   switch (queue->type)
3980   {
3981     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_DESTROY:
3982     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN:
3983     case GNUNET_MESSAGE_TYPE_MESH_FWD:
3984     case GNUNET_MESSAGE_TYPE_MESH_BCK:
3985     case GNUNET_MESSAGE_TYPE_MESH_ACK:
3986     case GNUNET_MESSAGE_TYPE_MESH_POLL:
3987       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3988                   "*   raw: %s\n",
3989                   GNUNET_MESH_DEBUG_M2S (queue->type));
3990       /* Fall through */
3991     case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
3992     case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
3993       data_size = send_core_data_raw (queue->cls, size, buf);
3994       msg = (struct GNUNET_MessageHeader *) buf;
3995       type = ntohs (msg->type);
3996       break;
3997     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE:
3998       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*   path create\n");
3999       if (NULL != c->t->channel_head)
4000         data_size = send_core_connection_create (queue->cls, size, buf);
4001       else
4002         data_size = send_core_data_raw (queue->cls, size, buf);
4003       break;
4004     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK:
4005       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*   path ack\n");
4006       if (NULL != c->t->channel_head)
4007         data_size = send_core_connection_ack (queue->cls, size, buf);
4008       else
4009         data_size = send_core_data_raw (queue->cls, size, buf);
4010       break;
4011     default:
4012       GNUNET_break (0);
4013       GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "*   type unknown: %u\n",
4014                   queue->type);
4015       data_size = 0;
4016   }
4017
4018   fc->queue_n--;
4019
4020   if (0 < drop_percent &&
4021       GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, 101) < drop_percent)
4022   {
4023     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4024                 "Dropping message of type %s\n",
4025                 GNUNET_MESH_DEBUG_M2S (queue->type));
4026     data_size = 0;
4027   }
4028   /* Free queue, but cls was freed by send_core_* */
4029   queue_destroy (queue, GNUNET_NO);
4030
4031   /* Send ACK if needed, after accounting for sent ID in fc->queue_n */
4032   fwd = GNUNET_NO;
4033   switch (type)
4034   {
4035     case GNUNET_MESSAGE_TYPE_MESH_FWD:
4036       fwd = GNUNET_YES;
4037       /* fall through */
4038     case GNUNET_MESSAGE_TYPE_MESH_BCK:
4039       pid = ntohl ( ((struct GNUNET_MESH_Encrypted *) buf)->pid );
4040       fc->last_pid_sent = pid;
4041       connection_send_ack (c, fwd);
4042       break;
4043     default:
4044       break;
4045   }
4046
4047   /* If more data in queue, send next */
4048   queue = fc->queue_head;
4049   if (NULL != queue)
4050   {
4051     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*   more data!\n");
4052     if (NULL == fc->core_transmit) {
4053       peer->fc->core_transmit =
4054           GNUNET_CORE_notify_transmit_ready(core_handle,
4055                                             0,
4056                                             0,
4057                                             GNUNET_TIME_UNIT_FOREVER_REL,
4058                                             dst_id,
4059                                             queue->size,
4060                                             &queue_send,
4061                                             peer);
4062     }
4063     else
4064     {
4065       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4066                   "*   tmt rdy called somewhere else\n");
4067     }
4068     if (GNUNET_SCHEDULER_NO_TASK == fc->poll_task)
4069     {
4070       GNUNET_log (GNUNET_ERROR_TYPE_INFO, "*   %s starting poll timeout\n");
4071       fc->poll_task =
4072           GNUNET_SCHEDULER_add_delayed (fc->poll_time, &peer_poll, fc);
4073     }
4074   }
4075   else
4076   {
4077     if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task)
4078     {
4079       GNUNET_SCHEDULER_cancel (fc->poll_task);
4080       fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
4081     }
4082   }
4083   if (NULL != c)
4084   {
4085     c->pending_messages--;
4086     if (GNUNET_YES == c->destroy && 0 == c->pending_messages)
4087     {
4088       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*  destroying connection!\n");
4089       connection_destroy (c);
4090     }
4091   }
4092
4093   if (NULL != t)
4094   {
4095     t->pending_messages--;
4096     if (GNUNET_YES == t->destroy && 0 == t->pending_messages)
4097     {
4098       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*  destroying tunnel!\n");
4099       tunnel_destroy (t);
4100     }
4101   }
4102   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*  Return %d\n", data_size);
4103   return data_size;
4104 }
4105
4106
4107 static void
4108 queue_add (void *cls, uint16_t type, size_t size,
4109            struct MeshPeer *dst,
4110            struct MeshConnection *c,
4111            struct MeshChannel *ch)
4112 {
4113   struct MeshPeerQueue *queue;
4114   struct MeshFlowControl *fc;
4115   int priority;
4116
4117   fc = dst->fc;
4118   if (NULL == fc)
4119   {
4120     GNUNET_break (0);
4121     return;
4122   }
4123
4124   priority = 0;
4125
4126   if (GNUNET_MESSAGE_TYPE_MESH_POLL == type ||
4127       GNUNET_MESSAGE_TYPE_MESH_ACK == type)
4128     priority = 100;
4129
4130   if (NULL != ch &&
4131       ( (NULL != ch->owner && GNUNET_MESSAGE_TYPE_MESH_FWD == type) ||
4132         (NULL != ch->client && GNUNET_MESSAGE_TYPE_MESH_BCK == type) ))
4133     priority = 50;
4134
4135   if (fc->queue_n >= fc->queue_max && 0 == priority)
4136   {
4137     GNUNET_STATISTICS_update (stats, "# messages dropped (buffer full)",
4138                               1, GNUNET_NO);
4139     GNUNET_break (0);
4140     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4141                 "queue full: %u/%u\n",
4142                 fc->queue_n, fc->queue_max);
4143     return; /* Drop this message */
4144   }
4145
4146   fc->queue_n++;
4147   if (GMC_is_pid_bigger(fc->last_pid_sent + 1, fc->last_ack_recv) &&
4148       GNUNET_SCHEDULER_NO_TASK == fc->poll_task)
4149     fc->poll_task = GNUNET_SCHEDULER_add_delayed (fc->poll_time,
4150                                                   &peer_poll,
4151                                                   dst);
4152   queue = GNUNET_malloc (sizeof (struct MeshPeerQueue));
4153   queue->cls = cls;
4154   queue->type = type;
4155   queue->size = size;
4156   queue->peer = dst;
4157   queue->c = c;
4158   queue->ch = ch;
4159   if (100 <= priority)
4160     GNUNET_CONTAINER_DLL_insert (fc->queue_head, fc->queue_tail, queue);
4161   else
4162     GNUNET_CONTAINER_DLL_insert_tail (fc->queue_head, fc->queue_tail, queue);
4163
4164   if (NULL == fc->core_transmit)
4165   {
4166     fc->core_transmit =
4167         GNUNET_CORE_notify_transmit_ready (core_handle,
4168                                            0,
4169                                            0,
4170                                            GNUNET_TIME_UNIT_FOREVER_REL,
4171                                            GNUNET_PEER_resolve2 (dst->id),
4172                                            size,
4173                                            &queue_send,
4174                                            dst);
4175   }
4176   c->pending_messages++;
4177   c->t->pending_messages++;
4178 }
4179
4180
4181 /******************************************************************************/
4182 /********************      MESH NETWORK HANDLERS     **************************/
4183 /******************************************************************************/
4184
4185
4186 /**
4187  * Core handler for connection creation.
4188  *
4189  * @param cls Closure (unused).
4190  * @param peer Sender (neighbor).
4191  * @param message Message.
4192  *
4193  * @return GNUNET_OK to keep the connection open,
4194  *         GNUNET_SYSERR to close it (signal serious error)
4195  */
4196 static int
4197 handle_mesh_connection_create (void *cls,
4198                                const struct GNUNET_PeerIdentity *peer,
4199                                const struct GNUNET_MessageHeader *message)
4200 {
4201   struct GNUNET_MESH_ConnectionCreate *msg;
4202   struct GNUNET_PeerIdentity *id;
4203   struct GNUNET_HashCode *tid;
4204   struct MeshPeerPath *path;
4205   struct MeshPeer *dest_peer;
4206   struct MeshPeer *orig_peer;
4207   struct MeshConnection *c;
4208   unsigned int own_pos;
4209   uint32_t cid;
4210   uint16_t size;
4211   uint16_t i;
4212
4213   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a connection create msg\n");
4214
4215   /* Check size */
4216   size = ntohs (message->size);
4217   if (size < sizeof (struct GNUNET_MESH_ConnectionCreate))
4218   {
4219     GNUNET_break_op (0);
4220     return GNUNET_OK;
4221   }
4222
4223   /* Calculate hops */
4224   size -= sizeof (struct GNUNET_MESH_ConnectionCreate);
4225   if (size % sizeof (struct GNUNET_PeerIdentity))
4226   {
4227     GNUNET_break_op (0);
4228     return GNUNET_OK;
4229   }
4230   size /= sizeof (struct GNUNET_PeerIdentity);
4231   if (1 > size)
4232   {
4233     GNUNET_break_op (0);
4234     return GNUNET_OK;
4235   }
4236   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
4237
4238   /* Get parameters */
4239   msg = (struct GNUNET_MESH_ConnectionCreate *) message;
4240   cid = ntohl (msg->cid);
4241   tid = &msg->tid;
4242   id = (struct GNUNET_PeerIdentity *) &msg[1];
4243   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4244               "    connection %s[%X] (%s).\n",
4245               GNUNET_h2s (tid), cid, GNUNET_i2s (id));
4246
4247   /* Create connection */
4248   c = connection_get (tid, cid);
4249   if (NULL == c)
4250   {
4251     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating connection\n");
4252     c = connection_new (tid, cid);
4253     if (NULL == c)
4254       return GNUNET_OK;
4255   }
4256   connection_reset_timeout (c, GNUNET_YES);
4257   tunnel_change_state (c->t,  MESH_TUNNEL_WAITING);
4258
4259   /* Remember peers */
4260   dest_peer = peer_get (&id[size - 1]);
4261   orig_peer = peer_get (&id[0]7);
4262
4263   /* Create path */
4264   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
4265   path = path_new (size);
4266   own_pos = 0;
4267   for (i = 0; i < size; i++)
4268   {
4269     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ... adding %s\n",
4270                 GNUNET_i2s (&id[i]));
4271     path->peers[i] = GNUNET_PEER_intern (&id[i]);
4272     if (path->peers[i] == myid)
4273       own_pos = i;
4274   }
4275   if (own_pos == 0 && path->peers[own_pos] != myid)
4276   {
4277     /* create path: self not found in path through self */
4278     GNUNET_break_op (0);
4279     path_destroy (path);
4280     connection_destroy (c);
4281     return GNUNET_OK;
4282   }
4283   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
4284   path_add_to_peers (path, GNUNET_NO);
4285   c->path = path;
4286   c->own_pos = own_pos;
4287
4288   /* Is it a connection to us? */
4289   if (own_pos == size - 1)
4290   {
4291     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
4292     peer_add_path_to_origin (orig_peer, path, GNUNET_YES);
4293
4294     send_connection_ack (c);
4295
4296     /* Keep tunnel alive in direction dest->owner*/
4297     connection_reset_timeout (c, GNUNET_NO); 
4298   }
4299   else
4300   {
4301     /* It's for somebody else! Retransmit. */
4302     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Retransmitting.\n");
4303     peer_add_path (dest_peer, path_duplicate (path), GNUNET_NO);
4304     peer_add_path_to_origin (orig_peer, path, GNUNET_NO);
4305     send_prebuilt_message_connection (message, c, NULL, GNUNET_YES);
4306   }
4307   return GNUNET_OK;
4308 }
4309
4310
4311 /**
4312  * Core handler for path ACKs
4313  *
4314  * @param cls closure
4315  * @param message message
4316  * @param peer peer identity this notification is about
4317  *
4318  * @return GNUNET_OK to keep the connection open,
4319  *         GNUNET_SYSERR to close it (signal serious error)
4320  */
4321 static int
4322 handle_mesh_path_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
4323                       const struct GNUNET_MessageHeader *message)
4324 {
4325   struct GNUNET_MESH_PathACK *msg;
4326   struct MeshPeer *peer_info;
4327   struct MeshPeerPath *p;
4328   struct MeshTunnel *t;
4329
4330   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a path ACK msg [%s]\n",
4331               GNUNET_i2s (&my_full_id));
4332   msg = (struct GNUNET_MESH_PathACK *) message;
4333   t = channel_get (&msg->oid, ntohl(msg->tid));
4334   if (NULL == t)
4335   {
4336     /* TODO notify that we don't know the tunnel */
4337     GNUNET_STATISTICS_update (stats, "# control on unknown tunnel", 1, GNUNET_NO);
4338     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  don't know the tunnel %s [%X]!\n",
4339                 GNUNET_i2s (&msg->oid), ntohl(msg->tid));
4340     return GNUNET_OK;
4341   }
4342   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %s [%X]\n",
4343               GNUNET_i2s (&msg->oid), ntohl(msg->tid));
4344
4345   peer_info = peer_get (&msg->peer_id);
4346   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by peer %s\n",
4347               GNUNET_i2s (&msg->peer_id));
4348   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  via peer %s\n",
4349               GNUNET_i2s (peer));
4350
4351   /* Add path to peers? */
4352   p = t->path;
4353   if (NULL != p)
4354   {
4355     path_add_to_peers (p, GNUNET_YES);
4356   }
4357   else
4358   {
4359     GNUNET_break (0);
4360   }
4361   tunnel_change_state (t, MESH_TUNNEL_READY);
4362   tunnel_reset_timeout (t, GNUNET_NO);
4363   t->next_fc.last_ack_recv = (NULL == t->client) ? ntohl (msg->ack) : 0;
4364   t->prev_fc.last_ack_sent = ntohl (msg->ack);
4365
4366   /* Message for us? */
4367   if (0 == memcmp (&msg->oid, &my_full_id, sizeof (struct GNUNET_PeerIdentity)))
4368   {
4369     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
4370     if (NULL == t->owner)
4371     {
4372       GNUNET_break_op (0);
4373       return GNUNET_OK;
4374     }
4375     if (NULL != peer_info->dhtget)
4376     {
4377       GNUNET_DHT_get_stop (peer_info->dhtget);
4378       peer_info->dhtget = NULL;
4379     }
4380     tunnel_send_ack (t, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK, GNUNET_YES);
4381     tunnel_send_ack (t, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK, GNUNET_NO);
4382     return GNUNET_OK;
4383   }
4384
4385   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4386               "  not for us, retransmitting...\n");
4387   send_prebuilt_message (message, t->prev_hop, t);
4388   return GNUNET_OK;
4389 }
4390
4391
4392 /**
4393  * Core handler for notifications of broken paths
4394  *
4395  * @param cls closure
4396  * @param message message
4397  * @param peer peer identity this notification is about
4398  *
4399  * @return GNUNET_OK to keep the connection open,
4400  *         GNUNET_SYSERR to close it (signal serious error)
4401  */
4402 static int
4403 handle_mesh_path_broken (void *cls, const struct GNUNET_PeerIdentity *peer,
4404                          const struct GNUNET_MessageHeader *message)
4405 {
4406   struct GNUNET_MESH_PathBroken *msg;
4407   struct MeshTunnel *t;
4408
4409   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4410               "Received a PATH BROKEN msg from %s\n", GNUNET_i2s (peer));
4411   msg = (struct GNUNET_MESH_PathBroken *) message;
4412   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
4413               GNUNET_i2s (&msg->peer1));
4414   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
4415               GNUNET_i2s (&msg->peer2));
4416   t = channel_get (&msg->oid, ntohl (msg->tid));
4417   if (NULL == t)
4418   {
4419     GNUNET_break_op (0);
4420     return GNUNET_OK;
4421   }
4422   tunnel_notify_connection_broken (t, GNUNET_PEER_search (&msg->peer1),
4423                                    GNUNET_PEER_search (&msg->peer2));
4424   return GNUNET_OK;
4425
4426 }
4427
4428
4429 /**
4430  * Core handler for tunnel destruction
4431  *
4432  * @param cls closure
4433  * @param message message
4434  * @param peer peer identity this notification is about
4435  *
4436  * @return GNUNET_OK to keep the connection open,
4437  *         GNUNET_SYSERR to close it (signal serious error)
4438  */
4439 static int
4440 handle_mesh_tunnel_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
4441                             const struct GNUNET_MessageHeader *message)
4442 {
4443   struct GNUNET_MESH_TunnelDestroy *msg;
4444   struct MeshTunnel *t;
4445
4446   msg = (struct GNUNET_MESH_TunnelDestroy *) message;
4447   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4448               "Got a TUNNEL DESTROY packet from %s\n",
4449               GNUNET_i2s (peer));
4450   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4451               "  for tunnel %s [%u]\n",
4452               GNUNET_i2s (&msg->oid), ntohl (msg->tid));
4453   t = channel_get (&msg->oid, ntohl (msg->tid));
4454   if (NULL == t)
4455   {
4456     /* Probably already got the message from another path,
4457      * destroyed the tunnel and retransmitted to children.
4458      * Safe to ignore.
4459      */
4460     GNUNET_STATISTICS_update (stats, "# control on unknown tunnel",
4461                               1, GNUNET_NO);
4462     return GNUNET_OK;
4463   }
4464   if (t->local_tid_dest >= GNUNET_MESH_LOCAL_CHANNEL_ID_SERV)
4465   {
4466     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "INCOMING TUNNEL %X %X\n",
4467                 t->local_tid, t->local_tid_dest);
4468   }
4469   if (GNUNET_PEER_search (peer) == t->prev_hop)
4470   {
4471     // TODO check owner's signature
4472     // TODO add owner's signatue to tunnel for retransmission
4473     peer_cancel_queues (t->prev_hop, t);
4474     GNUNET_PEER_change_rc (t->prev_hop, -1);
4475     t->prev_hop = 0;
4476   }
4477   else if (GNUNET_PEER_search (peer) == t->next_hop)
4478   {
4479     // TODO check dest's signature
4480     // TODO add dest's signatue to tunnel for retransmission
4481     peer_cancel_queues (t->next_hop, t);
4482     GNUNET_PEER_change_rc (t->next_hop, -1);
4483     t->next_hop = 0;
4484   }
4485   else
4486   {
4487     GNUNET_break_op (0);
4488     // TODO check both owner AND destination's signature to see which matches
4489     // TODO restransmit in appropriate direction
4490     return GNUNET_OK;
4491   }
4492   tunnel_destroy_empty (t);
4493
4494   // TODO: add timeout to destroy the tunnel anyway
4495   return GNUNET_OK;
4496 }
4497
4498
4499 /**
4500  * Generic handler for mesh network payload traffic.
4501  *
4502  * @param peer Peer identity this notification is about.
4503  * @param message Data message.
4504  * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
4505  *
4506  * @return GNUNET_OK to keep the connection open,
4507  *         GNUNET_SYSERR to close it (signal serious error)
4508  */
4509 static int
4510 handle_mesh_data (const struct GNUNET_PeerIdentity *peer,
4511                   const struct GNUNET_MessageHeader *message,
4512                   int fwd)
4513 {
4514   struct GNUNET_MESH_Data *msg;
4515   struct MeshFlowControl *fc;
4516   struct MeshChannelReliability *rel;
4517   struct MeshTunnel *t;
4518   struct MeshClient *c;
4519   GNUNET_PEER_Id hop;
4520   uint32_t pid;
4521   uint32_t ttl;
4522   uint16_t type;
4523   size_t size;
4524
4525   /* Check size */
4526   size = ntohs (message->size);
4527   if (size <
4528       sizeof (struct GNUNET_MESH_Data) +
4529       sizeof (struct GNUNET_MessageHeader))
4530   {
4531     GNUNET_break (0);
4532     return GNUNET_OK;
4533   }
4534   type =ntohs (message->type);
4535   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a %s message from %s\n",
4536               GNUNET_MESH_DEBUG_M2S (type), GNUNET_i2s (peer));
4537   msg = (struct GNUNET_MESH_Data *) message;
4538   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n",
4539               GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
4540   /* Check tunnel */
4541   t = channel_get (&msg->oid, ntohl (msg->tid));
4542   if (NULL == t)
4543   {
4544     /* TODO notify back: we don't know this tunnel */
4545     GNUNET_STATISTICS_update (stats, "# data on unknown tunnel", 1, GNUNET_NO);
4546     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "WARNING tunnel unknown\n");
4547     return GNUNET_OK;
4548   }
4549
4550   /*  Initialize FWD/BCK data */
4551   pid = ntohl (msg->pid);
4552   fc =  fwd ? &t->prev_fc : &t->next_fc;
4553   c =   fwd ? t->client   : t->owner;
4554   rel = fwd ? t->bck_rel  : t->fwd_rel;
4555   hop = fwd ? t->next_hop : t->prev_hop;
4556   if (GMC_is_pid_bigger (pid, fc->last_ack_sent))
4557   {
4558     GNUNET_STATISTICS_update (stats, "# unsolicited data", 1, GNUNET_NO);
4559     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4560                 "WARNING Received PID %u, (prev %u), ACK %u\n",
4561                 pid, fc->last_pid_recv, fc->last_ack_sent);
4562     return GNUNET_OK;
4563   }
4564   if (NULL != c)
4565     tunnel_change_state (t, MESH_TUNNEL_READY);
4566   tunnel_reset_timeout (t, fwd);
4567   if (NULL != c)
4568   {
4569     /* TODO signature verification */
4570     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  it's for us! sending to client\n");
4571     GNUNET_STATISTICS_update (stats, "# data received", 1, GNUNET_NO);
4572     if (GMC_is_pid_bigger (pid, fc->last_pid_recv))
4573     {
4574       uint32_t mid;
4575
4576       mid = ntohl (msg->mid);
4577       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4578                   " pid %u (mid %u) not seen yet\n", pid, mid);
4579       fc->last_pid_recv = pid;
4580
4581       if (GNUNET_NO == t->reliable ||
4582           ( !GMC_is_pid_bigger (rel->mid_recv, mid) &&
4583             GMC_is_pid_bigger (rel->mid_recv + 64, mid) ) )
4584       {
4585         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4586                     "!!! RECV %u\n", ntohl (msg->mid));
4587         if (GNUNET_YES == t->reliable)
4588         {
4589           /* Is this the exact next expected messasge? */
4590           if (mid == rel->mid_recv)
4591           {
4592             GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "as expected\n");
4593             rel->mid_recv++;
4594             tunnel_send_client_data (t, msg, fwd);
4595             tunnel_send_client_buffered_data (t, c, rel);
4596           }
4597           else
4598           {
4599             GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "save for later\n");
4600             tunnel_add_buffered_data (t, msg, rel);
4601           }
4602         }
4603         else /* Tunnel unreliable, send to clients directly */
4604         {
4605           tunnel_send_client_data (t, msg, fwd);
4606         }
4607       }
4608       else
4609       {
4610         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4611                     " MID %u not expected (%u - %u), dropping!\n",
4612                     ntohl (msg->mid), rel->mid_recv, rel->mid_recv + 64);
4613       }
4614     }
4615     else
4616     {
4617 //       GNUNET_STATISTICS_update (stats, "# duplicate PID", 1, GNUNET_NO);
4618       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4619                   " Pid %u not expected (%u+), dropping!\n",
4620                   pid, fc->last_pid_recv + 1);
4621     }
4622     tunnel_send_ack (t, type, fwd);
4623     return GNUNET_OK;
4624   }
4625   fc->last_pid_recv = pid;
4626   if (0 == hop)
4627   {
4628     GNUNET_STATISTICS_update (stats, "# data on dying tunnel", 1, GNUNET_NO);
4629     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "data on dying tunnel %s[%X]\n",
4630                 GNUNET_PEER_resolve2 (t->id.oid), ntohl (msg->tid));
4631     return GNUNET_OK; /* Next hop has destoyed the tunnel, drop */
4632   }
4633   ttl = ntohl (msg->ttl);
4634   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ttl: %u\n", ttl);
4635   if (ttl == 0)
4636   {
4637     GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
4638     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
4639     tunnel_send_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK, fwd);
4640     return GNUNET_OK;
4641   }
4642
4643   if (myid != hop)
4644   {
4645     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  not for us, retransmitting...\n");
4646     send_prebuilt_message (message, hop, t);
4647     GNUNET_STATISTICS_update (stats, "# unicast forwarded", 1, GNUNET_NO);
4648   }
4649   return GNUNET_OK;
4650 }
4651
4652
4653 /**
4654  * Core handler for mesh network traffic going from the origin to a peer
4655  *
4656  * @param cls Closure (unused).
4657  * @param message Message received.
4658  * @param peer Peer who sent the message.
4659  *
4660  * @return GNUNET_OK to keep the connection open,
4661  *         GNUNET_SYSERR to close it (signal serious error)
4662  */
4663 static int
4664 handle_mesh_unicast (void *cls, const struct GNUNET_PeerIdentity *peer,
4665                      const struct GNUNET_MessageHeader *message)
4666 {
4667   return handle_mesh_data (peer, message, GNUNET_YES);
4668 }
4669
4670 /**
4671  * Core handler for mesh network traffic towards the owner of a tunnel.
4672  *
4673  * @param cls Closure (unused).
4674  * @param message Message received.
4675  * @param peer Peer who sent the message.
4676  *
4677  * @return GNUNET_OK to keep the connection open,
4678  *         GNUNET_SYSERR to close it (signal serious error)
4679  */
4680 static int
4681 handle_mesh_to_orig (void *cls, const struct GNUNET_PeerIdentity *peer,
4682                      const struct GNUNET_MessageHeader *message)
4683 {
4684   return handle_mesh_data (peer, message, GNUNET_NO);
4685 }
4686
4687
4688 /**
4689  * Core handler for mesh network traffic end-to-end ACKs.
4690  *
4691  * @param cls Closure.
4692  * @param message Message.
4693  * @param peer Peer identity this notification is about.
4694  *
4695  * @return GNUNET_OK to keep the connection open,
4696  *         GNUNET_SYSERR to close it (signal serious error)
4697  */
4698 static int
4699 handle_mesh_data_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
4700                       const struct GNUNET_MessageHeader *message)
4701 {
4702   struct GNUNET_MESH_DataACK *msg;
4703   struct MeshChannelReliability *rel;
4704   struct MeshReliableMessage *copy;
4705   struct MeshReliableMessage *next;
4706   struct MeshTunnel *t;
4707   GNUNET_PEER_Id id;
4708   uint32_t ack;
4709   uint16_t type;
4710   int work;
4711
4712   type = ntohs (message->type);
4713   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a %s message from %s!\n",
4714               GNUNET_MESH_DEBUG_M2S (type), GNUNET_i2s (peer));
4715   msg = (struct GNUNET_MESH_DataACK *) message;
4716
4717   t = channel_get (&msg->oid, ntohl (msg->tid));
4718   if (NULL == t)
4719   {
4720     /* TODO notify that we dont know this tunnel (whom)? */
4721     GNUNET_STATISTICS_update (stats, "# ack on unknown tunnel", 1, GNUNET_NO);
4722     return GNUNET_OK;
4723   }
4724   ack = ntohl (msg->mid);
4725   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ACK %u\n", ack);
4726
4727   /* Is this a forward or backward ACK? */
4728   id = GNUNET_PEER_search (peer);
4729   if (t->next_hop == id && GNUNET_MESSAGE_TYPE_MESH_UNICAST_ACK == type)
4730   {
4731     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  FWD ACK\n");
4732     if (NULL == t->owner)
4733     {
4734       send_prebuilt_message (message, t->prev_hop, t);
4735       return GNUNET_OK;
4736     }
4737     rel = t->fwd_rel;
4738   }
4739   else if (t->prev_hop == id && GNUNET_MESSAGE_TYPE_MESH_TO_ORIG_ACK == type)
4740   {
4741     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  BCK ACK\n");
4742     if (NULL == t->client)
4743     {
4744       send_prebuilt_message (message, t->next_hop, t);
4745       return GNUNET_OK;
4746     }
4747     rel = t->bck_rel;
4748   }
4749   else
4750   {
4751     GNUNET_break_op (0);
4752     return GNUNET_OK;
4753   }
4754
4755   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! ACK %u\n", ack);
4756   for (work = GNUNET_NO, copy = rel->head_sent; copy != NULL; copy = next)
4757   {
4758    if (GMC_is_pid_bigger (copy->mid, ack))
4759     {
4760       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!!  head %u, out!\n", copy->mid);
4761       tunnel_free_sent_reliable (t, msg, rel);
4762       break;
4763     }
4764     work = GNUNET_YES;
4765     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!!  id %u\n", copy->mid);
4766     next = copy->next;
4767     tunnel_free_reliable_message (copy);
4768   }
4769   /* Once buffers have been free'd, send ACK */
4770   tunnel_send_ack (t, type, GNUNET_MESSAGE_TYPE_MESH_UNICAST_ACK == type);
4771
4772   /* If some message was free'd, update the retransmission delay*/
4773   if (GNUNET_YES == work)
4774   {
4775     if (GNUNET_SCHEDULER_NO_TASK != rel->retry_task)
4776     {
4777       GNUNET_SCHEDULER_cancel (rel->retry_task);
4778       if (NULL == rel->head_sent)
4779       {
4780         rel->retry_task = GNUNET_SCHEDULER_NO_TASK;
4781       }
4782       else
4783       {
4784         struct GNUNET_TIME_Absolute new_target;
4785         struct GNUNET_TIME_Relative delay;
4786
4787         delay = GNUNET_TIME_relative_multiply (rel->retry_timer,
4788                                                MESH_RETRANSMIT_MARGIN);
4789         new_target = GNUNET_TIME_absolute_add (rel->head_sent->timestamp,
4790                                                delay);
4791         delay = GNUNET_TIME_absolute_get_remaining (new_target);
4792         rel->retry_task =
4793             GNUNET_SCHEDULER_add_delayed (delay,
4794                                           &tunnel_retransmit_message,
4795                                           rel);
4796       }
4797     }
4798     else
4799       GNUNET_break (0);
4800   }
4801   return GNUNET_OK;
4802 }
4803
4804 /**
4805  * Core handler for mesh network traffic point-to-point acks.
4806  *
4807  * @param cls closure
4808  * @param message message
4809  * @param peer peer identity this notification is about
4810  *
4811  * @return GNUNET_OK to keep the connection open,
4812  *         GNUNET_SYSERR to close it (signal serious error)
4813  */
4814 static int
4815 handle_mesh_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
4816                  const struct GNUNET_MessageHeader *message)
4817 {
4818   struct GNUNET_MESH_ACK *msg;
4819   struct MeshTunnel *t;
4820   struct MeshFlowControl *fc;
4821   GNUNET_PEER_Id id;
4822   uint32_t ack;
4823
4824   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got an ACK packet from %s!\n",
4825               GNUNET_i2s (peer));
4826   msg = (struct GNUNET_MESH_ACK *) message;
4827
4828   t = channel_get (&msg->oid, ntohl (msg->tid));
4829
4830   if (NULL == t)
4831   {
4832     /* TODO notify that we dont know this tunnel (whom)? */
4833     GNUNET_STATISTICS_update (stats, "# ack on unknown tunnel", 1, GNUNET_NO);
4834     return GNUNET_OK;
4835   }
4836   ack = ntohl (msg->pid);
4837   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ACK %u\n", ack);
4838
4839   /* Is this a forward or backward ACK? */
4840   id = GNUNET_PEER_search (peer);
4841   if (t->next_hop == id)
4842   {
4843     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  FWD ACK\n");
4844     fc = &t->next_fc;
4845   }
4846   else if (t->prev_hop == id)
4847   {
4848     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  BCK ACK\n");
4849     fc = &t->prev_fc;
4850   }
4851   else
4852   {
4853     GNUNET_break_op (0);
4854     return GNUNET_OK;
4855   }
4856
4857   if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task &&
4858       GMC_is_pid_bigger (ack, fc->last_ack_recv))
4859   {
4860     GNUNET_SCHEDULER_cancel (fc->poll_task);
4861     fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
4862     fc->poll_time = GNUNET_TIME_UNIT_SECONDS;
4863   }
4864
4865   fc->last_ack_recv = ack;
4866   peer_unlock_queue (id);
4867   tunnel_change_state (t, MESH_TUNNEL_READY);
4868
4869   tunnel_send_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK, t->next_hop == id);
4870
4871   return GNUNET_OK;
4872 }
4873
4874
4875 /**
4876  * Core handler for mesh network traffic point-to-point ack polls.
4877  *
4878  * @param cls closure
4879  * @param message message
4880  * @param peer peer identity this notification is about
4881  *
4882  * @return GNUNET_OK to keep the connection open,
4883  *         GNUNET_SYSERR to close it (signal serious error)
4884  */
4885 static int
4886 handle_mesh_poll (void *cls, const struct GNUNET_PeerIdentity *peer,
4887                   const struct GNUNET_MessageHeader *message)
4888 {
4889   struct GNUNET_MESH_Poll *msg;
4890   struct MeshTunnel *t;
4891   struct MeshFlowControl *fc;
4892   GNUNET_PEER_Id id;
4893   uint32_t pid;
4894   uint32_t old;
4895
4896   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a POLL packet from %s!\n",
4897               GNUNET_i2s (peer));
4898
4899   msg = (struct GNUNET_MESH_Poll *) message;
4900
4901   t = channel_get (&msg->oid, ntohl (msg->tid));
4902
4903   if (NULL == t)
4904   {
4905     /* TODO notify that we dont know this tunnel (whom)? */
4906     GNUNET_STATISTICS_update (stats, "# poll on unknown tunnel", 1, GNUNET_NO);
4907     GNUNET_break_op (0);
4908     return GNUNET_OK;
4909   }
4910
4911   /* Is this a forward or backward ACK? */
4912   id = GNUNET_PEER_search (peer);
4913   pid = ntohl (msg->pid);
4914   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  PID %u\n", pid);
4915   if (t->next_hop == id)
4916   {
4917     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  from FWD\n");
4918     fc = &t->next_fc;
4919     old = fc->last_pid_recv;
4920   }
4921   else if (t->prev_hop == id)
4922   {
4923     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  from BCK\n");
4924     fc = &t->prev_fc;
4925     old = fc->last_pid_recv;
4926   }
4927   else
4928   {
4929     GNUNET_break (0);
4930     return GNUNET_OK;
4931   }
4932
4933   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  was %u\n", fc->last_pid_recv);
4934   fc->last_pid_recv = pid;
4935   tunnel_send_ack (t, GNUNET_MESSAGE_TYPE_MESH_POLL, t->prev_hop == id);
4936
4937   if (GNUNET_YES == t->reliable)
4938     fc->last_pid_recv = old;
4939
4940   return GNUNET_OK;
4941 }
4942
4943
4944 /**
4945  * Core handler for mesh keepalives.
4946  *
4947  * @param cls closure
4948  * @param message message
4949  * @param peer peer identity this notification is about
4950  * @return GNUNET_OK to keep the connection open,
4951  *         GNUNET_SYSERR to close it (signal serious error)
4952  *
4953  * TODO: Check who we got this from, to validate route.
4954  */
4955 static int
4956 handle_mesh_keepalive (void *cls, const struct GNUNET_PeerIdentity *peer,
4957                        const struct GNUNET_MessageHeader *message)
4958 {
4959   struct GNUNET_MESH_TunnelKeepAlive *msg;
4960   struct MeshTunnel *t;
4961   struct MeshClient *c;
4962   GNUNET_PEER_Id hop;
4963   int fwd;
4964
4965   msg = (struct GNUNET_MESH_TunnelKeepAlive *) message;
4966   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a keepalive packet from %s\n",
4967               GNUNET_i2s (peer));
4968
4969   t = channel_get (&msg->oid, ntohl (msg->tid));
4970   if (NULL == t)
4971   {
4972     /* TODO notify that we dont know that tunnel */
4973     GNUNET_STATISTICS_update (stats, "# keepalive on unknown tunnel", 1,
4974                               GNUNET_NO);
4975     return GNUNET_OK;
4976   }
4977
4978   fwd = GNUNET_MESSAGE_TYPE_MESH_FWD_KEEPALIVE == ntohs (message->type) ? 
4979         GNUNET_YES : GNUNET_NO;
4980   c   = fwd ? t->client   : t->owner;
4981   hop = fwd ? t->next_hop : t->prev_hop;
4982
4983   if (NULL != c)
4984     tunnel_change_state (t, MESH_TUNNEL_READY);
4985   tunnel_reset_timeout (t, fwd);
4986   if (NULL != c || 0 == hop || myid == hop)
4987     return GNUNET_OK;
4988
4989   GNUNET_STATISTICS_update (stats, "# keepalives forwarded", 1, GNUNET_NO);
4990   send_prebuilt_message (message, hop, t);
4991   return GNUNET_OK;
4992   }
4993
4994
4995
4996 /**
4997  * Functions to handle messages from core
4998  */
4999 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
5000   {&handle_mesh_connection_create, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE, 0},
5001   {&handle_mesh_path_broken, GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN,
5002    sizeof (struct GNUNET_MESH_PathBroken)},
5003   {&handle_mesh_tunnel_destroy, GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY,
5004    sizeof (struct GNUNET_MESH_TunnelDestroy)},
5005   {&handle_mesh_unicast, GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
5006   {&handle_mesh_to_orig, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
5007   {&handle_mesh_data_ack, GNUNET_MESSAGE_TYPE_MESH_UNICAST_ACK,
5008     sizeof (struct GNUNET_MESH_DataACK)},
5009   {&handle_mesh_data_ack, GNUNET_MESSAGE_TYPE_MESH_TO_ORIG_ACK,
5010     sizeof (struct GNUNET_MESH_DataACK)},
5011   {&handle_mesh_keepalive, GNUNET_MESSAGE_TYPE_MESH_FWD_KEEPALIVE,
5012     sizeof (struct GNUNET_MESH_TunnelKeepAlive)},
5013   {&handle_mesh_keepalive, GNUNET_MESSAGE_TYPE_MESH_BCK_KEEPALIVE,
5014     sizeof (struct GNUNET_MESH_TunnelKeepAlive)},
5015   {&handle_mesh_ack, GNUNET_MESSAGE_TYPE_MESH_ACK,
5016     sizeof (struct GNUNET_MESH_ACK)},
5017   {&handle_mesh_poll, GNUNET_MESSAGE_TYPE_MESH_POLL,
5018     sizeof (struct GNUNET_MESH_Poll)},
5019   {&handle_mesh_path_ack, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK,
5020    sizeof (struct GNUNET_MESH_PathACK)},
5021   {NULL, 0, 0}
5022 };
5023
5024
5025 /**
5026  * Function to process paths received for a new peer addition. The recorded
5027  * paths form the initial tunnel, which can be optimized later.
5028  * Called on each result obtained for the DHT search.
5029  *
5030  * @param cls closure
5031  * @param exp when will this value expire
5032  * @param key key of the result
5033  * @param get_path path of the get request
5034  * @param get_path_length lenght of get_path
5035  * @param put_path path of the put request
5036  * @param put_path_length length of the put_path
5037  * @param type type of the result
5038  * @param size number of bytes in data
5039  * @param data pointer to the result data
5040  */
5041 static void
5042 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
5043                     const struct GNUNET_HashCode * key,
5044                     const struct GNUNET_PeerIdentity *get_path,
5045                     unsigned int get_path_length,
5046                     const struct GNUNET_PeerIdentity *put_path,
5047                     unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
5048                     size_t size, const void *data)
5049 {
5050   struct MeshPeer *peer = cls;
5051   struct MeshPeerPath *p;
5052   struct MeshConnection *c;
5053   struct GNUNET_PeerIdentity pi;
5054   int i;
5055
5056   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got results from DHT!\n");
5057   GNUNET_PEER_resolve (peer->id, &pi);
5058   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for %s\n", GNUNET_i2s (&pi));
5059
5060   p = path_build_from_dht (get_path, get_path_length,
5061                            put_path, put_path_length);
5062   path_add_to_peers (p, GNUNET_NO);
5063   path_destroy (p);
5064
5065   /* Count connections */
5066   for (c = peer->tunnel->connection_head, i = 0; NULL != c; c = c->next, i++);
5067
5068   /* If we already have 3 (or more (?!)) connections, it's enough */
5069   if (3 <= i)
5070     return;
5071
5072   if (peer->tunnel->state == MESH_TUNNEL_SEARCHING)
5073   {
5074     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ... connect!\n");
5075     peer_connect (peer);
5076   }
5077   return;
5078 }
5079
5080
5081 /******************************************************************************/
5082 /*********************       MESH LOCAL HANDLES      **************************/
5083 /******************************************************************************/
5084
5085
5086 /**
5087  * Handler for client connection.
5088  *
5089  * @param cls Closure (unused).
5090  * @param client Client handler.
5091  */
5092 static void
5093 handle_local_client_connect (void *cls, struct GNUNET_SERVER_Client *client)
5094 {
5095   struct MeshClient *c;
5096
5097   if (NULL == client)
5098     return;
5099   c = GNUNET_malloc (sizeof (struct MeshClient));
5100   c->handle = client;
5101   GNUNET_SERVER_client_keep (client);
5102   GNUNET_SERVER_client_set_user_context (client, c);
5103   GNUNET_CONTAINER_DLL_insert (clients_head, clients_tail, c);
5104 }
5105
5106
5107 /**
5108  * Handler for client disconnection
5109  *
5110  * @param cls closure
5111  * @param client identification of the client; NULL
5112  *        for the last call when the server is destroyed
5113  */
5114 static void
5115 handle_local_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
5116 {
5117   struct MeshClient *c;
5118   struct MeshClient *next;
5119
5120   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client disconnected: %p\n", client);
5121   if (client == NULL)
5122   {
5123     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   (SERVER DOWN)\n");
5124     return;
5125   }
5126
5127   c = client_get (client);
5128   if (NULL != c)
5129   {
5130     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "matching client found (%u, %p)\n",
5131                 c->id, c);
5132     GNUNET_SERVER_client_drop (c->handle);
5133     c->shutting_down = GNUNET_YES;
5134     if (NULL != c->own_tunnels)
5135     {
5136       GNUNET_CONTAINER_multihashmap32_iterate (c->own_tunnels,
5137                                                &tunnel_destroy_iterator, c);
5138       GNUNET_CONTAINER_multihashmap32_destroy (c->own_tunnels);
5139     }
5140
5141     if (NULL != c->incoming_tunnels)
5142     {
5143       GNUNET_CONTAINER_multihashmap32_iterate (c->incoming_tunnels,
5144                                                &tunnel_destroy_iterator, c);
5145       GNUNET_CONTAINER_multihashmap32_destroy (c->incoming_tunnels);
5146     }
5147
5148     if (NULL != c->ports)
5149     {
5150       GNUNET_CONTAINER_multihashmap32_iterate (c->ports,
5151                                                &client_release_ports, c);
5152       GNUNET_CONTAINER_multihashmap32_destroy (c->ports);
5153     }
5154     next = c->next;
5155     GNUNET_CONTAINER_DLL_remove (clients_head, clients_tail, c);
5156     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  client free (%p)\n", c);
5157     GNUNET_free (c);
5158     GNUNET_STATISTICS_update (stats, "# clients", -1, GNUNET_NO);
5159     c = next;
5160   }
5161   else
5162   {
5163     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " context NULL!\n");
5164   }
5165   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "done!\n");
5166   return;
5167 }
5168
5169
5170 /**
5171  * Handler for new clients
5172  *
5173  * @param cls closure
5174  * @param client identification of the client
5175  * @param message the actual message, which includes messages the client wants
5176  */
5177 static void
5178 handle_local_new_client (void *cls, struct GNUNET_SERVER_Client *client,
5179                          const struct GNUNET_MessageHeader *message)
5180 {
5181   struct GNUNET_MESH_ClientConnect *cc_msg;
5182   struct MeshClient *c;
5183   unsigned int size;
5184   uint32_t *p;
5185   unsigned int i;
5186
5187   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client connected %p\n", client);
5188
5189   /* Check data sanity */
5190   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_ClientConnect);
5191   cc_msg = (struct GNUNET_MESH_ClientConnect *) message;
5192   if (0 != (size % sizeof (uint32_t)))
5193   {
5194     GNUNET_break (0);
5195     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5196     return;
5197   }
5198   size /= sizeof (uint32_t);
5199
5200   /* Initialize new client structure */
5201   c = GNUNET_SERVER_client_get_user_context (client, struct MeshClient);
5202   c->id = next_client_id++; /* overflow not important: just for debug */
5203   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  client id %u\n", c->id);
5204   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  client has %u ports\n", size);
5205   if (size > 0)
5206   {
5207     uint32_t u32;
5208
5209     p = (uint32_t *) &cc_msg[1];
5210     c->ports = GNUNET_CONTAINER_multihashmap32_create (size);
5211     for (i = 0; i < size; i++)
5212     {
5213       u32 = ntohl (p[i]);
5214       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    port: %u\n", u32);
5215
5216       /* store in client's hashmap */
5217       GNUNET_CONTAINER_multihashmap32_put (c->ports, u32, c,
5218                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
5219       /* store in global hashmap */
5220       /* FIXME only allow one client to have the port open,
5221        *       have a backup hashmap with waiting clients */
5222       GNUNET_CONTAINER_multihashmap32_put (ports, u32, c,
5223                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
5224     }
5225   }
5226
5227   c->own_channels = GNUNET_CONTAINER_multihashmap32_create (32);
5228   c->incoming_channels = GNUNET_CONTAINER_multihashmap32_create (32);
5229   GNUNET_SERVER_notification_context_add (nc, client);
5230   GNUNET_STATISTICS_update (stats, "# clients", 1, GNUNET_NO);
5231
5232   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5233   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client processed\n");
5234 }
5235
5236
5237 /**
5238  * Handler for requests of new tunnels
5239  *
5240  * @param cls Closure.
5241  * @param client Identification of the client.
5242  * @param message The actual message.
5243  */
5244 static void
5245 handle_local_channel_create (void *cls, struct GNUNET_SERVER_Client *client,
5246                             const struct GNUNET_MessageHeader *message)
5247 {
5248   struct GNUNET_MESH_ChannelMessage *msg;
5249   struct MeshPeer *peer;
5250   struct MeshTunnel2 *t;
5251   struct MeshChannel *ch;
5252   struct MeshClient *c;
5253   MESH_ChannelNumber chid;
5254
5255   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new channel requested\n");
5256
5257   /* Sanity check for client registration */
5258   if (NULL == (c = client_get (client)))
5259   {
5260     GNUNET_break (0);
5261     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5262     return;
5263   }
5264   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
5265
5266   /* Message size sanity check */
5267   if (sizeof (struct GNUNET_MESH_ChannelMessage) != ntohs (message->size))
5268   {
5269     GNUNET_break (0);
5270     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5271     return;
5272   }
5273
5274   msg = (struct GNUNET_MESH_ChannelMessage *) message;
5275   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  towards %s:%u\n",
5276               GNUNET_i2s (&msg->peer), ntohl (msg->port));
5277   chid = ntohl (msg->channel_id);
5278
5279   /* Sanity check for duplicate tunnel IDs */
5280   if (NULL != channel_get_by_local_id (c, chid))
5281   {
5282     GNUNET_break (0);
5283     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5284     return;
5285   }
5286
5287   peer = peer_get (&msg->peer);
5288   if (NULL == peer->tunnel)
5289     peer->tunnel = tunnel_new ();
5290   t = peer->tunnel;
5291
5292   /* Create channel */
5293   while (NULL != channel_get_by_pi (myid, next_tid))
5294     next_tid = (next_tid + 1) & ~GNUNET_MESH_LOCAL_CHANNEL_ID_CLI;
5295   t = tunnel_new (myid, next_tid, c, chid);
5296   next_tid = (next_tid + 1) & ~GNUNET_MESH_LOCAL_CHANNEL_ID_CLI;
5297   if (NULL == t)
5298   {
5299     GNUNET_break (0);
5300     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5301     return;
5302   }
5303   t->port = ntohl (msg->port);
5304   tunnel_set_options (t, ntohl (msg->opt));
5305   if (GNUNET_YES == t->reliable)
5306   {
5307     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! Reliable\n");
5308     t->fwd_rel = GNUNET_malloc (sizeof (struct MeshChannelReliability));
5309     t->fwd_rel->t = t;
5310     t->fwd_rel->expected_delay = MESH_RETRANSMIT_TIME;
5311   }
5312
5313   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CREATED TUNNEL %s[%x]:%u (%x)\n",
5314               GNUNET_i2s (&my_full_id), t->id.tid, t->port, t->local_tid);
5315
5316   peer_info = peer_get (&msg->peer);
5317   peer_add_tunnel (peer_info, t);
5318   peer_connect (peer_info, t);
5319   tunnel_reset_timeout (t, GNUNET_YES);
5320   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5321   return;
5322 }
5323
5324
5325 /**
5326  * Handler for requests of deleting tunnels
5327  *
5328  * @param cls closure
5329  * @param client identification of the client
5330  * @param message the actual message
5331  */
5332 static void
5333 handle_local_channel_destroy (void *cls, struct GNUNET_SERVER_Client *client,
5334                              const struct GNUNET_MessageHeader *message)
5335 {
5336   struct GNUNET_MESH_ChannelMessage *tunnel_msg;
5337   struct MeshClient *c;
5338   struct MeshTunnel *t;
5339   MESH_ChannelNumber tid;
5340
5341   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5342               "Got a DESTROY TUNNEL from client!\n");
5343
5344   /* Sanity check for client registration */
5345   if (NULL == (c = client_get (client)))
5346   {
5347     GNUNET_break (0);
5348     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5349     return;
5350   }
5351   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
5352
5353   /* Message sanity check */
5354   if (sizeof (struct GNUNET_MESH_ChannelMessage) != ntohs (message->size))
5355   {
5356     GNUNET_break (0);
5357     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5358     return;
5359   }
5360
5361   tunnel_msg = (struct GNUNET_MESH_ChannelMessage *) message;
5362
5363   /* Retrieve tunnel */
5364   tid = ntohl (tunnel_msg->channel_id);
5365   t = channel_get_by_local_id (c, tid);
5366   if (NULL == t)
5367   {
5368     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  tunnel %X not found\n", tid);
5369     GNUNET_break (0);
5370     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5371     return;
5372   }
5373
5374   /* Cleanup after the tunnel */
5375   client_delete_tunnel (c, t);
5376   if (c == t->client && GNUNET_MESH_LOCAL_CHANNEL_ID_SERV <= tid)
5377   {
5378     t->client = NULL;
5379   }
5380   else if (c == t->owner && GNUNET_MESH_LOCAL_CHANNEL_ID_SERV > tid)
5381   {
5382     peer_remove_tunnel (peer_get_short (t->dest), t);
5383     t->owner = NULL;
5384   }
5385   else 
5386   {
5387     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5388                 "  tunnel %X client %p (%p, %p)\n",
5389                 tid, c, t->owner, t->client);
5390     GNUNET_break (0);
5391   }
5392
5393   /* The tunnel will be destroyed when the last message is transmitted. */
5394   tunnel_destroy_empty (t);
5395
5396   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5397   return;
5398 }
5399
5400
5401 /**
5402  * Handler for client traffic
5403  *
5404  * @param cls closure
5405  * @param client identification of the client
5406  * @param message the actual message
5407  */
5408 static void
5409 handle_local_data (void *cls, struct GNUNET_SERVER_Client *client,
5410                    const struct GNUNET_MessageHeader *message)
5411 {
5412   struct GNUNET_MESH_LocalData *data_msg;
5413   struct MeshClient *c;
5414   struct MeshTunnel *t;
5415   struct MeshFlowControl *fc;
5416   MESH_ChannelNumber tid;
5417   size_t size;
5418
5419   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5420               "Got data from a client!\n");
5421
5422   /* Sanity check for client registration */
5423   if (NULL == (c = client_get (client)))
5424   {
5425     GNUNET_break (0);
5426     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5427     return;
5428   }
5429   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
5430
5431   data_msg = (struct GNUNET_MESH_LocalData *) message;
5432
5433   /* Sanity check for message size */
5434   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_LocalData);
5435   if (size < sizeof (struct GNUNET_MessageHeader))
5436   {
5437     GNUNET_break (0);
5438     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5439     return;
5440   }
5441
5442   /* Tunnel exists? */
5443   tid = ntohl (data_msg->tid);
5444   t = channel_get_by_local_id (c, tid);
5445   if (NULL == t)
5446   {
5447     GNUNET_break (0);
5448     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5449     return;
5450   }
5451
5452   /* Is the client in the tunnel? */
5453   if ( !( (tid < GNUNET_MESH_LOCAL_CHANNEL_ID_SERV &&
5454            t->owner &&
5455            t->owner->handle == client)
5456          ||
5457           (tid >= GNUNET_MESH_LOCAL_CHANNEL_ID_SERV &&
5458            t->client && 
5459            t->client->handle == client) ) )
5460   {
5461     GNUNET_break (0);
5462     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5463     return;
5464   }
5465
5466   /* Ok, everything is correct, send the message
5467    * (pretend we got it from a mesh peer)
5468    */
5469   {
5470     struct GNUNET_MESH_Data *payload;
5471     char cbuf[sizeof(struct GNUNET_MESH_Data) + size];
5472
5473     fc = tid < GNUNET_MESH_LOCAL_CHANNEL_ID_SERV ? &t->prev_fc : &t->next_fc;
5474     if (GNUNET_YES == t->reliable)
5475     {
5476       struct MeshChannelReliability *rel;
5477       struct MeshReliableMessage *copy;
5478
5479       rel = (tid < GNUNET_MESH_LOCAL_CHANNEL_ID_SERV) ? t->fwd_rel : t->bck_rel;
5480       copy = GNUNET_malloc (sizeof (struct MeshReliableMessage)
5481                             + sizeof(struct GNUNET_MESH_Data)
5482                             + size);
5483       copy->mid = rel->mid_sent++;
5484       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! DATA %u\n", copy->mid);
5485       copy->timestamp = GNUNET_TIME_absolute_get ();
5486       copy->rel = rel;
5487       rel->n_sent++;
5488       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " n_sent %u\n", rel->n_sent);
5489       GNUNET_CONTAINER_DLL_insert_tail (rel->head_sent, rel->tail_sent, copy);
5490       if (GNUNET_SCHEDULER_NO_TASK == rel->retry_task)
5491       {
5492         rel->retry_timer =
5493             GNUNET_TIME_relative_multiply (rel->expected_delay,
5494                                            MESH_RETRANSMIT_MARGIN);
5495         rel->retry_task =
5496             GNUNET_SCHEDULER_add_delayed (rel->retry_timer,
5497                                           &tunnel_retransmit_message,
5498                                           rel);
5499       }
5500       payload = (struct GNUNET_MESH_Data *) &copy[1];
5501       payload->mid = htonl (copy->mid);
5502     }
5503     else
5504     {
5505       payload = (struct GNUNET_MESH_Data *) cbuf;
5506       payload->mid = htonl (fc->last_pid_recv + 1);
5507     }
5508     memcpy (&payload[1], &data_msg[1], size);
5509     payload->header.size = htons (sizeof (struct GNUNET_MESH_Data) + size);
5510     payload->header.type = htons (tid < GNUNET_MESH_LOCAL_CHANNEL_ID_SERV ?
5511                                   GNUNET_MESSAGE_TYPE_MESH_UNICAST :
5512                                   GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN);
5513     GNUNET_PEER_resolve(t->id.oid, &payload->oid);;
5514     payload->tid = htonl (t->id.tid);
5515     payload->ttl = htonl (default_ttl);
5516     payload->pid = htonl (fc->last_pid_recv + 1);
5517     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5518                 "  calling generic handler...\n");
5519     if (tid < GNUNET_MESH_LOCAL_CHANNEL_ID_SERV)
5520       handle_mesh_unicast (NULL, &my_full_id, &payload->header);
5521     else
5522       handle_mesh_to_orig (NULL, &my_full_id, &payload->header);
5523   }
5524   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "receive done OK\n");
5525   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5526
5527   return;
5528 }
5529
5530
5531 /**
5532  * Handler for client's ACKs for payload traffic.
5533  *
5534  * @param cls Closure (unused).
5535  * @param client Identification of the client.
5536  * @param message The actual message.
5537  */
5538 static void
5539 handle_local_ack (void *cls, struct GNUNET_SERVER_Client *client,
5540                   const struct GNUNET_MessageHeader *message)
5541 {
5542   struct GNUNET_MESH_LocalAck *msg;
5543   struct MeshTunnel *t;
5544   struct MeshClient *c;
5545   MESH_ChannelNumber tid;
5546
5547   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a local ACK\n");
5548   /* Sanity check for client registration */
5549   if (NULL == (c = client_get (client)))
5550   {
5551     GNUNET_break (0);
5552     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5553     return;
5554   }
5555   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
5556
5557   msg = (struct GNUNET_MESH_LocalAck *) message;
5558
5559   /* Tunnel exists? */
5560   tid = ntohl (msg->channel_id);
5561   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", tid);
5562   t = channel_get_by_local_id (c, tid);
5563   if (NULL == t)
5564   {
5565     GNUNET_break (0);
5566     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Tunnel %X unknown.\n", tid);
5567     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  for client %u.\n", c->id);
5568     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5569     return;
5570   }
5571
5572   /* Does client own tunnel? I.E: Is this an ACK for BCK traffic? */
5573   if (tid < GNUNET_MESH_LOCAL_CHANNEL_ID_SERV)
5574   {
5575     /* The client owns the tunnel, ACK is for data to_origin, send BCK ACK. */
5576     t->prev_fc.last_ack_recv++;
5577     tunnel_send_ack (t, GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK, GNUNET_NO);
5578   }
5579   else
5580   {
5581     /* The client doesn't own the tunnel, this ACK is for FWD traffic. */
5582     t->next_fc.last_ack_recv++;
5583     tunnel_send_ack (t, GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK, GNUNET_YES);
5584   }
5585
5586   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5587
5588   return;
5589 }
5590
5591
5592
5593 /**
5594  * Iterator over all tunnels to send a monitoring client info about each tunnel.
5595  *
5596  * @param cls Closure (client handle).
5597  * @param key Key (hashed tunnel ID, unused).
5598  * @param value Tunnel info.
5599  *
5600  * @return GNUNET_YES, to keep iterating.
5601  */
5602 static int
5603 monitor_all_tunnels_iterator (void *cls,
5604                               const struct GNUNET_HashCode * key,
5605                               void *value)
5606 {
5607   struct GNUNET_SERVER_Client *client = cls;
5608   struct MeshTunnel *t = value;
5609   struct GNUNET_MESH_LocalMonitor *msg;
5610
5611   msg = GNUNET_malloc (sizeof(struct GNUNET_MESH_LocalMonitor));
5612   GNUNET_PEER_resolve(t->id.oid, &msg->owner);
5613   msg->channel_id = htonl (t->id.tid);
5614   msg->header.size = htons (sizeof (struct GNUNET_MESH_LocalMonitor));
5615   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS);
5616   GNUNET_PEER_resolve (t->dest, &msg->destination);
5617
5618   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5619               "*  sending info about tunnel %s [%u]\n",
5620               GNUNET_i2s (&msg->owner), t->id.tid);
5621
5622   GNUNET_SERVER_notification_context_unicast (nc, client,
5623                                               &msg->header, GNUNET_NO);
5624   return GNUNET_YES;
5625 }
5626
5627
5628 /**
5629  * Handler for client's MONITOR request.
5630  *
5631  * @param cls Closure (unused).
5632  * @param client Identification of the client.
5633  * @param message The actual message.
5634  */
5635 static void
5636 handle_local_get_tunnels (void *cls, struct GNUNET_SERVER_Client *client,
5637                           const struct GNUNET_MessageHeader *message)
5638 {
5639   struct MeshClient *c;
5640
5641   /* Sanity check for client registration */
5642   if (NULL == (c = client_get (client)))
5643   {
5644     GNUNET_break (0);
5645     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5646     return;
5647   }
5648
5649   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5650               "Received get tunnels request from client %u\n",
5651               c->id);
5652   GNUNET_CONTAINER_multihashmap_iterate (tunnels,
5653                                          monitor_all_tunnels_iterator,
5654                                          client);
5655   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5656               "Get tunnels request from client %u completed\n",
5657               c->id);
5658   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5659 }
5660
5661
5662 /**
5663  * Handler for client's MONITOR_TUNNEL request.
5664  *
5665  * @param cls Closure (unused).
5666  * @param client Identification of the client.
5667  * @param message The actual message.
5668  */
5669 static void
5670 handle_local_show_tunnel (void *cls, struct GNUNET_SERVER_Client *client,
5671                           const struct GNUNET_MessageHeader *message)
5672 {
5673   const struct GNUNET_MESH_LocalMonitor *msg;
5674   struct GNUNET_MESH_LocalMonitor *resp;
5675   struct MeshClient *c;
5676   struct MeshTunnel *t;
5677
5678   /* Sanity check for client registration */
5679   if (NULL == (c = client_get (client)))
5680   {
5681     GNUNET_break (0);
5682     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5683     return;
5684   }
5685
5686   msg = (struct GNUNET_MESH_LocalMonitor *) message;
5687   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5688               "Received tunnel info request from client %u for tunnel %s[%X]\n",
5689               c->id,
5690               &msg->owner,
5691               ntohl (msg->channel_id));
5692   t = channel_get (&msg->owner, ntohl (msg->channel_id));
5693   if (NULL == t)
5694   {
5695     /* We don't know the tunnel FIXME */
5696     struct GNUNET_MESH_LocalMonitor warn;
5697
5698     warn = *msg;
5699     GNUNET_SERVER_notification_context_unicast (nc, client,
5700                                                 &warn.header,
5701                                                 GNUNET_NO);
5702     GNUNET_SERVER_receive_done (client, GNUNET_OK);
5703     return;
5704   }
5705
5706   /* Initialize context */
5707   resp = GNUNET_malloc (sizeof (struct GNUNET_MESH_LocalMonitor));
5708   *resp = *msg;
5709   GNUNET_PEER_resolve (t->dest, &resp->destination);
5710   resp->header.size = htons (sizeof (struct GNUNET_MESH_LocalMonitor));
5711   GNUNET_SERVER_notification_context_unicast (nc, c->handle,
5712                                               &resp->header, GNUNET_NO);
5713   GNUNET_free (resp);
5714
5715   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5716               "Monitor tunnel request from client %u completed\n",
5717               c->id);
5718   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5719 }
5720
5721
5722 /**
5723  * Functions to handle messages from clients
5724  */
5725 static struct GNUNET_SERVER_MessageHandler client_handlers[] = {
5726   {&handle_local_new_client, NULL,
5727    GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT, 0},
5728   {&handle_local_channel_create, NULL,
5729    GNUNET_MESSAGE_TYPE_MESH_LOCAL_CHANNEL_CREATE,
5730    sizeof (struct GNUNET_MESH_ChannelMessage)},
5731   {&handle_local_channel_destroy, NULL,
5732    GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY,
5733    sizeof (struct GNUNET_MESH_ChannelMessage)},
5734   {&handle_local_data, NULL,
5735    GNUNET_MESSAGE_TYPE_MESH_LOCAL_DATA, 0},
5736   {&handle_local_ack, NULL,
5737    GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK,
5738    sizeof (struct GNUNET_MESH_LocalAck)},
5739   {&handle_local_get_tunnels, NULL,
5740    GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS,
5741    sizeof (struct GNUNET_MessageHeader)},
5742   {&handle_local_show_tunnel, NULL,
5743    GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNEL,
5744      sizeof (struct GNUNET_MESH_LocalMonitor)},
5745   {NULL, NULL, 0, 0}
5746 };
5747
5748
5749 /**
5750  * Method called whenever a given peer connects.
5751  *
5752  * @param cls closure
5753  * @param peer peer identity this notification is about
5754  */
5755 static void
5756 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer)
5757 {
5758   struct MeshPeer *peer_info;
5759   struct MeshPeerPath *path;
5760
5761   DEBUG_CONN ("Peer connected\n");
5762   DEBUG_CONN ("     %s\n", GNUNET_i2s (&my_full_id));
5763   peer_info = peer_get (peer);
5764   if (myid == peer_info->id)
5765   {
5766     DEBUG_CONN ("     (self)\n");
5767     path = path_new (1);
5768   }
5769   else
5770   {
5771     DEBUG_CONN ("     %s\n", GNUNET_i2s (peer));
5772     path = path_new (2);
5773     path->peers[1] = peer_info->id;
5774     GNUNET_PEER_change_rc (peer_info->id, 1);
5775     GNUNET_STATISTICS_update (stats, "# peers", 1, GNUNET_NO);
5776   }
5777   path->peers[0] = myid;
5778   GNUNET_PEER_change_rc (myid, 1);
5779   peer_add_path (peer_info, path, GNUNET_YES);
5780   if (NULL == peer_info->fc)
5781   {
5782     peer_info->fc = GNUNET_new (struct MeshFlowControl);
5783     fc_init (peer_info->fc);
5784     peer_info->fc->peer = peer_info;
5785   }
5786   return;
5787 }
5788
5789
5790 /**
5791  * Method called whenever a peer disconnects.
5792  *
5793  * @param cls closure
5794  * @param peer peer identity this notification is about
5795  */
5796 static void
5797 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
5798 {
5799   struct MeshPeer *pi;
5800   struct MeshPeerQueue *q;
5801   struct MeshPeerQueue *n;
5802   struct MeshFlowControl *fc;
5803
5804   DEBUG_CONN ("Peer disconnected\n");
5805   pi = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
5806   if (NULL == pi)
5807   {
5808     GNUNET_break (0);
5809     return;
5810   }
5811   fc = pi->fc;
5812   if (NULL != fc)
5813   {
5814     GNUNET_break (0);
5815     return;
5816   }
5817   pi->fc = NULL;
5818
5819   q = fc->queue_head;
5820   while (NULL != q)
5821   {
5822       n = q->next;
5823       queue_destroy (q, GNUNET_YES);
5824       q = n;
5825   }
5826   if (NULL != fc->core_transmit)
5827     GNUNET_CORE_notify_transmit_ready_cancel (fc->core_transmit);
5828   if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task)
5829     GNUNET_SCHEDULER_cancel (fc->poll_task);
5830
5831   peer_remove_path (pi, pi->id, myid);
5832   if (myid == pi->id)
5833   {
5834     DEBUG_CONN ("     (self)\n");
5835   }
5836   GNUNET_STATISTICS_update (stats, "# peers", -1, GNUNET_NO);
5837   GNUNET_free (fc);
5838
5839   return;
5840 }
5841
5842
5843 /**
5844  * Install server (service) handlers and start listening to clients.
5845  */
5846 static void
5847 server_init (void)
5848 {
5849   GNUNET_SERVER_add_handlers (server_handle, client_handlers);
5850   GNUNET_SERVER_connect_notify (server_handle,
5851                                 &handle_local_client_connect, NULL);
5852   GNUNET_SERVER_disconnect_notify (server_handle,
5853                                    &handle_local_client_disconnect, NULL);
5854   nc = GNUNET_SERVER_notification_context_create (server_handle, 1);
5855
5856   clients_head = NULL;
5857   clients_tail = NULL;
5858   next_client_id = 0;
5859   GNUNET_SERVER_resume (server_handle);
5860 }
5861
5862
5863 /**
5864  * To be called on core init/fail.
5865  *
5866  * @param cls Closure (config)
5867  * @param server handle to the server for this service
5868  * @param identity the public identity of this peer
5869  */
5870 static void
5871 core_init (void *cls, struct GNUNET_CORE_Handle *server,
5872            const struct GNUNET_PeerIdentity *identity)
5873 {
5874   const struct GNUNET_CONFIGURATION_Handle *c = cls;
5875   static int i = 0;
5876
5877   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Core init\n");
5878   GNUNET_break (core_handle == server);
5879   if (0 != memcmp (identity, &my_full_id, sizeof (my_full_id)) ||
5880     NULL == server)
5881   {
5882     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Wrong CORE service\n"));
5883     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5884                 " core id %s\n",
5885                 GNUNET_i2s (identity));
5886     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5887                 " my id %s\n",
5888                 GNUNET_i2s (&my_full_id));
5889     GNUNET_CORE_disconnect (core_handle);
5890     core_handle = GNUNET_CORE_connect (c, /* Main configuration */
5891                                        NULL,      /* Closure passed to MESH functions */
5892                                        &core_init,        /* Call core_init once connected */
5893                                        &core_connect,     /* Handle connects */
5894                                        &core_disconnect,  /* remove peers on disconnects */
5895                                        NULL,      /* Don't notify about all incoming messages */
5896                                        GNUNET_NO, /* For header only in notification */
5897                                        NULL,      /* Don't notify about all outbound messages */
5898                                        GNUNET_NO, /* For header-only out notification */
5899                                        core_handlers);    /* Register these handlers */
5900     if (10 < i++)
5901       GNUNET_abort();
5902   }
5903   server_init ();
5904   return;
5905 }
5906
5907
5908 /******************************************************************************/
5909 /************************      MAIN FUNCTIONS      ****************************/
5910 /******************************************************************************/
5911
5912 /**
5913  * Iterator over tunnel hash map entries to destroy the tunnel during shutdown.
5914  *
5915  * @param cls closure
5916  * @param key current key code
5917  * @param value value in the hash map
5918  * @return GNUNET_YES if we should continue to iterate,
5919  *         GNUNET_NO if not.
5920  */
5921 static int
5922 shutdown_tunnel (void *cls, const struct GNUNET_HashCode * key, void *value)
5923 {
5924   struct MeshTunnel *t = value;
5925
5926   tunnel_destroy (t);
5927   return GNUNET_YES;
5928 }
5929
5930 /**
5931  * Iterator over peer hash map entries to destroy the tunnel during shutdown.
5932  *
5933  * @param cls closure
5934  * @param key current key code
5935  * @param value value in the hash map
5936  * @return GNUNET_YES if we should continue to iterate,
5937  *         GNUNET_NO if not.
5938  */
5939 static int
5940 shutdown_peer (void *cls, const struct GNUNET_HashCode * key, void *value)
5941 {
5942   struct MeshPeer *p = value;
5943   struct MeshPeerQueue *q;
5944   struct MeshPeerQueue *n;
5945
5946   q = p->queue_head;
5947   while (NULL != q)
5948   {
5949       n = q->next;
5950       if (q->peer == p)
5951       {
5952         queue_destroy(q, GNUNET_YES);
5953       }
5954       q = n;
5955   }
5956   peer_destroy (p);
5957   return GNUNET_YES;
5958 }
5959
5960
5961 /**
5962  * Task run during shutdown.
5963  *
5964  * @param cls unused
5965  * @param tc unused
5966  */
5967 static void
5968 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
5969 {
5970   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shutting down\n");
5971
5972   if (core_handle != NULL)
5973   {
5974     GNUNET_CORE_disconnect (core_handle);
5975     core_handle = NULL;
5976   }
5977   GNUNET_CONTAINER_multihashmap_iterate (tunnels, &shutdown_tunnel, NULL);
5978   GNUNET_CONTAINER_multihashmap_iterate (peers, &shutdown_peer, NULL);
5979   if (dht_handle != NULL)
5980   {
5981     GNUNET_DHT_disconnect (dht_handle);
5982     dht_handle = NULL;
5983   }
5984   if (nc != NULL)
5985   {
5986     GNUNET_SERVER_notification_context_destroy (nc);
5987     nc = NULL;
5988   }
5989   if (GNUNET_SCHEDULER_NO_TASK != announce_id_task)
5990   {
5991     GNUNET_SCHEDULER_cancel (announce_id_task);
5992     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
5993   }
5994   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shut down\n");
5995 }
5996
5997
5998 /**
5999  * Process mesh requests.
6000  *
6001  * @param cls closure
6002  * @param server the initialized server
6003  * @param c configuration to use
6004  */
6005 static void
6006 run (void *cls, struct GNUNET_SERVER_Handle *server,
6007      const struct GNUNET_CONFIGURATION_Handle *c)
6008 {
6009   char *keyfile;
6010   struct GNUNET_CRYPTO_EccPrivateKey *pk;
6011
6012   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "starting to run\n");
6013   server_handle = server;
6014   GNUNET_SERVER_suspend (server_handle);
6015
6016   if (GNUNET_OK !=
6017       GNUNET_CONFIGURATION_get_value_filename (c, "PEER", "PRIVATE_KEY",
6018                                                &keyfile))
6019   {
6020     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6021                 _
6022                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
6023                 "mesh", "peer/privatekey");
6024     GNUNET_SCHEDULER_shutdown ();
6025     return;
6026   }
6027
6028   if (GNUNET_OK !=
6029       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "REFRESH_CONNECTION_TIME",
6030                                            &refresh_connection_time))
6031   {
6032     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6033                 _
6034                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
6035                 "mesh", "refresh path time");
6036     GNUNET_SCHEDULER_shutdown ();
6037     return;
6038   }
6039
6040   if (GNUNET_OK !=
6041       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "ID_ANNOUNCE_TIME",
6042                                            &id_announce_time))
6043   {
6044     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6045                 _
6046                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
6047                 "mesh", "id announce time");
6048     GNUNET_SCHEDULER_shutdown ();
6049     return;
6050   }
6051
6052   if (GNUNET_OK !=
6053       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "CONNECT_TIMEOUT",
6054                                            &connect_timeout))
6055   {
6056     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6057                 _
6058                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
6059                 "mesh", "connect timeout");
6060     GNUNET_SCHEDULER_shutdown ();
6061     return;
6062   }
6063
6064   if (GNUNET_OK !=
6065       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_MSGS_QUEUE",
6066                                              &max_msgs_queue))
6067   {
6068     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6069                 _
6070                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
6071                 "mesh", "max msgs queue");
6072     GNUNET_SCHEDULER_shutdown ();
6073     return;
6074   }
6075
6076   if (GNUNET_OK !=
6077       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_TUNNELS",
6078                                              &max_tunnels))
6079   {
6080     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
6081                 _
6082                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
6083                 "mesh", "max tunnels");
6084     GNUNET_SCHEDULER_shutdown ();
6085     return;
6086   }
6087
6088   if (GNUNET_OK !=
6089       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DEFAULT_TTL",
6090                                              &default_ttl))
6091   {
6092     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
6093                 _
6094                 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
6095                 "mesh", "default ttl", 64);
6096     default_ttl = 64;
6097   }
6098
6099   if (GNUNET_OK !=
6100       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_PEERS",
6101                                              &max_peers))
6102   {
6103     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
6104                 _("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
6105                 "mesh", "max peers", 1000);
6106     max_peers = 1000;
6107   }
6108
6109   if (GNUNET_OK !=
6110       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DROP_PERCENT",
6111                                              &drop_percent))
6112   {
6113     drop_percent = 0;
6114   }
6115   else
6116   {
6117     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
6118                 "Mesh is running with drop mode enabled. "
6119                 "This is NOT a good idea! "
6120                 "Remove the DROP_PERCENT option from your configuration.\n");
6121   }
6122
6123   if (GNUNET_OK !=
6124       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DHT_REPLICATION_LEVEL",
6125                                              &dht_replication_level))
6126   {
6127     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
6128                 _
6129                 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
6130                 "mesh", "dht replication level", 3);
6131     dht_replication_level = 3;
6132   }
6133
6134   tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
6135   incoming_tunnels = GNUNET_CONTAINER_multihashmap32_create (32);
6136   peers = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
6137   ports = GNUNET_CONTAINER_multihashmap32_create (32);
6138
6139   dht_handle = GNUNET_DHT_connect (c, 64);
6140   if (NULL == dht_handle)
6141   {
6142     GNUNET_break (0);
6143   }
6144   stats = GNUNET_STATISTICS_create ("mesh", c);
6145
6146   /* Scheduled the task to clean up when shutdown is called */
6147   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
6148                                 NULL);
6149   pk = GNUNET_CRYPTO_ecc_key_create_from_file (keyfile);
6150   GNUNET_free (keyfile);
6151   GNUNET_assert (NULL != pk);
6152   my_private_key = pk;
6153   GNUNET_CRYPTO_ecc_key_get_public (my_private_key, &my_public_key);
6154   GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
6155                       &my_full_id.hashPubKey);
6156   myid = GNUNET_PEER_intern (&my_full_id);
6157   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
6158               "Mesh for peer [%s] starting\n",
6159               GNUNET_i2s(&my_full_id));
6160
6161   core_handle = GNUNET_CORE_connect (c, /* Main configuration */
6162                                      NULL,      /* Closure passed to MESH functions */
6163                                      &core_init,        /* Call core_init once connected */
6164                                      &core_connect,     /* Handle connects */
6165                                      &core_disconnect,  /* remove peers on disconnects */
6166                                      NULL,      /* Don't notify about all incoming messages */
6167                                      GNUNET_NO, /* For header only in notification */
6168                                      NULL,      /* Don't notify about all outbound messages */
6169                                      GNUNET_NO, /* For header-only out notification */
6170                                      core_handlers);    /* Register these handlers */
6171   if (NULL == core_handle)
6172   {
6173     GNUNET_break (0);
6174     GNUNET_SCHEDULER_shutdown ();
6175     return;
6176   }
6177   next_tid = 0;
6178   next_local_tid = GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
6179   announce_id_task = GNUNET_SCHEDULER_add_now (&announce_id, cls);
6180   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Mesh service running\n");
6181 }
6182
6183
6184 /**
6185  * The main function for the mesh service.
6186  *
6187  * @param argc number of arguments from the command line
6188  * @param argv command line arguments
6189  * @return 0 ok, 1 on error
6190  */
6191 int
6192 main (int argc, char *const *argv)
6193 {
6194   int ret;
6195   int r;
6196
6197   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main()\n");
6198   r = GNUNET_SERVICE_run (argc, argv, "mesh", GNUNET_SERVICE_OPTION_NONE, &run,
6199                           NULL);
6200   ret = (GNUNET_OK == r) ? 0 : 1;
6201   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main() END\n");
6202
6203   INTERVAL_SHOW;
6204
6205   return ret;
6206 }