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