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