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