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