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