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