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