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