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