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