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