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