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