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