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