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