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