Small fix, improved comment
[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     GNUNET_free (info);
1162     return;
1163   }
1164   i = peer_info_transmit_slot (neighbor);
1165   info->handler_n = i;
1166   info->peer = neighbor;
1167   neighbor->types[i] = GNUNET_MESSAGE_TYPE_MESH_UNICAST;
1168   neighbor->infos[i] = info;
1169   neighbor->core_transmit[i] =
1170       GNUNET_CORE_notify_transmit_ready (core_handle, 0, 100,
1171                                          GNUNET_TIME_UNIT_FOREVER_REL, peer,
1172                                          size, &send_core_data_raw, info);
1173
1174 }
1175
1176
1177 /**
1178  * Sends a CREATE PATH message for a path to a peer, properly registrating
1179  * all used resources.
1180  *
1181  * @param peer PeerInfo of the final peer for whom this path is being created.
1182  * @param p Path itself.
1183  * @param t Tunnel for which the path is created.
1184  */
1185 static void
1186 send_create_path (struct MeshPeerInfo *peer, struct MeshPeerPath *p,
1187                   struct MeshTunnel *t)
1188 {
1189   struct GNUNET_PeerIdentity id;
1190   struct MeshPathInfo *path_info;
1191   struct MeshPeerInfo *neighbor;
1192   unsigned int i;
1193
1194   if (NULL == p)
1195   {
1196     p = tree_get_path_to_peer (t->tree, peer->id);
1197     if (NULL == p)
1198     {
1199       GNUNET_break (0);
1200       return;
1201     }
1202   }
1203   for (i = 0; i < p->length; i++)
1204   {
1205     if (p->peers[i] == myid)
1206       break;
1207   }
1208   if (i >= p->length - 1)
1209   {
1210     path_destroy (p);
1211     GNUNET_break (0);
1212     return;
1213   }
1214   GNUNET_PEER_resolve (p->peers[i + 1], &id);
1215
1216   path_info = GNUNET_malloc (sizeof (struct MeshPathInfo));
1217   path_info->path = p;
1218   path_info->t = t;
1219   neighbor = peer_info_get (&id);
1220   path_info->peer = neighbor;
1221   path_info->pos = peer_info_transmit_slot (neighbor);
1222   neighbor->types[path_info->pos] = GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE;
1223   neighbor->infos[path_info->pos] = path_info;
1224   neighbor->core_transmit[path_info->pos] = GNUNET_CORE_notify_transmit_ready (core_handle,     /* handle */
1225                                                                                0,       /* cork */
1226                                                                                0,       /* priority */
1227                                                                                GNUNET_TIME_UNIT_FOREVER_REL,    /* timeout */
1228                                                                                &id,     /* target */
1229                                                                                sizeof (struct GNUNET_MESH_ManipulatePath) + (p->length * sizeof (struct GNUNET_PeerIdentity)),  /*size */
1230                                                                                &send_core_create_path,  /* callback */
1231                                                                                path_info);      /* cls */
1232 }
1233
1234
1235 /**
1236  * Sends a DESTROY PATH message to free resources for a path in a tunnel
1237  *
1238  * @param t Tunnel whose path to destroy.
1239  * @param destination Short ID of the peer to whom the path to destroy.
1240  */
1241 static void
1242 send_destroy_path (struct MeshTunnel *t, GNUNET_PEER_Id destination)
1243 {
1244   struct MeshPeerPath *p;
1245   size_t size;
1246
1247   p = tree_get_path_to_peer (t->tree, destination);
1248   if (NULL == p)
1249   {
1250     GNUNET_break (0);
1251     return;
1252   }
1253   size = sizeof (struct GNUNET_MESH_ManipulatePath);
1254   size += p->length * sizeof (struct GNUNET_PeerIdentity);
1255   {
1256     struct GNUNET_MESH_ManipulatePath *msg;
1257     struct GNUNET_PeerIdentity *pi;
1258     char cbuf[size];
1259     unsigned int i;
1260
1261     msg = (struct GNUNET_MESH_ManipulatePath *) cbuf;
1262     msg->header.size = htons (size);
1263     msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_DESTROY);
1264     msg->tid = htonl (t->id.tid);
1265     pi = (struct GNUNET_PeerIdentity *) &msg[1];
1266     for (i = 0; i < p->length; i++)
1267     {
1268       GNUNET_PEER_resolve (p->peers[i], &pi[i]);
1269     }
1270     send_message (&msg->header, path_get_first_hop (t->tree, destination));
1271   }
1272   path_destroy (p);
1273 }
1274
1275
1276 /**
1277  * Try to establish a new connection to this peer.
1278  * Use the best path for the given tunnel.
1279  * If the peer doesn't have any path to it yet, try to get one.
1280  * If the peer already has some path, send a CREATE PATH towards it.
1281  *
1282  * @param peer PeerInfo of the peer.
1283  * @param t Tunnel for which to create the path, if possible.
1284  */
1285 static void
1286 peer_info_connect (struct MeshPeerInfo *peer, struct MeshTunnel *t)
1287 {
1288   struct MeshPeerPath *p;
1289   struct MeshPathInfo *path_info;
1290
1291   if (NULL != peer->path_head)
1292   {
1293     p = tree_get_path_to_peer (t->tree, peer->id);
1294     if (NULL == p)
1295     {
1296       GNUNET_break (0);
1297       return;
1298     }
1299
1300     if (p->length > 1)
1301     {
1302       send_create_path (peer, p, t);
1303     }
1304     else
1305     {
1306       path_destroy (p);
1307       send_client_peer_connected (t, myid);
1308     }
1309   }
1310   else if (NULL == peer->dhtget)
1311   {
1312     struct GNUNET_PeerIdentity id;
1313
1314     GNUNET_PEER_resolve (peer->id, &id);
1315     path_info = GNUNET_malloc (sizeof (struct MeshPathInfo));
1316     path_info->peer = peer;
1317     path_info->t = t;
1318     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1319                 "MESH:   Starting DHT GET for peer %s\n", GNUNET_i2s (&id));
1320     peer->dhtgetcls = path_info;
1321     peer->dhtget = GNUNET_DHT_get_start (dht_handle,    /* handle */
1322                                          GNUNET_TIME_UNIT_FOREVER_REL,  /* timeout */
1323                                          GNUNET_BLOCK_TYPE_TEST,        /* type */
1324                                          &id.hashPubKey,        /* key to search */
1325                                          4,     /* replication level */
1326                                          GNUNET_DHT_RO_RECORD_ROUTE | GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE, NULL,       /* xquery */
1327                                          0,     /* xquery bits */
1328                                          &dht_get_id_handler, path_info);
1329   }
1330   /* Otherwise, there is no path but the DHT get is already started. */
1331 }
1332
1333
1334 /**
1335  * Task to delay the connection of a peer
1336  *
1337  * @param cls Closure (path info with tunnel and peer to connect).
1338  *            Will be free'd on exection.
1339  * @param tc TaskContext
1340  */
1341 static void
1342 peer_info_connect_task (void *cls,
1343                         const struct GNUNET_SCHEDULER_TaskContext *tc)
1344 {
1345   struct MeshPathInfo *path_info = cls;
1346
1347   if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
1348   {
1349     GNUNET_free (cls);
1350     return;
1351   }
1352   peer_info_connect (path_info->peer, path_info->t);
1353   GNUNET_free (cls);
1354 }
1355
1356
1357 /**
1358  * Destroy the peer_info and free any allocated resources linked to it
1359  *
1360  * @param pi The peer_info to destroy.
1361  *
1362  * @return GNUNET_OK on success
1363  */
1364 static int
1365 peer_info_destroy (struct MeshPeerInfo *pi)
1366 {
1367   struct GNUNET_PeerIdentity id;
1368   struct MeshPeerPath *p;
1369   struct MeshPeerPath *nextp;
1370   unsigned int i;
1371
1372   GNUNET_PEER_resolve (pi->id, &id);
1373   GNUNET_PEER_change_rc (pi->id, -1);
1374
1375   if (GNUNET_YES !=
1376       GNUNET_CONTAINER_multihashmap_remove (peers, &id.hashPubKey, pi))
1377   {
1378     GNUNET_break (0);
1379     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1380                 "MESH: removing peer %s, not in hashmap\n", GNUNET_i2s (&id));
1381   }
1382   if (NULL != pi->dhtget)
1383   {
1384     GNUNET_DHT_get_stop (pi->dhtget);
1385     GNUNET_free (pi->dhtgetcls);
1386   }
1387   for (i = 0; i < CORE_QUEUE_SIZE; i++)
1388   {
1389     peer_info_cancel_transmission (pi, i);
1390   }
1391   p = pi->path_head;
1392   while (NULL != p)
1393   {
1394     nextp = p->next;
1395     GNUNET_CONTAINER_DLL_remove (pi->path_head, pi->path_tail, p);
1396     path_destroy (p);
1397     p = nextp;
1398   }
1399   GNUNET_free (pi);
1400   return GNUNET_OK;
1401 }
1402
1403
1404 /**
1405  * Remove all paths that rely on a direct connection between p1 and p2
1406  * from the peer itself and notify all tunnels about it.
1407  *
1408  * @param peer PeerInfo of affected peer.
1409  * @param p1 GNUNET_PEER_Id of one peer.
1410  * @param p2 GNUNET_PEER_Id of another peer that was connected to the first and
1411  *           no longer is.
1412  *
1413  * TODO: optimize (see below)
1414  */
1415 static void
1416 peer_info_remove_path (struct MeshPeerInfo *peer, GNUNET_PEER_Id p1,
1417                        GNUNET_PEER_Id p2)
1418 {
1419   struct MeshPeerPath *p;
1420   struct MeshPeerPath *aux;
1421   struct MeshPeerInfo *peer_d;
1422   GNUNET_PEER_Id d;
1423   unsigned int destroyed;
1424   unsigned int best;
1425   unsigned int cost;
1426   unsigned int i;
1427
1428   destroyed = 0;
1429   p = peer->path_head;
1430   while (NULL != p)
1431   {
1432     aux = p->next;
1433     for (i = 0; i < (p->length - 1); i++)
1434     {
1435       if ((p->peers[i] == p1 && p->peers[i + 1] == p2) ||
1436           (p->peers[i] == p2 && p->peers[i + 1] == p1))
1437       {
1438         GNUNET_CONTAINER_DLL_remove (peer->path_head, peer->path_tail, p);
1439         path_destroy (p);
1440         destroyed++;
1441         break;
1442       }
1443     }
1444     p = aux;
1445   }
1446   if (0 == destroyed)
1447     return;
1448
1449   for (i = 0; i < peer->ntunnels; i++)
1450   {
1451     d = tunnel_notify_connection_broken (peer->tunnels[i], p1, p2);
1452     if (0 == d) continue;
1453     /* TODO
1454      * Problem: one or more peers have been deleted from the tunnel tree.
1455      * We don't know who they are to try to add them again.
1456      * We need to try to find a new path for each of the disconnected peers.
1457      * Some of them might already have a path to reach them that does not
1458      * involve p1 and p2. Adding all anew might render in a better tree than
1459      * the trivial immediate fix.
1460      *
1461      * Trivial immiediate fix: try to reconnect to the disconnected node. All
1462      * its children will be reachable trough him.
1463      */
1464     peer_d = peer_info_get_short (d);
1465     best = UINT_MAX;
1466     aux = NULL;
1467     for (p = peer_d->path_head; NULL != p; p = p->next)
1468     {
1469       if ((cost = path_get_cost (peer->tunnels[i]->tree, p)) < best)
1470       {
1471         best = cost;
1472         aux = p;
1473       }
1474     }
1475     if (NULL != aux)
1476     {
1477       /* No callback, as peer will be already disconnected and a connection
1478        * scheduled by tunnel_notify_connection_broken.
1479        */
1480       tree_add_path (peer->tunnels[i]->tree, aux, NULL, NULL);
1481     }
1482     else
1483     {
1484       peer_info_connect (peer_d, peer->tunnels[i]);
1485     }
1486   }
1487 }
1488
1489
1490 /**
1491  * Add the path to the peer and update the path used to reach it in case this
1492  * is the shortest.
1493  *
1494  * @param peer_info Destination peer to add the path to.
1495  * @param path New path to add. Last peer must be the peer in arg 1.
1496  *             Path will be either used of freed if already known.
1497  * @param trusted Do we trust that this path is real?
1498  */
1499 void
1500 peer_info_add_path (struct MeshPeerInfo *peer_info, struct MeshPeerPath *path,
1501                     int trusted)
1502 {
1503   struct MeshPeerPath *aux;
1504   unsigned int l;
1505   unsigned int l2;
1506
1507   if ((NULL == peer_info) || (NULL == path))
1508   {
1509     GNUNET_break (0);
1510     path_destroy (path);
1511     return;
1512   }
1513   if (path->length <= 2 && GNUNET_NO == trusted)
1514   {
1515     /* Only allow CORE to tell us about direct paths */
1516     path_destroy (path);
1517     return;
1518   }
1519   GNUNET_assert (peer_info->id == path->peers[path->length - 1]);
1520   for (l = 1; l < path->length; l++)
1521   {
1522     if (path->peers[l] == myid)
1523     {
1524       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: shortening path by %u\n", l);
1525       for (l2 = 0; l2 < path->length - l; l2++)
1526       {
1527         path->peers[l2] = path->peers[l + l2];
1528       }
1529       path->length -= l;
1530       l = 1;
1531       path->peers =
1532           GNUNET_realloc (path->peers, path->length * sizeof (GNUNET_PEER_Id));
1533     }
1534   }
1535 #if MESH_DEBUG
1536   {
1537     struct GNUNET_PeerIdentity id;
1538
1539     GNUNET_PEER_resolve (peer_info->id, &id);
1540     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: adding path [%u] to peer %s\n",
1541                 path->length, GNUNET_i2s (&id));
1542   }
1543 #endif
1544   l = path_get_length (path);
1545   if (0 == l)
1546   {
1547     GNUNET_free (path);
1548     return;
1549   }
1550
1551   GNUNET_assert (peer_info->id == path->peers[path->length - 1]);
1552   for (aux = peer_info->path_head; aux != NULL; aux = aux->next)
1553   {
1554     l2 = path_get_length (aux);
1555     if (l2 > l)
1556     {
1557       GNUNET_CONTAINER_DLL_insert_before (peer_info->path_head,
1558                                           peer_info->path_tail, aux, path);
1559       return;
1560     }
1561     else
1562     {
1563       if (l2 == l && memcmp (path->peers, aux->peers, l) == 0)
1564       {
1565         path_destroy (path);
1566         return;
1567       }
1568     }
1569   }
1570   GNUNET_CONTAINER_DLL_insert_tail (peer_info->path_head, peer_info->path_tail,
1571                                     path);
1572   return;
1573 }
1574
1575
1576 /**
1577  * Add the path to the origin peer and update the path used to reach it in case
1578  * this is the shortest.
1579  * The path is given in peer_info -> destination, therefore we turn the path
1580  * upside down first.
1581  *
1582  * @param peer_info Peer to add the path to, being the origin of the path.
1583  * @param path New path to add after being inversed.
1584  * @param trusted Do we trust that this path is real?
1585  */
1586 static void
1587 peer_info_add_path_to_origin (struct MeshPeerInfo *peer_info,
1588                               struct MeshPeerPath *path, int trusted)
1589 {
1590   path_invert (path);
1591   peer_info_add_path (peer_info, path, trusted);
1592 }
1593
1594
1595 /**
1596  * Build a PeerPath from the paths returned from the DHT, reversing the paths
1597  * to obtain a local peer -> destination path and interning the peer ids.
1598  *
1599  * @return Newly allocated and created path
1600  */
1601 static struct MeshPeerPath *
1602 path_build_from_dht (const struct GNUNET_PeerIdentity *get_path,
1603                      unsigned int get_path_length,
1604                      const struct GNUNET_PeerIdentity *put_path,
1605                      unsigned int put_path_length)
1606 {
1607   struct MeshPeerPath *p;
1608   GNUNET_PEER_Id id;
1609   int i;
1610
1611   p = path_new (1);
1612   p->peers[0] = myid;
1613   GNUNET_PEER_change_rc (myid, 1);
1614   i = get_path_length;
1615   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    GET has %d hops.\n", i);
1616   for (i--; i >= 0; i--)
1617   {
1618     id = GNUNET_PEER_intern (&get_path[i]);
1619     if (p->length > 0 && id == p->peers[p->length - 1])
1620     {
1621       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    Optimizing 1 hop out.\n");
1622       GNUNET_PEER_change_rc (id, -1);
1623     }
1624     else
1625     {
1626       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    Adding from GET: %s.\n",
1627                   GNUNET_i2s (&get_path[i]));
1628       p->length++;
1629       p->peers = GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * p->length);
1630       p->peers[p->length - 1] = id;
1631     }
1632   }
1633   i = put_path_length;
1634   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    PUT has %d hops.\n", i);
1635   for (i--; i >= 0; i--)
1636   {
1637     id = GNUNET_PEER_intern (&put_path[i]);
1638     if (id == myid)
1639     {
1640       /* PUT path went through us, so discard the path up until now and start
1641        * from here to get a much shorter (and loop-free) path.
1642        */
1643       path_destroy (p);
1644       p = path_new (0);
1645     }
1646     if (p->length > 0 && id == p->peers[p->length - 1])
1647     {
1648       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    Optimizing 1 hop out.\n");
1649       GNUNET_PEER_change_rc (id, -1);
1650     }
1651     else
1652     {
1653       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    Adding from PUT: %s.\n",
1654                   GNUNET_i2s (&put_path[i]));
1655       p->length++;
1656       p->peers = GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * p->length);
1657       p->peers[p->length - 1] = id;
1658     }
1659   }
1660 #if MESH_DEBUG
1661   if (get_path_length > 0)
1662     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    (first of GET: %s)\n",
1663                 GNUNET_i2s (&get_path[0]));
1664   if (put_path_length > 0)
1665     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    (first of PUT: %s)\n",
1666                 GNUNET_i2s (&put_path[0]));
1667   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    In total: %d hops\n",
1668               p->length);
1669   for (i = 0; i < p->length; i++)
1670   {
1671     struct GNUNET_PeerIdentity peer_id;
1672
1673     GNUNET_PEER_resolve (p->peers[i], &peer_id);
1674     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:        %u: %s\n", p->peers[i],
1675                 GNUNET_i2s (&peer_id));
1676   }
1677 #endif
1678   return p;
1679 }
1680
1681
1682 /**
1683  * Send keepalive packets for a peer
1684  *
1685  * @param cls Closure (tunnel for which to send the keepalive).
1686  * @param tc Notification context.
1687  *
1688  * TODO: implement explicit multicast keepalive?
1689  */
1690 static void
1691 path_refresh (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
1692
1693
1694 /**
1695  * Search for a tunnel among the incoming tunnels
1696  *
1697  * @param tid the local id of the tunnel
1698  *
1699  * @return tunnel handler, NULL if doesn't exist
1700  */
1701 static struct MeshTunnel *
1702 tunnel_get_incoming (MESH_TunnelNumber tid)
1703 {
1704   GNUNET_HashCode hash;
1705
1706   GNUNET_assert (tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV);
1707   GNUNET_CRYPTO_hash (&tid, sizeof (MESH_TunnelNumber), &hash);
1708   return GNUNET_CONTAINER_multihashmap_get (incoming_tunnels, &hash);
1709 }
1710
1711
1712 /**
1713  * Search for a tunnel among the tunnels for a client
1714  *
1715  * @param c the client whose tunnels to search in
1716  * @param tid the local id of the tunnel
1717  *
1718  * @return tunnel handler, NULL if doesn't exist
1719  */
1720 static struct MeshTunnel *
1721 tunnel_get_by_local_id (struct MeshClient *c, MESH_TunnelNumber tid)
1722 {
1723   if (tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
1724   {
1725     return tunnel_get_incoming (tid);
1726   }
1727   else
1728   {
1729     GNUNET_HashCode hash;
1730
1731     GNUNET_CRYPTO_hash (&tid, sizeof (MESH_TunnelNumber), &hash);
1732     return GNUNET_CONTAINER_multihashmap_get (c->tunnels, &hash);
1733   }
1734 }
1735
1736
1737 /**
1738  * Search for a tunnel by global ID using PEER_ID
1739  *
1740  * @param pi owner of the tunnel
1741  * @param tid global tunnel number
1742  *
1743  * @return tunnel handler, NULL if doesn't exist
1744  */
1745 static struct MeshTunnel *
1746 tunnel_get_by_pi (GNUNET_PEER_Id pi, MESH_TunnelNumber tid)
1747 {
1748   struct MESH_TunnelID id;
1749   GNUNET_HashCode hash;
1750
1751   id.oid = pi;
1752   id.tid = tid;
1753
1754   GNUNET_CRYPTO_hash (&id, sizeof (struct MESH_TunnelID), &hash);
1755   return GNUNET_CONTAINER_multihashmap_get (tunnels, &hash);
1756 }
1757
1758
1759 /**
1760  * Search for a tunnel by global ID using full PeerIdentities
1761  *
1762  * @param oid owner of the tunnel
1763  * @param tid global tunnel number
1764  *
1765  * @return tunnel handler, NULL if doesn't exist
1766  */
1767 static struct MeshTunnel *
1768 tunnel_get (struct GNUNET_PeerIdentity *oid, MESH_TunnelNumber tid)
1769 {
1770   return tunnel_get_by_pi (GNUNET_PEER_search (oid), tid);
1771 }
1772
1773
1774 /**
1775  * Callback used to notify a client owner of a tunnel that a peer has
1776  * disconnected, most likely because of a path change.
1777  *
1778  * @param cls Closure (tunnel this notification is about).
1779  * @param peer_id Short ID of disconnected peer.
1780  */
1781 void
1782 notify_peer_disconnected (void *cls, GNUNET_PEER_Id peer_id)
1783 {
1784   struct MeshTunnel *t = cls;
1785   struct MeshPeerInfo *peer;
1786   struct MeshPathInfo *path_info;
1787
1788   if (NULL != t->client && NULL != nc)
1789   {
1790     struct GNUNET_MESH_PeerControl msg;
1791
1792     msg.header.size = htons (sizeof (msg));
1793     msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL);
1794     msg.tunnel_id = htonl (t->local_tid);
1795     GNUNET_PEER_resolve (peer_id, &msg.peer);
1796     GNUNET_SERVER_notification_context_unicast (nc, t->client->handle,
1797                                                 &msg.header, GNUNET_NO);
1798   }
1799   peer = peer_info_get_short (peer_id);
1800   path_info = GNUNET_malloc (sizeof (struct MeshPathInfo));
1801   path_info->peer = peer;
1802   path_info->t = t;
1803   GNUNET_SCHEDULER_add_now (&peer_info_connect_task, path_info);
1804 }
1805
1806
1807 /**
1808  * Add a peer to a tunnel, accomodating paths accordingly and initializing all
1809  * needed rescources.
1810  * If peer already exists, reevaluate shortest path and change if different.
1811  *
1812  * @param t Tunnel we want to add a new peer to
1813  * @param peer PeerInfo of the peer being added
1814  *
1815  */
1816 static void
1817 tunnel_add_peer (struct MeshTunnel *t, struct MeshPeerInfo *peer)
1818 {
1819   struct GNUNET_PeerIdentity id;
1820   struct MeshPeerPath *best_p;
1821   struct MeshPeerPath *p;
1822   unsigned int best_cost;
1823   unsigned int cost;
1824
1825   GNUNET_PEER_resolve (peer->id, &id);
1826   if (GNUNET_NO ==
1827       GNUNET_CONTAINER_multihashmap_contains (t->peers, &id.hashPubKey))
1828   {
1829     t->peers_total++;
1830     GNUNET_array_append (peer->tunnels, peer->ntunnels, t);
1831     GNUNET_assert (GNUNET_OK ==
1832                    GNUNET_CONTAINER_multihashmap_put (t->peers, &id.hashPubKey,
1833                                                       peer,
1834                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
1835   }
1836
1837   if (NULL != (p = peer->path_head))
1838   {
1839     best_p = p;
1840     best_cost = path_get_cost (t->tree, p);
1841     while (NULL != p)
1842     {
1843       if ((cost = path_get_cost (t->tree, p)) < best_cost)
1844       {
1845         best_cost = cost;
1846         best_p = p;
1847       }
1848       p = p->next;
1849     }
1850     tree_add_path (t->tree, best_p, &notify_peer_disconnected, t);
1851     if (GNUNET_SCHEDULER_NO_TASK == t->path_refresh_task)
1852       t->path_refresh_task =
1853           GNUNET_SCHEDULER_add_delayed (REFRESH_PATH_TIME, &path_refresh, t);
1854   }
1855   else
1856   {
1857     /* Start a DHT get if necessary */
1858     peer_info_connect (peer, t);
1859   }
1860 }
1861
1862 /**
1863  * Add a path to a tunnel which we don't own, just to remember the next hop.
1864  * If destination node was already in the tunnel, the first hop information
1865  * will be replaced with the new path.
1866  *
1867  * @param t Tunnel we want to add a new peer to
1868  * @param p Path to add
1869  * @param own_pos Position of local node in path.
1870  *
1871  */
1872 static void
1873 tunnel_add_path (struct MeshTunnel *t, struct MeshPeerPath *p,
1874                  unsigned int own_pos)
1875 {
1876   struct GNUNET_PeerIdentity id;
1877
1878   GNUNET_assert (0 != own_pos);
1879   tree_add_path (t->tree, p, NULL, NULL);
1880   if (tree_get_me (t->tree) == 0)
1881     tree_set_me (t->tree, p->peers[own_pos]);
1882   if (own_pos < p->length - 1)
1883   {
1884     GNUNET_PEER_resolve (p->peers[own_pos + 1], &id);
1885     tree_update_first_hops (t->tree, tree_get_me (t->tree), &id);
1886   }
1887 }
1888
1889
1890 /**
1891  * Notifies a tunnel that a connection has broken that affects at least
1892  * some of its peers. Sends a notification towards the root of the tree.
1893  * In case the peer is the owner of the tree, notifies the client that owns
1894  * the tunnel and tries to reconnect.
1895  *
1896  * @param t Tunnel affected.
1897  * @param p1 Peer that got disconnected from p2.
1898  * @param p2 Peer that got disconnected from p1.
1899  *
1900  * @return Short ID of the peer disconnected (either p1 or p2).
1901  *         0 if the tunnel remained unaffected.
1902  */
1903 static GNUNET_PEER_Id
1904 tunnel_notify_connection_broken (struct MeshTunnel *t, GNUNET_PEER_Id p1,
1905                                  GNUNET_PEER_Id p2)
1906 {
1907   GNUNET_PEER_Id pid;
1908
1909   pid =
1910       tree_notify_connection_broken (t->tree, p1, p2, &notify_peer_disconnected,
1911                                      t);
1912   if (myid != p1 && myid != p2)
1913   {
1914     return pid;
1915   }
1916   if (pid != myid)
1917   {
1918     if (tree_get_predecessor (t->tree) != 0)
1919     {
1920       /* We are the peer still connected, notify owner of the disconnection. */
1921       struct GNUNET_MESH_PathBroken msg;
1922       struct GNUNET_PeerIdentity neighbor;
1923
1924       msg.header.size = htons (sizeof (msg));
1925       msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN);
1926       GNUNET_PEER_resolve (t->id.oid, &msg.oid);
1927       msg.tid = htonl (t->id.tid);
1928       msg.peer1 = my_full_id;
1929       GNUNET_PEER_resolve (pid, &msg.peer2);
1930       GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &neighbor);
1931       send_message (&msg.header, &neighbor);
1932     }
1933   }
1934   return pid;
1935 }
1936
1937
1938 struct MeshMulticastData
1939 {
1940   struct MeshTunnel *t;
1941
1942   GNUNET_SCHEDULER_TaskIdentifier *task;
1943
1944   unsigned int *reference_counter;
1945
1946   size_t data_len;
1947
1948   void *data;
1949 };
1950
1951
1952 /**
1953  * Send a multicast packet to a neighbor.
1954  */
1955 static void
1956 tunnel_send_multicast_iterator (void *cls, GNUNET_PEER_Id neighbor_id)
1957 {
1958   struct MeshMulticastData *mdata = cls;
1959   struct MeshDataDescriptor *info;
1960   struct GNUNET_PeerIdentity neighbor;
1961   unsigned int i;
1962
1963   info = GNUNET_malloc (sizeof (struct MeshDataDescriptor));
1964
1965   info->data = mdata->data;
1966   info->size = mdata->data_len;
1967   info->copies = mdata->reference_counter;
1968   (*(mdata->reference_counter))++;
1969
1970   if (NULL != mdata->t->client)
1971   {
1972     info->client = mdata->t->client->handle;
1973     info->timeout_task = mdata->task;
1974   }
1975   info->destination = neighbor_id;
1976   GNUNET_PEER_resolve (neighbor_id, &neighbor);
1977 #if MESH_DEBUG
1978   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    sending to %s...\n",
1979               GNUNET_i2s (&neighbor));
1980 #endif
1981   info->peer = peer_info_get (&neighbor);
1982   GNUNET_assert (NULL != info->peer);
1983   i = peer_info_transmit_slot (info->peer);
1984   info->handler_n = i;
1985   info->peer->infos[i] = info;
1986   info->peer->types[i] = GNUNET_MESSAGE_TYPE_MESH_MULTICAST;
1987   info->peer->core_transmit[i] =
1988       GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
1989                                          GNUNET_TIME_UNIT_FOREVER_REL,
1990                                          &neighbor, info->size,
1991                                          &send_core_data_multicast, info);
1992 }
1993
1994 /**
1995  * Send a message in a tunnel in multicast, sending a copy to each child node
1996  * down the local one in the tunnel tree.
1997  *
1998  * @param t Tunnel in which to send the data.
1999  * @param msg Message to be sent
2000  */
2001 static void
2002 tunnel_send_multicast (struct MeshTunnel *t,
2003                        const struct GNUNET_MessageHeader *msg)
2004 {
2005   struct MeshMulticastData *mdata;
2006
2007 #if MESH_DEBUG
2008   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2009               "MESH:  sending a multicast packet...\n");
2010 #endif
2011   GNUNET_assert (tree_get_me (t->tree) != 0);
2012   mdata = GNUNET_malloc (sizeof (struct MeshMulticastData));
2013   mdata->data_len = ntohs (msg->size);
2014   mdata->reference_counter = GNUNET_malloc (sizeof (unsigned int));
2015   mdata->data = GNUNET_malloc (mdata->data_len);
2016   mdata->t = t;
2017   memcpy (mdata->data, msg, mdata->data_len);
2018   if (NULL != t->client)
2019   {
2020     mdata->task = GNUNET_malloc (sizeof (GNUNET_SCHEDULER_TaskIdentifier));
2021     *(mdata->task) =
2022         GNUNET_SCHEDULER_add_delayed (UNACKNOWLEDGED_WAIT, &client_allow_send,
2023                                       t->client->handle);
2024   }
2025
2026   tree_iterate_children (t->tree, &tunnel_send_multicast_iterator, mdata);
2027   if (*(mdata->reference_counter) == 0)
2028   {
2029     GNUNET_free (mdata->data);
2030     GNUNET_free (mdata->reference_counter);
2031     if (NULL != mdata->task)
2032     {
2033       GNUNET_free (mdata->task);
2034     }
2035   }
2036   GNUNET_free (mdata);
2037 #if MESH_DEBUG
2038   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2039               "MESH:  sending a multicast packet done\n");
2040 #endif
2041   return;
2042 }
2043
2044
2045 /**
2046  * Send a message to all peers in this tunnel that the tunnel is no longer
2047  * valid.
2048  *
2049  * @param t The tunnel whose peers to notify.
2050  */
2051 static void
2052 tunnel_send_destroy (struct MeshTunnel *t)
2053 {
2054   struct GNUNET_MESH_TunnelDestroy msg;
2055
2056   msg.header.size = htons (sizeof (msg));
2057   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY);
2058   GNUNET_PEER_resolve (t->id.oid, &msg.oid);
2059   msg.tid = htonl (t->id.tid);
2060   tunnel_send_multicast (t, &msg.header);
2061 }
2062
2063
2064
2065 /**
2066  * Destroy the tunnel and free any allocated resources linked to it
2067  *
2068  * @param t the tunnel to destroy
2069  *
2070  * @return GNUNET_OK on success
2071  */
2072 static int
2073 tunnel_destroy (struct MeshTunnel *t)
2074 {
2075   struct MeshClient *c;
2076   struct MeshQueue *q;
2077   struct MeshQueue *qn;
2078   GNUNET_HashCode hash;
2079   int r;
2080
2081   if (NULL == t)
2082     return GNUNET_OK;
2083
2084   c = t->client;
2085 #if MESH_DEBUG
2086   {
2087     struct GNUNET_PeerIdentity id;
2088
2089     GNUNET_PEER_resolve (t->id.oid, &id);
2090     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: destroying tunnel %s [%x]\n",
2091                 GNUNET_i2s (&id), t->id.tid);
2092     if (NULL != c)
2093       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   by client %u\n", c->id);
2094   }
2095 #endif
2096
2097   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
2098   if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_remove (tunnels, &hash, t))
2099   {
2100     r = GNUNET_SYSERR;
2101   }
2102
2103   GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
2104   if (NULL != c &&
2105       GNUNET_YES != GNUNET_CONTAINER_multihashmap_remove (c->tunnels, &hash, t))
2106   {
2107     r = GNUNET_SYSERR;
2108   }
2109   if (t->local_tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
2110   {
2111     GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
2112     GNUNET_break (GNUNET_YES ==
2113                   GNUNET_CONTAINER_multihashmap_remove (incoming_tunnels, &hash,
2114                                                         t));
2115   }
2116   if (NULL != t->peers)
2117   {
2118     GNUNET_CONTAINER_multihashmap_iterate (t->peers, &peer_info_delete_tunnel,
2119                                            t);
2120     GNUNET_CONTAINER_multihashmap_destroy (t->peers);
2121   }
2122   q = t->queue_head;
2123   while (NULL != q)
2124   {
2125     if (NULL != q->data)
2126       GNUNET_free (q->data);
2127     qn = q->next;
2128     GNUNET_free (q);
2129     q = qn;
2130     /* TODO cancel core transmit ready in case it was active */
2131   }
2132   tree_destroy (t->tree);
2133   if (NULL != t->dht_get_type)
2134     GNUNET_DHT_get_stop (t->dht_get_type);
2135   if (GNUNET_SCHEDULER_NO_TASK != t->timeout_task)
2136     GNUNET_SCHEDULER_cancel (t->timeout_task);
2137   if (GNUNET_SCHEDULER_NO_TASK != t->path_refresh_task)
2138     GNUNET_SCHEDULER_cancel (t->path_refresh_task);
2139   GNUNET_free (t);
2140   return r;
2141 }
2142
2143
2144 /**
2145  * Removes an explicit path from a tunnel, freeing all intermediate nodes
2146  * that are no longer needed, as well as nodes of no longer reachable peers.
2147  * The tunnel itself is also destoyed if results in a remote empty tunnel.
2148  *
2149  * @param t Tunnel from which to remove the path.
2150  * @param p Peer which should be removed.
2151  */
2152 static void
2153 tunnel_delete_peer (struct MeshTunnel *t, GNUNET_PEER_Id peer)
2154 {
2155   if (GNUNET_NO == tree_del_peer (t->tree, peer, NULL, NULL))
2156     tunnel_destroy (t);
2157 }
2158
2159
2160 /**
2161  * tunnel_destroy_iterator: iterator for deleting each tunnel that belongs to a
2162  * client when the client disconnects.
2163  *
2164  * @param cls closure (client that is disconnecting)
2165  * @param key the hash of the local tunnel id (used to access the hashmap)
2166  * @param value the value stored at the key (tunnel to destroy)
2167  *
2168  * @return GNUNET_OK on success
2169  */
2170 static int
2171 tunnel_destroy_iterator (void *cls, const GNUNET_HashCode * key, void *value)
2172 {
2173   struct MeshTunnel *t = value;
2174   int r;
2175
2176   r = tunnel_destroy (t);
2177   return r;
2178 }
2179
2180
2181 /**
2182  * Timeout function, destroys tunnel if called
2183  *
2184  * @param cls Closure (tunnel to destroy).
2185  * @param tc TaskContext
2186  */
2187 static void
2188 tunnel_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2189 {
2190   struct MeshTunnel *t = cls;
2191
2192   if (GNUNET_SCHEDULER_REASON_SHUTDOWN == tc->reason)
2193     return;
2194   t->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2195   tunnel_destroy (t);
2196 }
2197
2198 /**
2199  * Resets the tunnel timeout. Starts it if no timeout was running.
2200  *
2201  * @param t Tunnel whose timeout to reset.
2202  */
2203 static void
2204 tunnel_reset_timeout (struct MeshTunnel *t)
2205 {
2206   if (GNUNET_SCHEDULER_NO_TASK != t->timeout_task)
2207     GNUNET_SCHEDULER_cancel (t->timeout_task);
2208   t->timeout_task =
2209       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
2210                                     (REFRESH_PATH_TIME, 4), &tunnel_timeout, t);
2211 }
2212
2213
2214 /******************************************************************************/
2215 /****************      MESH NETWORK HANDLER HELPERS     ***********************/
2216 /******************************************************************************/
2217
2218 /**
2219  * Function called to notify a client about the socket
2220  * being ready to queue more data.  "buf" will be
2221  * NULL and "size" zero if the socket was closed for
2222  * writing in the meantime.
2223  *
2224  * @param cls closure
2225  * @param size number of bytes available in buf
2226  * @param buf where the callee should write the message
2227  * @return number of bytes written to buf
2228  */
2229 static size_t
2230 send_core_create_path (void *cls, size_t size, void *buf)
2231 {
2232   struct MeshPathInfo *info = cls;
2233   struct GNUNET_MESH_ManipulatePath *msg;
2234   struct GNUNET_PeerIdentity *peer_ptr;
2235   struct MeshPeerInfo *peer = info->peer;
2236   struct MeshTunnel *t = info->t;
2237   struct MeshPeerPath *p = info->path;
2238   size_t size_needed;
2239   int i;
2240
2241   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: CREATE PATH sending...\n");
2242   size_needed =
2243       sizeof (struct GNUNET_MESH_ManipulatePath) +
2244       p->length * sizeof (struct GNUNET_PeerIdentity);
2245
2246   if (size < size_needed || NULL == buf)
2247   {
2248     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: create path retransmit!\n");
2249     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   buf:  %p\n", buf);
2250     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   size: (%u/%u)\n", size,
2251                 size_needed);
2252     info->peer->core_transmit[info->pos] =
2253         GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
2254                                            GNUNET_TIME_UNIT_FOREVER_REL,
2255                                            path_get_first_hop (t->tree,
2256                                                                peer->id),
2257                                            size_needed, &send_core_create_path,
2258                                            info);
2259     return 0;
2260   }
2261   info->peer->core_transmit[info->pos] = NULL;
2262 #if MESH_DEBUG
2263   {
2264     struct GNUNET_PeerIdentity id;
2265
2266     GNUNET_PEER_resolve (peer->id, &id);
2267     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2268                 "MESH:   setting core_transmit %s [%u] to NULL\n",
2269                 GNUNET_i2s (&id), info->pos);
2270   }
2271 #endif
2272   msg = (struct GNUNET_MESH_ManipulatePath *) buf;
2273   msg->header.size = htons (size_needed);
2274   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE);
2275   msg->tid = ntohl (t->id.tid);
2276
2277   peer_ptr = (struct GNUNET_PeerIdentity *) &msg[1];
2278   for (i = 0; i < p->length; i++)
2279   {
2280     GNUNET_PEER_resolve (p->peers[i], peer_ptr++);
2281   }
2282
2283   path_destroy (p);
2284   GNUNET_free (info);
2285
2286   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2287               "MESH: CREATE PATH (%u bytes long) sent!\n", size_needed);
2288   return size_needed;
2289 }
2290
2291
2292 /**
2293  * Function called to notify a client about the socket
2294  * being ready to queue more data.  "buf" will be
2295  * NULL and "size" zero if the socket was closed for
2296  * writing in the meantime.
2297  *
2298  * @param cls closure (data itself)
2299  * @param size number of bytes available in buf
2300  * @param buf where the callee should write the message
2301  *
2302  * @return number of bytes written to buf
2303  */
2304 static size_t
2305 send_core_data_multicast (void *cls, size_t size, void *buf)
2306 {
2307   struct MeshDataDescriptor *info = cls;
2308   size_t total_size;
2309
2310   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Multicast callback.\n");
2311   GNUNET_assert (NULL != info);
2312   GNUNET_assert (NULL != info->peer);
2313   total_size = info->size;
2314   GNUNET_assert (total_size < GNUNET_SERVER_MAX_MESSAGE_SIZE);
2315
2316   if (total_size > size)
2317   {
2318     /* Retry */
2319     struct GNUNET_PeerIdentity id;
2320
2321     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2322                 "MESH: Multicast: retransmitting... (%u/%u)\n", size,
2323                 total_size);
2324     GNUNET_PEER_resolve (info->peer->id, &id);
2325     info->peer->core_transmit[info->handler_n] =
2326         GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
2327                                            GNUNET_TIME_UNIT_FOREVER_REL, &id,
2328                                            total_size,
2329                                            &send_core_data_multicast, info);
2330     return 0;
2331   }
2332   info->peer->core_transmit[info->handler_n] = NULL;
2333   info->peer->infos[info->handler_n] = NULL;
2334   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  copying data...\n");
2335   memcpy (buf, info->data, total_size);
2336 #if MESH_DEBUG
2337   {
2338     struct GNUNET_MESH_Multicast *mc;
2339     struct GNUNET_MessageHeader *mh;
2340
2341     mh = buf;
2342     if (ntohs (mh->type) == GNUNET_MESSAGE_TYPE_MESH_MULTICAST)
2343     {
2344       mc = (struct GNUNET_MESH_Multicast *) mh;
2345       mh = (struct GNUNET_MessageHeader *) &mc[1];
2346       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2347                   "MESH:  multicast, payload type %u\n", ntohs (mh->type));
2348       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2349                   "MESH:  multicast, payload size %u\n", ntohs (mh->size));
2350     }
2351     else
2352     {
2353       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  type %u\n",
2354                   ntohs (mh->type));
2355     }
2356   }
2357 #endif
2358   data_descriptor_decrement_multicast (info);
2359   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: freeing info...\n");
2360   GNUNET_free (info);
2361   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: return %u\n", total_size);
2362   return total_size;
2363 }
2364
2365
2366 /**
2367  * Function called to notify a client about the socket
2368  * being ready to queue more data.  "buf" will be
2369  * NULL and "size" zero if the socket was closed for
2370  * writing in the meantime.
2371  *
2372  * @param cls closure (MeshDataDescriptor)
2373  * @param size number of bytes available in buf
2374  * @param buf where the callee should write the message
2375  * @return number of bytes written to buf
2376  */
2377 static size_t
2378 send_core_path_ack (void *cls, size_t size, void *buf)
2379 {
2380   struct MeshDataDescriptor *info = cls;
2381   struct GNUNET_MESH_PathACK *msg = buf;
2382
2383   GNUNET_assert (NULL != info);
2384   if (info->peer)
2385   {
2386     info->peer->core_transmit[info->handler_n] = NULL;
2387   }
2388   if (sizeof (struct GNUNET_MESH_PathACK) > size)
2389   {
2390     GNUNET_break (0);
2391     return 0;
2392   }
2393   msg->header.size = htons (sizeof (struct GNUNET_MESH_PathACK));
2394   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_ACK);
2395   GNUNET_PEER_resolve (info->origin->oid, &msg->oid);
2396   msg->tid = htonl (info->origin->tid);
2397   msg->peer_id = my_full_id;
2398   GNUNET_free (info);
2399   /* TODO add signature */
2400
2401   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: PATH ACK sent!\n");
2402   return sizeof (struct GNUNET_MESH_PathACK);
2403 }
2404
2405
2406 /******************************************************************************/
2407 /********************      MESH NETWORK HANDLERS     **************************/
2408 /******************************************************************************/
2409
2410
2411 /**
2412  * Core handler for path creation
2413  *
2414  * @param cls closure
2415  * @param message message
2416  * @param peer peer identity this notification is about
2417  * @param atsi performance data
2418  * @param atsi_count number of records in 'atsi'
2419  *
2420  * @return GNUNET_OK to keep the connection open,
2421  *         GNUNET_SYSERR to close it (signal serious error)
2422  */
2423 static int
2424 handle_mesh_path_create (void *cls, const struct GNUNET_PeerIdentity *peer,
2425                          const struct GNUNET_MessageHeader *message,
2426                          const struct GNUNET_ATS_Information *atsi,
2427                          unsigned int atsi_count)
2428 {
2429   unsigned int own_pos;
2430   uint16_t size;
2431   uint16_t i;
2432   MESH_TunnelNumber tid;
2433   struct GNUNET_MESH_ManipulatePath *msg;
2434   struct GNUNET_PeerIdentity *pi;
2435   GNUNET_HashCode hash;
2436   struct MeshPeerPath *path;
2437   struct MeshPeerInfo *dest_peer_info;
2438   struct MeshPeerInfo *orig_peer_info;
2439   struct MeshTunnel *t;
2440
2441   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2442               "MESH: Received a path create msg [%s]\n",
2443               GNUNET_i2s (&my_full_id));
2444   size = ntohs (message->size);
2445   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
2446   {
2447     GNUNET_break_op (0);
2448     return GNUNET_OK;
2449   }
2450
2451   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
2452   if (size % sizeof (struct GNUNET_PeerIdentity))
2453   {
2454     GNUNET_break_op (0);
2455     return GNUNET_OK;
2456   }
2457   size /= sizeof (struct GNUNET_PeerIdentity);
2458   if (size < 2)
2459   {
2460     GNUNET_break_op (0);
2461     return GNUNET_OK;
2462   }
2463   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:     path has %u hops.\n", size);
2464   msg = (struct GNUNET_MESH_ManipulatePath *) message;
2465
2466   tid = ntohl (msg->tid);
2467   pi = (struct GNUNET_PeerIdentity *) &msg[1];
2468   t = tunnel_get (pi, tid);
2469   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2470               "MESH:     path is for tunnel %s [%X].\n", GNUNET_i2s (pi), tid);
2471   if (NULL == t)
2472   {
2473     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   Creating tunnel\n");
2474     t = GNUNET_malloc (sizeof (struct MeshTunnel));
2475     t->id.oid = GNUNET_PEER_intern (pi);
2476     t->id.tid = tid;
2477     while (NULL != tunnel_get_incoming (next_local_tid))
2478       next_local_tid = (next_local_tid + 1) | GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
2479     t->local_tid = next_local_tid++;
2480     next_local_tid = next_local_tid | GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
2481     t->tree = tree_new (t->id.oid);
2482
2483     GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
2484     if (GNUNET_OK !=
2485         GNUNET_CONTAINER_multihashmap_put (tunnels, &hash, t,
2486                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
2487     {
2488       tunnel_destroy (t);
2489       GNUNET_break (0);
2490       return GNUNET_OK;
2491     }
2492     tunnel_reset_timeout (t);
2493     GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
2494     if (GNUNET_OK !=
2495         GNUNET_CONTAINER_multihashmap_put (incoming_tunnels, &hash, t,
2496                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
2497     {
2498       tunnel_destroy (t);
2499       GNUNET_break (0);
2500       return GNUNET_OK;
2501     }
2502   }
2503   dest_peer_info =
2504       GNUNET_CONTAINER_multihashmap_get (peers, &pi[size - 1].hashPubKey);
2505   if (NULL == dest_peer_info)
2506   {
2507     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2508                 "MESH:   Creating PeerInfo for destination.\n");
2509     dest_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
2510     dest_peer_info->id = GNUNET_PEER_intern (&pi[size - 1]);
2511     GNUNET_CONTAINER_multihashmap_put (peers, &pi[size - 1].hashPubKey,
2512                                        dest_peer_info,
2513                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2514   }
2515   orig_peer_info = GNUNET_CONTAINER_multihashmap_get (peers, &pi->hashPubKey);
2516   if (NULL == orig_peer_info)
2517   {
2518     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2519                 "MESH:   Creating PeerInfo for origin.\n");
2520     orig_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
2521     orig_peer_info->id = GNUNET_PEER_intern (pi);
2522     GNUNET_CONTAINER_multihashmap_put (peers, &pi->hashPubKey, orig_peer_info,
2523                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2524   }
2525   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   Creating path...\n");
2526   path = path_new (size);
2527   own_pos = 0;
2528   for (i = 0; i < size; i++)
2529   {
2530     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   ... adding %s\n",
2531                 GNUNET_i2s (&pi[i]));
2532     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
2533     if (path->peers[i] == myid)
2534       own_pos = i;
2535   }
2536   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   Own position: %u\n", own_pos);
2537   if (own_pos == 0)
2538   {
2539     /* cannot be self, must be 'not found' */
2540     /* create path: self not found in path through self */
2541     GNUNET_break_op (0);
2542     path_destroy (path);
2543     /* FIXME error. destroy tunnel? leave for timeout? */
2544     return 0;
2545   }
2546   tunnel_add_path (t, path, own_pos);
2547   if (own_pos == size - 1)
2548   {
2549     /* It is for us! Send ack. */
2550     struct GNUNET_MESH_TunnelNotification cmsg;
2551     struct MeshDataDescriptor *info;
2552     unsigned int j;
2553
2554     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   It's for us!\n");
2555     peer_info_add_path_to_origin (orig_peer_info, path, GNUNET_NO);
2556     if (NULL == t->peers)
2557       t->peers = GNUNET_CONTAINER_multihashmap_create (4);
2558     GNUNET_break (GNUNET_OK ==
2559                   GNUNET_CONTAINER_multihashmap_put (t->peers,
2560                                                      &my_full_id.hashPubKey,
2561                                                      peer_info_get
2562                                                      (&my_full_id),
2563                                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
2564     /* FIXME use send_message */
2565     info = GNUNET_malloc (sizeof (struct MeshDataDescriptor));
2566     info->origin = &t->id;
2567     info->peer = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
2568     GNUNET_assert (NULL != info->peer);
2569     j = peer_info_transmit_slot (info->peer);
2570     info->handler_n = j;
2571     info->peer->types[j] = GNUNET_MESSAGE_TYPE_MESH_PATH_ACK;
2572     info->peer->infos[j] = info;
2573     info->peer->core_transmit[j] =
2574         GNUNET_CORE_notify_transmit_ready (core_handle, 0, 100,
2575                                            GNUNET_TIME_UNIT_FOREVER_REL, peer,
2576                                            sizeof (struct GNUNET_MESH_PathACK),
2577                                            &send_core_path_ack, info);
2578     cmsg.header.size = htons (sizeof (cmsg));
2579     cmsg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE);
2580     GNUNET_PEER_resolve (t->id.oid, &cmsg.peer);
2581     cmsg.tunnel_id = htonl (t->local_tid);
2582     GNUNET_SERVER_notification_context_broadcast (nc, &cmsg.header, GNUNET_NO);
2583   }
2584   else
2585   {
2586     struct MeshPeerPath *path2;
2587
2588     /* It's for somebody else! Retransmit. */
2589     path2 = path_duplicate (path);
2590     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   Retransmitting.\n");
2591     peer_info_add_path (dest_peer_info, path2, GNUNET_NO);
2592     path2 = path_duplicate (path);
2593     peer_info_add_path_to_origin (orig_peer_info, path2, GNUNET_NO);
2594     send_create_path (dest_peer_info, path, t);
2595   }
2596   return GNUNET_OK;
2597 }
2598
2599
2600 /**
2601  * Core handler for path destruction
2602  *
2603  * @param cls closure
2604  * @param message message
2605  * @param peer peer identity this notification is about
2606  * @param atsi performance data
2607  * @param atsi_count number of records in 'atsi'
2608  *
2609  * @return GNUNET_OK to keep the connection open,
2610  *         GNUNET_SYSERR to close it (signal serious error)
2611  */
2612 static int
2613 handle_mesh_path_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
2614                           const struct GNUNET_MessageHeader *message,
2615                           const struct GNUNET_ATS_Information *atsi,
2616                           unsigned int atsi_count)
2617 {
2618   struct GNUNET_MESH_ManipulatePath *msg;
2619   struct GNUNET_PeerIdentity *pi;
2620   struct MeshPeerPath *path;
2621   struct MeshTunnel *t;
2622   unsigned int own_pos;
2623   unsigned int i;
2624   size_t size;
2625
2626   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2627               "MESH: Received a PATH DESTROY msg from %s\n", GNUNET_i2s (peer));
2628   size = ntohs (message->size);
2629   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
2630   {
2631     GNUNET_break_op (0);
2632     return GNUNET_OK;
2633   }
2634
2635   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
2636   if (size % sizeof (struct GNUNET_PeerIdentity))
2637   {
2638     GNUNET_break_op (0);
2639     return GNUNET_OK;
2640   }
2641   size /= sizeof (struct GNUNET_PeerIdentity);
2642   if (size < 2)
2643   {
2644     GNUNET_break_op (0);
2645     return GNUNET_OK;
2646   }
2647   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:     path has %u hops.\n", size);
2648
2649   msg = (struct GNUNET_MESH_ManipulatePath *) message;
2650   pi = (struct GNUNET_PeerIdentity *) &msg[1];
2651   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2652               "MESH:     path is for tunnel %s [%X].\n", GNUNET_i2s (pi),
2653               msg->tid);
2654   t = tunnel_get (pi, ntohl (msg->tid));
2655   if (NULL == t)
2656   {
2657     /* TODO notify back: we don't know this tunnel */
2658     GNUNET_break_op (0);
2659     return GNUNET_OK;
2660   }
2661   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   Creating path...\n");
2662   path = path_new (size);
2663   own_pos = 0;
2664   for (i = 0; i < size; i++)
2665   {
2666     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   ... adding %s\n",
2667                 GNUNET_i2s (&pi[i]));
2668     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
2669     if (path->peers[i] == myid)
2670       own_pos = i;
2671   }
2672   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   Own position: %u\n", own_pos);
2673   if (own_pos < path->length - 1)
2674     send_message (message, &pi[own_pos + 1]);
2675   tunnel_delete_peer (t, path->peers[path->length - 1]);
2676   path_destroy (path);
2677   return GNUNET_OK;
2678 }
2679
2680
2681 /**
2682  * Core handler for notifications of broken paths
2683  *
2684  * @param cls closure
2685  * @param message message
2686  * @param peer peer identity this notification is about
2687  * @param atsi performance data
2688  * @param atsi_count number of records in 'atsi'
2689  *
2690  * @return GNUNET_OK to keep the connection open,
2691  *         GNUNET_SYSERR to close it (signal serious error)
2692  */
2693 static int
2694 handle_mesh_path_broken (void *cls, const struct GNUNET_PeerIdentity *peer,
2695                          const struct GNUNET_MessageHeader *message,
2696                          const struct GNUNET_ATS_Information *atsi,
2697                          unsigned int atsi_count)
2698 {
2699   struct GNUNET_MESH_PathBroken *msg;
2700   struct MeshTunnel *t;
2701
2702   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2703               "MESH: Received a PATH BROKEN msg from %s\n", GNUNET_i2s (peer));
2704   msg = (struct GNUNET_MESH_PathBroken *) message;
2705   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   regarding %s\n",
2706               GNUNET_i2s (&msg->peer1));
2707   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   regarding %s\n",
2708               GNUNET_i2s (&msg->peer2));
2709   t = tunnel_get (&msg->oid, ntohl (msg->tid));
2710   if (NULL == t)
2711   {
2712     GNUNET_break_op (0);
2713     return GNUNET_OK;
2714   }
2715   tunnel_notify_connection_broken (t, GNUNET_PEER_search (&msg->peer1),
2716                                    GNUNET_PEER_search (&msg->peer2));
2717   return GNUNET_OK;
2718
2719 }
2720
2721
2722 /**
2723  * Core handler for tunnel destruction
2724  *
2725  * @param cls closure
2726  * @param message message
2727  * @param peer peer identity this notification is about
2728  * @param atsi performance data
2729  * @param atsi_count number of records in 'atsi'
2730  *
2731  * @return GNUNET_OK to keep the connection open,
2732  *         GNUNET_SYSERR to close it (signal serious error)
2733  */
2734 static int
2735 handle_mesh_tunnel_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
2736                             const struct GNUNET_MessageHeader *message,
2737                             const struct GNUNET_ATS_Information *atsi,
2738                             unsigned int atsi_count)
2739 {
2740   struct GNUNET_MESH_TunnelDestroy *msg;
2741   struct MeshTunnel *t;
2742
2743   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2744               "MESH: Got a TUNNEL DESTROY packet from %s\n", GNUNET_i2s (peer));
2745   msg = (struct GNUNET_MESH_TunnelDestroy *) message;
2746   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   for tunnel %s [%u]\n",
2747               GNUNET_i2s (&msg->oid), ntohl (msg->tid));
2748   t = tunnel_get (&msg->oid, ntohl (msg->tid));
2749   if (NULL == t)
2750   {
2751     /* Probably already got the message from another path,
2752      * destroyed the tunnel and retransmitted to children.
2753      * Safe to ignore.
2754      */
2755     return GNUNET_OK;
2756   }
2757   if (t->id.oid == myid)
2758   {
2759     GNUNET_break_op (0);
2760     return GNUNET_OK;
2761   }
2762   if (t->local_tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
2763   {
2764     /* Tunnel was incoming, notify clients */
2765     send_clients_tunnel_destroy (t);
2766   }
2767   tunnel_send_destroy (t);
2768   tunnel_destroy (t);
2769   return GNUNET_OK;
2770 }
2771
2772
2773 /**
2774  * Core handler for mesh network traffic going from the origin to a peer
2775  *
2776  * @param cls closure
2777  * @param peer peer identity this notification is about
2778  * @param message message
2779  * @param atsi performance data
2780  * @param atsi_count number of records in 'atsi'
2781  * @return GNUNET_OK to keep the connection open,
2782  *         GNUNET_SYSERR to close it (signal serious error)
2783  */
2784 static int
2785 handle_mesh_data_unicast (void *cls, const struct GNUNET_PeerIdentity *peer,
2786                           const struct GNUNET_MessageHeader *message,
2787                           const struct GNUNET_ATS_Information *atsi,
2788                           unsigned int atsi_count)
2789 {
2790   struct GNUNET_MESH_Unicast *msg;
2791   struct MeshTunnel *t;
2792   GNUNET_PEER_Id pid;
2793   size_t size;
2794
2795   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: got a unicast packet from %s\n",
2796               GNUNET_i2s (peer));
2797   size = ntohs (message->size);
2798   if (size <
2799       sizeof (struct GNUNET_MESH_Unicast) +
2800       sizeof (struct GNUNET_MessageHeader))
2801   {
2802     GNUNET_break (0);
2803     return GNUNET_OK;
2804   }
2805   msg = (struct GNUNET_MESH_Unicast *) message;
2806   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  of type %u\n",
2807               ntohs (msg[1].header.type));
2808   t = tunnel_get (&msg->oid, ntohl (msg->tid));
2809   if (NULL == t)
2810   {
2811     /* TODO notify back: we don't know this tunnel */
2812     GNUNET_break_op (0);
2813     return GNUNET_OK;
2814   }
2815   tunnel_reset_timeout (t);
2816   pid = GNUNET_PEER_search (&msg->destination);
2817   if (pid == myid)
2818   {
2819     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2820                 "MESH:   it's for us! sending to clients...\n");
2821     send_subscribed_clients (message, (struct GNUNET_MessageHeader *) &msg[1]);
2822     return GNUNET_OK;
2823   }
2824   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2825               "MESH:   not for us, retransmitting...\n");
2826   send_message (message, path_get_first_hop (t->tree, pid));
2827   return GNUNET_OK;
2828 }
2829
2830
2831 /**
2832  * Core handler for mesh network traffic going from the origin to all peers
2833  *
2834  * @param cls closure
2835  * @param message message
2836  * @param peer peer identity this notification is about
2837  * @param atsi performance data
2838  * @param atsi_count number of records in 'atsi'
2839  * @return GNUNET_OK to keep the connection open,
2840  *         GNUNET_SYSERR to close it (signal serious error)
2841  *
2842  * TODO: Check who we got this from, to validate route.
2843  */
2844 static int
2845 handle_mesh_data_multicast (void *cls, const struct GNUNET_PeerIdentity *peer,
2846                             const struct GNUNET_MessageHeader *message,
2847                             const struct GNUNET_ATS_Information *atsi,
2848                             unsigned int atsi_count)
2849 {
2850   struct GNUNET_MESH_Multicast *msg;
2851   struct MeshTunnel *t;
2852   size_t size;
2853
2854   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: got a multicast packet from %s\n",
2855               GNUNET_i2s (peer));
2856   size = ntohs (message->size);
2857   if (sizeof (struct GNUNET_MESH_Multicast) +
2858       sizeof (struct GNUNET_MessageHeader) > size)
2859   {
2860     GNUNET_break_op (0);
2861     return GNUNET_OK;
2862   }
2863   msg = (struct GNUNET_MESH_Multicast *) message;
2864   t = tunnel_get (&msg->oid, ntohl (msg->tid));
2865
2866   if (NULL == t)
2867   {
2868     /* TODO notify that we dont know that tunnel */
2869     GNUNET_break_op (0);
2870     return GNUNET_OK;
2871   }
2872   tunnel_reset_timeout (t);
2873
2874   /* Transmit to locally interested clients */
2875   if (NULL != t->peers &&
2876       GNUNET_CONTAINER_multihashmap_contains (t->peers, &my_full_id.hashPubKey))
2877   {
2878     send_subscribed_clients (message, &msg[1].header);
2879   }
2880   tunnel_send_multicast (t, message);
2881   return GNUNET_OK;
2882 }
2883
2884
2885 /**
2886  * Core handler for mesh network traffic toward the owner of a tunnel
2887  *
2888  * @param cls closure
2889  * @param message message
2890  * @param peer peer identity this notification is about
2891  * @param atsi performance data
2892  * @param atsi_count number of records in 'atsi'
2893  *
2894  * @return GNUNET_OK to keep the connection open,
2895  *         GNUNET_SYSERR to close it (signal serious error)
2896  */
2897 static int
2898 handle_mesh_data_to_orig (void *cls, const struct GNUNET_PeerIdentity *peer,
2899                           const struct GNUNET_MessageHeader *message,
2900                           const struct GNUNET_ATS_Information *atsi,
2901                           unsigned int atsi_count)
2902 {
2903   struct GNUNET_MESH_ToOrigin *msg;
2904   struct GNUNET_PeerIdentity id;
2905   struct MeshPeerInfo *peer_info;
2906   struct MeshTunnel *t;
2907   size_t size;
2908
2909   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: got a ToOrigin packet from %s\n",
2910               GNUNET_i2s (peer));
2911   size = ntohs (message->size);
2912   if (size < sizeof (struct GNUNET_MESH_ToOrigin) +     /* Payload must be */
2913       sizeof (struct GNUNET_MessageHeader))     /* at least a header */
2914   {
2915     GNUNET_break_op (0);
2916     return GNUNET_OK;
2917   }
2918   msg = (struct GNUNET_MESH_ToOrigin *) message;
2919   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  of type %u\n",
2920               ntohs (msg[1].header.type));
2921   t = tunnel_get (&msg->oid, ntohl (msg->tid));
2922
2923   if (NULL == t)
2924   {
2925     /* TODO notify that we dont know this tunnel (whom)? */
2926     GNUNET_break_op (0);
2927     return GNUNET_OK;
2928   }
2929
2930   if (t->id.oid == myid)
2931   {
2932     char cbuf[size];
2933     struct GNUNET_MESH_ToOrigin *copy;
2934
2935     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2936                 "MESH:   it's for us! sending to clients...\n");
2937     if (NULL == t->client)
2938     {
2939       /* got data packet for ownerless tunnel */
2940       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   no clients!\n");
2941       GNUNET_break_op (0);
2942       return GNUNET_OK;
2943     }
2944     /* TODO signature verification */
2945     memcpy (cbuf, message, size);
2946     copy = (struct GNUNET_MESH_ToOrigin *) cbuf;
2947     copy->tid = htonl (t->local_tid);
2948     GNUNET_SERVER_notification_context_unicast (nc, t->client->handle,
2949                                                 &copy->header, GNUNET_YES);
2950     return GNUNET_OK;
2951   }
2952   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2953               "MESH:   not for us, retransmitting...\n");
2954
2955   peer_info = peer_info_get (&msg->oid);
2956   if (NULL == peer_info)
2957   {
2958     /* unknown origin of tunnel */
2959     GNUNET_break (0);
2960     return GNUNET_OK;
2961   }
2962   GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &id);
2963   send_message (message, &id);
2964
2965   return GNUNET_OK;
2966 }
2967
2968
2969 /**
2970  * Core handler for path ACKs
2971  *
2972  * @param cls closure
2973  * @param message message
2974  * @param peer peer identity this notification is about
2975  * @param atsi performance data
2976  * @param atsi_count number of records in 'atsi'
2977  *
2978  * @return GNUNET_OK to keep the connection open,
2979  *         GNUNET_SYSERR to close it (signal serious error)
2980  */
2981 static int
2982 handle_mesh_path_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
2983                       const struct GNUNET_MessageHeader *message,
2984                       const struct GNUNET_ATS_Information *atsi,
2985                       unsigned int atsi_count)
2986 {
2987   struct GNUNET_MESH_PathACK *msg;
2988   struct GNUNET_PeerIdentity id;
2989   struct MeshPeerInfo *peer_info;
2990   struct MeshTunnel *t;
2991
2992   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Received a path ACK msg [%s]\n",
2993               GNUNET_i2s (&my_full_id));
2994   msg = (struct GNUNET_MESH_PathACK *) message;
2995   t = tunnel_get (&msg->oid, msg->tid);
2996   if (NULL == t)
2997   {
2998     /* TODO notify that we don't know the tunnel */
2999     return GNUNET_OK;
3000   }
3001
3002   /* Message for us? */
3003   if (0 == memcmp (&msg->oid, &my_full_id, sizeof (struct GNUNET_PeerIdentity)))
3004   {
3005     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   It's for us!\n");
3006     if (NULL == t->client)
3007     {
3008       GNUNET_break_op (0);
3009       return GNUNET_OK;
3010     }
3011     if (NULL != t->dht_get_type)
3012     {
3013       GNUNET_DHT_get_stop (t->dht_get_type);
3014       t->dht_get_type = NULL;
3015     }
3016     peer_info = peer_info_get (&msg->peer_id);
3017     tree_set_status (t->tree, peer_info->id, MESH_PEER_READY);
3018     send_client_peer_connected (t, peer_info->id);
3019     return GNUNET_OK;
3020   }
3021
3022   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3023               "MESH:   not for us, retransmitting...\n");
3024   GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &id);
3025   peer_info = peer_info_get (&msg->oid);
3026   if (NULL == peer_info)
3027   {
3028     /* If we know the tunnel, we should DEFINITELY know the peer */
3029     GNUNET_break (0);
3030     return GNUNET_OK;
3031   }
3032   send_message (message, &id);
3033   return GNUNET_OK;
3034 }
3035
3036
3037 /**
3038  * Functions to handle messages from core
3039  */
3040 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
3041   {&handle_mesh_path_create, GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE, 0},
3042   {&handle_mesh_path_destroy, GNUNET_MESSAGE_TYPE_MESH_PATH_DESTROY, 0},
3043   {&handle_mesh_path_broken, GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN,
3044    sizeof (struct GNUNET_MESH_PathBroken)},
3045   {&handle_mesh_tunnel_destroy, GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY, 0},
3046   {&handle_mesh_data_unicast, GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
3047   {&handle_mesh_data_multicast, GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
3048   {&handle_mesh_data_to_orig, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
3049   {&handle_mesh_path_ack, GNUNET_MESSAGE_TYPE_MESH_PATH_ACK,
3050    sizeof (struct GNUNET_MESH_PathACK)},
3051   {NULL, 0, 0}
3052 };
3053
3054
3055
3056 /******************************************************************************/
3057 /****************       MESH LOCAL HANDLER HELPERS      ***********************/
3058 /******************************************************************************/
3059
3060 /**
3061  * deregister_app: iterator for removing each application registered by a client
3062  *
3063  * @param cls closure
3064  * @param key the hash of the application id (used to access the hashmap)
3065  * @param value the value stored at the key (client)
3066  *
3067  * @return GNUNET_OK on success
3068  */
3069 static int
3070 deregister_app (void *cls, const GNUNET_HashCode * key, void *value)
3071 {
3072   GNUNET_break (GNUNET_YES ==
3073                 GNUNET_CONTAINER_multihashmap_remove (applications, key,
3074                                                       value));
3075   return GNUNET_OK;
3076 }
3077
3078 #if LATER
3079 /**
3080  * notify_client_connection_failure: notify a client that the connection to the
3081  * requested remote peer is not possible (for instance, no route found)
3082  * Function called when the socket is ready to queue more data. "buf" will be
3083  * NULL and "size" zero if the socket was closed for writing in the meantime.
3084  *
3085  * @param cls closure
3086  * @param size number of bytes available in buf
3087  * @param buf where the callee should write the message
3088  * @return number of bytes written to buf
3089  */
3090 static size_t
3091 notify_client_connection_failure (void *cls, size_t size, void *buf)
3092 {
3093   int size_needed;
3094   struct MeshPeerInfo *peer_info;
3095   struct GNUNET_MESH_PeerControl *msg;
3096   struct GNUNET_PeerIdentity id;
3097
3098   if (0 == size && NULL == buf)
3099   {
3100     // TODO retry? cancel?
3101     return 0;
3102   }
3103
3104   size_needed = sizeof (struct GNUNET_MESH_PeerControl);
3105   peer_info = (struct MeshPeerInfo *) cls;
3106   msg = (struct GNUNET_MESH_PeerControl *) buf;
3107   msg->header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
3108   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DISCONNECTED);
3109 //     msg->tunnel_id = htonl(peer_info->t->tid);
3110   GNUNET_PEER_resolve (peer_info->id, &id);
3111   memcpy (&msg->peer, &id, sizeof (struct GNUNET_PeerIdentity));
3112
3113   return size_needed;
3114 }
3115 #endif
3116
3117
3118 /**
3119  * Send keepalive packets for a peer
3120  *
3121  * @param cls Closure (tunnel for which to send the keepalive).
3122  * @param tc Notification context.
3123  *
3124  * TODO: implement explicit multicast keepalive?
3125  */
3126 static void
3127 path_refresh (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3128 {
3129   struct MeshTunnel *t = cls;
3130   struct GNUNET_MessageHeader *payload;
3131   struct GNUNET_MESH_Multicast *msg;
3132   size_t size =
3133       sizeof (struct GNUNET_MESH_Multicast) +
3134       sizeof (struct GNUNET_MessageHeader);
3135   char cbuf[size];
3136
3137   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3138   {
3139     return;
3140   }
3141   t->path_refresh_task = GNUNET_SCHEDULER_NO_TASK;
3142
3143   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3144               "MESH: sending keepalive for tunnel %d\n", t->id.tid);
3145
3146   msg = (struct GNUNET_MESH_Multicast *) cbuf;
3147   msg->header.size = htons (size);
3148   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
3149   msg->oid = my_full_id;
3150   msg->tid = htonl (t->id.tid);
3151   payload = (struct GNUNET_MessageHeader *) &msg[1];
3152   payload->size = htons (sizeof (struct GNUNET_MessageHeader));
3153   payload->type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE);
3154   tunnel_send_multicast (t, &msg->header);
3155
3156   t->path_refresh_task =
3157       GNUNET_SCHEDULER_add_delayed (REFRESH_PATH_TIME, &path_refresh, t);
3158   return;
3159 }
3160
3161
3162 /**
3163  * Function to process paths received for a new peer addition. The recorded
3164  * paths form the initial tunnel, which can be optimized later.
3165  * Called on each result obtained for the DHT search.
3166  *
3167  * @param cls closure
3168  * @param exp when will this value expire
3169  * @param key key of the result
3170  * @param type type of the result
3171  * @param size number of bytes in data
3172  * @param data pointer to the result data
3173  *
3174  * TODO: re-issue the request after certain time? cancel after X results?
3175  */
3176 static void
3177 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
3178                     const GNUNET_HashCode * key,
3179                     const struct GNUNET_PeerIdentity *get_path,
3180                     unsigned int get_path_length,
3181                     const struct GNUNET_PeerIdentity *put_path,
3182                     unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
3183                     size_t size, const void *data)
3184 {
3185   struct MeshPathInfo *path_info = cls;
3186   struct MeshPeerPath *p;
3187   struct GNUNET_PeerIdentity pi;
3188   int i;
3189
3190   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Got results from DHT!\n");
3191   GNUNET_PEER_resolve (path_info->peer->id, &pi);
3192   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   for %s\n", GNUNET_i2s (&pi));
3193 //   GNUNET_DHT_get_stop(path_info->peer->dhtget);
3194 //   path_info->peer->dhtget = NULL;
3195
3196   p = path_build_from_dht (get_path, get_path_length, put_path,
3197                            put_path_length);
3198   peer_info_add_path (path_info->peer, p, GNUNET_NO);
3199   for (i = 0; i < path_info->peer->ntunnels; i++)
3200   {
3201     tunnel_add_peer (path_info->peer->tunnels[i], path_info->peer);
3202     peer_info_connect (path_info->peer, path_info->t);
3203   }
3204 //   GNUNET_free (path_info);
3205
3206   return;
3207 }
3208
3209
3210 /**
3211  * Function to process paths received for a new peer addition. The recorded
3212  * paths form the initial tunnel, which can be optimized later.
3213  * Called on each result obtained for the DHT search.
3214  *
3215  * @param cls closure
3216  * @param exp when will this value expire
3217  * @param key key of the result
3218  * @param type type of the result
3219  * @param size number of bytes in data
3220  * @param data pointer to the result data
3221  */
3222 static void
3223 dht_get_type_handler (void *cls, struct GNUNET_TIME_Absolute exp,
3224                       const GNUNET_HashCode * key,
3225                       const struct GNUNET_PeerIdentity *get_path,
3226                       unsigned int get_path_length,
3227                       const struct GNUNET_PeerIdentity *put_path,
3228                       unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
3229                       size_t size, const void *data)
3230 {
3231   const struct GNUNET_PeerIdentity *pi = data;
3232   struct MeshTunnel *t = cls;
3233   struct MeshPeerInfo *peer_info;
3234   struct MeshPeerPath *p;
3235
3236   if (size != sizeof (struct GNUNET_PeerIdentity))
3237   {
3238     GNUNET_break_op (0);
3239     return;
3240   }
3241   GNUNET_assert (NULL != t->client);
3242   peer_info = peer_info_get (pi);
3243   (void) GNUNET_CONTAINER_multihashmap_put (t->peers, &pi->hashPubKey,
3244                                             peer_info,
3245                                             GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
3246
3247   p = path_build_from_dht (get_path, get_path_length, put_path,
3248                            put_path_length);
3249   peer_info_add_path (peer_info, p, GNUNET_NO);
3250   tunnel_add_peer (t, peer_info);
3251   peer_info_connect (peer_info, t);
3252 }
3253
3254
3255 /******************************************************************************/
3256 /*********************       MESH LOCAL HANDLES      **************************/
3257 /******************************************************************************/
3258
3259
3260 /**
3261  * Handler for client disconnection
3262  *
3263  * @param cls closure
3264  * @param client identification of the client; NULL
3265  *        for the last call when the server is destroyed
3266  */
3267 static void
3268 handle_local_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
3269 {
3270   struct MeshClient *c;
3271   struct MeshClient *next;
3272
3273   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: client disconnected\n");
3274   if (client == NULL)
3275   {
3276     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    (SERVER DOWN)\n");
3277     return;
3278   }
3279   c = clients;
3280   while (NULL != c)
3281   {
3282     if (c->handle != client && NULL != client)
3283     {
3284       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    ... searching\n");
3285       c = c->next;
3286       continue;
3287     }
3288     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: matching client found\n");
3289     GNUNET_SERVER_client_drop (c->handle);
3290     if (NULL != c->tunnels)
3291     {
3292       GNUNET_CONTAINER_multihashmap_iterate (c->tunnels,
3293                                              &tunnel_destroy_iterator, c);
3294       GNUNET_CONTAINER_multihashmap_destroy (c->tunnels);
3295     }
3296
3297     /* deregister clients applications */
3298     if (NULL != c->apps)
3299     {
3300       GNUNET_CONTAINER_multihashmap_iterate (c->apps, &deregister_app, NULL);
3301       GNUNET_CONTAINER_multihashmap_destroy (c->apps);
3302     }
3303     if (0 == GNUNET_CONTAINER_multihashmap_size (applications) &&
3304         GNUNET_SCHEDULER_NO_TASK != announce_applications_task)
3305     {
3306       GNUNET_SCHEDULER_cancel (announce_applications_task);
3307       announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
3308     }
3309     if (NULL != c->types)
3310       GNUNET_CONTAINER_multihashmap_destroy (c->types);
3311     next = c->next;
3312     GNUNET_CONTAINER_DLL_remove (clients, clients_tail, c);
3313     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   CLIENT FREE at %p\n", c);
3314     GNUNET_free (c);
3315     c = next;
3316   }
3317
3318   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    done!\n");
3319   return;
3320 }
3321
3322
3323 /**
3324  * Handler for new clients
3325  *
3326  * @param cls closure
3327  * @param client identification of the client
3328  * @param message the actual message, which includes messages the client wants
3329  */
3330 static void
3331 handle_local_new_client (void *cls, struct GNUNET_SERVER_Client *client,
3332                          const struct GNUNET_MessageHeader *message)
3333 {
3334   struct GNUNET_MESH_ClientConnect *cc_msg;
3335   struct MeshClient *c;
3336   GNUNET_MESH_ApplicationType *a;
3337   unsigned int size;
3338   uint16_t ntypes;
3339   uint16_t *t;
3340   uint16_t napps;
3341   uint16_t i;
3342
3343   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: new client connected\n");
3344   /* Check data sanity */
3345   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_ClientConnect);
3346   cc_msg = (struct GNUNET_MESH_ClientConnect *) message;
3347   ntypes = ntohs (cc_msg->types);
3348   napps = ntohs (cc_msg->applications);
3349   if (size !=
3350       ntypes * sizeof (uint16_t) + napps * sizeof (GNUNET_MESH_ApplicationType))
3351   {
3352     GNUNET_break (0);
3353     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3354     return;
3355   }
3356
3357   /* Create new client structure */
3358   c = GNUNET_malloc (sizeof (struct MeshClient));
3359 #if MESH_DEBUG
3360   c->id = next_client_id++;
3361 #endif
3362   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   CLIENT NEW %u at %p\n", c->id,
3363               c);
3364   c->handle = client;
3365   GNUNET_SERVER_client_keep (client);
3366   a = (GNUNET_MESH_ApplicationType *) &cc_msg[1];
3367   if (napps > 0)
3368   {
3369     GNUNET_MESH_ApplicationType at;
3370     GNUNET_HashCode hc;
3371
3372     c->apps = GNUNET_CONTAINER_multihashmap_create (napps);
3373     for (i = 0; i < napps; i++)
3374     {
3375       at = ntohl (a[i]);
3376       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   app type: %u\n", at);
3377       GNUNET_CRYPTO_hash (&at, sizeof (at), &hc);
3378       /* store in clients hashmap */
3379       GNUNET_CONTAINER_multihashmap_put (c->apps, &hc, c,
3380                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
3381       /* store in global hashmap, for announcements */
3382       GNUNET_CONTAINER_multihashmap_put (applications, &hc, c,
3383                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
3384     }
3385     if (GNUNET_SCHEDULER_NO_TASK == announce_applications_task)
3386       announce_applications_task =
3387           GNUNET_SCHEDULER_add_now (&announce_applications, NULL);
3388
3389   }
3390   if (ntypes > 0)
3391   {
3392     uint16_t u16;
3393     GNUNET_HashCode hc;
3394
3395     t = (uint16_t *) & a[napps];
3396     c->types = GNUNET_CONTAINER_multihashmap_create (ntypes);
3397     for (i = 0; i < ntypes; i++)
3398     {
3399       u16 = ntohs (t[i]);
3400       GNUNET_CRYPTO_hash (&u16, sizeof (u16), &hc);
3401
3402       /* store in clients hashmap */
3403       GNUNET_CONTAINER_multihashmap_put (c->types, &hc, c,
3404                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
3405       /* store in global hashmap */
3406       GNUNET_CONTAINER_multihashmap_put (types, &hc, c,
3407                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
3408     }
3409   }
3410   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3411               "MESH:  client has %u+%u subscriptions\n", napps, ntypes);
3412
3413   GNUNET_CONTAINER_DLL_insert (clients, clients_tail, c);
3414   c->tunnels = GNUNET_CONTAINER_multihashmap_create (32);
3415   GNUNET_SERVER_notification_context_add (nc, client);
3416
3417   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3418 #if MESH_DEBUG
3419   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: new client processed\n");
3420 #endif
3421 }
3422
3423
3424 /**
3425  * Handler for requests of new tunnels
3426  *
3427  * @param cls closure
3428  * @param client identification of the client
3429  * @param message the actual message
3430  */
3431 static void
3432 handle_local_tunnel_create (void *cls, struct GNUNET_SERVER_Client *client,
3433                             const struct GNUNET_MessageHeader *message)
3434 {
3435   struct GNUNET_MESH_TunnelMessage *t_msg;
3436   struct MeshTunnel *t;
3437   struct MeshClient *c;
3438   GNUNET_HashCode hash;
3439
3440   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: new tunnel requested\n");
3441
3442   /* Sanity check for client registration */
3443   if (NULL == (c = client_get (client)))
3444   {
3445     GNUNET_break (0);
3446     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3447     return;
3448   }
3449 #if MESH_DEBUG
3450   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   by client %u\n", c->id);
3451 #endif
3452
3453   /* Message sanity check */
3454   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
3455   {
3456     GNUNET_break (0);
3457     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3458     return;
3459   }
3460
3461   t_msg = (struct GNUNET_MESH_TunnelMessage *) message;
3462   /* Sanity check for tunnel numbering */
3463   if (0 == (ntohl (t_msg->tunnel_id) & GNUNET_MESH_LOCAL_TUNNEL_ID_CLI))
3464   {
3465     GNUNET_break (0);
3466     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3467     return;
3468   }
3469   /* Sanity check for duplicate tunnel IDs */
3470   if (NULL != tunnel_get_by_local_id (c, ntohl (t_msg->tunnel_id)))
3471   {
3472     GNUNET_break (0);
3473     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3474     return;
3475   }
3476
3477   t = GNUNET_malloc (sizeof (struct MeshTunnel));
3478   while (NULL != tunnel_get_by_pi (myid, next_tid))
3479     next_tid = (next_tid + 1) & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
3480   t->id.tid = next_tid++;
3481   next_tid = next_tid & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
3482   t->id.oid = myid;
3483   t->local_tid = ntohl (t_msg->tunnel_id);
3484 #if MESH_DEBUG
3485   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: CREATED TUNNEL %s [%x] (%x)\n",
3486               GNUNET_i2s (&my_full_id), t->id.tid, t->local_tid);
3487 #endif
3488   t->client = c;
3489   t->peers = GNUNET_CONTAINER_multihashmap_create (32);
3490
3491   GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
3492   if (GNUNET_OK !=
3493       GNUNET_CONTAINER_multihashmap_put (c->tunnels, &hash, t,
3494                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
3495   {
3496     GNUNET_break (0);
3497     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3498     return;
3499   }
3500
3501   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
3502   if (GNUNET_OK !=
3503       GNUNET_CONTAINER_multihashmap_put (tunnels, &hash, t,
3504                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
3505   {
3506     GNUNET_break (0);
3507     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3508     return;
3509   }
3510   t->tree = tree_new (myid);
3511   tree_set_me (t->tree, myid);
3512
3513   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3514   return;
3515 }
3516
3517
3518 /**
3519  * Handler for requests of deleting tunnels
3520  *
3521  * @param cls closure
3522  * @param client identification of the client
3523  * @param message the actual message
3524  */
3525 static void
3526 handle_local_tunnel_destroy (void *cls, struct GNUNET_SERVER_Client *client,
3527                              const struct GNUNET_MessageHeader *message)
3528 {
3529   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
3530   struct MeshClient *c;
3531   struct MeshTunnel *t;
3532   MESH_TunnelNumber tid;
3533   GNUNET_HashCode hash;
3534
3535   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3536               "MESH: Got a DESTROY TUNNEL from client!\n");
3537
3538   /* Sanity check for client registration */
3539   if (NULL == (c = client_get (client)))
3540   {
3541     GNUNET_break (0);
3542     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3543     return;
3544   }
3545   /* Message sanity check */
3546   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
3547   {
3548     GNUNET_break (0);
3549     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3550     return;
3551   }
3552 #if MESH_DEBUG
3553   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   by client %u\n", c->id);
3554 #endif
3555   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
3556
3557   /* Retrieve tunnel */
3558   tid = ntohl (tunnel_msg->tunnel_id);
3559
3560   /* Remove from local id hashmap */
3561   GNUNET_CRYPTO_hash (&tid, sizeof (MESH_TunnelNumber), &hash);
3562   t = GNUNET_CONTAINER_multihashmap_get (c->tunnels, &hash);
3563   GNUNET_assert (GNUNET_YES ==
3564                  GNUNET_CONTAINER_multihashmap_remove (c->tunnels, &hash, t));
3565
3566   t->client = NULL;
3567   tunnel_send_destroy (t);
3568   tunnel_destroy (t);
3569   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3570   return;
3571 }
3572
3573
3574 /**
3575  * Handler for connection requests to new peers
3576  *
3577  * @param cls closure
3578  * @param client identification of the client
3579  * @param message the actual message (PeerControl)
3580  */
3581 static void
3582 handle_local_connect_add (void *cls, struct GNUNET_SERVER_Client *client,
3583                           const struct GNUNET_MessageHeader *message)
3584 {
3585   struct GNUNET_MESH_PeerControl *peer_msg;
3586   struct MeshPeerInfo *peer_info;
3587   struct MeshClient *c;
3588   struct MeshTunnel *t;
3589   MESH_TunnelNumber tid;
3590
3591   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Got connection request\n");
3592   /* Sanity check for client registration */
3593   if (NULL == (c = client_get (client)))
3594   {
3595     GNUNET_break (0);
3596     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3597     return;
3598   }
3599
3600   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
3601   /* Sanity check for message size */
3602   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
3603   {
3604     GNUNET_break (0);
3605     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3606     return;
3607   }
3608
3609   /* Tunnel exists? */
3610   tid = ntohl (peer_msg->tunnel_id);
3611   t = tunnel_get_by_local_id (c, tid);
3612   if (NULL == t)
3613   {
3614     GNUNET_break (0);
3615     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3616     return;
3617   }
3618
3619   /* Does client own tunnel? */
3620   if (t->client->handle != client)
3621   {
3622     GNUNET_break (0);
3623     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3624     return;
3625   }
3626   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:      for %s\n",
3627               GNUNET_i2s (&peer_msg->peer));
3628   peer_info = peer_info_get (&peer_msg->peer);
3629
3630   tunnel_add_peer (t, peer_info);
3631   peer_info_connect (peer_info, t);
3632
3633   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3634   return;
3635 }
3636
3637
3638 /**
3639  * Handler for disconnection requests of peers in a tunnel
3640  *
3641  * @param cls closure
3642  * @param client identification of the client
3643  * @param message the actual message (PeerControl)
3644  */
3645 static void
3646 handle_local_connect_del (void *cls, struct GNUNET_SERVER_Client *client,
3647                           const struct GNUNET_MessageHeader *message)
3648 {
3649   struct GNUNET_MESH_PeerControl *peer_msg;
3650   struct MeshPeerInfo *peer_info;
3651   struct MeshClient *c;
3652   struct MeshTunnel *t;
3653   MESH_TunnelNumber tid;
3654
3655   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Got a PEER DEL request\n");
3656   /* Sanity check for client registration */
3657   if (NULL == (c = client_get (client)))
3658   {
3659     GNUNET_break (0);
3660     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3661     return;
3662   }
3663   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
3664   /* Sanity check for message size */
3665   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
3666   {
3667     GNUNET_break (0);
3668     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3669     return;
3670   }
3671
3672   /* Tunnel exists? */
3673   tid = ntohl (peer_msg->tunnel_id);
3674   t = tunnel_get_by_local_id (c, tid);
3675   if (NULL == t)
3676   {
3677     GNUNET_break (0);
3678     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3679     return;
3680   }
3681   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   on tunnel %X\n", t->id.tid);
3682
3683   /* Does client own tunnel? */
3684   if (t->client->handle != client)
3685   {
3686     GNUNET_break (0);
3687     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3688     return;
3689   }
3690
3691   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:   for peer %s\n",
3692               GNUNET_i2s (&peer_msg->peer));
3693   /* Is the peer in the tunnel? */
3694   peer_info =
3695       GNUNET_CONTAINER_multihashmap_get (t->peers, &peer_msg->peer.hashPubKey);
3696   if (NULL == peer_info)
3697   {
3698     GNUNET_break (0);
3699     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3700     return;
3701   }
3702
3703   /* Ok, delete peer from tunnel */
3704   GNUNET_CONTAINER_multihashmap_remove_all (t->peers,
3705                                             &peer_msg->peer.hashPubKey);
3706
3707   send_destroy_path (t, peer_info->id);
3708   tunnel_delete_peer (t, peer_info->id);
3709   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3710   return;
3711 }
3712
3713
3714 /**
3715  * Handler for connection requests to new peers by type
3716  *
3717  * @param cls closure
3718  * @param client identification of the client
3719  * @param message the actual message (ConnectPeerByType)
3720  */
3721 static void
3722 handle_local_connect_by_type (void *cls, struct GNUNET_SERVER_Client *client,
3723                               const struct GNUNET_MessageHeader *message)
3724 {
3725   struct GNUNET_MESH_ConnectPeerByType *connect_msg;
3726   struct MeshClient *c;
3727   struct MeshTunnel *t;
3728   GNUNET_HashCode hash;
3729   MESH_TunnelNumber tid;
3730
3731   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: got connect by type request\n");
3732   /* Sanity check for client registration */
3733   if (NULL == (c = client_get (client)))
3734   {
3735     GNUNET_break (0);
3736     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3737     return;
3738   }
3739
3740   connect_msg = (struct GNUNET_MESH_ConnectPeerByType *) message;
3741   /* Sanity check for message size */
3742   if (sizeof (struct GNUNET_MESH_ConnectPeerByType) !=
3743       ntohs (connect_msg->header.size))
3744   {
3745     GNUNET_break (0);
3746     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3747     return;
3748   }
3749
3750   /* Tunnel exists? */
3751   tid = ntohl (connect_msg->tunnel_id);
3752   t = tunnel_get_by_local_id (c, tid);
3753   if (NULL == t)
3754   {
3755     GNUNET_break (0);
3756     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3757     return;
3758   }
3759
3760   /* Does client own tunnel? */
3761   if (t->client->handle != client)
3762   {
3763     GNUNET_break (0);
3764     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3765     return;
3766   }
3767
3768   /* Do WE have the service? */
3769   t->type = ntohl (connect_msg->type);
3770   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  type requested: %u\n", t->type);
3771   GNUNET_CRYPTO_hash (&t->type, sizeof (GNUNET_MESH_ApplicationType), &hash);
3772   if (GNUNET_CONTAINER_multihashmap_contains (applications, &hash) ==
3773       GNUNET_YES)
3774   {
3775     /* Yes! Fast forward, add ourselves to the tunnel and send the
3776      * good news to the client
3777      */
3778     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  available locally\n");
3779     GNUNET_CONTAINER_multihashmap_put (t->peers, &my_full_id.hashPubKey,
3780                                        peer_info_get (&my_full_id),
3781                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3782
3783     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  notifying client\n");
3784     send_client_peer_connected (t, myid);
3785     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  Done\n");
3786     GNUNET_SERVER_receive_done (client, GNUNET_OK);
3787     return;
3788   }
3789   /* Ok, lets find a peer offering the service */
3790   if (NULL != t->dht_get_type)
3791   {
3792     GNUNET_DHT_get_stop (t->dht_get_type);
3793   }
3794   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  looking in DHT for %s\n",
3795               GNUNET_h2s (&hash));
3796   t->dht_get_type =
3797       GNUNET_DHT_get_start (dht_handle, GNUNET_TIME_UNIT_FOREVER_REL,
3798                             GNUNET_BLOCK_TYPE_TEST, &hash, 10U,
3799                             GNUNET_DHT_RO_RECORD_ROUTE |
3800                             GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE, NULL, 0,
3801                             &dht_get_type_handler, t);
3802
3803   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3804   return;
3805 }
3806
3807
3808 /**
3809  * Handler for client traffic directed to one peer
3810  *
3811  * @param cls closure
3812  * @param client identification of the client
3813  * @param message the actual message
3814  */
3815 static void
3816 handle_local_unicast (void *cls, struct GNUNET_SERVER_Client *client,
3817                       const struct GNUNET_MessageHeader *message)
3818 {
3819   struct MeshClient *c;
3820   struct MeshTunnel *t;
3821   struct MeshPeerInfo *pi;
3822   struct GNUNET_MESH_Unicast *data_msg;
3823   MESH_TunnelNumber tid;
3824   size_t size;
3825
3826   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3827               "MESH: Got a unicast request from a client!\n");
3828
3829   /* Sanity check for client registration */
3830   if (NULL == (c = client_get (client)))
3831   {
3832     GNUNET_break (0);
3833     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3834     return;
3835   }
3836   data_msg = (struct GNUNET_MESH_Unicast *) message;
3837   /* Sanity check for message size */
3838   size = ntohs (message->size);
3839   if (sizeof (struct GNUNET_MESH_Unicast) +
3840       sizeof (struct GNUNET_MessageHeader) > size)
3841   {
3842     GNUNET_break (0);
3843     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3844     return;
3845   }
3846
3847   /* Tunnel exists? */
3848   tid = ntohl (data_msg->tid);
3849   t = tunnel_get_by_local_id (c, tid);
3850   if (NULL == t)
3851   {
3852     GNUNET_break (0);
3853     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3854     return;
3855   }
3856
3857   /*  Is it a local tunnel? Then, does client own the tunnel? */
3858   if (NULL != t->client && NULL != t->client->handle &&
3859       t->client->handle != client)
3860   {
3861     GNUNET_break (0);
3862     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3863     return;
3864   }
3865
3866   pi = GNUNET_CONTAINER_multihashmap_get (t->peers,
3867                                           &data_msg->destination.hashPubKey);
3868   /* Is the selected peer in the tunnel? */
3869   if (NULL == pi)
3870   {
3871     GNUNET_break (0);
3872     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3873     return;
3874   }
3875
3876   /* Ok, everything is correct, send the message
3877    * (pretend we got it from a mesh peer)
3878    */
3879   {
3880     char buf[ntohs (message->size)];
3881     struct GNUNET_MESH_Unicast *copy;
3882
3883     /* Work around const limitation */
3884     copy = (struct GNUNET_MESH_Unicast *) buf;
3885     memcpy (buf, data_msg, size);
3886     copy->oid = my_full_id;
3887     copy->tid = htonl (t->id.tid);
3888     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3889                 "MESH:   calling generic handler...\n");
3890     handle_mesh_data_unicast (NULL, &my_full_id, &copy->header, NULL, 0);
3891   }
3892   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3893   return;
3894 }
3895
3896
3897 /**
3898  * Handler for client traffic directed to the origin
3899  *
3900  * @param cls closure
3901  * @param client identification of the client
3902  * @param message the actual message
3903  */
3904 static void
3905 handle_local_to_origin (void *cls, struct GNUNET_SERVER_Client *client,
3906                         const struct GNUNET_MessageHeader *message)
3907 {
3908   struct GNUNET_MESH_ToOrigin *data_msg;
3909   struct GNUNET_PeerIdentity id;
3910   struct MeshClient *c;
3911   struct MeshTunnel *t;
3912   MESH_TunnelNumber tid;
3913   size_t size;
3914
3915   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3916               "MESH: Got a ToOrigin request from a client!\n");
3917
3918   /* Sanity check for client registration */
3919   if (NULL == (c = client_get (client)))
3920   {
3921     GNUNET_break (0);
3922     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3923     return;
3924   }
3925   data_msg = (struct GNUNET_MESH_ToOrigin *) message;
3926   /* Sanity check for message size */
3927   size = ntohs (message->size);
3928   if (sizeof (struct GNUNET_MESH_ToOrigin) +
3929       sizeof (struct GNUNET_MessageHeader) > size)
3930   {
3931     GNUNET_break (0);
3932     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3933     return;
3934   }
3935
3936   /* Tunnel exists? */
3937   tid = ntohl (data_msg->tid);
3938   if (tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
3939   {
3940     GNUNET_break (0);
3941     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3942     return;
3943   }
3944   t = tunnel_get_by_local_id (c, tid);
3945   if (NULL == t)
3946   {
3947     GNUNET_break (0);
3948     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3949     return;
3950   }
3951
3952   /*  It shouldn't be a local tunnel.  */
3953   if (NULL != t->client)
3954   {
3955     GNUNET_break (0);
3956     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3957     return;
3958   }
3959   GNUNET_PEER_resolve (t->id.oid, &id);
3960
3961   /* Ok, everything is correct, send the message
3962    * (pretend we got it from a mesh peer)
3963    */
3964   {
3965     char buf[ntohs (message->size)];
3966     struct GNUNET_MESH_ToOrigin *copy;
3967
3968     /* Work around const limitation */
3969     copy = (struct GNUNET_MESH_ToOrigin *) buf;
3970     memcpy (buf, data_msg, size);
3971     copy->oid = id;
3972     copy->tid = htonl (t->id.tid);
3973     copy->sender = my_full_id;
3974     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3975                 "MESH:   calling generic handler...\n");
3976     handle_mesh_data_to_orig (NULL, &my_full_id, &copy->header, NULL, 0);
3977   }
3978   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3979   return;
3980 }
3981
3982
3983 /**
3984  * Handler for client traffic directed to all peers in a tunnel
3985  *
3986  * @param cls closure
3987  * @param client identification of the client
3988  * @param message the actual message
3989  */
3990 static void
3991 handle_local_multicast (void *cls, struct GNUNET_SERVER_Client *client,
3992                         const struct GNUNET_MessageHeader *message)
3993 {
3994   struct MeshClient *c;
3995   struct MeshTunnel *t;
3996   struct GNUNET_MESH_Multicast *data_msg;
3997   MESH_TunnelNumber tid;
3998
3999   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4000               "MESH: Got a multicast request from a client!\n");
4001
4002   /* Sanity check for client registration */
4003   if (NULL == (c = client_get (client)))
4004   {
4005     GNUNET_break (0);
4006     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4007     return;
4008   }
4009   data_msg = (struct GNUNET_MESH_Multicast *) message;
4010   /* Sanity check for message size */
4011   if (sizeof (struct GNUNET_MESH_Multicast) +
4012       sizeof (struct GNUNET_MessageHeader) > ntohs (data_msg->header.size))
4013   {
4014     GNUNET_break (0);
4015     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4016     return;
4017   }
4018
4019   /* Tunnel exists? */
4020   tid = ntohl (data_msg->tid);
4021   t = tunnel_get_by_local_id (c, tid);
4022   if (NULL == t)
4023   {
4024     GNUNET_break (0);
4025     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4026     return;
4027   }
4028
4029   /* Does client own tunnel? */
4030   if (t->client->handle != client)
4031   {
4032     GNUNET_break (0);
4033     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4034     return;
4035   }
4036
4037   {
4038     char buf[ntohs (message->size)];
4039     struct GNUNET_MESH_Multicast *copy;
4040
4041     copy = (struct GNUNET_MESH_Multicast *) buf;
4042     memcpy (buf, message, ntohs (message->size));
4043     copy->oid = my_full_id;
4044     copy->tid = htonl (t->id.tid);
4045     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4046                 "MESH:   calling generic handler...\n");
4047     handle_mesh_data_multicast (client, &my_full_id, &copy->header, NULL, 0);
4048   }
4049
4050   /* receive done gets called when last copy is sent to a neighbor */
4051   return;
4052 }
4053
4054 /**
4055  * Functions to handle messages from clients
4056  */
4057 static struct GNUNET_SERVER_MessageHandler client_handlers[] = {
4058   {&handle_local_new_client, NULL,
4059    GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT, 0},
4060   {&handle_local_tunnel_create, NULL,
4061    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE,
4062    sizeof (struct GNUNET_MESH_TunnelMessage)},
4063   {&handle_local_tunnel_destroy, NULL,
4064    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY,
4065    sizeof (struct GNUNET_MESH_TunnelMessage)},
4066   {&handle_local_connect_add, NULL,
4067    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD,
4068    sizeof (struct GNUNET_MESH_PeerControl)},
4069   {&handle_local_connect_del, NULL,
4070    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL,
4071    sizeof (struct GNUNET_MESH_PeerControl)},
4072   {&handle_local_connect_by_type, NULL,
4073    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_TYPE,
4074    sizeof (struct GNUNET_MESH_ConnectPeerByType)},
4075   {&handle_local_unicast, NULL,
4076    GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
4077   {&handle_local_to_origin, NULL,
4078    GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
4079   {&handle_local_multicast, NULL,
4080    GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
4081   {NULL, NULL, 0, 0}
4082 };
4083
4084
4085 /**
4086  * To be called on core init/fail.
4087  *
4088  * @param cls service closure
4089  * @param server handle to the server for this service
4090  * @param identity the public identity of this peer
4091  */
4092 static void
4093 core_init (void *cls, struct GNUNET_CORE_Handle *server,
4094            const struct GNUNET_PeerIdentity *identity)
4095 {
4096   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Core init\n");
4097   core_handle = server;
4098   if (0 != memcmp (identity, &my_full_id, sizeof (my_full_id)) ||
4099       NULL == server)
4100   {
4101     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("MESH: Wrong CORE service\n"));
4102     GNUNET_SCHEDULER_shutdown ();
4103   }
4104   return;
4105 }
4106
4107 /**
4108  * Method called whenever a given peer connects.
4109  *
4110  * @param cls closure
4111  * @param peer peer identity this notification is about
4112  * @param atsi performance data for the connection
4113  * @param atsi_count number of records in 'atsi'
4114  */
4115 static void
4116 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
4117               const struct GNUNET_ATS_Information *atsi,
4118               unsigned int atsi_count)
4119 {
4120   struct MeshPeerInfo *peer_info;
4121   struct MeshPeerPath *path;
4122
4123 #if MESH_DEBUG_CONNECTION
4124   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Peer connected\n");
4125   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:      %s\n",
4126               GNUNET_i2s (&my_full_id));
4127 #endif
4128   peer_info = peer_info_get (peer);
4129   if (myid == peer_info->id)
4130   {
4131 #if MESH_DEBUG_CONNECTION
4132     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:      (self)\n");
4133 #endif
4134     return;
4135   }
4136 #if MESH_DEBUG_CONNECTION
4137   else
4138   {
4139     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:      %s\n", GNUNET_i2s (peer));
4140   }
4141 #endif
4142   path = path_new (2);
4143   path->peers[0] = myid;
4144   path->peers[1] = peer_info->id;
4145   GNUNET_PEER_change_rc (myid, 1);
4146   GNUNET_PEER_change_rc (peer_info->id, 1);
4147   peer_info_add_path (peer_info, path, GNUNET_YES);
4148   return;
4149 }
4150
4151 /**
4152  * Method called whenever a peer disconnects.
4153  *
4154  * @param cls closure
4155  * @param peer peer identity this notification is about
4156  */
4157 static void
4158 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
4159 {
4160   struct MeshPeerInfo *pi;
4161   unsigned int i;
4162
4163 #if MESH_DEBUG_CONNECTION
4164   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Peer disconnected\n");
4165 #endif
4166   pi = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
4167   if (NULL == pi)
4168   {
4169     GNUNET_break (0);
4170     return;
4171   }
4172   for (i = 0; i < CORE_QUEUE_SIZE; i++)
4173   {
4174     /* TODO: notify that the transmission failed */
4175     peer_info_cancel_transmission (pi, i);
4176   }
4177   peer_info_remove_path (pi, pi->id, myid);
4178 #if MESH_DEBUG_CONNECTION
4179   if (myid == pi->id)
4180   {
4181     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:      (self)\n");
4182   }
4183 #endif
4184   return;
4185 }
4186
4187
4188 /******************************************************************************/
4189 /************************      MAIN FUNCTIONS      ****************************/
4190 /******************************************************************************/
4191
4192 /**
4193  * Iterator over tunnel hash map entries to destroy the tunnel during shutdown.
4194  *
4195  * @param cls closure
4196  * @param key current key code
4197  * @param value value in the hash map
4198  * @return GNUNET_YES if we should continue to iterate,
4199  *         GNUNET_NO if not.
4200  */
4201 static int
4202 shutdown_tunnel (void *cls, const GNUNET_HashCode * key, void *value)
4203 {
4204   struct MeshTunnel *t = value;
4205
4206   tunnel_destroy (t);
4207   return GNUNET_YES;
4208 }
4209
4210 /**
4211  * Iterator over peer hash map entries to destroy the tunnel during shutdown.
4212  *
4213  * @param cls closure
4214  * @param key current key code
4215  * @param value value in the hash map
4216  * @return GNUNET_YES if we should continue to iterate,
4217  *         GNUNET_NO if not.
4218  */
4219 static int
4220 shutdown_peer (void *cls, const GNUNET_HashCode * key, void *value)
4221 {
4222   struct MeshPeerInfo *p = value;
4223
4224   peer_info_destroy (p);
4225   return GNUNET_YES;
4226 }
4227
4228 /**
4229  * Task run during shutdown.
4230  *
4231  * @param cls unused
4232  * @param tc unused
4233  */
4234 static void
4235 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4236 {
4237   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: shutting down\n");
4238   /* TODO: destroy tunnels? */
4239   if (core_handle != NULL)
4240   {
4241     GNUNET_CORE_disconnect (core_handle);
4242     core_handle = NULL;
4243   }
4244   GNUNET_CONTAINER_multihashmap_iterate (tunnels, &shutdown_tunnel, NULL);
4245   GNUNET_CONTAINER_multihashmap_iterate (peers, &shutdown_peer, NULL);
4246   if (dht_handle != NULL)
4247   {
4248     GNUNET_DHT_disconnect (dht_handle);
4249     dht_handle = NULL;
4250   }
4251   if (nc != NULL)
4252   {
4253     GNUNET_SERVER_notification_context_destroy (nc);
4254     nc = NULL;
4255   }
4256   if (GNUNET_SCHEDULER_NO_TASK != announce_id_task)
4257   {
4258     GNUNET_SCHEDULER_cancel (announce_id_task);
4259     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
4260   }
4261   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: shut down\n");
4262 }
4263
4264 /**
4265  * Process mesh requests.
4266  *
4267  * @param cls closure
4268  * @param server the initialized server
4269  * @param c configuration to use
4270  */
4271 static void
4272 run (void *cls, struct GNUNET_SERVER_Handle *server,
4273      const struct GNUNET_CONFIGURATION_Handle *c)
4274 {
4275   struct MeshPeerInfo *peer;
4276   struct MeshPeerPath *p;
4277   char *keyfile;
4278
4279   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: starting to run\n");
4280   server_handle = server;
4281   core_handle = GNUNET_CORE_connect (c, /* Main configuration */
4282                                      CORE_QUEUE_SIZE,   /* queue size */
4283                                      NULL,      /* Closure passed to MESH functions */
4284                                      &core_init,        /* Call core_init once connected */
4285                                      &core_connect,     /* Handle connects */
4286                                      &core_disconnect,  /* remove peers on disconnects */
4287                                      NULL,      /* Don't notify about all incoming messages */
4288                                      GNUNET_NO, /* For header only in notification */
4289                                      NULL,      /* Don't notify about all outbound messages */
4290                                      GNUNET_NO, /* For header-only out notification */
4291                                      core_handlers);    /* Register these handlers */
4292
4293   if (core_handle == NULL)
4294   {
4295     GNUNET_break (0);
4296     GNUNET_SCHEDULER_shutdown ();
4297     return;
4298   }
4299
4300   if (GNUNET_OK !=
4301       GNUNET_CONFIGURATION_get_value_filename (c, "GNUNETD", "HOSTKEY",
4302                                                &keyfile))
4303   {
4304     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4305                 _
4306                 ("Mesh service is lacking key configuration settings.  Exiting.\n"));
4307     GNUNET_SCHEDULER_shutdown ();
4308     return;
4309   }
4310   my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
4311   GNUNET_free (keyfile);
4312   if (my_private_key == NULL)
4313   {
4314     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4315                 _("Mesh service could not access hostkey.  Exiting.\n"));
4316     GNUNET_SCHEDULER_shutdown ();
4317     return;
4318   }
4319   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
4320   GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
4321                       &my_full_id.hashPubKey);
4322   myid = GNUNET_PEER_intern (&my_full_id);
4323
4324 // //   transport_handle = GNUNET_TRANSPORT_connect(c,
4325 // //                                               &my_full_id,
4326 // //                                               NULL,
4327 // //                                               NULL,
4328 // //                                               NULL,
4329 // //                                               NULL);
4330
4331   dht_handle = GNUNET_DHT_connect (c, 64);
4332   if (dht_handle == NULL)
4333   {
4334     GNUNET_break (0);
4335   }
4336
4337   next_tid = 0;
4338   next_local_tid = GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
4339
4340   tunnels = GNUNET_CONTAINER_multihashmap_create (32);
4341   incoming_tunnels = GNUNET_CONTAINER_multihashmap_create (32);
4342   peers = GNUNET_CONTAINER_multihashmap_create (32);
4343   applications = GNUNET_CONTAINER_multihashmap_create (32);
4344   types = GNUNET_CONTAINER_multihashmap_create (32);
4345
4346   GNUNET_SERVER_add_handlers (server_handle, client_handlers);
4347   nc = GNUNET_SERVER_notification_context_create (server_handle,
4348                                                   LOCAL_QUEUE_SIZE);
4349   GNUNET_SERVER_disconnect_notify (server_handle,
4350                                    &handle_local_client_disconnect, NULL);
4351
4352
4353   clients = NULL;
4354   clients_tail = NULL;
4355 #if MESH_DEBUG
4356   next_client_id = 0;
4357 #endif
4358
4359   announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
4360   announce_id_task = GNUNET_SCHEDULER_add_now (&announce_id, cls);
4361
4362   /* Create a peer_info for the local peer */
4363   peer = peer_info_get (&my_full_id);
4364   p = path_new (1);
4365   p->peers[0] = myid;
4366   GNUNET_PEER_change_rc (myid, 1);
4367   peer_info_add_path (peer, p, GNUNET_YES);
4368
4369   /* Scheduled the task to clean up when shutdown is called */
4370   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
4371                                 NULL);
4372
4373   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: end of run()\n");
4374 }
4375
4376 /**
4377  * The main function for the mesh service.
4378  *
4379  * @param argc number of arguments from the command line
4380  * @param argv command line arguments
4381  * @return 0 ok, 1 on error
4382  */
4383 int
4384 main (int argc, char *const *argv)
4385 {
4386   int ret;
4387
4388   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: main()\n");
4389   ret =
4390       (GNUNET_OK ==
4391        GNUNET_SERVICE_run (argc, argv, "mesh", GNUNET_SERVICE_OPTION_NONE, &run,
4392                            NULL)) ? 0 : 1;
4393   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: main() END\n");
4394
4395   return ret;
4396 }