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