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