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