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