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