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