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