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