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