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