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