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