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