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