Fixed test local to pass at least when DHT is not used
[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),
828                   APP_ANNOUNCE_TIME,
829 #if MESH_DEBUG
830                   &mesh_debug, "DHT_put for app completed");
831 #else
832                   NULL, NULL);
833 #endif
834   return GNUNET_OK;
835 }
836
837
838 /**
839  * Periodically announce what applications are provided by local clients
840  *
841  * @param cls closure
842  * @param tc task context
843  */
844 static void
845 announce_applications (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
846 {
847   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
848   {
849     announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
850     return;
851   }
852   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Starting PUT for apps\n");
853   GNUNET_CONTAINER_multihashmap_iterate(applications,
854                                         &announce_application,
855                                         NULL);
856   announce_applications_task =
857       GNUNET_SCHEDULER_add_delayed (APP_ANNOUNCE_TIME, &announce_applications,
858                                     cls);
859   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Finished PUT for apps\n");
860   return;
861 }
862
863
864 /**
865  * Periodically announce self id in the DHT
866  *
867  * @param cls closure
868  * @param tc task context
869  */
870 static void
871 announce_id (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
872 {
873   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
874   {
875     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
876     return;
877   }
878   /* TODO
879    * - Set data expiration in function of X
880    * - Adapt X to churn
881    */
882   GNUNET_DHT_put (dht_handle,   /* DHT handle */
883                   &my_full_id.hashPubKey,       /* Key to use */
884                   10U,          /* Replication level */
885                   GNUNET_DHT_RO_RECORD_ROUTE,   /* DHT options */
886                   GNUNET_BLOCK_TYPE_TEST,        /* Block type */
887                   0,            /* Size of the data */
888                   NULL,         /* Data itself */
889                   GNUNET_TIME_absolute_get_forever (),  /* Data expiration */
890                   GNUNET_TIME_UNIT_FOREVER_REL, /* Retry time */
891 #if MESH_DEBUG
892                   &mesh_debug, "DHT_put for id completed");
893 #else
894                   NULL,         /* Continuation */
895                   NULL);        /* Continuation closure */
896 #endif
897   announce_id_task =
898       GNUNET_SCHEDULER_add_delayed (ID_ANNOUNCE_TIME, &announce_id, cls);
899 }
900
901 /******************************************************************************/
902 /****************      MESH NETWORK HANDLER HELPERS     ***********************/
903 /******************************************************************************/
904
905 /**
906  * Function called to notify a client about the socket
907  * being ready to queue more data.  "buf" will be
908  * NULL and "size" zero if the socket was closed for
909  * writing in the meantime.
910  *
911  * @param cls closure
912  * @param size number of bytes available in buf
913  * @param buf where the callee should write the message
914  * @return number of bytes written to buf
915  */
916 static size_t
917 send_core_create_path_for_peer (void *cls, size_t size, void *buf)
918 {
919   struct MeshPeerInfo *peer_info = cls;
920   struct GNUNET_MESH_ManipulatePath *msg;
921   struct MeshPath *p;
922   struct GNUNET_PeerIdentity *peer_ptr;
923   struct GNUNET_PeerIdentity id;
924   size_t size_needed;
925   int i;
926
927   if (0 == size && NULL == buf)
928   {
929     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Retransmitting create path\n");
930     GNUNET_PEER_resolve (get_first_hop (peer_info->path), &id);
931     GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
932                                        GNUNET_TIME_UNIT_FOREVER_REL, &id,
933                                        sizeof (struct
934                                                GNUNET_MESH_ManipulatePath) +
935                                        (peer_info->path->length *
936                                         sizeof (struct GNUNET_PeerIdentity)),
937                                        &send_core_create_path_for_peer,
938                                        peer_info);
939     return 0;
940   }
941   p = peer_info->path;
942   while (NULL != p)
943   {
944     if (p->in_use)
945     {
946       break;
947     }
948     p = p->next;
949   }
950   if (p == NULL)
951     return 0;                   // TODO Notify ERROR Path not found
952
953   size_needed =
954       sizeof (struct GNUNET_MESH_ManipulatePath) +
955       p->length * sizeof (struct GNUNET_PeerIdentity);
956   if (size < size_needed)
957   {
958     // TODO retry? cancel?
959     return 0;
960   }
961
962   msg = (struct GNUNET_MESH_ManipulatePath *) buf;
963   msg->header.size = htons (size_needed);
964   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE);
965
966   peer_ptr = (struct GNUNET_PeerIdentity *) &msg[1];
967   for (i = 0; i < p->length; i++)
968   {
969     GNUNET_PEER_resolve (p->peers[i], peer_ptr++);
970   }
971
972   peer_info->state = MESH_PEER_WAITING;
973
974   return size_needed;
975 }
976
977
978 #if LATER
979 /**
980  * Function called to notify a client about the socket
981  * being ready to queue more data.  "buf" will be
982  * NULL and "size" zero if the socket was closed for
983  * writing in the meantime.
984  *
985  * @param cls closure (MeshDataDescriptor with all info to build packet)
986  * @param size number of bytes available in buf
987  * @param buf where the callee should write the message
988  * @return number of bytes written to buf
989  */
990 static size_t
991 send_core_data_to_origin (void *cls, size_t size, void *buf)
992 {
993   struct MeshDataDescriptor *info = cls;
994   struct GNUNET_MESH_ToOrigin *msg = buf;
995   size_t total_size;
996
997   GNUNET_assert (NULL != info);
998   total_size = sizeof (struct GNUNET_MESH_ToOrigin) + info->size;
999   GNUNET_assert (total_size < 65536);   /* UNIT16_MAX */
1000
1001   if (total_size > size)
1002   {
1003     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1004                 "not enough buffer to send data to origin\n");
1005     return 0;
1006   }
1007   msg->header.size = htons (total_size);
1008   msg->header.type = htons (GNUNET_MESSAGE_TYPE_DATA_MESSAGE_TO_ORIGIN);
1009   GNUNET_PEER_resolve (info->origin->oid, &msg->oid);
1010   msg->tid = htonl (info->origin->tid);
1011   if (0 != info->size)
1012   {
1013     memcpy (&msg[1], &info[1], info->size);
1014   }
1015   if (NULL != info->client)
1016   {
1017     GNUNET_SERVER_receive_done (info->client, GNUNET_OK);
1018   }
1019   GNUNET_free (info);
1020   return total_size;
1021 }
1022 #endif
1023
1024 /**
1025  * Function called to notify a client about the socket
1026  * being ready to queue more data.  "buf" will be
1027  * NULL and "size" zero if the socket was closed for
1028  * writing in the meantime.
1029  *
1030  * @param cls closure (data itself)
1031  * @param size number of bytes available in buf
1032  * @param buf where the callee should write the message
1033  * @return number of bytes written to buf
1034  */
1035 static size_t
1036 send_core_data_unicast (void *cls, size_t size, void *buf)
1037 {
1038   struct MeshDataDescriptor *info = cls;
1039   struct GNUNET_MESH_Unicast *msg = buf;
1040   size_t total_size;
1041
1042   GNUNET_assert (NULL != info);
1043   total_size = sizeof (struct GNUNET_MESH_Unicast) + info->size;
1044   GNUNET_assert (total_size < 65536);   /* UNIT16_MAX */
1045
1046   if (total_size > size)
1047   {
1048     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1049                 "not enough buffer to send data to peer\n");
1050     return 0;
1051   }
1052   msg->header.size = htons (total_size);
1053   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_UNICAST);
1054   GNUNET_PEER_resolve (info->origin->oid, &msg->oid);
1055   GNUNET_PEER_resolve (info->destination, &msg->destination);
1056   msg->tid = htonl (info->origin->tid);
1057   if (0 != info->size)
1058   {
1059     memcpy (&msg[1], &info[1], info->size);
1060   }
1061   if (NULL != info->client)
1062   {
1063     GNUNET_SERVER_receive_done (info->client, GNUNET_OK);
1064   }
1065   GNUNET_free (info);
1066   return total_size;
1067 }
1068
1069
1070 /**
1071  * Function called to notify a client about the socket
1072  * being ready to queue more data.  "buf" will be
1073  * NULL and "size" zero if the socket was closed for
1074  * writing in the meantime.
1075  *
1076  * @param cls closure (data itself)
1077  * @param size number of bytes available in buf
1078  * @param buf where the callee should write the message
1079  * @return number of bytes written to buf
1080  */
1081 static size_t
1082 send_core_data_multicast (void *cls, size_t size, void *buf)
1083 {
1084   struct MeshDataDescriptor *info = cls;
1085   struct GNUNET_MESH_Multicast *msg = buf;
1086   size_t total_size;
1087
1088   GNUNET_assert (NULL != info);
1089   total_size = info->size + sizeof (struct GNUNET_MESH_Multicast);
1090   GNUNET_assert (total_size < GNUNET_SERVER_MAX_MESSAGE_SIZE);
1091
1092   if (info->peer)
1093   {
1094     info->peer->core_transmit[info->handler_n] = NULL;
1095   }
1096   if (total_size > size)
1097   {
1098     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1099                 "not enough buffer to send data futher\n");
1100     return 0;
1101   }
1102   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
1103   msg->header.size = htons (total_size);
1104   GNUNET_PEER_resolve (info->origin->oid, &msg->oid);
1105   msg->tid = htonl (info->origin->tid);
1106   memcpy (&msg[1], &info[1], total_size);
1107   if (0 == --info->copies)
1108   {
1109     if (NULL != info->client)
1110     {
1111       GNUNET_SERVER_receive_done (info->client, GNUNET_OK);
1112     }
1113     GNUNET_free (info);
1114   }
1115   return total_size;
1116 }
1117
1118
1119 /**
1120  * Function called to notify a client about the socket
1121  * being ready to queue more data.  "buf" will be
1122  * NULL and "size" zero if the socket was closed for
1123  * writing in the meantime.
1124  *
1125  * @param cls closure (MeshDataDescriptor)
1126  * @param size number of bytes available in buf
1127  * @param buf where the callee should write the message
1128  * @return number of bytes written to buf
1129  */
1130 static size_t
1131 send_core_path_ack (void *cls, size_t size, void *buf)
1132 {
1133   struct MeshDataDescriptor *info = cls;
1134   struct GNUNET_MESH_PathACK *msg = buf;
1135
1136   GNUNET_assert (NULL != info);
1137   if (info->peer)
1138   {
1139     info->peer->core_transmit[info->handler_n] = NULL;
1140   }
1141   if (sizeof (struct GNUNET_MESH_PathACK) > size)
1142   {
1143     GNUNET_break (0);
1144     return 0;
1145   }
1146   msg->header.size = htons (sizeof (struct GNUNET_MESH_PathACK));
1147   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_ACK);
1148   GNUNET_PEER_resolve (info->origin->oid, &msg->oid);
1149   msg->tid = htonl (info->origin->tid);
1150   msg->peer_id = my_full_id;
1151   /* TODO add signature */
1152
1153   return sizeof (struct GNUNET_MESH_PathACK);
1154 }
1155
1156
1157 /**
1158  * Function called to notify a client about the socket
1159  * being ready to queue more data.  "buf" will be
1160  * NULL and "size" zero if the socket was closed for
1161  * writing in the meantime.
1162  *
1163  * @param cls closure (data itself)
1164  * @param size number of bytes available in buf
1165  * @param buf where the callee should write the message
1166  * @return number of bytes written to buf
1167  */
1168 static size_t
1169 send_core_data_raw (void *cls, size_t size, void *buf)
1170 {
1171   struct GNUNET_MessageHeader *msg = cls;
1172   size_t total_size;
1173
1174   GNUNET_assert (NULL != msg);
1175   total_size = ntohs (msg->size);
1176
1177   if (total_size > size)
1178   {
1179     GNUNET_break (0);
1180     return 0;
1181   }
1182   memcpy (buf, msg, total_size);
1183   GNUNET_free (cls);
1184   return total_size;
1185 }
1186
1187
1188 #if LATER
1189 /**
1190  * Send another peer a notification to destroy a tunnel
1191  * @param cls The tunnel to destroy
1192  * @param size Size in the buffer
1193  * @param buf Memory where to put the data to transmit
1194  * @return Size of data put in buffer
1195  */
1196 static size_t
1197 send_p2p_tunnel_destroy (void *cls, size_t size, void *buf)
1198 {
1199   struct MeshTunnel *t = cls;
1200   struct MeshClient *c;
1201   struct GNUNET_MESH_TunnelMessage *msg;
1202
1203   c = t->client;
1204   msg = buf;
1205   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY);
1206    /*FIXME*/ msg->header.size =
1207       htons (sizeof (struct GNUNET_MESH_TunnelMessage));
1208   msg->tunnel_id = htonl (t->id.tid);
1209
1210   destroy_tunnel (c, t);
1211   return sizeof (struct GNUNET_MESH_TunnelMessage);
1212 }
1213 #endif
1214
1215
1216 /**
1217  * Send the message to all clients that have subscribed to its type
1218  *
1219  * @param msg Pointer to the message itself
1220  * @return number of clients this message was sent to
1221  */
1222 static unsigned int
1223 send_subscribed_clients (struct GNUNET_MessageHeader *msg)
1224 {
1225   struct MeshClient *c;
1226   unsigned int count;
1227   uint16_t type;
1228
1229   type = ntohs (msg->type);
1230   for (count = 0, c = clients; c != NULL; c = c->next)
1231   {
1232     if (is_client_subscribed (type, c))
1233     {
1234       count++;
1235       GNUNET_SERVER_notification_context_unicast (nc, c->handle, msg,
1236                                                   GNUNET_YES);
1237     }
1238   }
1239   return count;
1240 }
1241
1242
1243 /**
1244  * Iterator over hash map peer entries collect all neighbors who to resend the
1245  * data to.
1246  *
1247  * @param cls closure (**GNUNET_PEER_Id to store hops to send packet)
1248  * @param key current key code (peer id hash)
1249  * @param value value in the hash map (peer_info)
1250  * @return GNUNET_YES if we should continue to iterate, GNUNET_NO if not.
1251  */
1252 static int
1253 iterate_collect_neighbors (void *cls, const GNUNET_HashCode * key, void *value)
1254 {
1255   struct MeshPeerInfo *peer_info = value;
1256   GNUNET_PEER_Id **neighbors = cls;
1257   GNUNET_PEER_Id id;
1258   unsigned int i;
1259
1260   if (peer_info->id == myid)
1261   {
1262     return GNUNET_YES;
1263   }
1264   id = get_first_hop (peer_info->path);
1265   for (i = 0; *neighbors[i] != 0; i++)
1266   {
1267     if (*neighbors[i] == id)
1268       return GNUNET_YES;
1269   }
1270   *neighbors = GNUNET_realloc (*neighbors, (i + 2) * sizeof (GNUNET_PEER_Id));
1271   *neighbors[i] = id;
1272   *neighbors[i + 1] = 0;
1273
1274   return GNUNET_YES;
1275 }
1276
1277
1278 /******************************************************************************/
1279 /********************      MESH NETWORK HANDLERS     **************************/
1280 /******************************************************************************/
1281
1282
1283 /**
1284  * Core handler for path creation
1285  * struct GNUNET_CORE_MessageHandler
1286  *
1287  * @param cls closure
1288  * @param message message
1289  * @param peer peer identity this notification is about
1290  * @param atsi performance data
1291  * @return GNUNET_OK to keep the connection open,
1292  *         GNUNET_SYSERR to close it (signal serious error)
1293  *
1294  */
1295 static int
1296 handle_mesh_path_create (void *cls, const struct GNUNET_PeerIdentity *peer,
1297                          const struct GNUNET_MessageHeader *message,
1298                          const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1299 {
1300   unsigned int own_pos;
1301   uint16_t size;
1302   uint16_t i;
1303   MESH_TunnelNumber tid;
1304   struct GNUNET_MESH_ManipulatePath *msg;
1305   struct GNUNET_PeerIdentity *pi;
1306   struct GNUNET_PeerIdentity id;
1307   GNUNET_HashCode hash;
1308   struct MeshPath *path;
1309   struct MeshPeerInfo *dest_peer_info;
1310   struct MeshPeerInfo *orig_peer_info;
1311   struct MeshTunnel *t;
1312
1313   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1314               "MESH: Received a MESH path create msg\n");
1315   size = ntohs (message->size);
1316   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
1317   {
1318     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1319                 "received create path message too short\n");
1320     return GNUNET_OK;
1321   }
1322
1323   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
1324   if (size < 2 * sizeof (struct GNUNET_PeerIdentity))
1325   {
1326     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1327                 "create path message lacks enough peers\n");
1328     return GNUNET_OK;
1329   }
1330   if (size % sizeof (struct GNUNET_PeerIdentity))
1331   {
1332     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1333                 "create path message of wrong size\n");
1334     return GNUNET_OK;
1335   }
1336   msg = (struct GNUNET_MESH_ManipulatePath *) message;
1337   size /= sizeof (struct GNUNET_PeerIdentity);
1338
1339   tid = ntohl (msg->tid);
1340   pi = (struct GNUNET_PeerIdentity *) &msg[1];
1341   t = retrieve_tunnel (pi, tid);
1342
1343   if (NULL == t)
1344   {
1345     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Creating tunnel\n");
1346     t = GNUNET_malloc (sizeof (struct MeshTunnel));
1347     t->id.oid = GNUNET_PEER_intern (pi);
1348     t->id.tid = tid;
1349     t->peers = GNUNET_CONTAINER_multihashmap_create (32);
1350
1351     GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
1352     if (GNUNET_OK !=
1353         GNUNET_CONTAINER_multihashmap_put (tunnels, &hash, t,
1354                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
1355     {
1356       GNUNET_break (0);
1357       return GNUNET_OK;
1358     }
1359
1360   }
1361   dest_peer_info =
1362       GNUNET_CONTAINER_multihashmap_get (peers, &pi[size - 1].hashPubKey);
1363   if (NULL == dest_peer_info)
1364   {
1365     dest_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
1366     dest_peer_info->id = GNUNET_PEER_intern (&pi[size - 1]);
1367     dest_peer_info->state = MESH_PEER_WAITING;
1368     GNUNET_CONTAINER_multihashmap_put (peers, &pi[size - 1].hashPubKey,
1369                                        dest_peer_info,
1370                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1371   }
1372   orig_peer_info = GNUNET_CONTAINER_multihashmap_get (peers, &pi->hashPubKey);
1373   if (NULL == orig_peer_info)
1374   {
1375     orig_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
1376     orig_peer_info->id = GNUNET_PEER_intern (pi);
1377     orig_peer_info->state = MESH_PEER_WAITING;
1378     GNUNET_CONTAINER_multihashmap_put (peers, &pi->hashPubKey, orig_peer_info,
1379                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1380   }
1381
1382
1383   path = GNUNET_malloc (sizeof (struct MeshPath));
1384   path->length = size;
1385   path->peers = GNUNET_malloc (size * sizeof (GNUNET_PEER_Id));
1386   own_pos = 0;
1387   for (i = 0; i < size; i++)
1388   {
1389     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
1390     if (path->peers[i] == myid)
1391       own_pos = i;
1392   }
1393   if (own_pos == 0)
1394   {                             /* cannot be self, must be 'not found' */
1395     /* create path: self not found in path through self */
1396     GNUNET_break_op (0);
1397     destroy_path (path);
1398     /* FIXME error. destroy tunnel? leave for timeout? */
1399     return 0;
1400   }
1401   if (own_pos == size - 1)
1402   {                             /* it is for us! */
1403     struct MeshDataDescriptor *info;
1404     unsigned int j;
1405
1406     add_path_to_origin (orig_peer_info, path);  /* inverts path!  */
1407     GNUNET_PEER_resolve (get_first_hop (path), &id);    /* path is inverted :) */
1408     info = GNUNET_malloc (sizeof (struct MeshDataDescriptor));
1409     info->origin = &t->id;
1410     info->peer = GNUNET_CONTAINER_multihashmap_get (peers, &id.hashPubKey);
1411     GNUNET_assert (info->peer);
1412     for (j = 0; info->peer->core_transmit[j]; j++)
1413     {
1414       if (j == 9)
1415       {
1416         GNUNET_break (0);
1417         return GNUNET_OK;
1418       }
1419     }
1420     info->handler_n = j;
1421     info->peer->core_transmit[j] =
1422         GNUNET_CORE_notify_transmit_ready (core_handle, 0, 100,
1423                                            GNUNET_TIME_UNIT_FOREVER_REL, &id,
1424                                            sizeof (struct GNUNET_MessageHeader),
1425                                            &send_core_path_ack, info);
1426   }
1427   else
1428   {
1429     add_path_to_peer (dest_peer_info, path);
1430     GNUNET_PEER_resolve (get_first_hop (path), &id);
1431     GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
1432                                        GNUNET_TIME_UNIT_FOREVER_REL, &id,
1433                                        sizeof (struct GNUNET_MessageHeader),
1434                                        &send_core_create_path_for_peer,
1435                                        dest_peer_info);
1436   }
1437   return GNUNET_OK;
1438 }
1439
1440
1441 /**
1442  * Core handler for mesh network traffic going from the origin to a peer
1443  *
1444  * @param cls closure
1445  * @param peer peer identity this notification is about
1446  * @param message message
1447  * @param atsi performance data
1448  * @return GNUNET_OK to keep the connection open,
1449  *         GNUNET_SYSERR to close it (signal serious error)
1450  */
1451 static int
1452 handle_mesh_data_unicast (void *cls, const struct GNUNET_PeerIdentity *peer,
1453                           const struct GNUNET_MessageHeader *message,
1454                           const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1455 {
1456   struct GNUNET_MESH_Unicast *msg;
1457   struct GNUNET_PeerIdentity id;
1458   struct MeshTunnel *t;
1459   struct MeshPeerInfo *pi;
1460   size_t size;
1461
1462   size = ntohs (message->size);
1463   if (size <
1464       sizeof (struct GNUNET_MESH_Unicast) +
1465       sizeof (struct GNUNET_MessageHeader))
1466   {
1467     GNUNET_break (0);
1468     return GNUNET_OK;
1469   }
1470   msg = (struct GNUNET_MESH_Unicast *) message;
1471   t = retrieve_tunnel (&msg->oid, ntohl (msg->tid));
1472   if (NULL == t)
1473   {
1474     /* TODO notify back: we don't know this tunnel */
1475     return GNUNET_OK;
1476   }
1477   pi = GNUNET_CONTAINER_multihashmap_get (t->peers,
1478                                           &msg->destination.hashPubKey);
1479   if (NULL == pi)
1480   {
1481     /* TODO maybe feedback, log to statistics */
1482     return GNUNET_OK;
1483   }
1484   if (pi->id == myid)
1485   {
1486     send_subscribed_clients ((struct GNUNET_MessageHeader *) &msg[1]);
1487     return GNUNET_OK;
1488   }
1489   GNUNET_PEER_resolve (get_first_hop (pi->path), &id);
1490   msg = GNUNET_malloc (size);
1491   memcpy (msg, message, size);
1492   GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
1493                                      GNUNET_TIME_UNIT_FOREVER_REL, &id, size,
1494                                      &send_core_data_raw, msg);
1495   return GNUNET_OK;
1496 }
1497
1498
1499 /**
1500  * Core handler for mesh network traffic going from the origin to all peers
1501  *
1502  * @param cls closure
1503  * @param message message
1504  * @param peer peer identity this notification is about
1505  * @param atsi performance data
1506  * @return GNUNET_OK to keep the connection open,
1507  *         GNUNET_SYSERR to close it (signal serious error)
1508  */
1509 static int
1510 handle_mesh_data_multicast (void *cls, const struct GNUNET_PeerIdentity *peer,
1511                             const struct GNUNET_MessageHeader *message,
1512                             const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1513 {
1514   struct GNUNET_MESH_Multicast *msg;
1515   struct GNUNET_PeerIdentity id;
1516   struct MeshTunnel *t;
1517   struct MeshDataDescriptor *info;
1518   GNUNET_PEER_Id *neighbors;
1519   size_t size;
1520   uint16_t i;
1521   uint16_t j;
1522
1523
1524   size = ntohs (message->size);
1525   if (size <
1526       sizeof (struct GNUNET_MESH_Multicast) +
1527       sizeof (struct GNUNET_MessageHeader))
1528   {
1529     GNUNET_break_op (0);
1530     return GNUNET_OK;
1531   }
1532   msg = (struct GNUNET_MESH_Multicast *) message;
1533   t = retrieve_tunnel (&msg->oid, ntohl (msg->tid));
1534
1535   if (NULL == t)
1536   {
1537     /* TODO notify that we dont know that tunnel */
1538     return GNUNET_OK;
1539   }
1540
1541   /* Transmit to locally interested clients */
1542   if (GNUNET_CONTAINER_multihashmap_contains (t->peers, &my_full_id.hashPubKey))
1543   {
1544     send_subscribed_clients ((struct GNUNET_MessageHeader *) &msg[1]);
1545   }
1546
1547   /* Retransmit to other peers */
1548   neighbors = GNUNET_malloc (sizeof (GNUNET_PEER_Id));
1549   neighbors[0] = 0;
1550   GNUNET_CONTAINER_multihashmap_iterate (t->peers, &iterate_collect_neighbors,
1551                                          &neighbors);
1552   if (!neighbors[0])
1553   {
1554     return GNUNET_OK;
1555   }
1556   size -= sizeof (struct GNUNET_MESH_Multicast);
1557   info = GNUNET_malloc (sizeof (struct MeshDataDescriptor) + size);
1558   info->origin = &t->id;
1559   info->copies = 0;
1560   for (i = 0; 0 != neighbors[i]; i++)
1561   {
1562     GNUNET_PEER_resolve (neighbors[i], &id);
1563     info->copies++;
1564     info->destination = neighbors[i];
1565     info->peer = GNUNET_CONTAINER_multihashmap_get (peers, &id.hashPubKey);
1566     GNUNET_assert (info->peer);
1567     for (j = 0; info->peer->core_transmit[j]; j++)
1568     {
1569       if (j == 9)
1570       {
1571         GNUNET_break (0);
1572         return GNUNET_OK;
1573       }
1574     }
1575     info->handler_n = j;
1576     info->peer->infos[j] = info;
1577     info->peer->core_transmit[j] =
1578         GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
1579                                            GNUNET_TIME_UNIT_FOREVER_REL, &id,
1580                                            ntohs (msg->header.size),
1581                                            &send_core_data_multicast, info);
1582   }
1583   return GNUNET_OK;
1584 }
1585
1586
1587 /**
1588  * Core handler for mesh network traffic
1589  *
1590  * @param cls closure
1591  * @param message message
1592  * @param peer peer identity this notification is about
1593  * @param atsi performance data
1594  * @return GNUNET_OK to keep the connection open,
1595  *         GNUNET_SYSERR to close it (signal serious error)
1596  */
1597 static int
1598 handle_mesh_data_to_orig (void *cls, const struct GNUNET_PeerIdentity *peer,
1599                           const struct GNUNET_MessageHeader *message,
1600                           const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1601 {
1602   struct GNUNET_MESH_ToOrigin *msg;
1603   struct GNUNET_PeerIdentity id;
1604   struct MeshTunnel *t;
1605   struct MeshPeerInfo *peer_info;
1606   size_t size;
1607
1608   size = ntohs (message->size);
1609   if (size <
1610       sizeof (struct GNUNET_MESH_ToOrigin) +
1611       sizeof (struct GNUNET_MessageHeader))
1612   {
1613     GNUNET_break_op (0);
1614     return GNUNET_OK;
1615   }
1616   msg = (struct GNUNET_MESH_ToOrigin *) message;
1617   t = retrieve_tunnel (&msg->oid, ntohl (msg->tid));
1618
1619   if (NULL == t)
1620   {
1621     /* TODO notify that we dont know this tunnel (whom)? */
1622     return GNUNET_OK;
1623   }
1624
1625   if (t->id.oid == myid)
1626   {
1627     if (NULL == t->client)
1628     {
1629       /* got data packet for ownerless tunnel */
1630       GNUNET_break_op (0);
1631       return GNUNET_OK;
1632     }
1633     GNUNET_SERVER_notification_context_unicast (nc, t->client->handle, message,
1634                                                 GNUNET_YES);
1635     return GNUNET_OK;
1636   }
1637   peer_info = get_peer_info (&msg->oid);
1638   if (NULL == peer_info)
1639   {
1640     /* unknown origin of tunnel */
1641     GNUNET_break (0);
1642     return GNUNET_OK;
1643   }
1644   GNUNET_PEER_resolve (get_first_hop (peer_info->path), &id);
1645   msg = GNUNET_malloc (size);
1646   memcpy (msg, message, size);
1647   GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
1648                                      GNUNET_TIME_UNIT_FOREVER_REL, &id, size,
1649                                      &send_core_data_raw, msg);
1650
1651   return GNUNET_OK;
1652 }
1653
1654
1655 /**
1656  * Core handler for path ACKs
1657  *
1658  * @param cls closure
1659  * @param message message
1660  * @param peer peer identity this notification is about
1661  * @param atsi performance data
1662  * @return GNUNET_OK to keep the connection open,
1663  *         GNUNET_SYSERR to close it (signal serious error)
1664  */
1665 static int
1666 handle_mesh_path_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
1667                       const struct GNUNET_MessageHeader *message,
1668                       const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1669 {
1670   struct GNUNET_MESH_PathACK *msg;
1671   struct GNUNET_PeerIdentity id;
1672   struct MeshTunnel *t;
1673   struct MeshPeerInfo *peer_info;
1674
1675   msg = (struct GNUNET_MESH_PathACK *) message;
1676   t = retrieve_tunnel (&msg->oid, msg->tid);
1677   if (NULL == t)
1678   {
1679     /* TODO notify that we don't know the tunnel */
1680     return GNUNET_OK;
1681   }
1682
1683   /* Message for us? */
1684   if (0 == memcmp (&msg->oid, &my_full_id, sizeof(struct GNUNET_PeerIdentity)))
1685   {
1686     struct GNUNET_MESH_PeerControl pc;
1687
1688     if (NULL == t->client)
1689     {
1690       GNUNET_break (0);
1691       return GNUNET_OK;
1692     }
1693     peer_info = get_peer_info (&msg->peer_id);
1694     if (NULL == peer_info)
1695     {
1696       GNUNET_break_op (0);
1697       return GNUNET_OK;
1698     }
1699     peer_info->state = MESH_PEER_READY;
1700     pc.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD);
1701     pc.header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
1702     pc.tunnel_id = htonl (t->local_tid);
1703     GNUNET_PEER_resolve (peer_info->id, &pc.peer);
1704     GNUNET_SERVER_notification_context_unicast (nc, t->client->handle,
1705                                                 &pc.header, GNUNET_NO);
1706     return GNUNET_OK;
1707   }
1708
1709   peer_info = get_peer_info (&msg->oid);
1710   if (NULL == peer_info)
1711   {
1712     /* If we know the tunnel, we should DEFINITELY know the peer */
1713     GNUNET_break (0);
1714     return GNUNET_OK;
1715   }
1716   GNUNET_PEER_resolve (get_first_hop (peer_info->path), &id);
1717   msg = GNUNET_malloc (sizeof (struct GNUNET_MESH_PathACK));
1718   memcpy (msg, message, sizeof (struct GNUNET_MESH_PathACK));
1719   GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
1720                                      GNUNET_TIME_UNIT_FOREVER_REL, &id,
1721                                      sizeof (struct GNUNET_MESH_PathACK),
1722                                      &send_core_data_raw, msg);
1723   return GNUNET_OK;
1724 }
1725
1726
1727 /**
1728  * Functions to handle messages from core
1729  */
1730 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
1731   {&handle_mesh_path_create, GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE, 0},
1732   {&handle_mesh_data_unicast, GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
1733   {&handle_mesh_data_multicast, GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
1734   {&handle_mesh_data_to_orig, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
1735   {&handle_mesh_path_ack, GNUNET_MESSAGE_TYPE_MESH_PATH_ACK,
1736    sizeof (struct GNUNET_MESH_PathACK)},
1737   {NULL, 0, 0}
1738 };
1739
1740
1741
1742 /******************************************************************************/
1743 /****************       MESH LOCAL HANDLER HELPERS      ***********************/
1744 /******************************************************************************/
1745
1746 /**
1747  * delete_tunnel_entry: iterator for deleting each tunnel that belongs to a
1748  * client when the client disconnects.
1749  * @param cls closure (client that is disconnecting)
1750  * @param key the hash of the local tunnel id (used to access the hashmap)
1751  * @param value the value stored at the key (tunnel to destroy)
1752  * @return GNUNET_OK on success
1753  */
1754 static int
1755 delete_tunnel_entry (void *cls, const GNUNET_HashCode * key, void *value)
1756 {
1757   int r;
1758
1759   r = destroy_tunnel ((struct MeshTunnel *) value);
1760   return r;
1761 }
1762
1763
1764 /**
1765  * deregister_app: iterator for removing each application registered by a client
1766  * @param cls closure
1767  * @param key the hash of the application id (used to access the hashmap)
1768  * @param value the value stored at the key (client)
1769  * @return GNUNET_OK on success
1770  */
1771 static int
1772 deregister_app (void *cls, const GNUNET_HashCode * key, void *value)
1773 {
1774   GNUNET_CONTAINER_multihashmap_remove(applications, key, value);
1775   return GNUNET_OK;
1776 }
1777
1778 #if LATER
1779 /**
1780  * notify_client_connection_failure: notify a client that the connection to the
1781  * requested remote peer is not possible (for instance, no route found)
1782  * Function called when the socket is ready to queue more data. "buf" will be
1783  * NULL and "size" zero if the socket was closed for writing in the meantime.
1784  *
1785  * @param cls closure
1786  * @param size number of bytes available in buf
1787  * @param buf where the callee should write the message
1788  * @return number of bytes written to buf
1789  */
1790 static size_t
1791 notify_client_connection_failure (void *cls, size_t size, void *buf)
1792 {
1793   int size_needed;
1794   struct MeshPeerInfo *peer_info;
1795   struct GNUNET_MESH_PeerControl *msg;
1796   struct GNUNET_PeerIdentity id;
1797
1798   if (0 == size && NULL == buf)
1799   {
1800     // TODO retry? cancel?
1801     return 0;
1802   }
1803
1804   size_needed = sizeof (struct GNUNET_MESH_PeerControl);
1805   peer_info = (struct MeshPeerInfo *) cls;
1806   msg = (struct GNUNET_MESH_PeerControl *) buf;
1807   msg->header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
1808   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DISCONNECTED);
1809 //     msg->tunnel_id = htonl(peer_info->t->tid);
1810   GNUNET_PEER_resolve (peer_info->id, &id);
1811   memcpy (&msg->peer, &id, sizeof (struct GNUNET_PeerIdentity));
1812
1813   return size_needed;
1814 }
1815 #endif
1816
1817
1818 /**
1819  * Send keepalive packets for a peer
1820  *
1821  * @param cls unused
1822  * @param tc unused
1823  */
1824 static void
1825 path_refresh (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1826 {
1827   struct MeshPeerInfo *peer_info = cls;
1828   struct GNUNET_PeerIdentity id;
1829
1830   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1831     return;
1832   GNUNET_PEER_resolve (get_first_hop (peer_info->path), &id);
1833   GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
1834                                      GNUNET_TIME_UNIT_FOREVER_REL, &id,
1835                                      sizeof (struct GNUNET_MESH_ManipulatePath)
1836                                      +
1837                                      (peer_info->path->length *
1838                                       sizeof (struct GNUNET_PeerIdentity)),
1839                                      &send_core_create_path_for_peer,
1840                                      peer_info);
1841   peer_info->path_refresh_task =
1842       GNUNET_SCHEDULER_add_delayed (REFRESH_PATH_TIME, &path_refresh,
1843                                     peer_info);
1844   return;
1845 }
1846
1847
1848 /**
1849  * Function to process paths received for a new peer addition. The recorded
1850  * paths form the initial tunnel, which can be optimized later.
1851  * Called on each result obtained for the DHT search.
1852  *
1853  * @param cls closure
1854  * @param exp when will this value expire
1855  * @param key key of the result
1856  * @param get_path NULL-terminated array of pointers
1857  *                 to the peers on reverse GET path (or NULL if not recorded)
1858  * @param put_path NULL-terminated array of pointers
1859  *                 to the peers on the PUT path (or NULL if not recorded)
1860  * @param type type of the result
1861  * @param size number of bytes in data
1862  * @param data pointer to the result data
1863  */
1864 static void
1865 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
1866                     const GNUNET_HashCode * key,
1867                     const struct GNUNET_PeerIdentity *const *get_path,
1868                     const struct GNUNET_PeerIdentity *const *put_path,
1869                     enum GNUNET_BLOCK_Type type, size_t size, const void *data)
1870 {
1871   struct MeshPeerInfo *peer_info = cls;
1872   struct MeshPath *p;
1873   struct GNUNET_PeerIdentity pi;
1874   int i;
1875
1876   if ((NULL == get_path || NULL == put_path) && NULL == peer_info->path)
1877   {
1878     // Find ourselves some alternate initial path to the destination: retry
1879     GNUNET_DHT_get_stop (peer_info->dhtget);
1880     GNUNET_PEER_resolve (peer_info->id, &pi);
1881     peer_info->dhtget = GNUNET_DHT_get_start (dht_handle,       /* handle */
1882                                               GNUNET_TIME_UNIT_FOREVER_REL,
1883                                               GNUNET_BLOCK_TYPE_TEST, /* type */
1884                                               &pi.hashPubKey, /*key to search */
1885                                               4,       /* replication level */
1886                                               GNUNET_DHT_RO_RECORD_ROUTE,
1887                                               NULL, /* bloom filter */
1888                                               0,        /* mutator */
1889                                               NULL,     /* xquery */
1890                                               0,        /* xquery bits */
1891                                               dht_get_id_handler,
1892                                               (void *) peer_info);
1893   }
1894
1895   p = GNUNET_malloc (sizeof (struct MeshPath));
1896   for (i = 0; get_path[i] != NULL; i++) ;
1897   for (i--; i >= 0; i--)
1898   {
1899     p->peers =
1900         GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * (p->length + 1));
1901     p->peers[p->length] = GNUNET_PEER_intern (get_path[i]);
1902     p->length++;
1903   }
1904   for (i = 0; put_path[i] != NULL; i++) ;
1905   for (i--; i >= 0; i--)
1906   {
1907     p->peers =
1908         GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * (p->length + 1));
1909     p->peers[p->length] = GNUNET_PEER_intern (put_path[i]);
1910     p->length++;
1911   }
1912   add_path_to_peer (peer_info, p);
1913   GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
1914                                      GNUNET_TIME_UNIT_FOREVER_REL, get_path[1],
1915                                      sizeof (struct GNUNET_MESH_ManipulatePath)
1916                                      +
1917                                      (p->length *
1918                                       sizeof (struct GNUNET_PeerIdentity)),
1919                                      &send_core_create_path_for_peer,
1920                                      peer_info);
1921   if (0 == peer_info->path_refresh_task)
1922   {
1923     peer_info->path_refresh_task =
1924         GNUNET_SCHEDULER_add_delayed (REFRESH_PATH_TIME, &path_refresh,
1925                                       peer_info);
1926   }
1927   return;
1928 }
1929
1930
1931 /**
1932  * Function to process paths received for a new peer addition. The recorded
1933  * paths form the initial tunnel, which can be optimized later.
1934  * Called on each result obtained for the DHT search.
1935  *
1936  * @param cls closure
1937  * @param exp when will this value expire
1938  * @param key key of the result
1939  * @param get_path NULL-terminated array of pointers
1940  *                 to the peers on reverse GET path (or NULL if not recorded)
1941  * @param put_path NULL-terminated array of pointers
1942  *                 to the peers on the PUT path (or NULL if not recorded)
1943  * @param type type of the result
1944  * @param size number of bytes in data
1945  * @param data pointer to the result data
1946  */
1947 static void
1948 dht_get_type_handler (void *cls, struct GNUNET_TIME_Absolute exp,
1949                       const GNUNET_HashCode * key,
1950                       const struct GNUNET_PeerIdentity *const *get_path,
1951                       const struct GNUNET_PeerIdentity *const *put_path,
1952                       enum GNUNET_BLOCK_Type type, size_t size,
1953                       const void *data)
1954 {
1955   const struct GNUNET_PeerIdentity *pi = data;
1956   struct MeshTunnel *t = cls;
1957   struct MeshPeerInfo *peer_info;
1958   struct MeshPath *p;
1959   int i;
1960
1961
1962   if (size != sizeof (struct GNUNET_PeerIdentity))
1963   {
1964     GNUNET_break_op (0);
1965     return;
1966   }
1967   peer_info = get_peer_info (pi);
1968   GNUNET_CONTAINER_multihashmap_put (t->peers, &pi->hashPubKey, peer_info,
1969                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1970   if ((NULL == get_path || NULL == put_path) && NULL == peer_info->path)
1971   {
1972     /* we don't have a route to the peer, let's try a direct lookup */
1973     if (NULL == peer_info->dhtget)
1974     {
1975       peer_info->dhtget = GNUNET_DHT_get_start (dht_handle, /* handle */
1976                                                 GNUNET_TIME_UNIT_FOREVER_REL,
1977                                                 GNUNET_BLOCK_TYPE_TEST,
1978                                                 &pi->hashPubKey,
1979                                                 10U,  /* replication level */
1980                                                 GNUNET_DHT_RO_RECORD_ROUTE,
1981                                                 NULL,   /* bloom filter */
1982                                                 0,      /* mutator */
1983                                                 NULL,   /* xquery */
1984                                                 0,      /* xquery bits */
1985                                                 dht_get_id_handler, peer_info);
1986     }
1987   }
1988   /* TODO refactor */
1989   p = GNUNET_malloc (sizeof (struct MeshPath));
1990   for (i = 0; get_path[i] != NULL; i++) ;
1991   for (i--; i >= 0; i--)
1992   {
1993     p->peers =
1994         GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * (p->length + 1));
1995     p->peers[p->length] = GNUNET_PEER_intern (get_path[i]);
1996     p->length++;
1997   }
1998   for (i = 0; put_path[i] != NULL; i++) ;
1999   for (i--; i >= 0; i--)
2000   {
2001     p->peers =
2002         GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * (p->length + 1));
2003     p->peers[p->length] = GNUNET_PEER_intern (put_path[i]);
2004     p->length++;
2005   }
2006   add_path_to_peer (peer_info, p);
2007   GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
2008                                      GNUNET_TIME_UNIT_FOREVER_REL, get_path[1],
2009                                      sizeof (struct GNUNET_MESH_ManipulatePath)
2010                                      +
2011                                      (p->length *
2012                                       sizeof (struct GNUNET_PeerIdentity)),
2013                                      &send_core_create_path_for_peer,
2014                                      peer_info);
2015
2016 }
2017
2018 /******************************************************************************/
2019 /*********************       MESH LOCAL HANDLES      **************************/
2020 /******************************************************************************/
2021
2022
2023 /**
2024  * Handler for client disconnection
2025  *
2026  * @param cls closure
2027  * @param client identification of the client; NULL
2028  *        for the last call when the server is destroyed
2029  */
2030 static void
2031 handle_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
2032 {
2033   struct MeshClient *c;
2034   struct MeshClient *next;
2035
2036   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: client disconnected\n");
2037   c = clients;
2038   while (NULL != c)
2039   {
2040     if (c->handle != client)
2041     {
2042       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    ... searching\n");
2043       c = c->next;
2044       continue;
2045     }
2046     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: matching client found\n");
2047     if (NULL != c->tunnels)
2048     {
2049       GNUNET_CONTAINER_multihashmap_iterate (c->tunnels,
2050                                              &delete_tunnel_entry,
2051                                              c);
2052       GNUNET_CONTAINER_multihashmap_destroy (c->tunnels);
2053     }
2054
2055     /* deregister clients applications */
2056     if (NULL != c->apps)
2057     {
2058       GNUNET_CONTAINER_multihashmap_iterate(c->apps, &deregister_app, NULL);
2059       GNUNET_CONTAINER_multihashmap_destroy(c->apps);
2060     }
2061     if (0 == GNUNET_CONTAINER_multihashmap_size(applications))
2062     {
2063       GNUNET_SCHEDULER_cancel (announce_applications_task);
2064     }
2065     if (NULL != c->types)
2066       GNUNET_CONTAINER_multihashmap_destroy(c->types);
2067     GNUNET_CONTAINER_DLL_remove (clients, clients_tail, c);
2068     next = c->next;
2069     GNUNET_free (c);
2070     c = next;
2071   }
2072
2073   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:    done!\n");
2074   return;
2075 }
2076
2077
2078 /**
2079  * Handler for new clients
2080  *
2081  * @param cls closure
2082  * @param client identification of the client
2083  * @param message the actual message, which includes messages the client wants
2084  */
2085 static void
2086 handle_local_new_client (void *cls, struct GNUNET_SERVER_Client *client,
2087                          const struct GNUNET_MessageHeader *message)
2088 {
2089   struct GNUNET_MESH_ClientConnect *cc_msg;
2090   struct MeshClient *c;
2091   GNUNET_MESH_ApplicationType *a;
2092   unsigned int size;
2093   uint16_t ntypes;
2094   uint16_t *t;
2095   uint16_t napps;
2096   uint16_t i;
2097
2098   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: new client connected\n");
2099   /* Check data sanity */
2100   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_ClientConnect);
2101   cc_msg = (struct GNUNET_MESH_ClientConnect *) message;
2102   ntypes = ntohs (cc_msg->types);
2103   napps = ntohs (cc_msg->applications);
2104   if (size !=
2105       ntypes * sizeof (uint16_t) + napps * sizeof (GNUNET_MESH_ApplicationType))
2106   {
2107     GNUNET_break (0);
2108     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2109     return;
2110   }
2111
2112   /* Create new client structure */
2113   c = GNUNET_malloc (sizeof (struct MeshClient));
2114   c->handle = client;
2115   a = (GNUNET_MESH_ApplicationType *) &cc_msg[1];
2116   if (napps > 0)
2117   {
2118     GNUNET_MESH_ApplicationType at;
2119     GNUNET_HashCode hc;
2120
2121     c->apps = GNUNET_CONTAINER_multihashmap_create(napps);
2122     for (i = 0; i < napps; i++)
2123     {
2124       at = ntohl(a[i]);
2125       GNUNET_CRYPTO_hash(&at, sizeof(at), &hc);
2126       /* store in clients hashmap */
2127       GNUNET_CONTAINER_multihashmap_put(
2128           c->apps,
2129           &hc,
2130           c,
2131           GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2132       /* store in global hashmap, for announcements */
2133       GNUNET_CONTAINER_multihashmap_put(
2134           applications,
2135           &hc,
2136           c,
2137           GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2138     }
2139     if (GNUNET_SCHEDULER_NO_TASK == announce_applications_task)
2140       announce_applications_task = GNUNET_SCHEDULER_add_now (
2141           &announce_applications, NULL);
2142
2143   }
2144   if (ntypes > 0)
2145   {
2146     uint16_t u16;
2147     GNUNET_HashCode hc;
2148
2149     t = (uint16_t *) &a[napps];
2150     c->types = GNUNET_CONTAINER_multihashmap_create(ntypes);
2151     for (i =0; i < ntypes; i++)
2152     {
2153       u16 = ntohs(t[i]);
2154       GNUNET_CRYPTO_hash(&u16, sizeof(u16), &hc);
2155       /* store in clients hashmap */
2156       GNUNET_CONTAINER_multihashmap_put(
2157           c->types,
2158           &hc,
2159           c,
2160           GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2161       /* store in global hashmap */
2162       GNUNET_CONTAINER_multihashmap_put(
2163           types,
2164           &hc,
2165           c,
2166           GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2167     }
2168   }
2169   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2170               "MESH:  client has %u+%u subscriptions\n", napps, ntypes);
2171
2172   GNUNET_CONTAINER_DLL_insert (clients, clients_tail, c);
2173   c->tunnels = GNUNET_CONTAINER_multihashmap_create (32);
2174   GNUNET_SERVER_notification_context_add (nc, client);
2175
2176   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2177
2178 }
2179
2180
2181 /**
2182  * Handler for requests of new tunnels
2183  *
2184  * @param cls closure
2185  * @param client identification of the client
2186  * @param message the actual message
2187  */
2188 static void
2189 handle_local_tunnel_create (void *cls, struct GNUNET_SERVER_Client *client,
2190                             const struct GNUNET_MessageHeader *message)
2191 {
2192   struct GNUNET_MESH_TunnelMessage *t_msg;
2193   struct MeshTunnel *t;
2194   struct MeshClient *c;
2195   GNUNET_HashCode hash;
2196
2197   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: new tunnel requested\n");
2198
2199   /* Sanity check for client registration */
2200   if (NULL == (c = retrieve_client (client)))
2201   {
2202     GNUNET_break (0);
2203     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2204     return;
2205   }
2206
2207   /* Message sanity check */
2208   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
2209   {
2210     GNUNET_break (0);
2211     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2212     return;
2213   }
2214
2215   t_msg = (struct GNUNET_MESH_TunnelMessage *) message;
2216   /* Sanity check for tunnel numbering */
2217   if (0 == (ntohl (t_msg->tunnel_id) & GNUNET_MESH_LOCAL_TUNNEL_ID_CLI))
2218   {
2219     GNUNET_break (0);
2220     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2221     return;
2222   }
2223   /* Sanity check for duplicate tunnel IDs */
2224   if (NULL != retrieve_tunnel_by_local_id (c, ntohl (t_msg->tunnel_id)))
2225   {
2226     GNUNET_break (0);
2227     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2228     return;
2229   }
2230
2231   t = GNUNET_malloc (sizeof (struct MeshTunnel));
2232   while (NULL != retrieve_tunnel_by_pi (myid, next_tid))
2233     next_tid = (next_tid + 1) & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
2234   t->id.tid = next_tid++;
2235   t->id.oid = myid;
2236   t->local_tid = ntohl (t_msg->tunnel_id);
2237   t->client = c;
2238   t->peers = GNUNET_CONTAINER_multihashmap_create (32);
2239
2240   GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
2241   if (GNUNET_OK !=
2242       GNUNET_CONTAINER_multihashmap_put (c->tunnels, &hash, t,
2243                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
2244   {
2245     GNUNET_break (0);
2246     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2247     return;
2248   }
2249
2250   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
2251   if (GNUNET_OK !=
2252       GNUNET_CONTAINER_multihashmap_put (tunnels, &hash, t,
2253                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
2254   {
2255     GNUNET_break (0);
2256     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2257     return;
2258   }
2259
2260   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2261   return;
2262 }
2263
2264
2265 /**
2266  * Handler for requests of deleting tunnels
2267  *
2268  * @param cls closure
2269  * @param client identification of the client
2270  * @param message the actual message
2271  */
2272 static void
2273 handle_local_tunnel_destroy (void *cls, struct GNUNET_SERVER_Client *client,
2274                              const struct GNUNET_MessageHeader *message)
2275 {
2276   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
2277   struct MeshClient *c;
2278   struct MeshTunnel *t;
2279   MESH_TunnelNumber tid;
2280   GNUNET_HashCode hash;
2281
2282   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: destroying tunnel\n");
2283
2284   /* Sanity check for client registration */
2285   if (NULL == (c = retrieve_client (client)))
2286   {
2287     GNUNET_break (0);
2288     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2289     return;
2290   }
2291   /* Message sanity check */
2292   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
2293   {
2294     GNUNET_break (0);
2295     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2296     return;
2297   }
2298
2299   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
2300
2301   /* Retrieve tunnel */
2302   tid = ntohl (tunnel_msg->tunnel_id);
2303
2304   /* Remove from local id hashmap */
2305   GNUNET_CRYPTO_hash (&tid, sizeof (MESH_TunnelNumber), &hash);
2306   t = GNUNET_CONTAINER_multihashmap_get (c->tunnels, &hash);
2307   GNUNET_CONTAINER_multihashmap_remove (c->tunnels, &hash, t);
2308
2309   /* Remove from global id hashmap */
2310   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
2311   GNUNET_CONTAINER_multihashmap_remove (tunnels, &hash, t);
2312
2313 //     notify_tunnel_destroy(t);
2314   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2315   return;
2316 }
2317
2318
2319 /**
2320  * Handler for connection requests to new peers
2321  *
2322  * @param cls closure
2323  * @param client identification of the client
2324  * @param message the actual message (PeerControl)
2325  */
2326 static void
2327 handle_local_connect_add (void *cls, struct GNUNET_SERVER_Client *client,
2328                           const struct GNUNET_MessageHeader *message)
2329 {
2330   struct GNUNET_MESH_PeerControl *peer_msg;
2331   struct MeshClient *c;
2332   struct MeshTunnel *t;
2333   MESH_TunnelNumber tid;
2334   struct MeshPeerInfo *peer_info;
2335
2336
2337   /* Sanity check for client registration */
2338   if (NULL == (c = retrieve_client (client)))
2339   {
2340     GNUNET_break (0);
2341     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2342     return;
2343   }
2344
2345   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
2346   /* Sanity check for message size */
2347   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
2348   {
2349     GNUNET_break (0);
2350     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2351     return;
2352   }
2353
2354   /* Tunnel exists? */
2355   tid = ntohl (peer_msg->tunnel_id);
2356   t = retrieve_tunnel_by_local_id (c, tid);
2357   if (NULL == t)
2358   {
2359     GNUNET_break (0);
2360     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2361     return;
2362   }
2363
2364   /* Does client own tunnel? */
2365   if (t->client->handle != client)
2366   {
2367     GNUNET_break (0);
2368     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2369     return;
2370   }
2371
2372   t->peers_total++;
2373   peer_info = get_peer_info (&peer_msg->peer);
2374
2375   /* Start DHT search if needed */
2376   if (MESH_PEER_READY != peer_info->state && NULL == peer_info->dhtget)
2377   {
2378     peer_info->dhtget = GNUNET_DHT_get_start (dht_handle, GNUNET_TIME_UNIT_FOREVER_REL,
2379                                               GNUNET_BLOCK_TYPE_TEST,
2380                                               &peer_msg->peer.hashPubKey, 4,   /* replication level */
2381                                               GNUNET_DHT_RO_RECORD_ROUTE, NULL, /* bloom filter */
2382                                               0,        /* mutator */
2383                                               NULL,     /* xquery */
2384                                               0,        /* xquery bits */
2385                                               dht_get_id_handler,
2386                                               (void *) peer_info);
2387   }
2388
2389   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2390   return;
2391 }
2392
2393
2394 /**
2395  * Handler for disconnection requests of peers in a tunnel
2396  *
2397  * @param cls closure
2398  * @param client identification of the client
2399  * @param message the actual message (PeerControl)
2400  */
2401 static void
2402 handle_local_connect_del (void *cls, struct GNUNET_SERVER_Client *client,
2403                           const struct GNUNET_MessageHeader *message)
2404 {
2405   struct GNUNET_MESH_PeerControl *peer_msg;
2406   struct MeshClient *c;
2407   struct MeshTunnel *t;
2408   MESH_TunnelNumber tid;
2409
2410   /* Sanity check for client registration */
2411   if (NULL == (c = retrieve_client (client)))
2412   {
2413     GNUNET_break (0);
2414     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2415     return;
2416   }
2417   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
2418   /* Sanity check for message size */
2419   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
2420   {
2421     GNUNET_break (0);
2422     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2423     return;
2424   }
2425
2426   /* Tunnel exists? */
2427   tid = ntohl (peer_msg->tunnel_id);
2428   t = retrieve_tunnel_by_local_id (c, tid);
2429   if (NULL == t)
2430   {
2431     GNUNET_break (0);
2432     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2433     return;
2434   }
2435
2436   /* Does client own tunnel? */
2437   if (t->client->handle != client)
2438   {
2439     GNUNET_break (0);
2440     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2441     return;
2442   }
2443
2444   /* Ok, delete peer from tunnel */
2445   GNUNET_CONTAINER_multihashmap_remove_all (t->peers,
2446                                             &peer_msg->peer.hashPubKey);
2447
2448   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2449   return;
2450 }
2451
2452
2453 /**
2454  * Handler for connection requests to new peers by type
2455  *
2456  * @param cls closure
2457  * @param client identification of the client
2458  * @param message the actual message (ConnectPeerByType)
2459  */
2460 static void
2461 handle_local_connect_by_type (void *cls, struct GNUNET_SERVER_Client *client,
2462                               const struct GNUNET_MessageHeader *message)
2463 {
2464   struct GNUNET_MESH_ConnectPeerByType *connect_msg;
2465   struct MeshClient *c;
2466   struct MeshTunnel *t;
2467   GNUNET_HashCode hash;
2468   GNUNET_MESH_ApplicationType type;
2469   MESH_TunnelNumber tid;
2470
2471   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: got connect by type request\n");
2472   /* Sanity check for client registration */
2473   if (NULL == (c = retrieve_client (client)))
2474   {
2475     GNUNET_break (0);
2476     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2477     return;
2478   }
2479
2480   connect_msg = (struct GNUNET_MESH_ConnectPeerByType *) message;
2481   /* Sanity check for message size */
2482   if (sizeof (struct GNUNET_MESH_ConnectPeerByType) !=
2483       ntohs (connect_msg->header.size))
2484   {
2485     GNUNET_break (0);
2486     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2487     return;
2488   }
2489
2490   /* Tunnel exists? */
2491   tid = ntohl (connect_msg->tunnel_id);
2492   t = retrieve_tunnel_by_local_id (c, tid);
2493   if (NULL == t)
2494   {
2495     GNUNET_break (0);
2496     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2497     return;
2498   }
2499
2500   /* Does client own tunnel? */
2501   if (t->client->handle != client)
2502   {
2503     GNUNET_break (0);
2504     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2505     return;
2506   }
2507
2508   /* Do WE have the service? */
2509   type = ntohl (connect_msg->type);
2510   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  type requested: %u\n", type);
2511   GNUNET_CRYPTO_hash (&type, sizeof (GNUNET_MESH_ApplicationType), &hash);
2512   if (GNUNET_CONTAINER_multihashmap_contains(applications, &hash) == GNUNET_YES)
2513   {
2514     /* Yes! Fast forward, add ourselves to the tunnel and send the
2515       * good news to the client
2516       */
2517     struct GNUNET_MESH_PeerControl pc;
2518
2519     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  available locally\n");
2520     pc.peer = my_full_id;
2521     GNUNET_CONTAINER_multihashmap_put (t->peers, &pc.peer.hashPubKey,
2522                                         get_peer_info (&pc.peer),
2523                                         GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2524     pc.header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
2525     pc.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD);
2526     pc.tunnel_id = htonl (t->local_tid);
2527     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  notifying client\n");
2528     GNUNET_SERVER_notification_context_unicast (nc,   /* context */
2529                                                 client,       /* dest */
2530                                                 &pc.header,   /* msg */
2531                                                 GNUNET_NO);   /* can drop? */
2532     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:  Done\n");
2533     GNUNET_SERVER_receive_done (client, GNUNET_OK);
2534     return;
2535   }
2536   /* Ok, lets find a peer offering the service */
2537   if (c->dht_get_type)
2538   {
2539     GNUNET_DHT_get_stop (c->dht_get_type);
2540   }
2541   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2542               "MESH:  looking in DHT for %s\n",
2543               GNUNET_h2s_full(&hash));
2544   c->dht_get_type =
2545       GNUNET_DHT_get_start (dht_handle,
2546                             GNUNET_TIME_UNIT_FOREVER_REL,
2547                             GNUNET_BLOCK_TYPE_TEST,
2548                             &hash,
2549                             10U,
2550                             GNUNET_DHT_RO_RECORD_ROUTE,
2551                             NULL,
2552                             0,
2553                             NULL,
2554                             0,
2555                             &dht_get_type_handler,
2556                             t);
2557
2558   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2559   return;
2560 }
2561
2562
2563 /**
2564  * Handler for client traffic directed to one peer
2565  *
2566  * @param cls closure
2567  * @param client identification of the client
2568  * @param message the actual message
2569  */
2570 static void
2571 handle_local_unicast (void *cls, struct GNUNET_SERVER_Client *client,
2572                       const struct GNUNET_MessageHeader *message)
2573 {
2574   struct MeshClient *c;
2575   struct MeshTunnel *t;
2576   struct MeshPeerInfo *pi;
2577   struct GNUNET_MESH_Unicast *data_msg;
2578   struct GNUNET_PeerIdentity next_hop;
2579   struct MeshDataDescriptor *info;
2580   MESH_TunnelNumber tid;
2581   size_t data_size;
2582
2583   /* Sanity check for client registration */
2584   if (NULL == (c = retrieve_client (client)))
2585   {
2586     GNUNET_break (0);
2587     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2588     return;
2589   }
2590   data_msg = (struct GNUNET_MESH_Unicast *) message;
2591   /* Sanity check for message size */
2592   if (sizeof (struct GNUNET_MESH_Unicast) +
2593       sizeof (struct GNUNET_MessageHeader) > ntohs (data_msg->header.size))
2594   {
2595     GNUNET_break (0);
2596     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2597     return;
2598   }
2599
2600   /* Tunnel exists? */
2601   tid = ntohl (data_msg->tid);
2602   t = retrieve_tunnel_by_local_id (c, tid);
2603   if (NULL == t)
2604   {
2605     GNUNET_break (0);
2606     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2607     return;
2608   }
2609
2610   /*  Is it a local tunnel? Then, does client own the tunnel? */
2611   if (t->client->handle != NULL && t->client->handle != client)
2612   {
2613     GNUNET_break (0);
2614     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2615     return;
2616   }
2617
2618   pi = GNUNET_CONTAINER_multihashmap_get (t->peers,
2619                                           &data_msg->destination.hashPubKey);
2620   /* Is the selected peer in the tunnel? */
2621   if (NULL == pi)
2622   {
2623     GNUNET_break (0);
2624     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2625     return;
2626   }
2627   if (pi->id == myid)
2628   {
2629     struct GNUNET_MESH_Unicast copy;
2630
2631     /* Work around const limitation */
2632     memcpy (&copy, data_msg, sizeof (struct GNUNET_MESH_Unicast));
2633     copy.oid = my_full_id;
2634     copy.tid = htonl(t->id.tid);
2635     handle_mesh_data_unicast (NULL, &my_full_id, &copy.header, NULL);
2636     return;
2637   }
2638   GNUNET_PEER_resolve (get_first_hop (pi->path), &next_hop);
2639   data_size = ntohs (message->size) - sizeof (struct GNUNET_MESH_Unicast);
2640   info = GNUNET_malloc (sizeof (struct MeshDataDescriptor) + data_size);
2641   memcpy (&info[1], &data_msg[1], data_size);
2642   info->destination = pi->id;
2643   info->origin = &t->id;
2644   info->size = data_size;
2645   info->client = client;
2646   GNUNET_CORE_notify_transmit_ready (core_handle, 0, 0,
2647                                      GNUNET_TIME_UNIT_FOREVER_REL, &next_hop,
2648                                      /* FIXME re-check types */
2649                                      data_size +
2650                                      sizeof (struct GNUNET_MESH_Unicast),
2651                                      &send_core_data_unicast, info);
2652   return;
2653 }
2654
2655 /**
2656  * Handler for client traffic directed to all peers in a tunnel
2657  *
2658  * @param cls closure
2659  * @param client identification of the client
2660  * @param message the actual message
2661  */
2662 static void
2663 handle_local_multicast (void *cls, struct GNUNET_SERVER_Client *client,
2664                         const struct GNUNET_MessageHeader *message)
2665 {
2666   struct MeshClient *c;
2667   struct MeshTunnel *t;
2668   struct GNUNET_MESH_Multicast *data_msg;
2669   MESH_TunnelNumber tid;
2670
2671   /* Sanity check for client registration */
2672   if (NULL == (c = retrieve_client (client)))
2673   {
2674     GNUNET_break (0);
2675     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2676     return;
2677   }
2678   data_msg = (struct GNUNET_MESH_Multicast *) message;
2679   /* Sanity check for message size */
2680   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (data_msg->header.size))
2681   {
2682     GNUNET_break (0);
2683     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2684     return;
2685   }
2686
2687   /* Tunnel exists? */
2688   tid = ntohl (data_msg->tid);
2689   t = retrieve_tunnel_by_local_id (c, tid);
2690   if (NULL == t)
2691   {
2692     GNUNET_break (0);
2693     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2694     return;
2695   }
2696
2697   /* Does client own tunnel? */
2698   if (t->client->handle != client)
2699   {
2700     GNUNET_break (0);
2701     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2702     return;
2703   }
2704
2705   /*  TODO */
2706
2707   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2708   return;
2709 }
2710
2711 /**
2712  * Functions to handle messages from clients
2713  */
2714 static struct GNUNET_SERVER_MessageHandler plugin_handlers[] = {
2715   {&handle_local_new_client, NULL, GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT, 0},
2716   {&handle_local_tunnel_create, NULL,
2717    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE,
2718    sizeof (struct GNUNET_MESH_TunnelMessage)},
2719   {&handle_local_tunnel_destroy, NULL,
2720    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY,
2721    sizeof (struct GNUNET_MESH_TunnelMessage)},
2722   {&handle_local_connect_add, NULL,
2723    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD,
2724    sizeof (struct GNUNET_MESH_PeerControl)},
2725   {&handle_local_connect_del, NULL,
2726    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL,
2727    sizeof (struct GNUNET_MESH_PeerControl)},
2728   {&handle_local_connect_by_type, NULL,
2729    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_TYPE,
2730    sizeof (struct GNUNET_MESH_ConnectPeerByType)},
2731   {&handle_local_unicast, NULL,
2732    GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
2733   {&handle_local_unicast, NULL,
2734    GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
2735   {&handle_local_multicast, NULL,
2736    GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
2737   {NULL, NULL, 0, 0}
2738 };
2739
2740
2741 /**
2742  * To be called on core init/fail.
2743  *
2744  * @param cls service closure
2745  * @param server handle to the server for this service
2746  * @param identity the public identity of this peer
2747  * @param publicKey the public key of this peer
2748  */
2749 static void
2750 core_init (void *cls, struct GNUNET_CORE_Handle *server,
2751            const struct GNUNET_PeerIdentity *identity,
2752            const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
2753 {
2754   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Core init\n");
2755   core_handle = server;
2756   my_full_id = *identity;
2757   myid = GNUNET_PEER_intern (identity);
2758   announce_id_task = GNUNET_SCHEDULER_add_now (&announce_id, cls);
2759   return;
2760 }
2761
2762 /**
2763  * Method called whenever a given peer connects.
2764  *
2765  * @param cls closure
2766  * @param peer peer identity this notification is about
2767  * @param atsi performance data for the connection
2768  */
2769 static void
2770 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
2771               const struct GNUNET_TRANSPORT_ATS_Information *atsi)
2772 {
2773 //     GNUNET_PEER_Id              pid;
2774   struct MeshPeerInfo *peer_info;
2775   struct MeshPath *path;
2776
2777   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Peer connected\n");
2778   peer_info = get_peer_info (peer);
2779   if (myid == peer_info->id)
2780   {
2781     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:      (self)\n");
2782   }
2783   path = GNUNET_malloc (sizeof (struct MeshPath));
2784   path->length = 2;
2785   path->peers = GNUNET_malloc (sizeof (GNUNET_PEER_Id) * 2);
2786   path->peers[0] = myid;
2787   path->peers[1] = peer_info->id;
2788   add_path_to_peer (peer_info, path);
2789   return;
2790 }
2791
2792 /**
2793  * Method called whenever a peer disconnects.
2794  *
2795  * @param cls closure
2796  * @param peer peer identity this notification is about
2797  */
2798 static void
2799 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
2800 {
2801   struct MeshPeerInfo *pi;
2802   unsigned int i;
2803
2804   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: Peer disconnected\n");
2805   pi = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
2806   if (!pi)
2807   {
2808     GNUNET_break (0);
2809     return;
2810   }
2811   for (i = 0; i < CORE_QUEUE_SIZE; i++)
2812   {
2813     if (pi->core_transmit[i])
2814     {
2815       GNUNET_CORE_notify_transmit_ready_cancel (pi->core_transmit[i]);
2816       /* TODO: notify that tranmission has failed */
2817       GNUNET_free (pi->infos[i]);
2818     }
2819   }
2820   if (myid == pi->id)
2821   {
2822     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH:      (self)\n");
2823   }
2824   return;
2825 }
2826
2827
2828 /******************************************************************************/
2829 /************************      MAIN FUNCTIONS      ****************************/
2830 /******************************************************************************/
2831
2832 /**
2833  * Task run during shutdown.
2834  *
2835  * @param cls unused
2836  * @param tc unused
2837  */
2838 static void
2839 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2840 {
2841   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: shutting down\n");
2842   if (core_handle != NULL)
2843   {
2844     GNUNET_CORE_disconnect (core_handle);
2845     core_handle = NULL;
2846   }
2847   if (dht_handle != NULL)
2848   {
2849     GNUNET_DHT_disconnect (dht_handle);
2850     dht_handle = NULL;
2851   }
2852   if (nc != NULL)
2853   {
2854     GNUNET_SERVER_notification_context_destroy (nc);
2855     nc = NULL;
2856   }
2857   if (0 != announce_id_task)
2858   {
2859     GNUNET_SCHEDULER_cancel (announce_id_task);
2860     announce_id_task = 0;
2861   }
2862   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: shut down\n");
2863 }
2864
2865 /**
2866  * Process mesh requests.
2867  *
2868  * @param cls closure
2869  * @param server the initialized server
2870  * @param c configuration to use
2871  */
2872 static void
2873 run (void *cls, struct GNUNET_SERVER_Handle *server,
2874      const struct GNUNET_CONFIGURATION_Handle *c)
2875 {
2876   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: starting to run\n");
2877   GNUNET_SERVER_add_handlers (server, plugin_handlers);
2878   GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
2879   server_handle = server;
2880   core_handle = GNUNET_CORE_connect (c, /* Main configuration */
2881                                      CORE_QUEUE_SIZE,   /* queue size */
2882                                      NULL,      /* Closure passed to MESH functions */
2883                                      &core_init,        /* Call core_init once connected */
2884                                      &core_connect,     /* Handle connects */
2885                                      &core_disconnect,  /* remove peers on disconnects */
2886                                      NULL,      /* Do we care about "status" updates? */
2887                                      NULL,      /* Don't notify about all incoming messages */
2888                                      GNUNET_NO, /* For header only in notification */
2889                                      NULL,      /* Don't notify about all outbound messages */
2890                                      GNUNET_NO, /* For header-only out notification */
2891                                      core_handlers);    /* Register these handlers */
2892   if (core_handle == NULL)
2893   {
2894     GNUNET_break (0);
2895   }
2896   dht_handle = GNUNET_DHT_connect (c, 64);
2897   if (dht_handle == NULL)
2898   {
2899     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Error connecting to DHT.\
2900                    Running without DHT has a severe\
2901                    impact in MESH capabilities.\n\
2902                    Plase check your configuretion and enable DHT.\n");
2903     GNUNET_break (0);
2904   }
2905
2906   next_tid = 0;
2907
2908   tunnels = GNUNET_CONTAINER_multihashmap_create (32);
2909   peers = GNUNET_CONTAINER_multihashmap_create (32);
2910   applications = GNUNET_CONTAINER_multihashmap_create (32);
2911   types = GNUNET_CONTAINER_multihashmap_create (32);
2912   nc = GNUNET_SERVER_notification_context_create (server_handle,
2913                                                   LOCAL_QUEUE_SIZE);
2914   clients = NULL;
2915   clients_tail = NULL;
2916
2917   announce_applications_task = 0;
2918
2919   /* Scheduled the task to clean up when shutdown is called */
2920   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
2921                                 NULL);
2922
2923   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: end of run()\n");
2924 }
2925
2926 /**
2927  * The main function for the mesh service.
2928  *
2929  * @param argc number of arguments from the command line
2930  * @param argv command line arguments
2931  * @return 0 ok, 1 on error
2932  */
2933 int
2934 main (int argc, char *const *argv)
2935 {
2936   int ret;
2937
2938   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: main()\n");
2939   ret =
2940       (GNUNET_OK ==
2941        GNUNET_SERVICE_run (argc, argv, "mesh", GNUNET_SERVICE_OPTION_NONE, &run,
2942                            NULL)) ? 0 : 1;
2943   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MESH: main() END\n");
2944   return ret;
2945 }