Added testcase for explicit case of DHT not finding apptype
[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  * - add connection confirmation message
44  * - handle trnsmt_rdy return values
45  */
46
47 #include "platform.h"
48 #include "gnunet_common.h"
49 #include "gnunet_util_lib.h"
50 #include "gnunet_peer_lib.h"
51 #include "gnunet_core_service.h"
52 #include "gnunet_protocols.h"
53
54 #include "mesh.h"
55 #include "mesh_protocol.h"
56 #include "gnunet_dht_service.h"
57
58 #define MESH_DEBUG              GNUNET_YES
59
60 #if MESH_DEBUG
61 /**
62  * GNUNET_SCHEDULER_Task for printing a message after some operation is done
63  * @param cls string to print
64  * @param tc task context
65  */
66 static void
67 mesh_debug (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
68 {
69   char *s = cls;
70
71   if (GNUNET_SCHEDULER_REASON_SHUTDOWN == tc->reason)
72   {
73     return;
74   }
75   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: %s\n", s);
76 }
77 #endif
78
79 /* TODO: move into configuration file */
80 #define CORE_QUEUE_SIZE         10
81 #define LOCAL_QUEUE_SIZE        100
82 #define REFRESH_PATH_TIME       GNUNET_TIME_relative_multiply(\
83                                     GNUNET_TIME_UNIT_SECONDS,\
84                                     300)
85 #define APP_ANNOUNCE_TIME       GNUNET_TIME_relative_multiply(\
86                                     GNUNET_TIME_UNIT_SECONDS,\
87                                     5)
88
89 #define ID_ANNOUNCE_TIME        GNUNET_TIME_relative_multiply(\
90                                     GNUNET_TIME_UNIT_SECONDS,\
91                                     5)
92
93
94
95 /******************************************************************************/
96 /************************      DATA STRUCTURES     ****************************/
97 /******************************************************************************/
98
99 /**
100  * Information regarding a path
101  */
102 struct MeshPath
103 {
104
105     /**
106      * Linked list
107      */
108   struct MeshPath *next;
109   struct MeshPath *prev;
110
111     /**
112      * Whether the path is serving traffic in a tunnel or is a backup
113      */
114   int in_use;
115
116     /**
117      * List of all the peers that form the path from origin to target
118      */
119   GNUNET_PEER_Id *peers;
120
121     /**
122      * Number of peers (hops) in the path
123      */
124   unsigned int length;
125 };
126
127
128 /**
129  * All the states a peer participating in a tunnel can be in.
130  */
131 enum MeshPeerState
132 {
133     /**
134      * Path to the peer not known yet
135      */
136   MESH_PEER_SEARCHING,
137
138     /**
139      * Request sent, not yet answered.
140      */
141   MESH_PEER_WAITING,
142
143     /**
144      * Peer connected and ready to accept data
145      */
146   MESH_PEER_READY,
147
148     /**
149      * Peer connected previosly but not responding
150      */
151   MESH_PEER_RECONNECTING
152 };
153
154
155 /** FWD declaration */
156 struct MeshPeerInfo;
157
158 /**
159  * Struct containing all info possibly needed to build a package when called
160  * back by core.
161  */
162 struct MeshDataDescriptor
163 {
164     /** ID of the tunnel this packet travels in */
165   struct MESH_TunnelID *origin;
166
167     /** Ultimate destination of the packet */
168   GNUNET_PEER_Id destination;
169
170     /** Number of identical messages sent to different hops (multicast) */
171   unsigned int copies;
172
173     /** Size of the data */
174   size_t size;
175
176     /** Client that asked for the transmission, if any */
177   struct GNUNET_SERVER_Client *client;
178
179     /** Who was is message being sent to */
180   struct MeshPeerInfo *peer;
181
182     /** Which handler was used to request the transmission */
183   unsigned int handler_n;
184
185   /* Data at the end */
186 };
187
188
189 /**
190  * Struct containing all information regarding a given peer
191  */
192 struct MeshPeerInfo
193 {
194     /**
195      * ID of the peer
196      */
197   GNUNET_PEER_Id id;
198
199     /**
200      * Is the peer reachable? Is the peer even connected?
201      */
202   enum MeshPeerState state;
203
204     /**
205      * Last time we heard from this peer
206      */
207   struct GNUNET_TIME_Absolute last_contact;
208
209     /**
210      * Number of attempts to reconnect so far
211      */
212   int n_reconnect_attempts;
213
214     /**
215      * Paths to reach the peer
216      */
217   struct MeshPath *path;
218   struct MeshPath *path_tail;
219
220     /**
221      * Handle to stop the DHT search for a path to this peer
222      */
223   struct GNUNET_DHT_GetHandle *dhtget;
224
225     /**
226      * Handles to stop queued transmissions for this peer
227      */
228   struct GNUNET_CORE_TransmitHandle *core_transmit[CORE_QUEUE_SIZE];
229
230     /**
231      * Pointer to info stuctures used as cls for queued transmissions
232      */
233   struct MeshDataDescriptor *infos[CORE_QUEUE_SIZE];
234
235     /**
236      * Task to send keepalive packets over the current active path
237      */
238   GNUNET_SCHEDULER_TaskIdentifier path_refresh_task;
239 };
240
241
242 /**
243  * Data scheduled to transmit (to local client or remote peer)
244  */
245 struct MeshQueue
246 {
247     /**
248      * Double linked list
249      */
250   struct MeshQueue *next;
251   struct MeshQueue *prev;
252
253     /**
254      * Target of the data (NULL if target is client)
255      */
256   struct MeshPeerInfo *peer;
257
258     /**
259      * Client to send the data to (NULL if target is peer)
260      */
261   struct MeshClient *client;
262
263     /**
264      * Size of the message to transmit
265      */
266   unsigned int size;
267
268     /**
269      * How old is the data?
270      */
271   struct GNUNET_TIME_Absolute timestamp;
272
273     /**
274      * Data itself
275      */
276   struct GNUNET_MessageHeader *data;
277 };
278
279 /**
280  * Globally unique tunnel identification (owner + number)
281  * DO NOT USE OVER THE NETWORK
282  */
283 struct MESH_TunnelID
284 {
285     /**
286      * Node that owns the tunnel
287      */
288   GNUNET_PEER_Id oid;
289
290     /**
291      * Tunnel number to differentiate all the tunnels owned by the node oid
292      * ( tid < GNUNET_MESH_LOCAL_TUNNEL_ID_CLI )
293      */
294   MESH_TunnelNumber tid;
295 };
296
297
298 struct MeshClient;              /* FWD declaration */
299
300 /**
301  * Struct containing all information regarding a tunnel
302  * For an intermediate node the improtant info used will be:
303  * - id        Tunnel unique identification
304  * - paths[0]  To know where to send it next
305  * - metainfo: ready, speeds, accounting
306  */
307 struct MeshTunnel
308 {
309     /**
310      * Tunnel ID
311      */
312   struct MESH_TunnelID id;
313
314     /**
315      * Local tunnel number ( >= GNUNET_MESH_LOCAL_TUNNEL_ID_CLI or 0 )
316      */
317   MESH_TunnelNumber local_tid;
318
319     /**
320      * Last time the tunnel was used
321      */
322   struct GNUNET_TIME_Absolute timestamp;
323
324     /**
325      * Peers in the tunnel, indexed by PeerIdentity -> (MeshPeerInfo)
326      */
327   struct GNUNET_CONTAINER_MultiHashMap *peers;
328
329     /**
330      * Number of peers that are connected and potentially ready to receive data
331      */
332   unsigned int peers_ready;
333
334     /**
335      * Number of peers that have been added to the tunnel
336      */
337   unsigned int peers_total;
338
339
340     /**
341      * Client owner of the tunnel, if any
342      */
343   struct MeshClient *client;
344
345     /**
346      * Messages ready to transmit
347      */
348   struct MeshQueue *queue_head;
349   struct MeshQueue *queue_tail;
350
351 };
352
353 /**
354  * Struct containing information about a client of the service
355  */
356 struct MeshClient
357 {
358     /**
359      * Linked list
360      */
361   struct MeshClient *next;
362   struct MeshClient *prev;
363
364     /**
365      * Tunnels that belong to this client, indexed by local id
366      */
367   struct GNUNET_CONTAINER_MultiHashMap *tunnels;
368
369     /**
370      * Handle to communicate with the client
371      */
372   struct GNUNET_SERVER_Client *handle;
373
374     /**
375      * Applications that this client has claimed to provide
376      */
377   struct GNUNET_CONTAINER_MultiHashMap *apps;
378
379     /**
380      * Messages that this client has declared interest in
381      */
382   struct GNUNET_CONTAINER_MultiHashMap *types;
383
384     /**
385      * Used for seachching peers offering a service
386      */
387   struct GNUNET_DHT_GetHandle *dht_get_type;
388
389 };
390
391 /******************************************************************************/
392 /***********************      GLOBAL VARIABLES     ****************************/
393 /******************************************************************************/
394
395 /**
396  * All the clients
397  */
398 static struct MeshClient *clients;
399 static struct MeshClient *clients_tail;
400
401 /**
402  * Tunnels known, indexed by MESH_TunnelID (MeshTunnel)
403  */
404 static struct GNUNET_CONTAINER_MultiHashMap *tunnels;
405
406 /**
407  * Peers known, indexed by PeerIdentity (MeshPeerInfo)
408  */
409 static struct GNUNET_CONTAINER_MultiHashMap *peers;
410
411 /**
412  * Handle to communicate with core
413  */
414 static struct GNUNET_CORE_Handle *core_handle;
415
416 /**
417  * Handle to use DHT
418  */
419 static struct GNUNET_DHT_Handle *dht_handle;
420
421 /**
422  * Handle to server
423  */
424 static struct GNUNET_SERVER_Handle *server_handle;
425
426 /**
427  * Notification context, to send messages to local clients
428  */
429 static struct GNUNET_SERVER_NotificationContext *nc;
430
431 /**
432  * Local peer own ID (memory efficient handle)
433  */
434 static GNUNET_PEER_Id myid;
435
436 /**
437  * Local peer own ID (full value)
438  */
439 static struct GNUNET_PeerIdentity my_full_id;
440
441 /**
442  * Tunnel ID for the next created tunnel (global tunnel number)
443  */
444 static MESH_TunnelNumber next_tid;
445
446 /**
447  * All application types provided by this peer
448  */
449 static struct GNUNET_CONTAINER_MultiHashMap *applications;
450
451 /**
452  * All message types clients of this peer are interested in
453  */
454 static struct GNUNET_CONTAINER_MultiHashMap *types;
455
456 /**
457  * Task to periodically announce provided applications
458  */
459 GNUNET_SCHEDULER_TaskIdentifier announce_applications_task;
460
461 /**
462  * Task to periodically announce itself in the network
463  */
464 GNUNET_SCHEDULER_TaskIdentifier announce_id_task;
465
466
467 /******************************************************************************/
468 /******************      GENERAL HELPER FUNCTIONS      ************************/
469 /******************************************************************************/
470
471 /**
472  * Retrieve the MeshPeerInfo stucture associated with the peer, create one
473  * and inster it in the appropiate structures if the peer is not known yet.
474  * @param peer Identity of the peer
475  * @return Existing or newly created peer info
476  */
477 static struct MeshPeerInfo *
478 get_peer_info (const struct GNUNET_PeerIdentity *peer)
479 {
480   struct MeshPeerInfo *peer_info;
481
482   peer_info = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
483   if (NULL == peer_info)
484   {
485     peer_info =
486         (struct MeshPeerInfo *) GNUNET_malloc (sizeof (struct MeshPeerInfo));
487     GNUNET_CONTAINER_multihashmap_put (peers, &peer->hashPubKey, peer_info,
488                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
489     peer_info->id = GNUNET_PEER_intern (peer);
490     peer_info->state = MESH_PEER_SEARCHING;
491   }
492
493   return peer_info;
494 }
495
496 /**
497  * Find the first peer whom to send a packet to go down this path
498  * @param path The path to use
499  * @return short id of the next peer, myid in case of local delivery,
500  * or 0 in case of error
501  */
502 static GNUNET_PEER_Id
503 get_first_hop (struct MeshPath *path)
504 {
505   unsigned int i;
506
507   while (NULL != path)
508   {
509     if (path->in_use)
510       break;
511     path = path->next;
512   }
513   if (NULL == path)
514   {
515     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
516                 "tried to get the next hop from an invalid path\n");
517     return 0;
518   }
519
520   for (i = 0; i < path->length; i++)
521   {
522     if (path->peers[i] == myid)
523     {
524       if (i < path->length - 1)
525       {
526         return path->peers[i + 1];
527       }
528       else
529       {
530         return myid;
531       }
532     }
533   }
534   return 0;
535 }
536
537
538 /**
539  * Get the cost of the path.
540  * @param path The path to analyze
541  * @return Number of hops to reach destination, UINT_MAX in case the peer is not
542  * in the path
543  */
544 static unsigned int
545 get_path_cost (struct MeshPath *path)
546 {
547   unsigned int i;
548
549   if (NULL == path)
550     return UINT_MAX;
551   for (i = 0; i < path->length; i++)
552   {
553     if (path->peers[i] == myid)
554     {
555       return path->length - i;
556     }
557   }
558   return UINT_MAX;
559 }
560
561
562 /**
563  * Add the path to the peer and update the path used to reach it in case this
564  * is the shortest.
565  * @param peer_info Destination peer to add the path to.
566  * @param path New path to add. Last peer must be the peer in arg 1.
567  */
568 static void
569 add_path_to_peer (struct MeshPeerInfo *peer_info, struct MeshPath *path)
570 {
571   unsigned int i;
572   unsigned int new_cost;
573   unsigned int best_cost;
574   struct MeshPath *aux;
575   struct MeshPath *best;
576
577   if (NULL == peer_info || NULL == path)
578     return;
579
580   new_cost = get_path_cost (path);
581   best_cost = UINT_MAX;
582   best = NULL;
583   for (aux = peer_info->path; aux != NULL; aux = aux->next)
584   {
585     if ((i = get_path_cost (aux)) < best_cost)
586     {
587       best = aux;
588       best_cost = i;
589     }
590   }
591   if (best_cost < new_cost)
592   {
593     path->in_use = 0;
594     GNUNET_CONTAINER_DLL_insert_tail (peer_info->path, peer_info->path_tail,
595                                       path);
596   }
597   else
598   {
599     if (NULL != best)
600       best->in_use = 0;
601     path->in_use = 1;
602     GNUNET_CONTAINER_DLL_insert (peer_info->path, peer_info->path_tail, path);
603   }
604   return;
605 }
606
607
608 /**
609  * Add the path to the peer and update the path used to reach it in case this
610  * is the shortest. The path is given in reverse, the destination peer is
611  * path[0]. The function modifies the path, inverting it to use the origin as
612  * destination.
613  * @param peer_info Destination peer to add the path to.
614  * @param path New path to add. First peer must be the peer in arg 1.
615  */
616 static void
617 add_path_to_origin (struct MeshPeerInfo *peer_info, struct MeshPath *path)
618 {
619   GNUNET_PEER_Id aux;
620   unsigned int i;
621
622   for (i = 0; i < path->length / 2; i++)
623   {
624     aux = path->peers[i];
625     path->peers[i] = path->peers[path->length - i - 1];
626     path->peers[path->length - i - 1] = aux;
627   }
628   add_path_to_peer (peer_info, path);
629 }
630
631
632 /**
633  * Check if client has registered with the service and has not disconnected
634  * @param client the client to check
635  * @return non-NULL if client exists in the global DLL
636  */
637 static struct MeshClient *
638 retrieve_client (struct GNUNET_SERVER_Client *client)
639 {
640   struct MeshClient *c;
641
642   c = clients;
643   while (NULL != c)
644   {
645     if (c->handle == client)
646       return c;
647     c = c->next;
648   }
649   return NULL;
650 }
651
652
653 /**
654  * Checks if a given client has subscribed to certain message type
655  * @param message_type Type of message to check
656  * @param c Client to check
657  * @return GNUNET_YES or GNUNET_NO, depending on subscription status
658  */
659 static int                      /* FIXME inline? */
660 is_client_subscribed (uint16_t message_type, struct MeshClient *c)
661 {
662   GNUNET_HashCode hc;
663
664   GNUNET_CRYPTO_hash(&message_type, sizeof(uint16_t), &hc);
665   return GNUNET_CONTAINER_multihashmap_contains(c->types, &hc);
666 }
667
668
669 /**
670  * Search for a tunnel among the tunnels for a client
671  * @param c the client whose tunnels to search in
672  * @param tid the local id of the tunnel
673  * @return tunnel handler, NULL if doesn't exist
674  */
675 static struct MeshTunnel *
676 retrieve_tunnel_by_local_id (struct MeshClient *c, MESH_TunnelNumber tid)
677 {
678   GNUNET_HashCode hash;
679
680   GNUNET_CRYPTO_hash (&tid, sizeof (MESH_TunnelNumber), &hash);
681   return GNUNET_CONTAINER_multihashmap_get (c->tunnels, &hash);
682 }
683
684 /**
685  * Search for a tunnel by global ID using PEER_ID
686  * @param pi owner of the tunnel
687  * @param tid global tunnel number
688  * @return tunnel handler, NULL if doesn't exist
689  */
690 static struct MeshTunnel *
691 retrieve_tunnel_by_pi (GNUNET_PEER_Id pi, MESH_TunnelNumber tid)
692 {
693   struct MESH_TunnelID id;
694   GNUNET_HashCode hash;
695
696   id.oid = pi;
697   id.tid = tid;
698
699   GNUNET_CRYPTO_hash (&id, sizeof (struct MESH_TunnelID), &hash);
700   return GNUNET_CONTAINER_multihashmap_get (tunnels, &hash);
701 }
702
703
704
705 /**
706  * Search for a tunnel by global ID using full PeerIdentities
707  * @param oid owner of the tunnel
708  * @param tid global tunnel number
709  * @return tunnel handler, NULL if doesn't exist
710  */
711 static struct MeshTunnel *
712 retrieve_tunnel (struct GNUNET_PeerIdentity *oid, MESH_TunnelNumber tid)
713 {
714   return retrieve_tunnel_by_pi (GNUNET_PEER_search (oid), tid);
715 }
716
717
718 /**
719  * Destroy the path and free any allocated resources linked to it
720  * @param p the path to destroy
721  * @return GNUNET_OK on success
722  */
723 static int
724 destroy_path (struct MeshPath *p)
725 {
726   GNUNET_PEER_decrement_rcs (p->peers, p->length);
727   GNUNET_free (p->peers);
728   GNUNET_free (p);
729   return GNUNET_OK;
730 }
731
732 #if LATER
733 /**
734  * Destroy the peer_info and free any allocated resources linked to it
735  * @param t tunnel the path belongs to
736  * @param pi the peer_info to destroy
737  * @return GNUNET_OK on success
738  */
739 static int
740 destroy_peer_info (struct MeshPeerInfo *pi)
741 {
742   GNUNET_HashCode hash;
743   struct GNUNET_PeerIdentity id;
744
745   GNUNET_PEER_resolve (pi->id, &id);
746   GNUNET_PEER_change_rc (pi->id, -1);
747   GNUNET_CRYPTO_hash (&id, sizeof (struct GNUNET_PeerIdentity), &hash);
748
749   GNUNET_CONTAINER_multihashmap_remove (peers, &hash, pi);
750   GNUNET_SCHEDULER_cancel (pi->path_refresh_task);
751   GNUNET_free (pi);
752   return GNUNET_OK;
753 }
754 #endif
755
756
757 /**
758  * Destroy the tunnel and free any allocated resources linked to it
759  * @param t the tunnel to destroy
760  * @return GNUNET_OK on success
761  */
762 static int
763 destroy_tunnel (struct MeshTunnel *t)
764 {
765   struct MeshClient *c;
766   struct MeshQueue *q;
767   struct MeshQueue *qn;
768   GNUNET_HashCode hash;
769   int r;
770
771   if (NULL == t)
772     return GNUNET_OK;
773
774   c = t->client;
775
776   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
777   if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_remove (tunnels, &hash, t))
778   {
779     r = GNUNET_SYSERR;
780   }
781
782   GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
783   if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_remove (c->tunnels, &hash, t))
784   {
785     r = GNUNET_SYSERR;
786   }
787   GNUNET_CONTAINER_multihashmap_destroy (t->peers);
788   q = t->queue_head;
789   while (NULL != q)
790   {
791     if (NULL != q->data)
792       GNUNET_free (q->data);
793     qn = q->next;
794     GNUNET_free (q);
795     q = qn;
796     /* TODO cancel core transmit ready in case it was active */
797   }
798   GNUNET_free (t);
799   return r;
800 }
801
802 /******************************************************************************/
803 /************************    PERIODIC FUNCTIONS    ****************************/
804 /******************************************************************************/
805
806 /**
807  * Announce iterator over for each application provided by the peer
808  *
809  * @param cls closure
810  * @param key current key code
811  * @param value value in the hash map
812  * @return GNUNET_YES if we should continue to
813  *         iterate,
814  *         GNUNET_NO if not.
815  */
816 static int
817 announce_application (void *cls, const GNUNET_HashCode * key, void *value)
818 {
819   /* FIXME are hashes in multihash map equal on all aquitectures? */
820   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
821               "MESH:  putting in DHT %s\n",
822               GNUNET_h2s_full(key));
823   GNUNET_DHT_put (dht_handle, key, 10U, GNUNET_DHT_RO_RECORD_ROUTE,
824                   GNUNET_BLOCK_TYPE_TEST, sizeof (struct GNUNET_PeerIdentity),
825                   (const char *) &my_full_id,
826 //                   GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get (),
827 //                                             APP_ANNOUNCE_TIME), FIXME
828 //                   APP_ANNOUNCE_TIME,
829                   GNUNET_TIME_UNIT_FOREVER_ABS, GNUNET_TIME_UNIT_FOREVER_REL,
830 #if MESH_DEBUG
831                   &mesh_debug, "DHT_put for app completed");
832 #else
833                   NULL, NULL);
834 #endif
835   return GNUNET_OK;
836 }
837
838
839 /**
840  * Periodically announce what applications are provided by local clients
841  *
842  * @param cls closure
843  * @param tc task context
844  */
845 static void
846 announce_applications (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
847 {
848   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
849   {
850     announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
851     return;
852   }
853   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Starting PUT for apps\n");
854   GNUNET_CONTAINER_multihashmap_iterate(applications,
855                                         &announce_application,
856                                         NULL);
857   announce_applications_task =
858       GNUNET_SCHEDULER_add_delayed (APP_ANNOUNCE_TIME, &announce_applications,
859                                     cls);
860   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Finished PUT for apps\n");
861   return;
862 }
863
864
865 /**
866  * Periodically announce self id in the DHT
867  *
868  * @param cls closure
869  * @param tc task context
870  */
871 static void
872 announce_id (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
873 {
874   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
875   {
876     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
877     return;
878   }
879   /* TODO
880    * - Set data expiration in function of X
881    * - Adapt X to churn
882    */
883   GNUNET_DHT_put (dht_handle,   /* DHT handle */
884                   &my_full_id.hashPubKey,       /* Key to use */
885                   10U,          /* Replication level */
886                   GNUNET_DHT_RO_RECORD_ROUTE,   /* DHT options */
887                   GNUNET_BLOCK_TYPE_TEST,        /* Block type */
888                   0,            /* Size of the data */
889                   NULL,         /* Data itself */
890                   GNUNET_TIME_absolute_get_forever (),  /* Data expiration */
891                   GNUNET_TIME_UNIT_FOREVER_REL, /* Retry time */
892 #if MESH_DEBUG
893                   &mesh_debug, "DHT_put for id completed");
894 #else
895                   NULL,         /* Continuation */
896                   NULL);        /* Continuation closure */
897 #endif
898   announce_id_task =
899       GNUNET_SCHEDULER_add_delayed (ID_ANNOUNCE_TIME, &announce_id, cls);
900 }
901
902 /******************************************************************************/
903 /****************      MESH NETWORK HANDLER HELPERS     ***********************/
904 /******************************************************************************/
905
906 /**
907  * Function called to notify a client about the socket
908  * being ready to queue more data.  "buf" will be
909  * NULL and "size" zero if the socket was closed for
910  * writing in the meantime.
911  *
912  * @param cls closure
913  * @param size number of bytes available in buf
914  * @param buf where the callee should write the message
915  * @return number of bytes written to buf
916  */
917 static size_t
918 send_core_create_path_for_peer (void *cls, size_t size, void *buf)
919 {
920   struct MeshPeerInfo *peer_info = cls;
921   struct GNUNET_MESH_ManipulatePath *msg;
922   struct MeshPath *p;
923   struct GNUNET_PeerIdentity *peer_ptr;
924   struct GNUNET_PeerIdentity id;
925   size_t size_needed;
926   int i;
927
928   if (0 == size && NULL == buf)
929   {
930     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Retransmitting create path\n");
931     GNUNET_PEER_resolve (get_first_hop (peer_info->path), &id);
932     GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
933                                        GNUNET_TIME_UNIT_FOREVER_REL, &id,
934                                        sizeof (struct
935                                                GNUNET_MESH_ManipulatePath) +
936                                        (peer_info->path->length *
937                                         sizeof (struct GNUNET_PeerIdentity)),
938                                        &send_core_create_path_for_peer,
939                                        peer_info);
940     return 0;
941   }
942   p = peer_info->path;
943   while (NULL != p)
944   {
945     if (p->in_use)
946     {
947       break;
948     }
949     p = p->next;
950   }
951   if (p == NULL)
952     return 0;                   // TODO Notify ERROR Path not found
953
954   size_needed =
955       sizeof (struct GNUNET_MESH_ManipulatePath) +
956       p->length * sizeof (struct GNUNET_PeerIdentity);
957   if (size < size_needed)
958   {
959     // TODO retry? cancel?
960     return 0;
961   }
962
963   msg = (struct GNUNET_MESH_ManipulatePath *) buf;
964   msg->header.size = htons (size_needed);
965   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE);
966
967   peer_ptr = (struct GNUNET_PeerIdentity *) &msg[1];
968   for (i = 0; i < p->length; i++)
969   {
970     GNUNET_PEER_resolve (p->peers[i], peer_ptr++);
971   }
972
973   peer_info->state = MESH_PEER_WAITING;
974
975   return size_needed;
976 }
977
978
979 #if LATER
980 /**
981  * Function called to notify a client about the socket
982  * being ready to queue more data.  "buf" will be
983  * NULL and "size" zero if the socket was closed for
984  * writing in the meantime.
985  *
986  * @param cls closure (MeshDataDescriptor with all info to build packet)
987  * @param size number of bytes available in buf
988  * @param buf where the callee should write the message
989  * @return number of bytes written to buf
990  */
991 static size_t
992 send_core_data_to_origin (void *cls, size_t size, void *buf)
993 {
994   struct MeshDataDescriptor *info = cls;
995   struct GNUNET_MESH_ToOrigin *msg = buf;
996   size_t total_size;
997
998   GNUNET_assert (NULL != info);
999   total_size = sizeof (struct GNUNET_MESH_ToOrigin) + info->size;
1000   GNUNET_assert (total_size < 65536);   /* UNIT16_MAX */
1001
1002   if (total_size > size)
1003   {
1004     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1005                 "not enough buffer to send data to origin\n");
1006     return 0;
1007   }
1008   msg->header.size = htons (total_size);
1009   msg->header.type = htons (GNUNET_MESSAGE_TYPE_DATA_MESSAGE_TO_ORIGIN);
1010   GNUNET_PEER_resolve (info->origin->oid, &msg->oid);
1011   msg->tid = htonl (info->origin->tid);
1012   if (0 != info->size)
1013   {
1014     memcpy (&msg[1], &info[1], info->size);
1015   }
1016   if (NULL != info->client)
1017   {
1018     GNUNET_SERVER_receive_done (info->client, GNUNET_OK);
1019   }
1020   GNUNET_free (info);
1021   return total_size;
1022 }
1023 #endif
1024
1025 /**
1026  * Function called to notify a client about the socket
1027  * being ready to queue more data.  "buf" will be
1028  * NULL and "size" zero if the socket was closed for
1029  * writing in the meantime.
1030  *
1031  * @param cls closure (data itself)
1032  * @param size number of bytes available in buf
1033  * @param buf where the callee should write the message
1034  * @return number of bytes written to buf
1035  */
1036 static size_t
1037 send_core_data_unicast (void *cls, size_t size, void *buf)
1038 {
1039   struct MeshDataDescriptor *info = cls;
1040   struct GNUNET_MESH_Unicast *msg = buf;
1041   size_t total_size;
1042
1043   GNUNET_assert (NULL != info);
1044   total_size = sizeof (struct GNUNET_MESH_Unicast) + info->size;
1045   GNUNET_assert (total_size < 65536);   /* UNIT16_MAX */
1046
1047   if (total_size > size)
1048   {
1049     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1050                 "not enough buffer to send data to peer\n");
1051     return 0;
1052   }
1053   msg->header.size = htons (total_size);
1054   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_UNICAST);
1055   GNUNET_PEER_resolve (info->origin->oid, &msg->oid);
1056   GNUNET_PEER_resolve (info->destination, &msg->destination);
1057   msg->tid = htonl (info->origin->tid);
1058   if (0 != info->size)
1059   {
1060     memcpy (&msg[1], &info[1], info->size);
1061   }
1062   if (NULL != info->client)
1063   {
1064     GNUNET_SERVER_receive_done (info->client, GNUNET_OK);
1065   }
1066   GNUNET_free (info);
1067   return total_size;
1068 }
1069
1070
1071 /**
1072  * Function called to notify a client about the socket
1073  * being ready to queue more data.  "buf" will be
1074  * NULL and "size" zero if the socket was closed for
1075  * writing in the meantime.
1076  *
1077  * @param cls closure (data itself)
1078  * @param size number of bytes available in buf
1079  * @param buf where the callee should write the message
1080  * @return number of bytes written to buf
1081  */
1082 static size_t
1083 send_core_data_multicast (void *cls, size_t size, void *buf)
1084 {
1085   struct MeshDataDescriptor *info = cls;
1086   struct GNUNET_MESH_Multicast *msg = buf;
1087   size_t total_size;
1088
1089   GNUNET_assert (NULL != info);
1090   total_size = info->size + sizeof (struct GNUNET_MESH_Multicast);
1091   GNUNET_assert (total_size < GNUNET_SERVER_MAX_MESSAGE_SIZE);
1092
1093   if (info->peer)
1094   {
1095     info->peer->core_transmit[info->handler_n] = NULL;
1096   }
1097   if (total_size > size)
1098   {
1099     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1100                 "not enough buffer to send data futher\n");
1101     return 0;
1102   }
1103   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
1104   msg->header.size = htons (total_size);
1105   GNUNET_PEER_resolve (info->origin->oid, &msg->oid);
1106   msg->tid = htonl (info->origin->tid);
1107   memcpy (&msg[1], &info[1], total_size);
1108   if (0 == --info->copies)
1109   {
1110     if (NULL != info->client)
1111     {
1112       GNUNET_SERVER_receive_done (info->client, GNUNET_OK);
1113     }
1114     GNUNET_free (info);
1115   }
1116   return total_size;
1117 }
1118
1119
1120 /**
1121  * Function called to notify a client about the socket
1122  * being ready to queue more data.  "buf" will be
1123  * NULL and "size" zero if the socket was closed for
1124  * writing in the meantime.
1125  *
1126  * @param cls closure (MeshDataDescriptor)
1127  * @param size number of bytes available in buf
1128  * @param buf where the callee should write the message
1129  * @return number of bytes written to buf
1130  */
1131 static size_t
1132 send_core_path_ack (void *cls, size_t size, void *buf)
1133 {
1134   struct MeshDataDescriptor *info = cls;
1135   struct GNUNET_MESH_PathACK *msg = buf;
1136
1137   GNUNET_assert (NULL != info);
1138   if (info->peer)
1139   {
1140     info->peer->core_transmit[info->handler_n] = NULL;
1141   }
1142   if (sizeof (struct GNUNET_MESH_PathACK) > size)
1143   {
1144     GNUNET_break (0);
1145     return 0;
1146   }
1147   msg->header.size = htons (sizeof (struct GNUNET_MESH_PathACK));
1148   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_ACK);
1149   GNUNET_PEER_resolve (info->origin->oid, &msg->oid);
1150   msg->tid = htonl (info->origin->tid);
1151   msg->peer_id = my_full_id;
1152   /* TODO add signature */
1153
1154   return sizeof (struct GNUNET_MESH_PathACK);
1155 }
1156
1157
1158 /**
1159  * Function called to notify a client about the socket
1160  * being ready to queue more data.  "buf" will be
1161  * NULL and "size" zero if the socket was closed for
1162  * writing in the meantime.
1163  *
1164  * @param cls closure (data itself)
1165  * @param size number of bytes available in buf
1166  * @param buf where the callee should write the message
1167  * @return number of bytes written to buf
1168  */
1169 static size_t
1170 send_core_data_raw (void *cls, size_t size, void *buf)
1171 {
1172   struct GNUNET_MessageHeader *msg = cls;
1173   size_t total_size;
1174
1175   GNUNET_assert (NULL != msg);
1176   total_size = ntohs (msg->size);
1177
1178   if (total_size > size)
1179   {
1180     GNUNET_break (0);
1181     return 0;
1182   }
1183   memcpy (buf, msg, total_size);
1184   GNUNET_free (cls);
1185   return total_size;
1186 }
1187
1188
1189 #if LATER
1190 /**
1191  * Send another peer a notification to destroy a tunnel
1192  * @param cls The tunnel to destroy
1193  * @param size Size in the buffer
1194  * @param buf Memory where to put the data to transmit
1195  * @return Size of data put in buffer
1196  */
1197 static size_t
1198 send_p2p_tunnel_destroy (void *cls, size_t size, void *buf)
1199 {
1200   struct MeshTunnel *t = cls;
1201   struct MeshClient *c;
1202   struct GNUNET_MESH_TunnelMessage *msg;
1203
1204   c = t->client;
1205   msg = buf;
1206   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY);
1207    /*FIXME*/ msg->header.size =
1208       htons (sizeof (struct GNUNET_MESH_TunnelMessage));
1209   msg->tunnel_id = htonl (t->id.tid);
1210
1211   destroy_tunnel (c, t);
1212   return sizeof (struct GNUNET_MESH_TunnelMessage);
1213 }
1214 #endif
1215
1216
1217 /**
1218  * Send the message to all clients that have subscribed to its type
1219  *
1220  * @param msg Pointer to the message itself
1221  * @return number of clients this message was sent to
1222  */
1223 static unsigned int
1224 send_subscribed_clients (struct GNUNET_MessageHeader *msg)
1225 {
1226   struct MeshClient *c;
1227   unsigned int count;
1228   uint16_t type;
1229
1230   type = ntohs (msg->type);
1231   for (count = 0, c = clients; c != NULL; c = c->next)
1232   {
1233     if (is_client_subscribed (type, c))
1234     {
1235       count++;
1236       GNUNET_SERVER_notification_context_unicast (nc, c->handle, msg,
1237                                                   GNUNET_YES);
1238     }
1239   }
1240   return count;
1241 }
1242
1243
1244 /**
1245  * Iterator over hash map peer entries collect all neighbors who to resend the
1246  * data to.
1247  *
1248  * @param cls closure (**GNUNET_PEER_Id to store hops to send packet)
1249  * @param key current key code (peer id hash)
1250  * @param value value in the hash map (peer_info)
1251  * @return GNUNET_YES if we should continue to iterate, GNUNET_NO if not.
1252  */
1253 static int
1254 iterate_collect_neighbors (void *cls, const GNUNET_HashCode * key, void *value)
1255 {
1256   struct MeshPeerInfo *peer_info = value;
1257   GNUNET_PEER_Id **neighbors = cls;
1258   GNUNET_PEER_Id id;
1259   unsigned int i;
1260
1261   if (peer_info->id == myid)
1262   {
1263     return GNUNET_YES;
1264   }
1265   id = get_first_hop (peer_info->path);
1266   for (i = 0; *neighbors[i] != 0; i++)
1267   {
1268     if (*neighbors[i] == id)
1269       return GNUNET_YES;
1270   }
1271   *neighbors = GNUNET_realloc (*neighbors, (i + 2) * sizeof (GNUNET_PEER_Id));
1272   *neighbors[i] = id;
1273   *neighbors[i + 1] = 0;
1274
1275   return GNUNET_YES;
1276 }
1277
1278
1279 /******************************************************************************/
1280 /********************      MESH NETWORK HANDLERS     **************************/
1281 /******************************************************************************/
1282
1283
1284 /**
1285  * Core handler for path creation
1286  * struct GNUNET_CORE_MessageHandler
1287  *
1288  * @param cls closure
1289  * @param message message
1290  * @param peer peer identity this notification is about
1291  * @param atsi performance data
1292  * @return GNUNET_OK to keep the connection open,
1293  *         GNUNET_SYSERR to close it (signal serious error)
1294  *
1295  */
1296 static int
1297 handle_mesh_path_create (void *cls, const struct GNUNET_PeerIdentity *peer,
1298                          const struct GNUNET_MessageHeader *message,
1299                          const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1300 {
1301   unsigned int own_pos;
1302   uint16_t size;
1303   uint16_t i;
1304   MESH_TunnelNumber tid;
1305   struct GNUNET_MESH_ManipulatePath *msg;
1306   struct GNUNET_PeerIdentity *pi;
1307   struct GNUNET_PeerIdentity id;
1308   GNUNET_HashCode hash;
1309   struct MeshPath *path;
1310   struct MeshPeerInfo *dest_peer_info;
1311   struct MeshPeerInfo *orig_peer_info;
1312   struct MeshTunnel *t;
1313
1314   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1315               "MESH: Received a MESH path create msg\n");
1316   size = ntohs (message->size);
1317   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
1318   {
1319     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1320                 "received create path message too short\n");
1321     return GNUNET_OK;
1322   }
1323
1324   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
1325   if (size < 2 * sizeof (struct GNUNET_PeerIdentity))
1326   {
1327     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1328                 "create path message lacks enough peers\n");
1329     return GNUNET_OK;
1330   }
1331   if (size % sizeof (struct GNUNET_PeerIdentity))
1332   {
1333     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1334                 "create path message of wrong size\n");
1335     return GNUNET_OK;
1336   }
1337   msg = (struct GNUNET_MESH_ManipulatePath *) message;
1338   size /= sizeof (struct GNUNET_PeerIdentity);
1339
1340   tid = ntohl (msg->tid);
1341   pi = (struct GNUNET_PeerIdentity *) &msg[1];
1342   t = retrieve_tunnel (pi, tid);
1343
1344   if (NULL == t)
1345   {
1346     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Creating tunnel\n");
1347     t = GNUNET_malloc (sizeof (struct MeshTunnel));
1348     t->id.oid = GNUNET_PEER_intern (pi);
1349     t->id.tid = tid;
1350     t->peers = GNUNET_CONTAINER_multihashmap_create (32);
1351
1352     GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
1353     if (GNUNET_OK !=
1354         GNUNET_CONTAINER_multihashmap_put (tunnels, &hash, t,
1355                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
1356     {
1357       GNUNET_break (0);
1358       return GNUNET_OK;
1359     }
1360
1361   }
1362   dest_peer_info =
1363       GNUNET_CONTAINER_multihashmap_get (peers, &pi[size - 1].hashPubKey);
1364   if (NULL == dest_peer_info)
1365   {
1366     dest_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
1367     dest_peer_info->id = GNUNET_PEER_intern (&pi[size - 1]);
1368     dest_peer_info->state = MESH_PEER_WAITING;
1369     GNUNET_CONTAINER_multihashmap_put (peers, &pi[size - 1].hashPubKey,
1370                                        dest_peer_info,
1371                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1372   }
1373   orig_peer_info = GNUNET_CONTAINER_multihashmap_get (peers, &pi->hashPubKey);
1374   if (NULL == orig_peer_info)
1375   {
1376     orig_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
1377     orig_peer_info->id = GNUNET_PEER_intern (pi);
1378     orig_peer_info->state = MESH_PEER_WAITING;
1379     GNUNET_CONTAINER_multihashmap_put (peers, &pi->hashPubKey, orig_peer_info,
1380                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1381   }
1382
1383
1384   path = GNUNET_malloc (sizeof (struct MeshPath));
1385   path->length = size;
1386   path->peers = GNUNET_malloc (size * sizeof (GNUNET_PEER_Id));
1387   own_pos = 0;
1388   for (i = 0; i < size; i++)
1389   {
1390     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
1391     if (path->peers[i] == myid)
1392       own_pos = i;
1393   }
1394   if (own_pos == 0)
1395   {                             /* cannot be self, must be 'not found' */
1396     /* create path: self not found in path through self */
1397     GNUNET_break_op (0);
1398     destroy_path (path);
1399     /* FIXME error. destroy tunnel? leave for timeout? */
1400     return 0;
1401   }
1402   if (own_pos == size - 1)
1403   {                             /* it is for us! */
1404     struct MeshDataDescriptor *info;
1405     unsigned int j;
1406
1407     add_path_to_origin (orig_peer_info, path);  /* inverts path!  */
1408     GNUNET_PEER_resolve (get_first_hop (path), &id);    /* path is inverted :) */
1409     info = GNUNET_malloc (sizeof (struct MeshDataDescriptor));
1410     info->origin = &t->id;
1411     info->peer = GNUNET_CONTAINER_multihashmap_get (peers, &id.hashPubKey);
1412     GNUNET_assert (info->peer);
1413     for (j = 0; info->peer->core_transmit[j]; j++)
1414     {
1415       if (j == 9)
1416       {
1417         GNUNET_break (0);
1418         return GNUNET_OK;
1419       }
1420     }
1421     info->handler_n = j;
1422     info->peer->core_transmit[j] =
1423         GNUNET_CORE_notify_transmit_ready (core_handle, 0, 100,
1424                                            GNUNET_TIME_UNIT_FOREVER_REL, &id,
1425                                            sizeof (struct GNUNET_MessageHeader),
1426                                            &send_core_path_ack, info);
1427   }
1428   else
1429   {
1430     add_path_to_peer (dest_peer_info, path);
1431     GNUNET_PEER_resolve (get_first_hop (path), &id);
1432     GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
1433                                        GNUNET_TIME_UNIT_FOREVER_REL, &id,
1434                                        sizeof (struct GNUNET_MessageHeader),
1435                                        &send_core_create_path_for_peer,
1436                                        dest_peer_info);
1437   }
1438   return GNUNET_OK;
1439 }
1440
1441
1442 /**
1443  * Core handler for mesh network traffic going from the origin to a peer
1444  *
1445  * @param cls closure
1446  * @param peer peer identity this notification is about
1447  * @param message message
1448  * @param atsi performance data
1449  * @return GNUNET_OK to keep the connection open,
1450  *         GNUNET_SYSERR to close it (signal serious error)
1451  */
1452 static int
1453 handle_mesh_data_unicast (void *cls, const struct GNUNET_PeerIdentity *peer,
1454                           const struct GNUNET_MessageHeader *message,
1455                           const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1456 {
1457   struct GNUNET_MESH_Unicast *msg;
1458   struct GNUNET_PeerIdentity id;
1459   struct MeshTunnel *t;
1460   struct MeshPeerInfo *pi;
1461   size_t size;
1462
1463   size = ntohs (message->size);
1464   if (size <
1465       sizeof (struct GNUNET_MESH_Unicast) +
1466       sizeof (struct GNUNET_MessageHeader))
1467   {
1468     GNUNET_break (0);
1469     return GNUNET_OK;
1470   }
1471   msg = (struct GNUNET_MESH_Unicast *) message;
1472   t = retrieve_tunnel (&msg->oid, ntohl (msg->tid));
1473   if (NULL == t)
1474   {
1475     /* TODO notify back: we don't know this tunnel */
1476     return GNUNET_OK;
1477   }
1478   pi = GNUNET_CONTAINER_multihashmap_get (t->peers,
1479                                           &msg->destination.hashPubKey);
1480   if (NULL == pi)
1481   {
1482     /* TODO maybe feedback, log to statistics */
1483     return GNUNET_OK;
1484   }
1485   if (pi->id == myid)
1486   {
1487     send_subscribed_clients ((struct GNUNET_MessageHeader *) &msg[1]);
1488     return GNUNET_OK;
1489   }
1490   GNUNET_PEER_resolve (get_first_hop (pi->path), &id);
1491   msg = GNUNET_malloc (size);
1492   memcpy (msg, message, size);
1493   GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
1494                                      GNUNET_TIME_UNIT_FOREVER_REL, &id, size,
1495                                      &send_core_data_raw, msg);
1496   return GNUNET_OK;
1497 }
1498
1499
1500 /**
1501  * Core handler for mesh network traffic going from the origin to all peers
1502  *
1503  * @param cls closure
1504  * @param message message
1505  * @param peer peer identity this notification is about
1506  * @param atsi performance data
1507  * @return GNUNET_OK to keep the connection open,
1508  *         GNUNET_SYSERR to close it (signal serious error)
1509  */
1510 static int
1511 handle_mesh_data_multicast (void *cls, const struct GNUNET_PeerIdentity *peer,
1512                             const struct GNUNET_MessageHeader *message,
1513                             const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1514 {
1515   struct GNUNET_MESH_Multicast *msg;
1516   struct GNUNET_PeerIdentity id;
1517   struct MeshTunnel *t;
1518   struct MeshDataDescriptor *info;
1519   GNUNET_PEER_Id *neighbors;
1520   size_t size;
1521   uint16_t i;
1522   uint16_t j;
1523
1524
1525   size = ntohs (message->size);
1526   if (size <
1527       sizeof (struct GNUNET_MESH_Multicast) +
1528       sizeof (struct GNUNET_MessageHeader))
1529   {
1530     GNUNET_break_op (0);
1531     return GNUNET_OK;
1532   }
1533   msg = (struct GNUNET_MESH_Multicast *) message;
1534   t = retrieve_tunnel (&msg->oid, ntohl (msg->tid));
1535
1536   if (NULL == t)
1537   {
1538     /* TODO notify that we dont know that tunnel */
1539     return GNUNET_OK;
1540   }
1541
1542   /* Transmit to locally interested clients */
1543   if (GNUNET_CONTAINER_multihashmap_contains (t->peers, &my_full_id.hashPubKey))
1544   {
1545     send_subscribed_clients ((struct GNUNET_MessageHeader *) &msg[1]);
1546   }
1547
1548   /* Retransmit to other peers */
1549   neighbors = GNUNET_malloc (sizeof (GNUNET_PEER_Id));
1550   neighbors[0] = 0;
1551   GNUNET_CONTAINER_multihashmap_iterate (t->peers, &iterate_collect_neighbors,
1552                                          &neighbors);
1553   if (!neighbors[0])
1554   {
1555     return GNUNET_OK;
1556   }
1557   size -= sizeof (struct GNUNET_MESH_Multicast);
1558   info = GNUNET_malloc (sizeof (struct MeshDataDescriptor) + size);
1559   info->origin = &t->id;
1560   info->copies = 0;
1561   for (i = 0; 0 != neighbors[i]; i++)
1562   {
1563     GNUNET_PEER_resolve (neighbors[i], &id);
1564     info->copies++;
1565     info->destination = neighbors[i];
1566     info->peer = GNUNET_CONTAINER_multihashmap_get (peers, &id.hashPubKey);
1567     GNUNET_assert (info->peer);
1568     for (j = 0; info->peer->core_transmit[j]; j++)
1569     {
1570       if (j == 9)
1571       {
1572         GNUNET_break (0);
1573         return GNUNET_OK;
1574       }
1575     }
1576     info->handler_n = j;
1577     info->peer->infos[j] = info;
1578     info->peer->core_transmit[j] =
1579         GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
1580                                            GNUNET_TIME_UNIT_FOREVER_REL, &id,
1581                                            ntohs (msg->header.size),
1582                                            &send_core_data_multicast, info);
1583   }
1584   return GNUNET_OK;
1585 }
1586
1587
1588 /**
1589  * Core handler for mesh network traffic
1590  *
1591  * @param cls closure
1592  * @param message message
1593  * @param peer peer identity this notification is about
1594  * @param atsi performance data
1595  * @return GNUNET_OK to keep the connection open,
1596  *         GNUNET_SYSERR to close it (signal serious error)
1597  */
1598 static int
1599 handle_mesh_data_to_orig (void *cls, const struct GNUNET_PeerIdentity *peer,
1600                           const struct GNUNET_MessageHeader *message,
1601                           const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1602 {
1603   struct GNUNET_MESH_ToOrigin *msg;
1604   struct GNUNET_PeerIdentity id;
1605   struct MeshTunnel *t;
1606   struct MeshPeerInfo *peer_info;
1607   size_t size;
1608
1609   size = ntohs (message->size);
1610   if (size <
1611       sizeof (struct GNUNET_MESH_ToOrigin) +
1612       sizeof (struct GNUNET_MessageHeader))
1613   {
1614     GNUNET_break_op (0);
1615     return GNUNET_OK;
1616   }
1617   msg = (struct GNUNET_MESH_ToOrigin *) message;
1618   t = retrieve_tunnel (&msg->oid, ntohl (msg->tid));
1619
1620   if (NULL == t)
1621   {
1622     /* TODO notify that we dont know this tunnel (whom)? */
1623     return GNUNET_OK;
1624   }
1625
1626   if (t->id.oid == myid)
1627   {
1628     if (NULL == t->client)
1629     {
1630       /* got data packet for ownerless tunnel */
1631       GNUNET_break_op (0);
1632       return GNUNET_OK;
1633     }
1634     GNUNET_SERVER_notification_context_unicast (nc, t->client->handle, message,
1635                                                 GNUNET_YES);
1636     return GNUNET_OK;
1637   }
1638   peer_info = get_peer_info (&msg->oid);
1639   if (NULL == peer_info)
1640   {
1641     /* unknown origin of tunnel */
1642     GNUNET_break (0);
1643     return GNUNET_OK;
1644   }
1645   GNUNET_PEER_resolve (get_first_hop (peer_info->path), &id);
1646   msg = GNUNET_malloc (size);
1647   memcpy (msg, message, size);
1648   GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
1649                                      GNUNET_TIME_UNIT_FOREVER_REL, &id, size,
1650                                      &send_core_data_raw, msg);
1651
1652   return GNUNET_OK;
1653 }
1654
1655
1656 /**
1657  * Core handler for path ACKs
1658  *
1659  * @param cls closure
1660  * @param message message
1661  * @param peer peer identity this notification is about
1662  * @param atsi performance data
1663  * @return GNUNET_OK to keep the connection open,
1664  *         GNUNET_SYSERR to close it (signal serious error)
1665  */
1666 static int
1667 handle_mesh_path_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
1668                       const struct GNUNET_MessageHeader *message,
1669                       const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1670 {
1671   struct GNUNET_MESH_PathACK *msg;
1672   struct GNUNET_PeerIdentity id;
1673   struct MeshTunnel *t;
1674   struct MeshPeerInfo *peer_info;
1675
1676   msg = (struct GNUNET_MESH_PathACK *) message;
1677   t = retrieve_tunnel (&msg->oid, msg->tid);
1678   if (NULL == t)
1679   {
1680     /* TODO notify that we don't know the tunnel */
1681     return GNUNET_OK;
1682   }
1683
1684   /* Message for us? */
1685   if (0 == memcmp (&msg->oid, &my_full_id, sizeof(struct GNUNET_PeerIdentity)))
1686   {
1687     struct GNUNET_MESH_PeerControl pc;
1688
1689     if (NULL == t->client)
1690     {
1691       GNUNET_break (0);
1692       return GNUNET_OK;
1693     }
1694     peer_info = get_peer_info (&msg->peer_id);
1695     if (NULL == peer_info)
1696     {
1697       GNUNET_break_op (0);
1698       return GNUNET_OK;
1699     }
1700     peer_info->state = MESH_PEER_READY;
1701     pc.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD);
1702     pc.header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
1703     pc.tunnel_id = htonl (t->local_tid);
1704     GNUNET_PEER_resolve (peer_info->id, &pc.peer);
1705     GNUNET_SERVER_notification_context_unicast (nc, t->client->handle,
1706                                                 &pc.header, GNUNET_NO);
1707     return GNUNET_OK;
1708   }
1709
1710   peer_info = get_peer_info (&msg->oid);
1711   if (NULL == peer_info)
1712   {
1713     /* If we know the tunnel, we should DEFINITELY know the peer */
1714     GNUNET_break (0);
1715     return GNUNET_OK;
1716   }
1717   GNUNET_PEER_resolve (get_first_hop (peer_info->path), &id);
1718   msg = GNUNET_malloc (sizeof (struct GNUNET_MESH_PathACK));
1719   memcpy (msg, message, sizeof (struct GNUNET_MESH_PathACK));
1720   GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
1721                                      GNUNET_TIME_UNIT_FOREVER_REL, &id,
1722                                      sizeof (struct GNUNET_MESH_PathACK),
1723                                      &send_core_data_raw, msg);
1724   return GNUNET_OK;
1725 }
1726
1727
1728 /**
1729  * Functions to handle messages from core
1730  */
1731 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
1732   {&handle_mesh_path_create, GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE, 0},
1733   {&handle_mesh_data_unicast, GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
1734   {&handle_mesh_data_multicast, GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
1735   {&handle_mesh_data_to_orig, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
1736   {&handle_mesh_path_ack, GNUNET_MESSAGE_TYPE_MESH_PATH_ACK,
1737    sizeof (struct GNUNET_MESH_PathACK)},
1738   {NULL, 0, 0}
1739 };
1740
1741
1742
1743 /******************************************************************************/
1744 /****************       MESH LOCAL HANDLER HELPERS      ***********************/
1745 /******************************************************************************/
1746
1747 /**
1748  * delete_tunnel_entry: iterator for deleting each tunnel that belongs to a
1749  * client when the client disconnects.
1750  * @param cls closure (client that is disconnecting)
1751  * @param key the hash of the local tunnel id (used to access the hashmap)
1752  * @param value the value stored at the key (tunnel to destroy)
1753  * @return GNUNET_OK on success
1754  */
1755 static int
1756 delete_tunnel_entry (void *cls, const GNUNET_HashCode * key, void *value)
1757 {
1758   int r;
1759
1760   r = destroy_tunnel ((struct MeshTunnel *) value);
1761   return r;
1762 }
1763
1764
1765 /**
1766  * deregister_app: iterator for removing each application registered by a client
1767  * @param cls closure
1768  * @param key the hash of the application id (used to access the hashmap)
1769  * @param value the value stored at the key (client)
1770  * @return GNUNET_OK on success
1771  */
1772 static int
1773 deregister_app (void *cls, const GNUNET_HashCode * key, void *value)
1774 {
1775   GNUNET_CONTAINER_multihashmap_remove(applications, key, value);
1776   return GNUNET_OK;
1777 }
1778
1779 #if LATER
1780 /**
1781  * notify_client_connection_failure: notify a client that the connection to the
1782  * requested remote peer is not possible (for instance, no route found)
1783  * Function called when the socket is ready to queue more data. "buf" will be
1784  * NULL and "size" zero if the socket was closed for writing in the meantime.
1785  *
1786  * @param cls closure
1787  * @param size number of bytes available in buf
1788  * @param buf where the callee should write the message
1789  * @return number of bytes written to buf
1790  */
1791 static size_t
1792 notify_client_connection_failure (void *cls, size_t size, void *buf)
1793 {
1794   int size_needed;
1795   struct MeshPeerInfo *peer_info;
1796   struct GNUNET_MESH_PeerControl *msg;
1797   struct GNUNET_PeerIdentity id;
1798
1799   if (0 == size && NULL == buf)
1800   {
1801     // TODO retry? cancel?
1802     return 0;
1803   }
1804
1805   size_needed = sizeof (struct GNUNET_MESH_PeerControl);
1806   peer_info = (struct MeshPeerInfo *) cls;
1807   msg = (struct GNUNET_MESH_PeerControl *) buf;
1808   msg->header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
1809   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DISCONNECTED);
1810 //     msg->tunnel_id = htonl(peer_info->t->tid);
1811   GNUNET_PEER_resolve (peer_info->id, &id);
1812   memcpy (&msg->peer, &id, sizeof (struct GNUNET_PeerIdentity));
1813
1814   return size_needed;
1815 }
1816 #endif
1817
1818
1819 /**
1820  * Send keepalive packets for a peer
1821  *
1822  * @param cls unused
1823  * @param tc unused
1824  */
1825 static void
1826 path_refresh (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1827 {
1828   struct MeshPeerInfo *peer_info = cls;
1829   struct GNUNET_PeerIdentity id;
1830
1831   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1832     return;
1833   GNUNET_PEER_resolve (get_first_hop (peer_info->path), &id);
1834   GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
1835                                      GNUNET_TIME_UNIT_FOREVER_REL, &id,
1836                                      sizeof (struct GNUNET_MESH_ManipulatePath)
1837                                      +
1838                                      (peer_info->path->length *
1839                                       sizeof (struct GNUNET_PeerIdentity)),
1840                                      &send_core_create_path_for_peer,
1841                                      peer_info);
1842   peer_info->path_refresh_task =
1843       GNUNET_SCHEDULER_add_delayed (REFRESH_PATH_TIME, &path_refresh,
1844                                     peer_info);
1845   return;
1846 }
1847
1848
1849 /**
1850  * Function to process paths received for a new peer addition. The recorded
1851  * paths form the initial tunnel, which can be optimized later.
1852  * Called on each result obtained for the DHT search.
1853  *
1854  * @param cls closure
1855  * @param exp when will this value expire
1856  * @param key key of the result
1857  * @param get_path NULL-terminated array of pointers
1858  *                 to the peers on reverse GET path (or NULL if not recorded)
1859  * @param put_path NULL-terminated array of pointers
1860  *                 to the peers on the PUT path (or NULL if not recorded)
1861  * @param type type of the result
1862  * @param size number of bytes in data
1863  * @param data pointer to the result data
1864  */
1865 static void
1866 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
1867                     const GNUNET_HashCode * key,
1868                     const struct GNUNET_PeerIdentity *const *get_path,
1869                     const struct GNUNET_PeerIdentity *const *put_path,
1870                     enum GNUNET_BLOCK_Type type, size_t size, const void *data)
1871 {
1872   struct MeshPeerInfo *peer_info = cls;
1873   struct MeshPath *p;
1874   struct GNUNET_PeerIdentity pi;
1875   int i;
1876
1877   if ((NULL == get_path || NULL == put_path) && NULL == peer_info->path)
1878   {
1879     // Find ourselves some alternate initial path to the destination: retry
1880     GNUNET_DHT_get_stop (peer_info->dhtget);
1881     GNUNET_PEER_resolve (peer_info->id, &pi);
1882     peer_info->dhtget = GNUNET_DHT_get_start (dht_handle,       /* handle */
1883                                               GNUNET_TIME_UNIT_FOREVER_REL,
1884                                               GNUNET_BLOCK_TYPE_TEST, /* type */
1885                                               &pi.hashPubKey, /*key to search */
1886                                               4,       /* replication level */
1887                                               GNUNET_DHT_RO_RECORD_ROUTE,
1888                                               NULL, /* bloom filter */
1889                                               0,        /* mutator */
1890                                               NULL,     /* xquery */
1891                                               0,        /* xquery bits */
1892                                               dht_get_id_handler,
1893                                               (void *) peer_info);
1894   }
1895
1896   p = GNUNET_malloc (sizeof (struct MeshPath));
1897   for (i = 0; get_path[i] != NULL; i++) ;
1898   for (i--; i >= 0; i--)
1899   {
1900     p->peers =
1901         GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * (p->length + 1));
1902     p->peers[p->length] = GNUNET_PEER_intern (get_path[i]);
1903     p->length++;
1904   }
1905   for (i = 0; put_path[i] != NULL; i++) ;
1906   for (i--; i >= 0; i--)
1907   {
1908     p->peers =
1909         GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * (p->length + 1));
1910     p->peers[p->length] = GNUNET_PEER_intern (put_path[i]);
1911     p->length++;
1912   }
1913   add_path_to_peer (peer_info, p);
1914   GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
1915                                      GNUNET_TIME_UNIT_FOREVER_REL, get_path[1],
1916                                      sizeof (struct GNUNET_MESH_ManipulatePath)
1917                                      +
1918                                      (p->length *
1919                                       sizeof (struct GNUNET_PeerIdentity)),
1920                                      &send_core_create_path_for_peer,
1921                                      peer_info);
1922   if (0 == peer_info->path_refresh_task)
1923   {
1924     peer_info->path_refresh_task =
1925         GNUNET_SCHEDULER_add_delayed (REFRESH_PATH_TIME, &path_refresh,
1926                                       peer_info);
1927   }
1928   return;
1929 }
1930
1931
1932 /**
1933  * Function to process paths received for a new peer addition. The recorded
1934  * paths form the initial tunnel, which can be optimized later.
1935  * Called on each result obtained for the DHT search.
1936  *
1937  * @param cls closure
1938  * @param exp when will this value expire
1939  * @param key key of the result
1940  * @param get_path NULL-terminated array of pointers
1941  *                 to the peers on reverse GET path (or NULL if not recorded)
1942  * @param put_path NULL-terminated array of pointers
1943  *                 to the peers on the PUT path (or NULL if not recorded)
1944  * @param type type of the result
1945  * @param size number of bytes in data
1946  * @param data pointer to the result data
1947  */
1948 static void
1949 dht_get_type_handler (void *cls, struct GNUNET_TIME_Absolute exp,
1950                       const GNUNET_HashCode * key,
1951                       const struct GNUNET_PeerIdentity *const *get_path,
1952                       const struct GNUNET_PeerIdentity *const *put_path,
1953                       enum GNUNET_BLOCK_Type type, size_t size,
1954                       const void *data)
1955 {
1956   const struct GNUNET_PeerIdentity *pi = data;
1957   struct MeshTunnel *t = cls;
1958   struct MeshPeerInfo *peer_info;
1959   struct MeshPath *p;
1960   int i;
1961
1962
1963   if (size != sizeof (struct GNUNET_PeerIdentity))
1964   {
1965     GNUNET_break_op (0);
1966     return;
1967   }
1968   peer_info = get_peer_info (pi);
1969   GNUNET_CONTAINER_multihashmap_put (t->peers, &pi->hashPubKey, peer_info,
1970                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1971   if ((NULL == get_path || NULL == put_path) && NULL == peer_info->path)
1972   {
1973     /* we don't have a route to the peer, let's try a direct lookup */
1974     if (NULL == peer_info->dhtget)
1975     {
1976       peer_info->dhtget = GNUNET_DHT_get_start (dht_handle, /* handle */
1977                                                 GNUNET_TIME_UNIT_FOREVER_REL,
1978                                                 GNUNET_BLOCK_TYPE_TEST,
1979                                                 &pi->hashPubKey,
1980                                                 10U,  /* replication level */
1981                                                 GNUNET_DHT_RO_RECORD_ROUTE,
1982                                                 NULL,   /* bloom filter */
1983                                                 0,      /* mutator */
1984                                                 NULL,   /* xquery */
1985                                                 0,      /* xquery bits */
1986                                                 dht_get_id_handler, peer_info);
1987     }
1988   }
1989   /* TODO refactor */
1990   p = GNUNET_malloc (sizeof (struct MeshPath));
1991   for (i = 0; get_path[i] != NULL; i++) ;
1992   for (i--; i >= 0; i--)
1993   {
1994     p->peers =
1995         GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * (p->length + 1));
1996     p->peers[p->length] = GNUNET_PEER_intern (get_path[i]);
1997     p->length++;
1998   }
1999   for (i = 0; put_path[i] != NULL; i++) ;
2000   for (i--; i >= 0; i--)
2001   {
2002     p->peers =
2003         GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * (p->length + 1));
2004     p->peers[p->length] = GNUNET_PEER_intern (put_path[i]);
2005     p->length++;
2006   }
2007   add_path_to_peer (peer_info, p);
2008   GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
2009                                      GNUNET_TIME_UNIT_FOREVER_REL, get_path[1],
2010                                      sizeof (struct GNUNET_MESH_ManipulatePath)
2011                                      +
2012                                      (p->length *
2013                                       sizeof (struct GNUNET_PeerIdentity)),
2014                                      &send_core_create_path_for_peer,
2015                                      peer_info);
2016
2017 }
2018
2019 /******************************************************************************/
2020 /*********************       MESH LOCAL HANDLES      **************************/
2021 /******************************************************************************/
2022
2023
2024 /**
2025  * Handler for client disconnection
2026  *
2027  * @param cls closure
2028  * @param client identification of the client; NULL
2029  *        for the last call when the server is destroyed
2030  */
2031 static void
2032 handle_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
2033 {
2034   struct MeshClient *c;
2035   struct MeshClient *next;
2036
2037   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: client disconnected\n");
2038   c = clients;
2039   while (NULL != c)
2040   {
2041     if (c->handle != client)
2042     {
2043       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    ... searching\n");
2044       c = c->next;
2045       continue;
2046     }
2047     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: matching client found\n");
2048     if (NULL != c->tunnels)
2049     {
2050       GNUNET_CONTAINER_multihashmap_iterate (c->tunnels,
2051                                              &delete_tunnel_entry,
2052                                              c);
2053       GNUNET_CONTAINER_multihashmap_destroy (c->tunnels);
2054     }
2055
2056     /* deregister clients applications */
2057     if (NULL != c->apps)
2058     {
2059       GNUNET_CONTAINER_multihashmap_iterate(c->apps, &deregister_app, NULL);
2060       GNUNET_CONTAINER_multihashmap_destroy(c->apps);
2061     }
2062     if (0 == GNUNET_CONTAINER_multihashmap_size(applications))
2063     {
2064       GNUNET_SCHEDULER_cancel (announce_applications_task);
2065     }
2066     if (NULL != c->types)
2067       GNUNET_CONTAINER_multihashmap_destroy(c->types);
2068     GNUNET_CONTAINER_DLL_remove (clients, clients_tail, c);
2069     next = c->next;
2070     GNUNET_free (c);
2071     c = next;
2072   }
2073
2074   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    done!\n");
2075   return;
2076 }
2077
2078
2079 /**
2080  * Handler for new clients
2081  *
2082  * @param cls closure
2083  * @param client identification of the client
2084  * @param message the actual message, which includes messages the client wants
2085  */
2086 static void
2087 handle_local_new_client (void *cls, struct GNUNET_SERVER_Client *client,
2088                          const struct GNUNET_MessageHeader *message)
2089 {
2090   struct GNUNET_MESH_ClientConnect *cc_msg;
2091   struct MeshClient *c;
2092   GNUNET_MESH_ApplicationType *a;
2093   unsigned int size;
2094   uint16_t ntypes;
2095   uint16_t *t;
2096   uint16_t napps;
2097   uint16_t i;
2098
2099   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: new client connected\n");
2100   /* Check data sanity */
2101   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_ClientConnect);
2102   cc_msg = (struct GNUNET_MESH_ClientConnect *) message;
2103   ntypes = ntohs (cc_msg->types);
2104   napps = ntohs (cc_msg->applications);
2105   if (size !=
2106       ntypes * sizeof (uint16_t) + napps * sizeof (GNUNET_MESH_ApplicationType))
2107   {
2108     GNUNET_break (0);
2109     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2110     return;
2111   }
2112
2113   /* Create new client structure */
2114   c = GNUNET_malloc (sizeof (struct MeshClient));
2115   c->handle = client;
2116   a = (GNUNET_MESH_ApplicationType *) &cc_msg[1];
2117   if (napps > 0)
2118   {
2119     GNUNET_MESH_ApplicationType at;
2120     GNUNET_HashCode hc;
2121
2122     c->apps = GNUNET_CONTAINER_multihashmap_create(napps);
2123     for (i = 0; i < napps; i++)
2124     {
2125       at = ntohl(a[i]);
2126       GNUNET_CRYPTO_hash(&at, sizeof(at), &hc);
2127       /* store in clients hashmap */
2128       GNUNET_CONTAINER_multihashmap_put(
2129           c->apps,
2130           &hc,
2131           c,
2132           GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2133       /* store in global hashmap, for announcements */
2134       GNUNET_CONTAINER_multihashmap_put(
2135           applications,
2136           &hc,
2137           c,
2138           GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2139     }
2140     if (GNUNET_SCHEDULER_NO_TASK == announce_applications_task)
2141       announce_applications_task = GNUNET_SCHEDULER_add_now (
2142           &announce_applications, NULL);
2143
2144   }
2145   if (ntypes > 0)
2146   {
2147     uint16_t u16;
2148     GNUNET_HashCode hc;
2149
2150     t = (uint16_t *) &a[napps];
2151     c->types = GNUNET_CONTAINER_multihashmap_create(ntypes);
2152     for (i =0; i < ntypes; i++)
2153     {
2154       u16 = ntohs(t[i]);
2155       GNUNET_CRYPTO_hash(&u16, sizeof(u16), &hc);
2156       /* store in clients hashmap */
2157       GNUNET_CONTAINER_multihashmap_put(
2158           c->types,
2159           &hc,
2160           c,
2161           GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2162       /* store in global hashmap */
2163       GNUNET_CONTAINER_multihashmap_put(
2164           types,
2165           &hc,
2166           c,
2167           GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2168     }
2169   }
2170   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2171               "MESH:  client has %u+%u subscriptions\n", napps, ntypes);
2172
2173   GNUNET_CONTAINER_DLL_insert (clients, clients_tail, c);
2174   c->tunnels = GNUNET_CONTAINER_multihashmap_create (32);
2175   GNUNET_SERVER_notification_context_add (nc, client);
2176
2177   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2178
2179 }
2180
2181
2182 /**
2183  * Handler for requests of new tunnels
2184  *
2185  * @param cls closure
2186  * @param client identification of the client
2187  * @param message the actual message
2188  */
2189 static void
2190 handle_local_tunnel_create (void *cls, struct GNUNET_SERVER_Client *client,
2191                             const struct GNUNET_MessageHeader *message)
2192 {
2193   struct GNUNET_MESH_TunnelMessage *t_msg;
2194   struct MeshTunnel *t;
2195   struct MeshClient *c;
2196   GNUNET_HashCode hash;
2197
2198   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: new tunnel requested\n");
2199
2200   /* Sanity check for client registration */
2201   if (NULL == (c = retrieve_client (client)))
2202   {
2203     GNUNET_break (0);
2204     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2205     return;
2206   }
2207
2208   /* Message sanity check */
2209   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
2210   {
2211     GNUNET_break (0);
2212     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2213     return;
2214   }
2215
2216   t_msg = (struct GNUNET_MESH_TunnelMessage *) message;
2217   /* Sanity check for tunnel numbering */
2218   if (0 == (ntohl (t_msg->tunnel_id) & GNUNET_MESH_LOCAL_TUNNEL_ID_CLI))
2219   {
2220     GNUNET_break (0);
2221     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2222     return;
2223   }
2224   /* Sanity check for duplicate tunnel IDs */
2225   if (NULL != retrieve_tunnel_by_local_id (c, ntohl (t_msg->tunnel_id)))
2226   {
2227     GNUNET_break (0);
2228     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2229     return;
2230   }
2231
2232   t = GNUNET_malloc (sizeof (struct MeshTunnel));
2233   while (NULL != retrieve_tunnel_by_pi (myid, next_tid))
2234     next_tid = (next_tid + 1) & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
2235   t->id.tid = next_tid++;
2236   t->id.oid = myid;
2237   t->local_tid = ntohl (t_msg->tunnel_id);
2238   t->client = c;
2239   t->peers = GNUNET_CONTAINER_multihashmap_create (32);
2240
2241   GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
2242   if (GNUNET_OK !=
2243       GNUNET_CONTAINER_multihashmap_put (c->tunnels, &hash, t,
2244                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
2245   {
2246     GNUNET_break (0);
2247     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2248     return;
2249   }
2250
2251   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
2252   if (GNUNET_OK !=
2253       GNUNET_CONTAINER_multihashmap_put (tunnels, &hash, t,
2254                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
2255   {
2256     GNUNET_break (0);
2257     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2258     return;
2259   }
2260
2261   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2262   return;
2263 }
2264
2265
2266 /**
2267  * Handler for requests of deleting tunnels
2268  *
2269  * @param cls closure
2270  * @param client identification of the client
2271  * @param message the actual message
2272  */
2273 static void
2274 handle_local_tunnel_destroy (void *cls, struct GNUNET_SERVER_Client *client,
2275                              const struct GNUNET_MessageHeader *message)
2276 {
2277   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
2278   struct MeshClient *c;
2279   struct MeshTunnel *t;
2280   MESH_TunnelNumber tid;
2281   GNUNET_HashCode hash;
2282
2283   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: destroying tunnel\n");
2284
2285   /* Sanity check for client registration */
2286   if (NULL == (c = retrieve_client (client)))
2287   {
2288     GNUNET_break (0);
2289     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2290     return;
2291   }
2292   /* Message sanity check */
2293   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
2294   {
2295     GNUNET_break (0);
2296     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2297     return;
2298   }
2299
2300   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
2301
2302   /* Retrieve tunnel */
2303   tid = ntohl (tunnel_msg->tunnel_id);
2304
2305   /* Remove from local id hashmap */
2306   GNUNET_CRYPTO_hash (&tid, sizeof (MESH_TunnelNumber), &hash);
2307   t = GNUNET_CONTAINER_multihashmap_get (c->tunnels, &hash);
2308   GNUNET_CONTAINER_multihashmap_remove (c->tunnels, &hash, t);
2309
2310   /* Remove from global id hashmap */
2311   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
2312   GNUNET_CONTAINER_multihashmap_remove (tunnels, &hash, t);
2313
2314 //     notify_tunnel_destroy(t);
2315   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2316   return;
2317 }
2318
2319
2320 /**
2321  * Handler for connection requests to new peers
2322  *
2323  * @param cls closure
2324  * @param client identification of the client
2325  * @param message the actual message (PeerControl)
2326  */
2327 static void
2328 handle_local_connect_add (void *cls, struct GNUNET_SERVER_Client *client,
2329                           const struct GNUNET_MessageHeader *message)
2330 {
2331   struct GNUNET_MESH_PeerControl *peer_msg;
2332   struct MeshClient *c;
2333   struct MeshTunnel *t;
2334   MESH_TunnelNumber tid;
2335   struct MeshPeerInfo *peer_info;
2336
2337
2338   /* Sanity check for client registration */
2339   if (NULL == (c = retrieve_client (client)))
2340   {
2341     GNUNET_break (0);
2342     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2343     return;
2344   }
2345
2346   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
2347   /* Sanity check for message size */
2348   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
2349   {
2350     GNUNET_break (0);
2351     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2352     return;
2353   }
2354
2355   /* Tunnel exists? */
2356   tid = ntohl (peer_msg->tunnel_id);
2357   t = retrieve_tunnel_by_local_id (c, tid);
2358   if (NULL == t)
2359   {
2360     GNUNET_break (0);
2361     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2362     return;
2363   }
2364
2365   /* Does client own tunnel? */
2366   if (t->client->handle != client)
2367   {
2368     GNUNET_break (0);
2369     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2370     return;
2371   }
2372
2373   t->peers_total++;
2374   peer_info = get_peer_info (&peer_msg->peer);
2375
2376   /* Start DHT search if needed */
2377   if (MESH_PEER_READY != peer_info->state && NULL == peer_info->dhtget)
2378   {
2379     peer_info->dhtget = GNUNET_DHT_get_start (dht_handle, GNUNET_TIME_UNIT_FOREVER_REL,
2380                                               GNUNET_BLOCK_TYPE_TEST,
2381                                               &peer_msg->peer.hashPubKey, 4,   /* replication level */
2382                                               GNUNET_DHT_RO_RECORD_ROUTE, NULL, /* bloom filter */
2383                                               0,        /* mutator */
2384                                               NULL,     /* xquery */
2385                                               0,        /* xquery bits */
2386                                               dht_get_id_handler,
2387                                               (void *) peer_info);
2388   }
2389
2390   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2391   return;
2392 }
2393
2394
2395 /**
2396  * Handler for disconnection requests of peers in a tunnel
2397  *
2398  * @param cls closure
2399  * @param client identification of the client
2400  * @param message the actual message (PeerControl)
2401  */
2402 static void
2403 handle_local_connect_del (void *cls, struct GNUNET_SERVER_Client *client,
2404                           const struct GNUNET_MessageHeader *message)
2405 {
2406   struct GNUNET_MESH_PeerControl *peer_msg;
2407   struct MeshClient *c;
2408   struct MeshTunnel *t;
2409   MESH_TunnelNumber tid;
2410
2411   /* Sanity check for client registration */
2412   if (NULL == (c = retrieve_client (client)))
2413   {
2414     GNUNET_break (0);
2415     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2416     return;
2417   }
2418   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
2419   /* Sanity check for message size */
2420   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
2421   {
2422     GNUNET_break (0);
2423     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2424     return;
2425   }
2426
2427   /* Tunnel exists? */
2428   tid = ntohl (peer_msg->tunnel_id);
2429   t = retrieve_tunnel_by_local_id (c, tid);
2430   if (NULL == t)
2431   {
2432     GNUNET_break (0);
2433     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2434     return;
2435   }
2436
2437   /* Does client own tunnel? */
2438   if (t->client->handle != client)
2439   {
2440     GNUNET_break (0);
2441     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2442     return;
2443   }
2444
2445   /* Ok, delete peer from tunnel */
2446   GNUNET_CONTAINER_multihashmap_remove_all (t->peers,
2447                                             &peer_msg->peer.hashPubKey);
2448
2449   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2450   return;
2451 }
2452
2453
2454 /**
2455  * Handler for connection requests to new peers by type
2456  *
2457  * @param cls closure
2458  * @param client identification of the client
2459  * @param message the actual message (ConnectPeerByType)
2460  */
2461 static void
2462 handle_local_connect_by_type (void *cls, struct GNUNET_SERVER_Client *client,
2463                               const struct GNUNET_MessageHeader *message)
2464 {
2465   struct GNUNET_MESH_ConnectPeerByType *connect_msg;
2466   struct MeshClient *c;
2467   struct MeshTunnel *t;
2468   GNUNET_HashCode hash;
2469   GNUNET_MESH_ApplicationType type;
2470   MESH_TunnelNumber tid;
2471
2472   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: got connect by type request\n");
2473   /* Sanity check for client registration */
2474   if (NULL == (c = retrieve_client (client)))
2475   {
2476     GNUNET_break (0);
2477     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2478     return;
2479   }
2480
2481   connect_msg = (struct GNUNET_MESH_ConnectPeerByType *) message;
2482   /* Sanity check for message size */
2483   if (sizeof (struct GNUNET_MESH_ConnectPeerByType) !=
2484       ntohs (connect_msg->header.size))
2485   {
2486     GNUNET_break (0);
2487     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2488     return;
2489   }
2490
2491   /* Tunnel exists? */
2492   tid = ntohl (connect_msg->tunnel_id);
2493   t = retrieve_tunnel_by_local_id (c, tid);
2494   if (NULL == t)
2495   {
2496     GNUNET_break (0);
2497     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2498     return;
2499   }
2500
2501   /* Does client own tunnel? */
2502   if (t->client->handle != client)
2503   {
2504     GNUNET_break (0);
2505     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2506     return;
2507   }
2508
2509   /* Do WE have the service? */
2510   type = ntohl (connect_msg->type);
2511   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  type requested: %u\n", type);
2512   GNUNET_CRYPTO_hash (&type, sizeof (GNUNET_MESH_ApplicationType), &hash);
2513   if (GNUNET_CONTAINER_multihashmap_contains(applications, &hash) == GNUNET_YES)
2514   {
2515     /* Yes! Fast forward, add ourselves to the tunnel and send the
2516       * good news to the client
2517       */
2518     struct GNUNET_MESH_PeerControl pc;
2519
2520     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  available locally\n");
2521     pc.peer = my_full_id;
2522     GNUNET_CONTAINER_multihashmap_put (t->peers, &pc.peer.hashPubKey,
2523                                         get_peer_info (&pc.peer),
2524                                         GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2525     pc.header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
2526     pc.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD);
2527     pc.tunnel_id = htonl (t->local_tid);
2528     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  notifying client\n");
2529     GNUNET_SERVER_notification_context_unicast (nc,   /* context */
2530                                                 client,       /* dest */
2531                                                 &pc.header,   /* msg */
2532                                                 GNUNET_NO);   /* can drop? */
2533     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  Done\n");
2534     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2535     return;
2536   }
2537   /* Ok, lets find a peer offering the service */
2538   if (c->dht_get_type)
2539   {
2540     GNUNET_DHT_get_stop (c->dht_get_type);
2541   }
2542   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2543               "MESH:  looking in DHT for %s\n",
2544               GNUNET_h2s_full(&hash));
2545   c->dht_get_type =
2546       GNUNET_DHT_get_start (dht_handle,
2547                             GNUNET_TIME_UNIT_FOREVER_REL,
2548                             GNUNET_BLOCK_TYPE_TEST,
2549                             &hash,
2550                             10U,
2551                             GNUNET_DHT_RO_RECORD_ROUTE,
2552                             NULL,
2553                             0,
2554                             NULL,
2555                             0,
2556                             &dht_get_type_handler,
2557                             t);
2558
2559   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2560   return;
2561 }
2562
2563
2564 /**
2565  * Handler for client traffic directed to one peer
2566  *
2567  * @param cls closure
2568  * @param client identification of the client
2569  * @param message the actual message
2570  */
2571 static void
2572 handle_local_unicast (void *cls, struct GNUNET_SERVER_Client *client,
2573                       const struct GNUNET_MessageHeader *message)
2574 {
2575   struct MeshClient *c;
2576   struct MeshTunnel *t;
2577   struct MeshPeerInfo *pi;
2578   struct GNUNET_MESH_Unicast *data_msg;
2579   struct GNUNET_PeerIdentity next_hop;
2580   struct MeshDataDescriptor *info;
2581   MESH_TunnelNumber tid;
2582   size_t data_size;
2583
2584   /* Sanity check for client registration */
2585   if (NULL == (c = retrieve_client (client)))
2586   {
2587     GNUNET_break (0);
2588     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2589     return;
2590   }
2591   data_msg = (struct GNUNET_MESH_Unicast *) message;
2592   /* Sanity check for message size */
2593   if (sizeof (struct GNUNET_MESH_Unicast) +
2594       sizeof (struct GNUNET_MessageHeader) > ntohs (data_msg->header.size))
2595   {
2596     GNUNET_break (0);
2597     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2598     return;
2599   }
2600
2601   /* Tunnel exists? */
2602   tid = ntohl (data_msg->tid);
2603   t = retrieve_tunnel_by_local_id (c, tid);
2604   if (NULL == t)
2605   {
2606     GNUNET_break (0);
2607     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2608     return;
2609   }
2610
2611   /*  Is it a local tunnel? Then, does client own the tunnel? */
2612   if (t->client->handle != NULL && t->client->handle != client)
2613   {
2614     GNUNET_break (0);
2615     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2616     return;
2617   }
2618
2619   pi = GNUNET_CONTAINER_multihashmap_get (t->peers,
2620                                           &data_msg->destination.hashPubKey);
2621   /* Is the selected peer in the tunnel? */
2622   if (NULL == pi)
2623   {
2624     GNUNET_break (0);
2625     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2626     return;
2627   }
2628   if (pi->id == myid)
2629   {
2630     struct GNUNET_MESH_Unicast copy;
2631
2632     /* Work around const limitation */
2633     memcpy (&copy, data_msg, sizeof (struct GNUNET_MESH_Unicast));
2634     copy.oid = my_full_id;
2635     copy.tid = htonl(t->id.tid);
2636     handle_mesh_data_unicast (NULL, &my_full_id, &copy.header, NULL);
2637     return;
2638   }
2639   GNUNET_PEER_resolve (get_first_hop (pi->path), &next_hop);
2640   data_size = ntohs (message->size) - sizeof (struct GNUNET_MESH_Unicast);
2641   info = GNUNET_malloc (sizeof (struct MeshDataDescriptor) + data_size);
2642   memcpy (&info[1], &data_msg[1], data_size);
2643   info->destination = pi->id;
2644   info->origin = &t->id;
2645   info->size = data_size;
2646   info->client = client;
2647   GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
2648                                      GNUNET_TIME_UNIT_FOREVER_REL, &next_hop,
2649                                      /* FIXME re-check types */
2650                                      data_size +
2651                                      sizeof (struct GNUNET_MESH_Unicast),
2652                                      &send_core_data_unicast, info);
2653   return;
2654 }
2655
2656 /**
2657  * Handler for client traffic directed to all peers in a tunnel
2658  *
2659  * @param cls closure
2660  * @param client identification of the client
2661  * @param message the actual message
2662  */
2663 static void
2664 handle_local_multicast (void *cls, struct GNUNET_SERVER_Client *client,
2665                         const struct GNUNET_MessageHeader *message)
2666 {
2667   struct MeshClient *c;
2668   struct MeshTunnel *t;
2669   struct GNUNET_MESH_Multicast *data_msg;
2670   MESH_TunnelNumber tid;
2671
2672   /* Sanity check for client registration */
2673   if (NULL == (c = retrieve_client (client)))
2674   {
2675     GNUNET_break (0);
2676     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2677     return;
2678   }
2679   data_msg = (struct GNUNET_MESH_Multicast *) message;
2680   /* Sanity check for message size */
2681   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (data_msg->header.size))
2682   {
2683     GNUNET_break (0);
2684     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2685     return;
2686   }
2687
2688   /* Tunnel exists? */
2689   tid = ntohl (data_msg->tid);
2690   t = retrieve_tunnel_by_local_id (c, tid);
2691   if (NULL == t)
2692   {
2693     GNUNET_break (0);
2694     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2695     return;
2696   }
2697
2698   /* Does client own tunnel? */
2699   if (t->client->handle != client)
2700   {
2701     GNUNET_break (0);
2702     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2703     return;
2704   }
2705
2706   /*  TODO */
2707
2708   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2709   return;
2710 }
2711
2712 /**
2713  * Functions to handle messages from clients
2714  */
2715 static struct GNUNET_SERVER_MessageHandler plugin_handlers[] = {
2716   {&handle_local_new_client, NULL, GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT, 0},
2717   {&handle_local_tunnel_create, NULL,
2718    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE,
2719    sizeof (struct GNUNET_MESH_TunnelMessage)},
2720   {&handle_local_tunnel_destroy, NULL,
2721    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY,
2722    sizeof (struct GNUNET_MESH_TunnelMessage)},
2723   {&handle_local_connect_add, NULL,
2724    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD,
2725    sizeof (struct GNUNET_MESH_PeerControl)},
2726   {&handle_local_connect_del, NULL,
2727    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL,
2728    sizeof (struct GNUNET_MESH_PeerControl)},
2729   {&handle_local_connect_by_type, NULL,
2730    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_TYPE,
2731    sizeof (struct GNUNET_MESH_ConnectPeerByType)},
2732   {&handle_local_unicast, NULL,
2733    GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
2734   {&handle_local_unicast, NULL,
2735    GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
2736   {&handle_local_multicast, NULL,
2737    GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
2738   {NULL, NULL, 0, 0}
2739 };
2740
2741
2742 /**
2743  * To be called on core init/fail.
2744  *
2745  * @param cls service closure
2746  * @param server handle to the server for this service
2747  * @param identity the public identity of this peer
2748  * @param publicKey the public key of this peer
2749  */
2750 static void
2751 core_init (void *cls, struct GNUNET_CORE_Handle *server,
2752            const struct GNUNET_PeerIdentity *identity,
2753            const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
2754 {
2755   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Core init\n");
2756   core_handle = server;
2757   my_full_id = *identity;
2758   myid = GNUNET_PEER_intern (identity);
2759   announce_id_task = GNUNET_SCHEDULER_add_now (&announce_id, cls);
2760   return;
2761 }
2762
2763 /**
2764  * Method called whenever a given peer connects.
2765  *
2766  * @param cls closure
2767  * @param peer peer identity this notification is about
2768  * @param atsi performance data for the connection
2769  */
2770 static void
2771 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
2772               const struct GNUNET_TRANSPORT_ATS_Information *atsi)
2773 {
2774 //     GNUNET_PEER_Id              pid;
2775   struct MeshPeerInfo *peer_info;
2776   struct MeshPath *path;
2777
2778   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Peer connected\n");
2779   peer_info = get_peer_info (peer);
2780   if (myid == peer_info->id)
2781   {
2782     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:      (self)\n");
2783   }
2784   path = GNUNET_malloc (sizeof (struct MeshPath));
2785   path->length = 2;
2786   path->peers = GNUNET_malloc (sizeof (GNUNET_PEER_Id) * 2);
2787   path->peers[0] = myid;
2788   path->peers[1] = peer_info->id;
2789   add_path_to_peer (peer_info, path);
2790   return;
2791 }
2792
2793 /**
2794  * Method called whenever a peer disconnects.
2795  *
2796  * @param cls closure
2797  * @param peer peer identity this notification is about
2798  */
2799 static void
2800 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
2801 {
2802   struct MeshPeerInfo *pi;
2803   unsigned int i;
2804
2805   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Peer disconnected\n");
2806   pi = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
2807   if (!pi)
2808   {
2809     GNUNET_break (0);
2810     return;
2811   }
2812   for (i = 0; i < CORE_QUEUE_SIZE; i++)
2813   {
2814     if (pi->core_transmit[i])
2815     {
2816       GNUNET_CORE_notify_transmit_ready_cancel (pi->core_transmit[i]);
2817       /* TODO: notify that tranmission has failed */
2818       GNUNET_free (pi->infos[i]);
2819     }
2820   }
2821   if (myid == pi->id)
2822   {
2823     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:      (self)\n");
2824   }
2825   return;
2826 }
2827
2828
2829 /******************************************************************************/
2830 /************************      MAIN FUNCTIONS      ****************************/
2831 /******************************************************************************/
2832
2833 /**
2834  * Task run during shutdown.
2835  *
2836  * @param cls unused
2837  * @param tc unused
2838  */
2839 static void
2840 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2841 {
2842   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: shutting down\n");
2843   if (core_handle != NULL)
2844   {
2845     GNUNET_CORE_disconnect (core_handle);
2846     core_handle = NULL;
2847   }
2848   if (dht_handle != NULL)
2849   {
2850     GNUNET_DHT_disconnect (dht_handle);
2851     dht_handle = NULL;
2852   }
2853   if (nc != NULL)
2854   {
2855     GNUNET_SERVER_notification_context_destroy (nc);
2856     nc = NULL;
2857   }
2858   if (0 != announce_id_task)
2859   {
2860     GNUNET_SCHEDULER_cancel (announce_id_task);
2861     announce_id_task = 0;
2862   }
2863   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: shut down\n");
2864 }
2865
2866 /**
2867  * Process mesh requests.
2868  *
2869  * @param cls closure
2870  * @param server the initialized server
2871  * @param c configuration to use
2872  */
2873 static void
2874 run (void *cls, struct GNUNET_SERVER_Handle *server,
2875      const struct GNUNET_CONFIGURATION_Handle *c)
2876 {
2877   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: starting to run\n");
2878   GNUNET_SERVER_add_handlers (server, plugin_handlers);
2879   GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
2880   server_handle = server;
2881   core_handle = GNUNET_CORE_connect (c, /* Main configuration */
2882                                      CORE_QUEUE_SIZE,   /* queue size */
2883                                      NULL,      /* Closure passed to MESH functions */
2884                                      &core_init,        /* Call core_init once connected */
2885                                      &core_connect,     /* Handle connects */
2886                                      &core_disconnect,  /* remove peers on disconnects */
2887                                      NULL,      /* Do we care about "status" updates? */
2888                                      NULL,      /* Don't notify about all incoming messages */
2889                                      GNUNET_NO, /* For header only in notification */
2890                                      NULL,      /* Don't notify about all outbound messages */
2891                                      GNUNET_NO, /* For header-only out notification */
2892                                      core_handlers);    /* Register these handlers */
2893   if (core_handle == NULL)
2894   {
2895     GNUNET_break (0);
2896   }
2897   dht_handle = GNUNET_DHT_connect (c, 64);
2898   if (dht_handle == NULL)
2899   {
2900     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Error connecting to DHT.\
2901                    Running without DHT has a severe\
2902                    impact in MESH capabilities.\n\
2903                    Plase check your configuretion and enable DHT.\n");
2904     GNUNET_break (0);
2905   }
2906
2907   next_tid = 0;
2908
2909   tunnels = GNUNET_CONTAINER_multihashmap_create (32);
2910   peers = GNUNET_CONTAINER_multihashmap_create (32);
2911   applications = GNUNET_CONTAINER_multihashmap_create (32);
2912   types = GNUNET_CONTAINER_multihashmap_create (32);
2913   nc = GNUNET_SERVER_notification_context_create (server_handle,
2914                                                   LOCAL_QUEUE_SIZE);
2915   clients = NULL;
2916   clients_tail = NULL;
2917
2918   announce_applications_task = 0;
2919
2920   /* Scheduled the task to clean up when shutdown is called */
2921   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
2922                                 NULL);
2923
2924   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: end of run()\n");
2925 }
2926
2927 /**
2928  * The main function for the mesh service.
2929  *
2930  * @param argc number of arguments from the command line
2931  * @param argv command line arguments
2932  * @return 0 ok, 1 on error
2933  */
2934 int
2935 main (int argc, char *const *argv)
2936 {
2937   int ret;
2938
2939   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: main()\n");
2940   ret =
2941       (GNUNET_OK ==
2942        GNUNET_SERVICE_run (argc, argv, "mesh", GNUNET_SERVICE_OPTION_NONE, &run,
2943                            NULL)) ? 0 : 1;
2944   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: main() END\n");
2945   return ret;
2946 }