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