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