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