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