- reuse old results for looping states in the dregex
[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 /**
4125  * Iterator over hash map entries.
4126  *
4127  * @param cls closure
4128  * @param key current key code
4129  * @param value value in the hash map
4130  * @return GNUNET_YES if we should continue to
4131  *         iterate,
4132  *         GNUNET_NO if not.
4133  */
4134 static int
4135 regex_result_iterator (void *cls,
4136                        const struct GNUNET_HashCode * key,
4137                        void *value)
4138 {
4139   struct MeshRegexBlock *block = value;
4140   struct MeshRegexSearchContext *ctx = cls;
4141
4142   // block was checked when stored, no need to check again
4143   (void) GNUNET_MESH_regex_block_iterate (block, SIZE_MAX,
4144                                           &regex_edge_iterator, ctx);
4145
4146   return GNUNET_YES;
4147 }
4148
4149 /**
4150  * Iterator over edges in a block.
4151  *
4152  * @param cls Closure.
4153  * @param token Token that follows to next state.
4154  * @param len Lenght of token.
4155  * @param key Hash of next state.
4156  *
4157  * @return GNUNET_YES if should keep iterating, GNUNET_NO otherwise.
4158  */
4159 static int
4160 regex_edge_iterator (void *cls,
4161                      const char *token,
4162                      size_t len,
4163                      const struct GNUNET_HashCode *key)
4164 {
4165   struct MeshRegexSearchContext *ctx = cls;
4166   struct GNUNET_DHT_GetHandle *get_h;
4167   char *current;
4168   size_t current_len;
4169
4170   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*    Start of regex edge iterator\n");
4171   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*     descr : %s\n", ctx->description);
4172   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*     posit : %u\n", ctx->position);
4173   current = &ctx->description[ctx->position];
4174   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*     currt : %s\n", current);
4175   current_len = strlen (ctx->description) - ctx->position;
4176   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*     ctlen : %u\n", current_len);
4177   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*     tklen : %u\n", len);
4178   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*     tk[0] : %c\n", token[0]);
4179   if (len > current_len)
4180   {
4181     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*     Token too long, END\n");
4182     return GNUNET_YES; // Token too long, wont match
4183   }
4184   if (0 != strncmp (current, token, len))
4185   {
4186     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*     Token doesn't match, END\n");
4187     return GNUNET_YES; // Token doesn't match
4188   }
4189
4190   if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(ctx->dht_get_handles,
4191                                                            key))
4192   {
4193     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*     GET running, END\n");
4194     GNUNET_CONTAINER_multihashmap_get_multiple (ctx->dht_get_results, key,
4195                                                 NULL, ctx);
4196     return GNUNET_YES; // We are already looking for it
4197   }
4198   /* Start search in DHT */
4199   get_h = 
4200       GNUNET_DHT_get_start (dht_handle,    /* handle */
4201                             GNUNET_BLOCK_TYPE_MESH_REGEX, /* type */
4202                             key,     /* key to search */
4203                             DHT_REPLICATION_LEVEL, /* replication level */
4204                             GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
4205                             NULL,       /* xquery */ // FIXME BLOOMFILTER
4206                             0,     /* xquery bits */ // FIXME BLOOMFILTER SIZE
4207                             &dht_get_string_handler, ctx);
4208   ctx->position += len;
4209   if (GNUNET_OK !=
4210       GNUNET_CONTAINER_multihashmap_put(ctx->dht_get_handles, key, get_h,
4211                                         GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
4212   {
4213     GNUNET_break (0);
4214     return GNUNET_YES;
4215   }
4216   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*    End of regex edge iterator\n");
4217   return GNUNET_YES;
4218 }
4219
4220
4221 /**
4222  * Function to process DHT string to regex matching..
4223  * Called on each result obtained for the DHT search.
4224  *
4225  * @param cls closure (search context)
4226  * @param exp when will this value expire
4227  * @param key key of the result
4228  * @param get_path path of the get request (not used)
4229  * @param get_path_length lenght of get_path (not used)
4230  * @param put_path path of the put request (not used)
4231  * @param put_path_length length of the put_path (not used)
4232  * @param type type of the result
4233  * @param size number of bytes in data
4234  * @param data pointer to the result data
4235  */
4236 static void
4237 dht_get_string_accept_handler (void *cls, struct GNUNET_TIME_Absolute exp,
4238                                const struct GNUNET_HashCode * key,
4239                                const struct GNUNET_PeerIdentity *get_path,
4240                                unsigned int get_path_length,
4241                                const struct GNUNET_PeerIdentity *put_path,
4242                                unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
4243                                size_t size, const void *data)
4244 {
4245   const struct MeshRegexAccept *block = data;
4246   struct MeshRegexSearchContext *ctx = cls;
4247   struct MeshPeerPath *p;
4248   struct MeshPeerInfo *peer_info;
4249
4250   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got results from DHT!\n");
4251
4252   peer_info = peer_info_get(&block->id);
4253   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for %s\n", ctx->description);
4254
4255   p = path_build_from_dht (get_path, get_path_length, put_path,
4256                            put_path_length);
4257   path_add_to_peers (p, GNUNET_NO);
4258   path_destroy(p);
4259
4260   tunnel_add_peer (ctx->t, peer_info);
4261   peer_info_connect (peer_info, ctx->t);
4262
4263   // FIXME cancel only AFTER successful connection (received ACK)
4264   regex_cancel_search (ctx);
4265
4266   return;
4267 }
4268
4269
4270 /**
4271  * Function to process DHT string to regex matching..
4272  * Called on each result obtained for the DHT search.
4273  *
4274  * @param cls closure (search context)
4275  * @param exp when will this value expire
4276  * @param key key of the result
4277  * @param get_path path of the get request (not used)
4278  * @param get_path_length lenght of get_path (not used)
4279  * @param put_path path of the put request (not used)
4280  * @param put_path_length length of the put_path (not used)
4281  * @param type type of the result
4282  * @param size number of bytes in data
4283  * @param data pointer to the result data
4284  *
4285  * TODO: re-issue the request after certain time? cancel after X results?
4286  */
4287 static void
4288 dht_get_string_handler (void *cls, struct GNUNET_TIME_Absolute exp,
4289                         const struct GNUNET_HashCode * key,
4290                         const struct GNUNET_PeerIdentity *get_path,
4291                         unsigned int get_path_length,
4292                         const struct GNUNET_PeerIdentity *put_path,
4293                         unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
4294                         size_t size, const void *data)
4295 {
4296   const struct MeshRegexBlock *block = data;
4297   struct MeshRegexSearchContext *ctx = cls;
4298   void *copy;
4299   char *proof;
4300   size_t len;
4301
4302   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4303               "DHT GET STRING RETURNED RESULTS\n");
4304   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4305               "  key: %s\n", GNUNET_h2s (key));
4306
4307   copy = GNUNET_malloc (size);
4308   memcpy (copy, data, size);
4309   GNUNET_break (GNUNET_OK ==
4310                 GNUNET_CONTAINER_multihashmap_put(ctx->dht_get_results, key, copy,
4311                                                   GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
4312   len = ntohl (block->n_proof);
4313   proof = GNUNET_malloc (len + 1);
4314   memcpy (proof, &block[1], len);
4315   proof[len] = '\0';
4316   if (GNUNET_OK != GNUNET_REGEX_check_proof (proof, key))
4317   {
4318     GNUNET_break_op (0);
4319     return;
4320   }
4321   len = strlen (ctx->description);
4322   if (len == ctx->position) // String processed
4323   {
4324     if (GNUNET_YES == ntohl (block->accepting))
4325     {
4326       struct GNUNET_DHT_GetHandle *get_h;
4327       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Found peer by service\n");
4328       get_h = GNUNET_DHT_get_start (dht_handle,    /* handle */
4329                                     GNUNET_BLOCK_TYPE_MESH_REGEX_ACCEPT, /* type */
4330                                     key,     /* key to search */
4331                                     DHT_REPLICATION_LEVEL, /* replication level */
4332                                     GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE |
4333                                     GNUNET_DHT_RO_RECORD_ROUTE,
4334                                     NULL,       /* xquery */ // FIXME BLOOMFILTER
4335                                     0,     /* xquery bits */ // FIXME BLOOMFILTER SIZE
4336                                     &dht_get_string_accept_handler, ctx);
4337       GNUNET_break (GNUNET_OK ==
4338                     GNUNET_CONTAINER_multihashmap_put(ctx->dht_get_handles, key, get_h,
4339                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
4340     }
4341     else
4342     {
4343       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  block not accepting!\n");
4344       // FIXME this block not successful, wait for more? start timeout?
4345     }
4346     return;
4347   }
4348   GNUNET_break (GNUNET_OK ==
4349                 GNUNET_MESH_regex_block_iterate (block, size,
4350                                                  &regex_edge_iterator, ctx));
4351   return;
4352 }
4353
4354 /******************************************************************************/
4355 /*********************       MESH LOCAL HANDLES      **************************/
4356 /******************************************************************************/
4357
4358
4359 /**
4360  * Handler for client disconnection
4361  *
4362  * @param cls closure
4363  * @param client identification of the client; NULL
4364  *        for the last call when the server is destroyed
4365  */
4366 static void
4367 handle_local_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
4368 {
4369   struct MeshClient *c;
4370   struct MeshClient *next;
4371   unsigned int i;
4372
4373   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client disconnected\n");
4374   if (client == NULL)
4375   {
4376     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   (SERVER DOWN)\n");
4377     return;
4378   }
4379   c = clients;
4380   while (NULL != c)
4381   {
4382     if (c->handle != client)
4383     {
4384       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ... searching\n");
4385       c = c->next;
4386       continue;
4387     }
4388     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "matching client found (%u)\n",
4389                 c->id);
4390     GNUNET_SERVER_client_drop (c->handle);
4391     c->shutting_down = GNUNET_YES;
4392     GNUNET_assert (NULL != c->own_tunnels);
4393     GNUNET_assert (NULL != c->incoming_tunnels);
4394     GNUNET_CONTAINER_multihashmap_iterate (c->own_tunnels,
4395                                            &tunnel_destroy_iterator, c);
4396     GNUNET_CONTAINER_multihashmap_iterate (c->incoming_tunnels,
4397                                            &tunnel_destroy_iterator, c);
4398     GNUNET_CONTAINER_multihashmap_iterate (c->ignore_tunnels,
4399                                            &tunnel_destroy_iterator, c);
4400     GNUNET_CONTAINER_multihashmap_destroy (c->own_tunnels);
4401     GNUNET_CONTAINER_multihashmap_destroy (c->incoming_tunnels);
4402     GNUNET_CONTAINER_multihashmap_destroy (c->ignore_tunnels);
4403
4404     /* deregister clients applications */
4405     if (NULL != c->apps)
4406     {
4407       GNUNET_CONTAINER_multihashmap_iterate (c->apps, &deregister_app, c->apps);
4408       GNUNET_CONTAINER_multihashmap_destroy (c->apps);
4409     }
4410     if (0 == GNUNET_CONTAINER_multihashmap_size (applications) &&
4411         GNUNET_SCHEDULER_NO_TASK != announce_applications_task)
4412     {
4413       GNUNET_SCHEDULER_cancel (announce_applications_task);
4414       announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
4415     }
4416     if (NULL != c->types)
4417       GNUNET_CONTAINER_multihashmap_destroy (c->types);
4418     for (i = 0; i < c->n_regex; i++)
4419     {
4420       GNUNET_free (c->regexes[i]);
4421     }
4422     if (GNUNET_SCHEDULER_NO_TASK != c->regex_announce_task)
4423       GNUNET_SCHEDULER_cancel (c->regex_announce_task);
4424     next = c->next;
4425     GNUNET_CONTAINER_DLL_remove (clients, clients_tail, c);
4426     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  CLIENT FREE at %p\n", c);
4427     GNUNET_free (c);
4428     c = next;
4429   }
4430   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   done!\n");
4431   return;
4432 }
4433
4434
4435 /**
4436  * Handler for new clients
4437  *
4438  * @param cls closure
4439  * @param client identification of the client
4440  * @param message the actual message, which includes messages the client wants
4441  */
4442 static void
4443 handle_local_new_client (void *cls, struct GNUNET_SERVER_Client *client,
4444                          const struct GNUNET_MessageHeader *message)
4445 {
4446   struct GNUNET_MESH_ClientConnect *cc_msg;
4447   struct MeshClient *c;
4448   GNUNET_MESH_ApplicationType *a;
4449   unsigned int size;
4450   uint16_t ntypes;
4451   uint16_t *t;
4452   uint16_t napps;
4453   uint16_t i;
4454
4455   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client connected\n");
4456   /* Check data sanity */
4457   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_ClientConnect);
4458   cc_msg = (struct GNUNET_MESH_ClientConnect *) message;
4459   ntypes = ntohs (cc_msg->types);
4460   napps = ntohs (cc_msg->applications);
4461   if (size !=
4462       ntypes * sizeof (uint16_t) + napps * sizeof (GNUNET_MESH_ApplicationType))
4463   {
4464     GNUNET_break (0);
4465     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4466     return;
4467   }
4468
4469   /* Create new client structure */
4470   c = GNUNET_malloc (sizeof (struct MeshClient));
4471   c->id = next_client_id++;
4472   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  CLIENT NEW %u\n", c->id);
4473   c->handle = client;
4474   GNUNET_SERVER_client_keep (client);
4475   a = (GNUNET_MESH_ApplicationType *) &cc_msg[1];
4476   if (napps > 0)
4477   {
4478     GNUNET_MESH_ApplicationType at;
4479     struct GNUNET_HashCode hc;
4480
4481     c->apps = GNUNET_CONTAINER_multihashmap_create (napps);
4482     for (i = 0; i < napps; i++)
4483     {
4484       at = ntohl (a[i]);
4485       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  app type: %u\n", at);
4486       GNUNET_CRYPTO_hash (&at, sizeof (at), &hc);
4487       /* store in clients hashmap */
4488       GNUNET_CONTAINER_multihashmap_put (c->apps, &hc, (void *) (long) at,
4489                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
4490       /* store in global hashmap, for announcements */
4491       GNUNET_CONTAINER_multihashmap_put (applications, &hc, c,
4492                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
4493     }
4494     if (GNUNET_SCHEDULER_NO_TASK == announce_applications_task)
4495       announce_applications_task =
4496           GNUNET_SCHEDULER_add_now (&announce_applications, NULL);
4497
4498   }
4499   if (ntypes > 0)
4500   {
4501     uint16_t u16;
4502     struct GNUNET_HashCode hc;
4503
4504     t = (uint16_t *) & a[napps];
4505     c->types = GNUNET_CONTAINER_multihashmap_create (ntypes);
4506     for (i = 0; i < ntypes; i++)
4507     {
4508       u16 = ntohs (t[i]);
4509       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  msg type: %u\n", u16);
4510       GNUNET_CRYPTO_hash (&u16, sizeof (u16), &hc);
4511
4512       /* store in clients hashmap */
4513       GNUNET_CONTAINER_multihashmap_put (c->types, &hc, c,
4514                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
4515       /* store in global hashmap */
4516       GNUNET_CONTAINER_multihashmap_put (types, &hc, c,
4517                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
4518     }
4519   }
4520   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4521               " client has %u+%u subscriptions\n", napps, ntypes);
4522
4523   GNUNET_CONTAINER_DLL_insert (clients, clients_tail, c);
4524   c->own_tunnels = GNUNET_CONTAINER_multihashmap_create (32);
4525   c->incoming_tunnels = GNUNET_CONTAINER_multihashmap_create (32);
4526   c->ignore_tunnels = GNUNET_CONTAINER_multihashmap_create (32);
4527   GNUNET_SERVER_notification_context_add (nc, client);
4528
4529   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4530   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client processed\n");
4531 }
4532
4533
4534 /**
4535  * Handler for clients announcing available services by a regular expression.
4536  *
4537  * @param cls closure
4538  * @param client identification of the client
4539  * @param message the actual message, which includes messages the client wants
4540  */
4541 static void
4542 handle_local_announce_regex (void *cls, struct GNUNET_SERVER_Client *client,
4543                              const struct GNUNET_MessageHeader *message)
4544 {
4545   struct MeshClient *c;
4546   char *regex;
4547   size_t len;
4548
4549   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "announce regex started\n");
4550
4551   /* Sanity check for client registration */
4552   if (NULL == (c = client_get (client)))
4553   {
4554     GNUNET_break (0);
4555     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4556     return;
4557   }
4558   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
4559
4560   len = ntohs (message->size) - sizeof(struct GNUNET_MessageHeader);
4561   regex = GNUNET_malloc (len + 1);
4562   memcpy (regex, &message[1], len);
4563   regex[len] = '\0';
4564   GNUNET_array_append (c->regexes, c->n_regex, regex);
4565   if (GNUNET_SCHEDULER_NO_TASK == c->regex_announce_task)
4566   {
4567     c->regex_announce_task = GNUNET_SCHEDULER_add_now(&announce_regex, c);
4568   }
4569   else
4570   {
4571     regex_put(regex);
4572   }
4573   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4574   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "announce regex processed\n");
4575 }
4576
4577
4578 /**
4579  * Handler for requests of new tunnels
4580  *
4581  * @param cls closure
4582  * @param client identification of the client
4583  * @param message the actual message
4584  */
4585 static void
4586 handle_local_tunnel_create (void *cls, struct GNUNET_SERVER_Client *client,
4587                             const struct GNUNET_MessageHeader *message)
4588 {
4589   struct GNUNET_MESH_TunnelMessage *t_msg;
4590   struct MeshTunnel *t;
4591   struct MeshClient *c;
4592
4593   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new tunnel requested\n");
4594
4595   /* Sanity check for client registration */
4596   if (NULL == (c = client_get (client)))
4597   {
4598     GNUNET_break (0);
4599     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4600     return;
4601   }
4602   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
4603
4604   /* Message sanity check */
4605   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
4606   {
4607     GNUNET_break (0);
4608     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4609     return;
4610   }
4611
4612   t_msg = (struct GNUNET_MESH_TunnelMessage *) message;
4613   /* Sanity check for tunnel numbering */
4614   if (0 == (ntohl (t_msg->tunnel_id) & GNUNET_MESH_LOCAL_TUNNEL_ID_CLI))
4615   {
4616     GNUNET_break (0);
4617     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4618     return;
4619   }
4620   /* Sanity check for duplicate tunnel IDs */
4621   if (NULL != tunnel_get_by_local_id (c, ntohl (t_msg->tunnel_id)))
4622   {
4623     GNUNET_break (0);
4624     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4625     return;
4626   }
4627
4628   while (NULL != tunnel_get_by_pi (myid, next_tid))
4629     next_tid = (next_tid + 1) & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
4630   t = tunnel_new (myid, next_tid++, c, ntohl (t_msg->tunnel_id));
4631   next_tid = next_tid & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
4632   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CREATED TUNNEL %s [%x] (%x)\n",
4633               GNUNET_i2s (&my_full_id), t->id.tid, t->local_tid);
4634   t->peers = GNUNET_CONTAINER_multihashmap_create (32);
4635
4636   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new tunnel created\n");
4637   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4638   return;
4639 }
4640
4641
4642 /**
4643  * Handler for requests of deleting tunnels
4644  *
4645  * @param cls closure
4646  * @param client identification of the client
4647  * @param message the actual message
4648  */
4649 static void
4650 handle_local_tunnel_destroy (void *cls, struct GNUNET_SERVER_Client *client,
4651                              const struct GNUNET_MessageHeader *message)
4652 {
4653   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
4654   struct MeshClient *c;
4655   struct MeshTunnel *t;
4656   MESH_TunnelNumber tid;
4657
4658   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4659               "Got a DESTROY TUNNEL from client!\n");
4660
4661   /* Sanity check for client registration */
4662   if (NULL == (c = client_get (client)))
4663   {
4664     GNUNET_break (0);
4665     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4666     return;
4667   }
4668   /* Message sanity check */
4669   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
4670   {
4671     GNUNET_break (0);
4672     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4673     return;
4674   }
4675   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
4676   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
4677
4678   /* Retrieve tunnel */
4679   tid = ntohl (tunnel_msg->tunnel_id);
4680   t = tunnel_get_by_local_id(c, tid);
4681   if (NULL == t)
4682   {
4683     GNUNET_break (0);
4684     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  tunnel %X not found\n", tid);
4685     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4686     return;
4687   }
4688   if (c != t->owner || tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
4689   {
4690     client_ignore_tunnel (c, t);
4691 #if 0
4692     // TODO: when to destroy incoming tunnel?
4693     if (t->nclients == 0)
4694     {
4695       GNUNET_assert (GNUNET_YES ==
4696                      GNUNET_CONTAINER_multihashmap_remove (incoming_tunnels,
4697                                                            &hash, t));
4698       GNUNET_assert (GNUNET_YES ==
4699                      GNUNET_CONTAINER_multihashmap_remove (t->peers,
4700                                                            &my_full_id.hashPubKey,
4701                                                            t));
4702     }
4703 #endif
4704     GNUNET_SERVER_receive_done (client, GNUNET_OK);
4705     return;
4706   }
4707   send_client_tunnel_disconnect(t, c);
4708   client_delete_tunnel(c, t);
4709
4710   /* Don't try to ACK the client about the tunnel_destroy multicast packet */
4711   t->owner = NULL;
4712   tunnel_send_destroy (t);
4713   tunnel_destroy (t);
4714   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4715   return;
4716 }
4717
4718
4719 /**
4720  * Handler for connection requests to new peers
4721  *
4722  * @param cls closure
4723  * @param client identification of the client
4724  * @param message the actual message (PeerControl)
4725  */
4726 static void
4727 handle_local_connect_add (void *cls, struct GNUNET_SERVER_Client *client,
4728                           const struct GNUNET_MessageHeader *message)
4729 {
4730   struct GNUNET_MESH_PeerControl *peer_msg;
4731   struct MeshPeerInfo *peer_info;
4732   struct MeshClient *c;
4733   struct MeshTunnel *t;
4734   MESH_TunnelNumber tid;
4735
4736   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got connection request\n");
4737   /* Sanity check for client registration */
4738   if (NULL == (c = client_get (client)))
4739   {
4740     GNUNET_break (0);
4741     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4742     return;
4743   }
4744
4745   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
4746   /* Sanity check for message size */
4747   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
4748   {
4749     GNUNET_break (0);
4750     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4751     return;
4752   }
4753
4754   /* Tunnel exists? */
4755   tid = ntohl (peer_msg->tunnel_id);
4756   t = tunnel_get_by_local_id (c, tid);
4757   if (NULL == t)
4758   {
4759     GNUNET_break (0);
4760     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4761     return;
4762   }
4763
4764   /* Does client own tunnel? */
4765   if (t->owner->handle != client)
4766   {
4767     GNUNET_break (0);
4768     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4769     return;
4770   }
4771   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "     for %s\n",
4772               GNUNET_i2s (&peer_msg->peer));
4773   peer_info = peer_info_get (&peer_msg->peer);
4774
4775   tunnel_add_peer (t, peer_info);
4776   peer_info_connect (peer_info, t);
4777
4778   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4779   return;
4780 }
4781
4782
4783 /**
4784  * Handler for disconnection requests of peers in a tunnel
4785  *
4786  * @param cls closure
4787  * @param client identification of the client
4788  * @param message the actual message (PeerControl)
4789  */
4790 static void
4791 handle_local_connect_del (void *cls, struct GNUNET_SERVER_Client *client,
4792                           const struct GNUNET_MessageHeader *message)
4793 {
4794   struct GNUNET_MESH_PeerControl *peer_msg;
4795   struct MeshPeerInfo *peer_info;
4796   struct MeshClient *c;
4797   struct MeshTunnel *t;
4798   MESH_TunnelNumber tid;
4799
4800   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a PEER DEL request\n");
4801   /* Sanity check for client registration */
4802   if (NULL == (c = client_get (client)))
4803   {
4804     GNUNET_break (0);
4805     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4806     return;
4807   }
4808   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
4809   /* Sanity check for message size */
4810   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
4811   {
4812     GNUNET_break (0);
4813     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4814     return;
4815   }
4816
4817   /* Tunnel exists? */
4818   tid = ntohl (peer_msg->tunnel_id);
4819   t = tunnel_get_by_local_id (c, tid);
4820   if (NULL == t)
4821   {
4822     GNUNET_break (0);
4823     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4824     return;
4825   }
4826   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", t->id.tid);
4827
4828   /* Does client own tunnel? */
4829   if (t->owner->handle != client)
4830   {
4831     GNUNET_break (0);
4832     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4833     return;
4834   }
4835
4836   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for peer %s\n",
4837               GNUNET_i2s (&peer_msg->peer));
4838   /* Is the peer in the tunnel? */
4839   peer_info =
4840       GNUNET_CONTAINER_multihashmap_get (t->peers, &peer_msg->peer.hashPubKey);
4841   if (NULL == peer_info)
4842   {
4843     GNUNET_break (0);
4844     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4845     return;
4846   }
4847
4848   /* Ok, delete peer from tunnel */
4849   GNUNET_CONTAINER_multihashmap_remove_all (t->peers,
4850                                             &peer_msg->peer.hashPubKey);
4851
4852   send_destroy_path (t, peer_info->id);
4853   tunnel_delete_peer (t, peer_info->id);
4854   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4855   return;
4856 }
4857
4858 /**
4859  * Handler for blacklist requests of peers in a tunnel
4860  *
4861  * @param cls closure
4862  * @param client identification of the client
4863  * @param message the actual message (PeerControl)
4864  */
4865 static void
4866 handle_local_blacklist (void *cls, struct GNUNET_SERVER_Client *client,
4867                           const struct GNUNET_MessageHeader *message)
4868 {
4869   struct GNUNET_MESH_PeerControl *peer_msg;
4870   struct MeshClient *c;
4871   struct MeshTunnel *t;
4872   MESH_TunnelNumber tid;
4873
4874   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a PEER BLACKLIST request\n");
4875   /* Sanity check for client registration */
4876   if (NULL == (c = client_get (client)))
4877   {
4878     GNUNET_break (0);
4879     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4880     return;
4881   }
4882   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
4883
4884   /* Sanity check for message size */
4885   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
4886   {
4887     GNUNET_break (0);
4888     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4889     return;
4890   }
4891
4892   /* Tunnel exists? */
4893   tid = ntohl (peer_msg->tunnel_id);
4894   t = tunnel_get_by_local_id (c, tid);
4895   if (NULL == t)
4896   {
4897     GNUNET_break (0);
4898     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4899     return;
4900   }
4901   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", t->id.tid);
4902
4903   GNUNET_array_append(t->blacklisted, t->nblacklisted,
4904                       GNUNET_PEER_intern(&peer_msg->peer));
4905 }
4906
4907
4908 /**
4909  * Handler for unblacklist requests of peers in a tunnel
4910  *
4911  * @param cls closure
4912  * @param client identification of the client
4913  * @param message the actual message (PeerControl)
4914  */
4915 static void
4916 handle_local_unblacklist (void *cls, struct GNUNET_SERVER_Client *client,
4917                           const struct GNUNET_MessageHeader *message)
4918 {
4919   struct GNUNET_MESH_PeerControl *peer_msg;
4920   struct MeshClient *c;
4921   struct MeshTunnel *t;
4922   MESH_TunnelNumber tid;
4923   GNUNET_PEER_Id pid;
4924   unsigned int i;
4925
4926   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a PEER UNBLACKLIST request\n");
4927   /* Sanity check for client registration */
4928   if (NULL == (c = client_get (client)))
4929   {
4930     GNUNET_break (0);
4931     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4932     return;
4933   }
4934   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
4935
4936   /* Sanity check for message size */
4937   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
4938   {
4939     GNUNET_break (0);
4940     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4941     return;
4942   }
4943
4944   /* Tunnel exists? */
4945   tid = ntohl (peer_msg->tunnel_id);
4946   t = tunnel_get_by_local_id (c, tid);
4947   if (NULL == t)
4948   {
4949     GNUNET_break (0);
4950     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4951     return;
4952   }
4953   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", t->id.tid);
4954
4955   /* if peer is not known, complain */
4956   pid = GNUNET_PEER_search (&peer_msg->peer);
4957   if (0 == pid)
4958   {
4959     GNUNET_break (0);
4960     return;
4961   }
4962
4963   /* search and remove from list */
4964   for (i = 0; i < t->nblacklisted; i++)
4965   {
4966     if (t->blacklisted[i] == pid)
4967     {
4968       t->blacklisted[i] = t->blacklisted[t->nblacklisted - 1];
4969       GNUNET_array_grow (t->blacklisted, t->nblacklisted, t->nblacklisted - 1);
4970       return;
4971     }
4972   }
4973
4974   /* if peer hasn't been blacklisted, complain */
4975   GNUNET_break (0);
4976 }
4977
4978
4979 /**
4980  * Handler for connection requests to new peers by type
4981  *
4982  * @param cls closure
4983  * @param client identification of the client
4984  * @param message the actual message (ConnectPeerByType)
4985  */
4986 static void
4987 handle_local_connect_by_type (void *cls, struct GNUNET_SERVER_Client *client,
4988                               const struct GNUNET_MessageHeader *message)
4989 {
4990   struct GNUNET_MESH_ConnectPeerByType *connect_msg;
4991   struct MeshClient *c;
4992   struct MeshTunnel *t;
4993   struct GNUNET_HashCode hash;
4994   MESH_TunnelNumber tid;
4995
4996   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got connect by type request\n");
4997   /* Sanity check for client registration */
4998   if (NULL == (c = client_get (client)))
4999   {
5000     GNUNET_break (0);
5001     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5002     return;
5003   }
5004
5005   connect_msg = (struct GNUNET_MESH_ConnectPeerByType *) message;
5006   /* Sanity check for message size */
5007   if (sizeof (struct GNUNET_MESH_ConnectPeerByType) !=
5008       ntohs (connect_msg->header.size))
5009   {
5010     GNUNET_break (0);
5011     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5012     return;
5013   }
5014
5015   /* Tunnel exists? */
5016   tid = ntohl (connect_msg->tunnel_id);
5017   t = tunnel_get_by_local_id (c, tid);
5018   if (NULL == t)
5019   {
5020     GNUNET_break (0);
5021     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5022     return;
5023   }
5024
5025   /* Does client own tunnel? */
5026   if (t->owner->handle != client)
5027   {
5028     GNUNET_break (0);
5029     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5030     return;
5031   }
5032
5033   /* Do WE have the service? */
5034   t->type = ntohl (connect_msg->type);
5035   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " type requested: %u\n", t->type);
5036   GNUNET_CRYPTO_hash (&t->type, sizeof (GNUNET_MESH_ApplicationType), &hash);
5037   if (GNUNET_CONTAINER_multihashmap_contains (applications, &hash) ==
5038       GNUNET_YES)
5039   {
5040     /* Yes! Fast forward, add ourselves to the tunnel and send the
5041      * good news to the client, and alert the destination client of
5042      * an incoming tunnel.
5043      *
5044      * FIXME send a path create to self, avoid code duplication
5045      */
5046     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " available locally\n");
5047     GNUNET_CONTAINER_multihashmap_put (t->peers, &my_full_id.hashPubKey,
5048                                        peer_info_get (&my_full_id),
5049                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
5050
5051     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " notifying client\n");
5052     send_client_peer_connected (t, myid);
5053     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Done\n");
5054     GNUNET_SERVER_receive_done (client, GNUNET_OK);
5055
5056     t->local_tid_dest = next_local_tid++;
5057     GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
5058     GNUNET_CONTAINER_multihashmap_put (incoming_tunnels, &hash, t,
5059                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
5060
5061     return;
5062   }
5063   /* Ok, lets find a peer offering the service */
5064   if (NULL != t->dht_get_type)
5065   {
5066     GNUNET_DHT_get_stop (t->dht_get_type);
5067   }
5068   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " looking in DHT for %s\n",
5069               GNUNET_h2s (&hash));
5070   t->dht_get_type =
5071       GNUNET_DHT_get_start (dht_handle, 
5072                             GNUNET_BLOCK_TYPE_MESH_PEER_BY_TYPE,
5073                             &hash,
5074                             DHT_REPLICATION_LEVEL,
5075                             GNUNET_DHT_RO_RECORD_ROUTE |
5076                             GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
5077                             NULL, 0,
5078                             &dht_get_type_handler, t);
5079
5080   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5081   return;
5082 }
5083
5084
5085 /**
5086  * Handler for connection requests to new peers by a string service description.
5087  *
5088  * @param cls closure
5089  * @param client identification of the client
5090  * @param message the actual message, which includes messages the client wants
5091  */
5092 static void
5093 handle_local_connect_by_string (void *cls, struct GNUNET_SERVER_Client *client,
5094                                 const struct GNUNET_MessageHeader *message)
5095 {
5096   struct GNUNET_MESH_ConnectPeerByString *msg;
5097   struct MeshRegexSearchContext *ctx;
5098   struct GNUNET_DHT_GetHandle *get_h;
5099   struct GNUNET_HashCode key;
5100   struct MeshTunnel *t;
5101   struct MeshClient *c;
5102   MESH_TunnelNumber tid;
5103   const char *string;
5104   size_t size;
5105   size_t len;
5106   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5107               "Connect by string started\n");
5108   msg = (struct GNUNET_MESH_ConnectPeerByString *) message;
5109   size = htons (message->size);
5110
5111   /* Sanity check for client registration */
5112   if (NULL == (c = client_get (client)))
5113   {
5114     GNUNET_break (0);
5115     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5116     return;
5117   }
5118
5119   /* Message size sanity check */
5120   if (sizeof(struct GNUNET_MESH_ConnectPeerByString) >= size)
5121   {
5122       GNUNET_break (0);
5123       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5124       return;
5125   }
5126
5127   /* Tunnel exists? */
5128   tid = ntohl (msg->tunnel_id);
5129   t = tunnel_get_by_local_id (c, tid);
5130   if (NULL == t)
5131   {
5132     GNUNET_break (0);
5133     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5134     return;
5135   }
5136
5137   /* Does client own tunnel? */
5138   if (t->owner->handle != client)
5139   {
5140     GNUNET_break (0);
5141     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5142     return;
5143   }
5144
5145   /* Only one connect_by_string allowed at the same time! */
5146   /* FIXME: allow more, return handle at api level to cancel, document */
5147   if (NULL != t->regex_ctx)
5148   {
5149     GNUNET_break (0);
5150     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5151     return;
5152   }
5153
5154   /* Find string itself */
5155   len = size - sizeof(struct GNUNET_MESH_ConnectPeerByString);
5156   string = (const char *) &msg[1];
5157
5158   /* Initialize context */
5159   size = GNUNET_REGEX_get_first_key(string, len, &key);
5160   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5161               "  consumed %u bits out of %u\n", size, len);
5162   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5163               "  looking for %s\n", GNUNET_h2s (&key));
5164
5165   ctx = GNUNET_malloc (sizeof (struct MeshRegexSearchContext));
5166   ctx->position = size;
5167   ctx->t = t;
5168   t->regex_ctx = ctx;
5169   ctx->description = GNUNET_malloc (len + 1);
5170   memcpy (ctx->description, string, len);
5171   ctx->description[len] = '\0';
5172   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   string: %s\n", ctx->description);
5173
5174   ctx->dht_get_handles = GNUNET_CONTAINER_multihashmap_create(32);
5175   ctx->dht_get_results = GNUNET_CONTAINER_multihashmap_create(32);
5176
5177   /* Start search in DHT */
5178   get_h = GNUNET_DHT_get_start (dht_handle,    /* handle */
5179                                 GNUNET_BLOCK_TYPE_MESH_REGEX, /* type */
5180                                 &key,     /* key to search */
5181                                 DHT_REPLICATION_LEVEL, /* replication level */
5182                                 GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
5183                                 NULL,       /* xquery */ // FIXME BLOOMFILTER
5184                                 0,     /* xquery bits */ // FIXME BLOOMFILTER SIZE
5185                                 &dht_get_string_handler, ctx);
5186   
5187   GNUNET_break (GNUNET_OK ==
5188                 GNUNET_CONTAINER_multihashmap_put(ctx->dht_get_handles,
5189                                                   &key,
5190                                                   get_h,
5191                                                   GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
5192
5193   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5194   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "connect by string processed\n");
5195 }
5196
5197
5198 /**
5199  * Handler for client traffic directed to one peer
5200  *
5201  * @param cls closure
5202  * @param client identification of the client
5203  * @param message the actual message
5204  */
5205 static void
5206 handle_local_unicast (void *cls, struct GNUNET_SERVER_Client *client,
5207                       const struct GNUNET_MessageHeader *message)
5208 {
5209   struct MeshClient *c;
5210   struct MeshTunnel *t;
5211   struct MeshPeerInfo *pi;
5212   struct GNUNET_MESH_Unicast *data_msg;
5213   MESH_TunnelNumber tid;
5214   size_t size;
5215
5216   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5217               "Got a unicast request from a client!\n");
5218
5219   /* Sanity check for client registration */
5220   if (NULL == (c = client_get (client)))
5221   {
5222     GNUNET_break (0);
5223     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5224     return;
5225   }
5226   data_msg = (struct GNUNET_MESH_Unicast *) message;
5227   /* Sanity check for message size */
5228   size = ntohs (message->size);
5229   if (sizeof (struct GNUNET_MESH_Unicast) +
5230       sizeof (struct GNUNET_MessageHeader) > size)
5231   {
5232     GNUNET_break (0);
5233     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5234     return;
5235   }
5236
5237   /* Tunnel exists? */
5238   tid = ntohl (data_msg->tid);
5239   t = tunnel_get_by_local_id (c, tid);
5240   if (NULL == t)
5241   {
5242     GNUNET_break (0);
5243     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5244     return;
5245   }
5246
5247   /*  Is it a local tunnel? Then, does client own the tunnel? */
5248   if (t->owner->handle != client)
5249   {
5250     GNUNET_break (0);
5251     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5252     return;
5253   }
5254
5255   pi = GNUNET_CONTAINER_multihashmap_get (t->peers,
5256                                           &data_msg->destination.hashPubKey);
5257   /* Is the selected peer in the tunnel? */
5258   if (NULL == pi)
5259   {
5260     GNUNET_break (0);
5261     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5262     return;
5263   }
5264
5265   /* Ok, everything is correct, send the message
5266    * (pretend we got it from a mesh peer)
5267    */
5268   {
5269     char buf[ntohs (message->size)] GNUNET_ALIGN;
5270     struct GNUNET_MESH_Unicast *copy;
5271
5272     /* Work around const limitation */
5273     copy = (struct GNUNET_MESH_Unicast *) buf;
5274     memcpy (buf, data_msg, size);
5275     copy->oid = my_full_id;
5276     copy->tid = htonl (t->id.tid);
5277     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5278                 "  calling generic handler...\n");
5279     handle_mesh_data_unicast (NULL, &my_full_id, &copy->header, NULL, 0);
5280   }
5281   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5282   return;
5283 }
5284
5285
5286 /**
5287  * Handler for client traffic directed to the origin
5288  *
5289  * @param cls closure
5290  * @param client identification of the client
5291  * @param message the actual message
5292  */
5293 static void
5294 handle_local_to_origin (void *cls, struct GNUNET_SERVER_Client *client,
5295                         const struct GNUNET_MessageHeader *message)
5296 {
5297   struct GNUNET_MESH_ToOrigin *data_msg;
5298   struct GNUNET_PeerIdentity id;
5299   struct MeshClient *c;
5300   struct MeshTunnel *t;
5301   MESH_TunnelNumber tid;
5302   size_t size;
5303
5304   /* Sanity check for client registration */
5305   if (NULL == (c = client_get (client)))
5306   {
5307     GNUNET_break (0);
5308     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5309     return;
5310   }
5311   data_msg = (struct GNUNET_MESH_ToOrigin *) message;
5312   /* Sanity check for message size */
5313   size = ntohs (message->size);
5314   if (sizeof (struct GNUNET_MESH_ToOrigin) +
5315       sizeof (struct GNUNET_MessageHeader) > size)
5316   {
5317     GNUNET_break (0);
5318     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5319     return;
5320   }
5321
5322   /* Tunnel exists? */
5323   tid = ntohl (data_msg->tid);
5324   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5325               "Got a ToOrigin request from a client! Tunnel %X\n", tid);
5326   if (tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
5327   {
5328     GNUNET_break (0);
5329     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5330     return;
5331   }
5332   t = tunnel_get_by_local_id (c, tid);
5333   if (NULL == t)
5334   {
5335     GNUNET_break (0);
5336     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5337     return;
5338   }
5339
5340   /*  It should be sent by someone who has this as incoming tunnel. */
5341   if (-1 == client_knows_tunnel (c, t))
5342   {
5343     GNUNET_break (0);
5344     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5345     return;
5346   }
5347   GNUNET_PEER_resolve (t->id.oid, &id);
5348
5349   /* Ok, everything is correct, send the message
5350    * (pretend we got it from a mesh peer)
5351    */
5352   {
5353     char buf[ntohs (message->size)] GNUNET_ALIGN;
5354     struct GNUNET_MESH_ToOrigin *copy;
5355
5356     /* Work around const limitation */
5357     copy = (struct GNUNET_MESH_ToOrigin *) buf;
5358     memcpy (buf, data_msg, size);
5359     copy->oid = id;
5360     copy->tid = htonl (t->id.tid);
5361     copy->sender = my_full_id;
5362     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5363                 "  calling generic handler...\n");
5364     handle_mesh_data_to_orig (NULL, &my_full_id, &copy->header, NULL, 0);
5365   }
5366   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5367   return;
5368 }
5369
5370
5371 /**
5372  * Handler for client traffic directed to all peers in a tunnel
5373  *
5374  * @param cls closure
5375  * @param client identification of the client
5376  * @param message the actual message
5377  */
5378 static void
5379 handle_local_multicast (void *cls, struct GNUNET_SERVER_Client *client,
5380                         const struct GNUNET_MessageHeader *message)
5381 {
5382   struct MeshClient *c;
5383   struct MeshTunnel *t;
5384   struct GNUNET_MESH_Multicast *data_msg;
5385   MESH_TunnelNumber tid;
5386
5387   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5388               "Got a multicast request from a client!\n");
5389
5390   /* Sanity check for client registration */
5391   if (NULL == (c = client_get (client)))
5392   {
5393     GNUNET_break (0);
5394     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5395     return;
5396   }
5397   data_msg = (struct GNUNET_MESH_Multicast *) message;
5398   /* Sanity check for message size */
5399   if (sizeof (struct GNUNET_MESH_Multicast) +
5400       sizeof (struct GNUNET_MessageHeader) > ntohs (data_msg->header.size))
5401   {
5402     GNUNET_break (0);
5403     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5404     return;
5405   }
5406
5407   /* Tunnel exists? */
5408   tid = ntohl (data_msg->tid);
5409   t = tunnel_get_by_local_id (c, tid);
5410   if (NULL == t)
5411   {
5412     GNUNET_break (0);
5413     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5414     return;
5415   }
5416
5417   /* Does client own tunnel? */
5418   if (t->owner->handle != client)
5419   {
5420     GNUNET_break (0);
5421     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5422     return;
5423   }
5424
5425   {
5426     char buf[ntohs (message->size)] GNUNET_ALIGN;
5427     struct GNUNET_MESH_Multicast *copy;
5428
5429     copy = (struct GNUNET_MESH_Multicast *) buf;
5430     memcpy (buf, message, ntohs (message->size));
5431     copy->oid = my_full_id;
5432     copy->tid = htonl (t->id.tid);
5433     copy->ttl = htonl (DEFAULT_TTL);
5434     copy->mid = htonl (t->mid + 1);
5435     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5436                 "  calling generic handler...\n");
5437     handle_mesh_data_multicast (client, &my_full_id, &copy->header, NULL, 0);
5438   }
5439
5440   /* receive done gets called when last copy is sent to a neighbor */
5441   return;
5442 }
5443
5444 /**
5445  * Functions to handle messages from clients
5446  */
5447 static struct GNUNET_SERVER_MessageHandler client_handlers[] = {
5448   {&handle_local_new_client, NULL,
5449    GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT, 0},
5450   {&handle_local_announce_regex, NULL,
5451    GNUNET_MESSAGE_TYPE_MESH_LOCAL_ANNOUNCE_REGEX, 0},
5452   {&handle_local_tunnel_create, NULL,
5453    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE,
5454    sizeof (struct GNUNET_MESH_TunnelMessage)},
5455   {&handle_local_tunnel_destroy, NULL,
5456    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY,
5457    sizeof (struct GNUNET_MESH_TunnelMessage)},
5458   {&handle_local_connect_add, NULL,
5459    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD,
5460    sizeof (struct GNUNET_MESH_PeerControl)},
5461   {&handle_local_connect_del, NULL,
5462    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL,
5463    sizeof (struct GNUNET_MESH_PeerControl)},
5464   {&handle_local_blacklist, NULL,
5465    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_BLACKLIST,
5466    sizeof (struct GNUNET_MESH_PeerControl)},
5467   {&handle_local_unblacklist, NULL,
5468    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_UNBLACKLIST,
5469    sizeof (struct GNUNET_MESH_PeerControl)},
5470   {&handle_local_connect_by_type, NULL,
5471    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_TYPE,
5472    sizeof (struct GNUNET_MESH_ConnectPeerByType)},
5473   {&handle_local_connect_by_string, NULL,
5474    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_STRING, 0},
5475   {&handle_local_unicast, NULL,
5476    GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
5477   {&handle_local_to_origin, NULL,
5478    GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
5479   {&handle_local_multicast, NULL,
5480    GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
5481   {NULL, NULL, 0, 0}
5482 };
5483
5484
5485 /**
5486  * To be called on core init/fail.
5487  *
5488  * @param cls service closure
5489  * @param server handle to the server for this service
5490  * @param identity the public identity of this peer
5491  */
5492 static void
5493 core_init (void *cls, struct GNUNET_CORE_Handle *server,
5494            const struct GNUNET_PeerIdentity *identity)
5495 {
5496   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Core init\n");
5497   core_handle = server;
5498   if (0 != memcmp (identity, &my_full_id, sizeof (my_full_id)) ||
5499       NULL == server)
5500   {
5501     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Wrong CORE service\n"));
5502     GNUNET_SCHEDULER_shutdown ();
5503   }
5504   return;
5505 }
5506
5507 /**
5508  * Method called whenever a given peer connects.
5509  *
5510  * @param cls closure
5511  * @param peer peer identity this notification is about
5512  * @param atsi performance data for the connection
5513  * @param atsi_count number of records in 'atsi'
5514  */
5515 static void
5516 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
5517               const struct GNUNET_ATS_Information *atsi,
5518               unsigned int atsi_count)
5519 {
5520   struct MeshPeerInfo *peer_info;
5521   struct MeshPeerPath *path;
5522
5523   DEBUG_CONN ("Peer connected\n");
5524   DEBUG_CONN ("     %s\n", GNUNET_i2s (&my_full_id));
5525   peer_info = peer_info_get (peer);
5526   if (myid == peer_info->id)
5527   {
5528     DEBUG_CONN ("     (self)\n");
5529     return;
5530   }
5531   else
5532   {
5533     DEBUG_CONN ("     %s\n", GNUNET_i2s (peer));
5534   }
5535   path = path_new (2);
5536   path->peers[0] = myid;
5537   path->peers[1] = peer_info->id;
5538   GNUNET_PEER_change_rc (myid, 1);
5539   GNUNET_PEER_change_rc (peer_info->id, 1);
5540   peer_info_add_path (peer_info, path, GNUNET_YES);
5541   return;
5542 }
5543
5544 /**
5545  * Method called whenever a peer disconnects.
5546  *
5547  * @param cls closure
5548  * @param peer peer identity this notification is about
5549  */
5550 static void
5551 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
5552 {
5553   struct MeshPeerInfo *pi;
5554   struct MeshPeerQueue *q;
5555   struct MeshPeerQueue *n;
5556
5557   DEBUG_CONN ("Peer disconnected\n");
5558   pi = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
5559   if (NULL == pi)
5560   {
5561     GNUNET_break (0);
5562     return;
5563   }
5564   q = pi->queue_head;
5565   while (NULL != q)
5566   {
5567       n = q->next;
5568       if (q->peer == pi)
5569       {
5570         /* try to reroute this traffic instead */
5571         queue_destroy(q, GNUNET_YES);
5572       }
5573       q = n;
5574   }
5575   peer_info_remove_path (pi, pi->id, myid);
5576   if (myid == pi->id)
5577   {
5578     DEBUG_CONN ("     (self)\n");
5579   }
5580   return;
5581 }
5582
5583
5584 /******************************************************************************/
5585 /************************      MAIN FUNCTIONS      ****************************/
5586 /******************************************************************************/
5587
5588 /**
5589  * Iterator over tunnel hash map entries to destroy the tunnel during shutdown.
5590  *
5591  * @param cls closure
5592  * @param key current key code
5593  * @param value value in the hash map
5594  * @return GNUNET_YES if we should continue to iterate,
5595  *         GNUNET_NO if not.
5596  */
5597 static int
5598 shutdown_tunnel (void *cls, const struct GNUNET_HashCode * key, void *value)
5599 {
5600   struct MeshTunnel *t = value;
5601
5602   tunnel_destroy (t);
5603   return GNUNET_YES;
5604 }
5605
5606 /**
5607  * Iterator over peer hash map entries to destroy the tunnel during shutdown.
5608  *
5609  * @param cls closure
5610  * @param key current key code
5611  * @param value value in the hash map
5612  * @return GNUNET_YES if we should continue to iterate,
5613  *         GNUNET_NO if not.
5614  */
5615 static int
5616 shutdown_peer (void *cls, const struct GNUNET_HashCode * key, void *value)
5617 {
5618   struct MeshPeerInfo *p = value;
5619   struct MeshPeerQueue *q;
5620   struct MeshPeerQueue *n;
5621
5622   q = p->queue_head;
5623   while (NULL != q)
5624   {
5625       n = q->next;
5626       if (q->peer == p)
5627       {
5628         queue_destroy(q, GNUNET_YES);
5629       }
5630       q = n;
5631   }
5632   peer_info_destroy (p);
5633   return GNUNET_YES;
5634 }
5635
5636 /**
5637  * Task run during shutdown.
5638  *
5639  * @param cls unused
5640  * @param tc unused
5641  */
5642 static void
5643 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
5644 {
5645   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shutting down\n");
5646
5647   if (core_handle != NULL)
5648   {
5649     GNUNET_CORE_disconnect (core_handle);
5650     core_handle = NULL;
5651   }
5652   GNUNET_CONTAINER_multihashmap_iterate (tunnels, &shutdown_tunnel, NULL);
5653   GNUNET_CONTAINER_multihashmap_iterate (peers, &shutdown_peer, NULL);
5654   if (dht_handle != NULL)
5655   {
5656     GNUNET_DHT_disconnect (dht_handle);
5657     dht_handle = NULL;
5658   }
5659   if (nc != NULL)
5660   {
5661     GNUNET_SERVER_notification_context_destroy (nc);
5662     nc = NULL;
5663   }
5664   if (GNUNET_SCHEDULER_NO_TASK != announce_id_task)
5665   {
5666     GNUNET_SCHEDULER_cancel (announce_id_task);
5667     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
5668   }
5669   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shut down\n");
5670 }
5671
5672 /**
5673  * Process mesh requests.
5674  *
5675  * @param cls closure
5676  * @param server the initialized server
5677  * @param c configuration to use
5678  */
5679 static void
5680 run (void *cls, struct GNUNET_SERVER_Handle *server,
5681      const struct GNUNET_CONFIGURATION_Handle *c)
5682 {
5683   struct MeshPeerInfo *peer;
5684   struct MeshPeerPath *p;
5685   char *keyfile;
5686
5687   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "starting to run\n");
5688   server_handle = server;
5689   core_handle = GNUNET_CORE_connect (c, /* Main configuration */
5690                                      NULL,      /* Closure passed to MESH functions */
5691                                      &core_init,        /* Call core_init once connected */
5692                                      &core_connect,     /* Handle connects */
5693                                      &core_disconnect,  /* remove peers on disconnects */
5694                                      NULL,      /* Don't notify about all incoming messages */
5695                                      GNUNET_NO, /* For header only in notification */
5696                                      NULL,      /* Don't notify about all outbound messages */
5697                                      GNUNET_NO, /* For header-only out notification */
5698                                      core_handlers);    /* Register these handlers */
5699
5700   if (core_handle == NULL)
5701   {
5702     GNUNET_break (0);
5703     GNUNET_SCHEDULER_shutdown ();
5704     return;
5705   }
5706
5707   if (GNUNET_OK !=
5708       GNUNET_CONFIGURATION_get_value_filename (c, "GNUNETD", "HOSTKEY",
5709                                                &keyfile))
5710   {
5711     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5712                 _
5713                 ("Mesh service is lacking key configuration settings.  Exiting.\n"));
5714     GNUNET_SCHEDULER_shutdown ();
5715     return;
5716   }
5717   my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
5718   GNUNET_free (keyfile);
5719   if (my_private_key == NULL)
5720   {
5721     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5722                 _("Mesh service could not access hostkey.  Exiting.\n"));
5723     GNUNET_SCHEDULER_shutdown ();
5724     return;
5725   }
5726   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
5727   GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
5728                       &my_full_id.hashPubKey);
5729   myid = GNUNET_PEER_intern (&my_full_id);
5730
5731 //   transport_handle = GNUNET_TRANSPORT_connect(c,
5732 //                                               &my_full_id,
5733 //                                               NULL,
5734 //                                               NULL,
5735 //                                               NULL,
5736 //                                               NULL);
5737
5738   dht_handle = GNUNET_DHT_connect (c, 64);
5739   if (dht_handle == NULL)
5740   {
5741     GNUNET_break (0);
5742   }
5743
5744   next_tid = 0;
5745   next_local_tid = GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
5746
5747   tunnels = GNUNET_CONTAINER_multihashmap_create (32);
5748   incoming_tunnels = GNUNET_CONTAINER_multihashmap_create (32);
5749   peers = GNUNET_CONTAINER_multihashmap_create (32);
5750   applications = GNUNET_CONTAINER_multihashmap_create (32);
5751   types = GNUNET_CONTAINER_multihashmap_create (32);
5752
5753   GNUNET_SERVER_add_handlers (server_handle, client_handlers);
5754   nc = GNUNET_SERVER_notification_context_create (server_handle,
5755                                                   LOCAL_QUEUE_SIZE);
5756   GNUNET_SERVER_disconnect_notify (server_handle,
5757                                    &handle_local_client_disconnect, NULL);
5758
5759
5760   clients = NULL;
5761   clients_tail = NULL;
5762   next_client_id = 0;
5763
5764   announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
5765   announce_id_task = GNUNET_SCHEDULER_add_now (&announce_id, cls);
5766
5767   /* Create a peer_info for the local peer */
5768   peer = peer_info_get (&my_full_id);
5769   p = path_new (1);
5770   p->peers[0] = myid;
5771   GNUNET_PEER_change_rc (myid, 1);
5772   peer_info_add_path (peer, p, GNUNET_YES);
5773
5774   /* Scheduled the task to clean up when shutdown is called */
5775   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
5776                                 NULL);
5777
5778   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "end of run()\n");
5779 }
5780
5781 /**
5782  * The main function for the mesh service.
5783  *
5784  * @param argc number of arguments from the command line
5785  * @param argv command line arguments
5786  * @return 0 ok, 1 on error
5787  */
5788 int
5789 main (int argc, char *const *argv)
5790 {
5791   int ret;
5792
5793   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main()\n");
5794   ret =
5795       (GNUNET_OK ==
5796        GNUNET_SERVICE_run (argc, argv, "mesh", GNUNET_SERVICE_OPTION_NONE, &run,
5797                            NULL)) ? 0 : 1;
5798   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main() END\n");
5799
5800   return ret;
5801 }