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