- more info on multicast fc
[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     mcast = (struct GNUNET_MESH_Multicast *) mdata->data;
3347     if (t->fwd_queue_n >= t->fwd_queue_max)
3348     {
3349       GNUNET_break (0);
3350       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  queue full!\n");
3351       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3352                   "  message from %s!\n",
3353                   GNUNET_i2s(&mcast->oid));
3354       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3355                   "  message at %s!\n",
3356                   GNUNET_i2s(&my_full_id));
3357       GNUNET_free (mdata->data);
3358       GNUNET_free (mdata->reference_counter);
3359       GNUNET_free (mdata);
3360       return;
3361     }
3362     t->fwd_queue_n++;
3363     mcast->ttl = htonl (ntohl (mcast->ttl) - 1);
3364     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  data packet, ttl: %u\n",
3365                 ntohl (mcast->ttl));
3366   }
3367   else
3368   {
3369     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  not a data packet, no ttl\n");
3370   }
3371   if (NULL != t->owner &&
3372       GNUNET_YES != t->owner->shutting_down &&
3373       GNUNET_NO == internal)
3374   {
3375     mdata->task = GNUNET_malloc (sizeof (GNUNET_SCHEDULER_TaskIdentifier));
3376     (*(mdata->task)) =
3377         GNUNET_SCHEDULER_add_delayed (unacknowledged_wait_time, &client_allow_send,
3378                                       mdata);
3379     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "timeout task %u\n",
3380                 *(mdata->task));
3381   }
3382
3383   tree_iterate_children (t->tree, &tunnel_send_multicast_iterator, mdata);
3384   if (*(mdata->reference_counter) == 0)
3385   {
3386     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3387               "  no one to send data to\n");
3388     GNUNET_free (mdata->data);
3389     GNUNET_free (mdata->reference_counter);
3390     if (NULL != mdata->task)
3391     {
3392       GNUNET_SCHEDULER_cancel(*(mdata->task));
3393       GNUNET_free (mdata->task);
3394       GNUNET_SERVER_receive_done (t->owner->handle, GNUNET_OK);
3395     }
3396     GNUNET_free (mdata);
3397     t->fwd_queue_n--;
3398   }
3399   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3400               " sending a multicast packet done\n");
3401   return;
3402 }
3403
3404
3405 /**
3406  * Increase the SKIP value of all peers that
3407  * have not received a unicast message.
3408  *
3409  * @param cls Closure (ID of the peer that HAS received the message).
3410  * @param key ID of the neighbor.
3411  * @param value Information about the neighbor.
3412  *
3413  * @return GNUNET_YES to keep iterating.
3414  */
3415 static int
3416 tunnel_add_skip (void *cls,
3417                  const struct GNUNET_HashCode * key,
3418                  void *value)
3419 {
3420   struct GNUNET_PeerIdentity *neighbor = cls;
3421   struct MeshTunnelChildInfo *cinfo = value;
3422
3423   /* TODO compare only pointers? key == neighbor? */
3424   if (0 == memcmp (&neighbor->hashPubKey, key, sizeof (struct GNUNET_HashCode)))
3425   {
3426     return GNUNET_YES;
3427   }
3428   cinfo->skip++;
3429   return GNUNET_YES;
3430 }
3431
3432
3433 /**
3434  * @brief Get neighbor's Flow Control information.
3435  *
3436  * Retrieves the MeshTunnelChildInfo containing Flow Control data about a direct
3437  * descendant of the local node in a certain tunnel.
3438  * If the info is not yet there (recently created path), creates the data struct
3439  * and inserts it into the tunnel info, initialized to the current tunnel ACK
3440  * values.
3441  *
3442  * @param t Tunnel related.
3443  * @param peer Neighbor whose Flow Control info is needed.
3444  *
3445  * @return Neighbor's Flow Control info.
3446  */
3447 static struct MeshTunnelChildInfo *
3448 tunnel_get_neighbor_fc (const struct MeshTunnel *t,
3449                         const struct GNUNET_PeerIdentity *peer)
3450 {
3451   struct MeshTunnelChildInfo *cinfo;
3452   cinfo = GNUNET_CONTAINER_multihashmap_get (t->children_fc,
3453                                              &peer->hashPubKey);
3454   if (NULL == cinfo)
3455   {
3456     uint32_t delta;
3457
3458     cinfo = GNUNET_malloc (sizeof (struct MeshTunnelChildInfo));
3459     cinfo->id = GNUNET_PEER_intern (peer);
3460     cinfo->skip = t->fwd_pid;
3461
3462     delta = t->nobuffer ? 1 : INITIAL_WINDOW_SIZE - 1;
3463     cinfo->fwd_ack = t->fwd_pid + delta;
3464     cinfo->bck_ack = delta;
3465
3466     cinfo->send_buffer =
3467         GNUNET_malloc (sizeof(struct MeshPeerQueue *) * t->fwd_queue_max);
3468
3469     GNUNET_assert (GNUNET_OK ==
3470       GNUNET_CONTAINER_multihashmap_put (t->children_fc,
3471                                          &peer->hashPubKey,
3472                                          cinfo,
3473                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
3474   }
3475   return cinfo;
3476 }
3477
3478
3479 /**
3480  * Get the Flow Control info of a client.
3481  * 
3482  * @param t Tunnel on which to look.
3483  * @param c Client whose ACK to get.
3484  * 
3485  * @return ACK value.
3486  */
3487 static struct MeshTunnelClientInfo *
3488 tunnel_get_client_fc (struct MeshTunnel *t,
3489                       struct MeshClient *c)
3490 {
3491   unsigned int i;
3492
3493   for (i = 0; i < t->nclients; i++)
3494   {
3495     if (t->clients[i] != c)
3496       continue;
3497     return &t->clients_fc[i];
3498   }
3499   GNUNET_assert (0);
3500   return NULL; // avoid compiler / coverity complaints
3501 }
3502
3503
3504 /**
3505  * Iterator to get the appropiate ACK value from all children nodes.
3506  *
3507  * @param cls Closue (tunnel).
3508  * @param id Id of the child node.
3509  */
3510 static void
3511 tunnel_get_child_fwd_ack (void *cls,
3512                           GNUNET_PEER_Id id)
3513 {
3514   struct GNUNET_PeerIdentity peer_id;
3515   struct MeshTunnelChildInfo *cinfo;
3516   struct MeshTunnelChildIteratorContext *ctx = cls;
3517   struct MeshTunnel *t = ctx->t;
3518   uint32_t ack;
3519
3520   GNUNET_PEER_resolve (id, &peer_id);
3521   cinfo = tunnel_get_neighbor_fc (t, &peer_id);
3522   ack = cinfo->fwd_ack;
3523
3524   ctx->nchildren++;
3525   if (GNUNET_NO == ctx->init)
3526   {
3527     ctx->max_child_ack = ack;
3528     ctx->init = GNUNET_YES;
3529   }
3530
3531   if (GNUNET_YES == t->speed_min)
3532   {
3533     ctx->max_child_ack = ctx->max_child_ack > ack ? ack : ctx->max_child_ack;
3534   }
3535   else
3536   {
3537     ctx->max_child_ack = ctx->max_child_ack > ack ? ctx->max_child_ack : ack;
3538   }
3539
3540 }
3541
3542
3543 /**
3544  * Get the maximum PID allowed to transmit to any
3545  * tunnel child of the local peer, depending on the tunnel
3546  * buffering/speed settings.
3547  *
3548  * @param t Tunnel.
3549  *
3550  * @return Maximum PID allowed (uint32 MAX), -1 if node has no children.
3551  */
3552 static int64_t
3553 tunnel_get_children_fwd_ack (struct MeshTunnel *t)
3554 {
3555   struct MeshTunnelChildIteratorContext ctx;
3556   ctx.t = t;
3557   ctx.max_child_ack = 0;
3558   ctx.nchildren = 0;
3559   tree_iterate_children (t->tree, tunnel_get_child_fwd_ack, &ctx);
3560
3561   if (0 == ctx.nchildren)
3562   {
3563     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3564             "  tunnel has no children, no FWD ACK\n");
3565     return -1LL;
3566   }
3567
3568   if (GNUNET_YES == t->nobuffer && GMC_is_pid_bigger(ctx.max_child_ack, t->fwd_pid))
3569     ctx.max_child_ack = t->fwd_pid + 1; // Might overflow, it's ok.
3570
3571   return (int64_t) ctx.max_child_ack;
3572 }
3573
3574
3575 /**
3576  * Set the FWD ACK value of a client in a particular tunnel.
3577  * 
3578  * @param t Tunnel affected.
3579  * @param c Client whose ACK to set.
3580  * @param ack ACK value.
3581  */
3582 static void
3583 tunnel_set_client_fwd_ack (struct MeshTunnel *t,
3584                            struct MeshClient *c, 
3585                            uint32_t ack)
3586 {
3587   unsigned int i;
3588
3589   for (i = 0; i < t->nclients; i++)
3590   {
3591     if (t->clients[i] != c)
3592       continue;
3593     t->clients_fc[i].fwd_ack = ack;
3594     return;
3595   }
3596   GNUNET_break (0);
3597 }
3598
3599
3600 /**
3601  * Get the highest ACK value of all clients in a particular tunnel,
3602  * according to the buffering/speed settings.
3603  * 
3604  * @param t Tunnel on which to look.
3605  * 
3606  * @return Corresponding ACK value (max uint32_t).
3607  *         If no clients are suscribed, -1.
3608  */
3609 static int64_t
3610 tunnel_get_clients_fwd_ack (struct MeshTunnel *t)
3611 {
3612   unsigned int i;
3613   int64_t ack;
3614
3615   if (0 == t->nclients)
3616   {
3617     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3618                 "  tunnel has no clients, no FWD ACK\n");
3619     return -1LL;
3620   }
3621
3622   for (ack = -1, i = 0; i < t->nclients; i++)
3623   {
3624     if (-1 == ack ||
3625         (GNUNET_YES == t->speed_min &&
3626          GNUNET_YES == GMC_is_pid_bigger (ack, t->clients_fc[i].fwd_ack)) ||
3627         (GNUNET_NO == t->speed_min &&
3628          GNUNET_YES == GMC_is_pid_bigger (t->clients_fc[i].fwd_ack, ack)))
3629     {
3630       ack = t->clients_fc[i].fwd_ack;
3631     }
3632   }
3633
3634   if (GNUNET_YES == t->nobuffer && GMC_is_pid_bigger(ack, t->fwd_pid))
3635     ack = (uint32_t) t->fwd_pid + 1; // Might overflow, it's ok.
3636
3637   return (uint32_t) ack;
3638 }
3639
3640
3641 /**
3642  * Get the current fwd ack value for a tunnel, taking in account the tunnel
3643  * mode and the status of all children nodes.
3644  *
3645  * @param t Tunnel.
3646  *
3647  * @return Maximum PID allowed.
3648  */
3649 static uint32_t
3650 tunnel_get_fwd_ack (struct MeshTunnel *t)
3651 {
3652   uint32_t count;
3653   uint32_t buffer_free;
3654   int64_t child_ack;
3655   int64_t client_ack;
3656   uint32_t ack;
3657
3658   count = t->fwd_pid - t->skip;
3659   buffer_free = t->fwd_queue_max - t->fwd_queue_n;
3660   ack = count + buffer_free; // Might overflow 32 bits, it's ok!
3661   child_ack = tunnel_get_children_fwd_ack (t);
3662   client_ack = tunnel_get_clients_fwd_ack (t);
3663   if (-1 == child_ack)
3664   {
3665     // Node has no children, child_ack AND core buffer are irrelevant.
3666     GNUNET_break (-1 != client_ack); // No children AND no clients? Not good!
3667     return (uint32_t) client_ack;
3668   }
3669
3670   if (GNUNET_YES == t->speed_min)
3671   {
3672     ack = GMC_min_pid ((uint32_t) child_ack, ack);
3673     ack = GMC_min_pid ((uint32_t) client_ack, ack);
3674   }
3675   else
3676   {
3677     ack = GMC_max_pid ((uint32_t) child_ack, ack);
3678     ack = GMC_max_pid ((uint32_t) client_ack, ack);
3679   }
3680   if (GNUNET_YES == t->nobuffer && GMC_is_pid_bigger(ack, t->fwd_pid))
3681     ack = t->fwd_pid + 1; // Might overflow 32 bits, it's ok!
3682   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "c %u, bf %u, ch %u, cl %u, ACK: %u\n",
3683               count, buffer_free, child_ack, client_ack, ack);
3684   return ack;
3685 }
3686
3687
3688 /**
3689  * Build a local ACK message and send it to a local client.
3690  * 
3691  * @param t Tunnel on which to send the ACK.
3692  * @param c Client to whom send the ACK.
3693  * @param ack Value of the ACK.
3694  */
3695 static void
3696 send_local_ack (struct MeshTunnel *t, struct MeshClient *c, uint32_t ack)
3697 {
3698   struct GNUNET_MESH_LocalAck msg;
3699
3700   msg.header.size = htons (sizeof (msg));
3701   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
3702   msg.tunnel_id = htonl (t->owner == c ? t->local_tid : t->local_tid_dest);
3703   msg.max_pid = htonl (ack); 
3704   GNUNET_SERVER_notification_context_unicast(nc,
3705                                               c->handle,
3706                                               &msg.header,
3707                                               GNUNET_NO);
3708 }
3709
3710 /**
3711  * Build an ACK message and queue it to send to the given peer.
3712  * 
3713  * @param t Tunnel on which to send the ACK.
3714  * @param peer Peer to whom send the ACK.
3715  * @param ack Value of the ACK.
3716  */
3717 static void
3718 send_ack (struct MeshTunnel *t, struct GNUNET_PeerIdentity *peer,  uint32_t ack)
3719 {
3720   struct GNUNET_MESH_ACK msg;
3721
3722   GNUNET_PEER_resolve (t->id.oid, &msg.oid);
3723   msg.header.size = htons (sizeof (msg));
3724   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_ACK);
3725   msg.pid = htonl (ack);
3726   msg.tid = htonl (t->id.tid);
3727
3728   send_message (&msg.header, peer, t);
3729 }
3730
3731
3732 /**
3733  * Notify a the owner of a tunnel about how many more
3734  * payload packages will we accept on a given tunnel.
3735  *
3736  * @param t Tunnel on which to send the ACK.
3737  */
3738 static void
3739 tunnel_send_client_fwd_ack (struct MeshTunnel *t)
3740 {
3741   uint32_t ack;
3742
3743   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3744               "Sending client FWD ACK on tunnel %X\n",
3745               t->local_tid);
3746
3747   ack = tunnel_get_fwd_ack (t);
3748
3749   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ack %u\n", ack);
3750   if (t->last_fwd_ack == ack)
3751     return;
3752
3753   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " sending!\n");
3754   t->last_fwd_ack = ack;
3755   send_local_ack (t, t->owner, ack);
3756 }
3757
3758
3759 /**
3760  * Send an ACK informing the predecessor about the available buffer space.
3761  * In case there is no predecessor, inform the owning client.
3762  * If buffering is off, send only on behalf of children or self if endpoint.
3763  * If buffering is on, send when sent to children and buffer space is free.
3764  * Note that although the name is fwd_ack, the FWD mean forward *traffic*,
3765  * the ACK itself goes "back" (towards root).
3766  * 
3767  * @param t Tunnel on which to send the ACK.
3768  * @param type Type of message that triggered the ACK transmission.
3769  */
3770 static void
3771 tunnel_send_fwd_ack (struct MeshTunnel *t, uint16_t type)
3772 {
3773   struct GNUNET_PeerIdentity id;
3774   uint32_t ack;
3775
3776   if (NULL != t->owner)
3777   {
3778     tunnel_send_client_fwd_ack (t);
3779     return;
3780   }
3781   /* Is it after unicast / multicast retransmission? */
3782   switch (type)
3783   {
3784     case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
3785     case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
3786       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3787                   "ACK due to FWD DATA retransmission\n");
3788       if (GNUNET_YES == t->nobuffer)
3789       {
3790         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending ACK, nobuffer\n");
3791         return;
3792       }
3793       if (t->fwd_queue_max > t->fwd_queue_n * 2 &&
3794           GMC_is_pid_bigger(t->last_fwd_ack, t->fwd_pid))
3795       {
3796         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending ACK, buffer free\n");
3797         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3798                     "  t->qmax: %u, t->qn: %u\n",
3799                     t->fwd_queue_max, t->fwd_queue_n);
3800         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3801                     "  t->pid: %u, t->ack: %u\n",
3802                     t->fwd_pid, t->last_fwd_ack);
3803         return;
3804       }
3805       break;
3806     case GNUNET_MESSAGE_TYPE_MESH_ACK:
3807     case GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK:
3808       break;
3809     default:
3810       GNUNET_break (0);
3811   }
3812
3813   /* Ok, ACK might be necessary, what PID to ACK? */
3814   ack = tunnel_get_fwd_ack (t);
3815
3816   /* If speed_min and not all children have ack'd, dont send yet */
3817   if (ack == t->last_fwd_ack)
3818   {
3819     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending FWD ACK, not ready\n");
3820     return;
3821   }
3822
3823   t->last_fwd_ack = ack;
3824   GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &id);
3825   send_ack (t, &id, ack);
3826 }
3827
3828
3829 /**
3830  * Iterator to send a child node a BCK ACK to allow him to send more
3831  * to_origin data.
3832  *
3833  * @param cls Closure (tunnel).
3834  * @param id Id of the child node.
3835  */
3836 static void
3837 tunnel_send_child_bck_ack (void *cls,
3838                            GNUNET_PEER_Id id)
3839 {
3840   struct MeshTunnel *t = cls;
3841   struct MeshTunnelChildInfo *cinfo;
3842   struct GNUNET_PeerIdentity peer;
3843
3844   GNUNET_PEER_resolve (id, &peer);
3845   cinfo = tunnel_get_neighbor_fc (t, &peer);
3846
3847   if (cinfo->bck_ack != cinfo->pid &&
3848       GNUNET_NO == GMC_is_pid_bigger (cinfo->bck_ack, cinfo->pid))
3849     return;
3850
3851   cinfo->bck_ack++;
3852   send_ack (t, &peer, cinfo->bck_ack);
3853 }
3854
3855
3856 /**
3857  * @brief Send BCK ACKs to clients to allow them more to_origin traffic
3858  * 
3859  * Iterates over all clients and sends BCK ACKs to the ones that need it.
3860  * 
3861  * @param t Tunnel on which to send the BCK ACKs.
3862  */
3863 static void
3864 tunnel_send_clients_bck_ack (struct MeshTunnel *t)
3865 {
3866   unsigned int i;
3867   unsigned int tunnel_delta;
3868
3869   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Sending BCK ACK to clients\n");
3870
3871   tunnel_delta = t->bck_ack - t->bck_pid;
3872   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   tunnel delta: %u\n", tunnel_delta);
3873
3874   /* Find client whom to allow to send to origin (with lowest buffer space) */
3875   for (i = 0; i < t->nclients; i++)
3876   {
3877     struct MeshTunnelClientInfo *clinfo;
3878     unsigned int delta;
3879
3880     clinfo = &t->clients_fc[i];
3881     delta = clinfo->bck_ack - clinfo->bck_pid;
3882     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    client %u delta: %u\n",
3883          t->clients[i]->id, delta);
3884
3885     if ((GNUNET_NO == t->nobuffer && tunnel_delta > delta) ||
3886         (GNUNET_YES == t->nobuffer && 0 == delta))
3887     {
3888       uint32_t ack;
3889
3890       ack = clinfo->bck_pid;
3891       ack += t->nobuffer ? 1 : tunnel_delta;
3892       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3893                   "    sending ack to client %u: %u\n",
3894                   t->clients[i]->id, ack);
3895       send_local_ack (t, t->clients[i], ack);
3896       clinfo->bck_ack = ack;
3897     }
3898   }
3899 }
3900
3901
3902 /**
3903  * Send an ACK informing the children nodes and destination clients about
3904  * the available buffer space.
3905  * If buffering is off, send only on behalf of root (can be self).
3906  * If buffering is on, send when sent to predecessor and buffer space is free.
3907  * Note that although the name is bck_ack, the BCK mean backwards *traffic*,
3908  * the ACK itself goes "forward" (towards children/clients).
3909  * 
3910  * @param t Tunnel on which to send the ACK.
3911  * @param type Type of message that triggered the ACK transmission.
3912  */
3913 static void
3914 tunnel_send_bck_ack (struct MeshTunnel *t, uint16_t type)
3915 {
3916   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3917               "Sending BCK ACK on tunnel %u [%u] due to %s\n",
3918               t->id.oid, t->id.tid, GNUNET_MESH_DEBUG_M2S(type));
3919   /* Is it after data to_origin retransmission? */
3920   switch (type)
3921   {
3922     case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
3923       if (GNUNET_YES == t->nobuffer)
3924       {
3925         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3926                     "    Not sending ACK, nobuffer\n");
3927         return;
3928       }
3929       break;
3930     case GNUNET_MESSAGE_TYPE_MESH_ACK:
3931     case GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK:
3932       break;
3933     default:
3934       GNUNET_break (0);
3935   }
3936
3937   tunnel_send_clients_bck_ack (t);
3938   tree_iterate_children (t->tree, &tunnel_send_child_bck_ack, t);
3939 }
3940
3941
3942 /**
3943  * @brief Re-initiate traffic to this peer if necessary.
3944  *
3945  * Check if there is traffic queued towards this peer
3946  * and the core transmit handle is NULL (traffic was stalled).
3947  * If so, call core tmt rdy.
3948  *
3949  * @param cls Closure (unused)
3950  * @param peer_id Short ID of peer to which initiate traffic.
3951  */
3952 static void
3953 peer_unlock_queue(void *cls, GNUNET_PEER_Id peer_id)
3954 {
3955   struct MeshPeerInfo *peer;
3956   struct GNUNET_PeerIdentity id;
3957   struct MeshPeerQueue *q;
3958   size_t size;
3959
3960   peer = peer_info_get_short(peer_id);
3961   if (NULL != peer->core_transmit)
3962     return;
3963
3964   q = queue_get_next(peer);
3965   if (NULL == q)
3966   {
3967     /* Might br multicast traffic already sent to this particular peer but
3968      * not to other children in this tunnel.
3969      * This way t->queue_n would be > 0 but the queue of this particular peer
3970      * would be empty.
3971      */
3972     return;
3973   }
3974   size = q->size;
3975   GNUNET_PEER_resolve (peer->id, &id);
3976   peer->core_transmit =
3977         GNUNET_CORE_notify_transmit_ready(core_handle,
3978                                           0,
3979                                           0,
3980                                           GNUNET_TIME_UNIT_FOREVER_REL,
3981                                           &id,
3982                                           size,
3983                                           &queue_send,
3984                                           peer);
3985         return;
3986 }
3987
3988
3989 /**
3990  * @brief Allow transmission of FWD traffic on this tunnel
3991  *
3992  * Check if there is traffic queued towards any children
3993  * and the core transmit handle is NULL, and if so, call core tmt rdy.
3994  *
3995  * @param t Tunnel on which to unlock FWD traffic.
3996  */
3997 static void
3998 tunnel_unlock_fwd_queues (struct MeshTunnel *t)
3999 {
4000   if (0 == t->fwd_queue_n)
4001     return;
4002
4003   tree_iterate_children (t->tree, &peer_unlock_queue, NULL);
4004 }
4005
4006
4007 /**
4008  * @brief Allow transmission of BCK traffic on this tunnel
4009  *
4010  * Check if there is traffic queued towards the root of the tree
4011  * and the core transmit handle is NULL, and if so, call core tmt rdy.
4012  *
4013  * @param t Tunnel on which to unlock BCK traffic.
4014  */
4015 static void
4016 tunnel_unlock_bck_queue (struct MeshTunnel *t)
4017 {
4018   if (0 == t->bck_queue_n)
4019     return;
4020
4021   peer_unlock_queue(NULL, tree_get_predecessor(t->tree));
4022 }
4023
4024
4025 /**
4026  * Send a message to all peers in this tunnel that the tunnel is no longer
4027  * valid.
4028  *
4029  * @param t The tunnel whose peers to notify.
4030  */
4031 static void
4032 tunnel_send_destroy (struct MeshTunnel *t)
4033 {
4034   struct GNUNET_MESH_TunnelDestroy msg;
4035
4036   msg.header.size = htons (sizeof (msg));
4037   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY);
4038   GNUNET_PEER_resolve (t->id.oid, &msg.oid);
4039   msg.tid = htonl (t->id.tid);
4040   tunnel_send_multicast (t, &msg.header, GNUNET_NO);
4041 }
4042
4043
4044 /**
4045  * Cancel all transmissions towards a neighbor that belong to a certain tunnel.
4046  *
4047  * @param cls Closure (Tunnel which to cancel).
4048  * @param neighbor_id Short ID of the neighbor to whom cancel the transmissions.
4049  */
4050 static void
4051 tunnel_cancel_queues (void *cls, GNUNET_PEER_Id neighbor_id)
4052 {
4053   struct MeshTunnel *t = cls;
4054   struct MeshPeerInfo *peer_info;
4055   struct MeshPeerQueue *pq;
4056   struct MeshPeerQueue *next;
4057
4058   peer_info = peer_info_get_short (neighbor_id);
4059   for (pq = peer_info->queue_head; NULL != pq; pq = next)
4060   {
4061     next = pq->next;
4062     if (pq->tunnel == t)
4063     {
4064       if (GNUNET_MESSAGE_TYPE_MESH_MULTICAST == pq->type ||
4065           GNUNET_MESSAGE_TYPE_MESH_UNICAST == pq->type ||
4066           GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN == pq->type)
4067       {
4068         // Should have been removed on destroy children
4069         GNUNET_break (0);
4070       }
4071       queue_destroy (pq, GNUNET_YES);
4072     }
4073   }
4074   if (NULL == peer_info->queue_head && NULL != peer_info->core_transmit)
4075   {
4076     GNUNET_CORE_notify_transmit_ready_cancel(peer_info->core_transmit);
4077     peer_info->core_transmit = NULL;
4078   }
4079 }
4080
4081 /**
4082  * Destroy the tunnel and free any allocated resources linked to it.
4083  *
4084  * @param t the tunnel to destroy
4085  *
4086  * @return GNUNET_OK on success
4087  */
4088 static int
4089 tunnel_destroy (struct MeshTunnel *t)
4090 {
4091   struct MeshClient *c;
4092   struct GNUNET_HashCode hash;
4093   unsigned int i;
4094   int r;
4095
4096   if (NULL == t)
4097     return GNUNET_OK;
4098
4099   r = GNUNET_OK;
4100   c = t->owner;
4101 #if MESH_DEBUG
4102   {
4103     struct GNUNET_PeerIdentity id;
4104
4105     GNUNET_PEER_resolve (t->id.oid, &id);
4106     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s [%x]\n",
4107                 GNUNET_i2s (&id), t->id.tid);
4108     if (NULL != c)
4109       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
4110   }
4111 #endif
4112
4113   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
4114   if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_remove (tunnels, &hash, t))
4115   {
4116     r = GNUNET_SYSERR;
4117   }
4118
4119   GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
4120   if (NULL != c &&
4121       GNUNET_YES !=
4122       GNUNET_CONTAINER_multihashmap_remove (c->own_tunnels, &hash, t))
4123   {
4124     r = GNUNET_SYSERR;
4125   }
4126   GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
4127   for (i = 0; i < t->nclients; i++)
4128   {
4129     c = t->clients[i];
4130     if (GNUNET_YES !=
4131           GNUNET_CONTAINER_multihashmap_remove (c->incoming_tunnels, &hash, t))
4132     {
4133       r = GNUNET_SYSERR;
4134     }
4135   }
4136   for (i = 0; i < t->nignore; i++)
4137   {
4138     c = t->ignore[i];
4139     if (GNUNET_YES !=
4140           GNUNET_CONTAINER_multihashmap_remove (c->ignore_tunnels, &hash, t))
4141     {
4142       r = GNUNET_SYSERR;
4143     }
4144   }
4145   if (t->nclients > 0)
4146   {
4147     if (GNUNET_YES !=
4148         GNUNET_CONTAINER_multihashmap_remove (incoming_tunnels, &hash, t))
4149     {
4150       r = GNUNET_SYSERR;
4151     }
4152     GNUNET_free (t->clients);
4153   }
4154   if (NULL != t->peers)
4155   {
4156     GNUNET_CONTAINER_multihashmap_iterate (t->peers, &peer_info_delete_tunnel,
4157                                            t);
4158     GNUNET_CONTAINER_multihashmap_destroy (t->peers);
4159   }
4160
4161   GNUNET_CONTAINER_multihashmap_iterate (t->children_fc,
4162                                          &tunnel_destroy_child,
4163                                          t);
4164   GNUNET_CONTAINER_multihashmap_destroy (t->children_fc);
4165
4166   tree_iterate_children (t->tree, &tunnel_cancel_queues, t);
4167
4168   tree_destroy (t->tree);
4169
4170   if (NULL != t->regex_ctx)
4171     regex_cancel_search (t->regex_ctx);
4172   if (NULL != t->dht_get_type)
4173     GNUNET_DHT_get_stop (t->dht_get_type);
4174   if (GNUNET_SCHEDULER_NO_TASK != t->timeout_task)
4175     GNUNET_SCHEDULER_cancel (t->timeout_task);
4176   if (GNUNET_SCHEDULER_NO_TASK != t->path_refresh_task)
4177     GNUNET_SCHEDULER_cancel (t->path_refresh_task);
4178
4179   n_tunnels--;
4180   GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
4181   GNUNET_assert (0 <= n_tunnels);
4182   GNUNET_free (t);
4183   return r;
4184 }
4185
4186
4187 /**
4188  * Create a new tunnel
4189  * 
4190  * @param owner Who is the owner of the tunnel (short ID).
4191  * @param tid Tunnel Number of the tunnel.
4192  * @param client Clients that owns the tunnel, NULL for foreign tunnels.
4193  * @param local Tunnel Number for the tunnel, for the client point of view.
4194  * 
4195  * @return A new initialized tunnel. NULL on error.
4196  */
4197 static struct MeshTunnel *
4198 tunnel_new (GNUNET_PEER_Id owner,
4199             MESH_TunnelNumber tid,
4200             struct MeshClient *client,
4201             MESH_TunnelNumber local)
4202 {
4203   struct MeshTunnel *t;
4204   struct GNUNET_HashCode hash;
4205
4206   if (n_tunnels >= max_tunnels && NULL == client)
4207     return NULL;
4208
4209   t = GNUNET_malloc (sizeof (struct MeshTunnel));
4210   t->id.oid = owner;
4211   t->id.tid = tid;
4212   t->fwd_queue_max = (max_msgs_queue / max_tunnels) + 1;
4213   t->bck_queue_max = t->fwd_queue_max;
4214   t->tree = tree_new (owner);
4215   t->owner = client;
4216   t->fwd_pid = (uint32_t) -1; // Next (expected) = 0
4217   t->bck_pid = (uint32_t) -1; // Next (expected) = 0
4218   t->bck_ack = INITIAL_WINDOW_SIZE - 1;
4219   t->last_fwd_ack = INITIAL_WINDOW_SIZE - 1;
4220   t->local_tid = local;
4221   t->children_fc = GNUNET_CONTAINER_multihashmap_create (8);
4222   n_tunnels++;
4223   GNUNET_STATISTICS_update (stats, "# tunnels", 1, GNUNET_NO);
4224
4225   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
4226   if (GNUNET_OK !=
4227       GNUNET_CONTAINER_multihashmap_put (tunnels, &hash, t,
4228                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
4229   {
4230     GNUNET_break (0);
4231     tunnel_destroy (t);
4232     if (NULL != client)
4233     {
4234       GNUNET_break (0);
4235       GNUNET_SERVER_receive_done (client->handle, GNUNET_SYSERR);
4236     }
4237     return NULL;
4238   }
4239
4240   if (NULL != client)
4241   {
4242     GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
4243     if (GNUNET_OK !=
4244         GNUNET_CONTAINER_multihashmap_put (client->own_tunnels, &hash, t,
4245                                           GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
4246     {
4247       tunnel_destroy (t);
4248       GNUNET_break (0);
4249       GNUNET_SERVER_receive_done (client->handle, GNUNET_SYSERR);
4250       return NULL;
4251     }
4252   }
4253
4254   return t;
4255 }
4256
4257
4258 /**
4259  * Removes an explicit path from a tunnel, freeing all intermediate nodes
4260  * that are no longer needed, as well as nodes of no longer reachable peers.
4261  * The tunnel itself is also destoyed if results in a remote empty tunnel.
4262  *
4263  * @param t Tunnel from which to remove the path.
4264  * @param peer Short id of the peer which should be removed.
4265  */
4266 static void
4267 tunnel_delete_peer (struct MeshTunnel *t, GNUNET_PEER_Id peer)
4268 {
4269   if (GNUNET_NO == tree_del_peer (t->tree, peer, NULL, NULL))
4270     tunnel_destroy (t);
4271 }
4272
4273
4274 /**
4275  * tunnel_destroy_iterator: iterator for deleting each tunnel that belongs to a
4276  * client when the client disconnects. If the client is not the owner, the
4277  * owner will get notified if no more clients are in the tunnel and the client
4278  * get removed from the tunnel's list.
4279  *
4280  * @param cls closure (client that is disconnecting)
4281  * @param key the hash of the local tunnel id (used to access the hashmap)
4282  * @param value the value stored at the key (tunnel to destroy)
4283  *
4284  * @return GNUNET_OK on success
4285  */
4286 static int
4287 tunnel_destroy_iterator (void *cls, const struct GNUNET_HashCode * key, void *value)
4288 {
4289   struct MeshTunnel *t = value;
4290   struct MeshClient *c = cls;
4291   int r;
4292
4293   send_client_tunnel_disconnect(t, c);
4294   if (c != t->owner)
4295   {
4296     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4297                 "Client %u is destination, keeping the tunnel alive.\n", c->id);
4298     tunnel_delete_client(t, c);
4299     client_delete_tunnel(c, t);
4300     return GNUNET_OK;
4301   }
4302   tunnel_send_destroy(t);
4303   r = tunnel_destroy (t);
4304   return r;
4305 }
4306
4307
4308 /**
4309  * Timeout function, destroys tunnel if called
4310  *
4311  * @param cls Closure (tunnel to destroy).
4312  * @param tc TaskContext
4313  */
4314 static void
4315 tunnel_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4316 {
4317   struct MeshTunnel *t = cls;
4318
4319   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
4320     return;
4321   t->timeout_task = GNUNET_SCHEDULER_NO_TASK;
4322   tunnel_destroy (t);
4323 }
4324
4325 /**
4326  * Resets the tunnel timeout. Starts it if no timeout was running.
4327  *
4328  * @param t Tunnel whose timeout to reset.
4329  *
4330  * TODO use heap to improve efficiency of scheduler.
4331  */
4332 static void
4333 tunnel_reset_timeout (struct MeshTunnel *t)
4334 {
4335   if (GNUNET_SCHEDULER_NO_TASK != t->timeout_task)
4336     GNUNET_SCHEDULER_cancel (t->timeout_task);
4337   t->timeout_task =
4338       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
4339                                     (refresh_path_time, 4), &tunnel_timeout, t);
4340 }
4341
4342
4343 /******************************************************************************/
4344 /****************      MESH NETWORK HANDLER HELPERS     ***********************/
4345 /******************************************************************************/
4346
4347 /**
4348  * Function to send a create path packet to a peer.
4349  *
4350  * @param cls closure
4351  * @param size number of bytes available in buf
4352  * @param buf where the callee should write the message
4353  * @return number of bytes written to buf
4354  */
4355 static size_t
4356 send_core_path_create (void *cls, size_t size, void *buf)
4357 {
4358   struct MeshPathInfo *info = cls;
4359   struct GNUNET_MESH_ManipulatePath *msg;
4360   struct GNUNET_PeerIdentity *peer_ptr;
4361   struct MeshTunnel *t = info->t;
4362   struct MeshPeerPath *p = info->path;
4363   size_t size_needed;
4364   uint32_t opt;
4365   int i;
4366
4367   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CREATE PATH sending...\n");
4368   size_needed =
4369       sizeof (struct GNUNET_MESH_ManipulatePath) +
4370       p->length * sizeof (struct GNUNET_PeerIdentity);
4371
4372   if (size < size_needed || NULL == buf)
4373   {
4374     GNUNET_break (0);
4375     return 0;
4376   }
4377   msg = (struct GNUNET_MESH_ManipulatePath *) buf;
4378   msg->header.size = htons (size_needed);
4379   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE);
4380   msg->tid = ntohl (t->id.tid);
4381
4382   if (GNUNET_YES == t->speed_min)
4383     opt = MESH_TUNNEL_OPT_SPEED_MIN;
4384   if (GNUNET_YES == t->nobuffer)
4385     opt |= MESH_TUNNEL_OPT_NOBUFFER;
4386   msg->opt = htonl(opt);
4387
4388   peer_ptr = (struct GNUNET_PeerIdentity *) &msg[1];
4389   for (i = 0; i < p->length; i++)
4390   {
4391     GNUNET_PEER_resolve (p->peers[i], peer_ptr++);
4392   }
4393
4394   path_destroy (p);
4395   GNUNET_free (info);
4396
4397   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4398               "CREATE PATH (%u bytes long) sent!\n", size_needed);
4399   return size_needed;
4400 }
4401
4402
4403 /**
4404  * Fill the core buffer 
4405  *
4406  * @param cls closure (data itself)
4407  * @param size number of bytes available in buf
4408  * @param buf where the callee should write the message
4409  *
4410  * @return number of bytes written to buf
4411  */
4412 static size_t
4413 send_core_data_multicast (void *cls, size_t size, void *buf)
4414 {
4415   struct MeshTransmissionDescriptor *info = cls;
4416   size_t total_size;
4417
4418   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Multicast callback.\n");
4419   GNUNET_assert (NULL != info);
4420   GNUNET_assert (NULL != info->peer);
4421   total_size = info->mesh_data->data_len;
4422   GNUNET_assert (total_size < GNUNET_SERVER_MAX_MESSAGE_SIZE);
4423
4424   if (total_size > size)
4425   {
4426     GNUNET_break (0);
4427     return 0;
4428   }
4429   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " copying data...\n");
4430   memcpy (buf, info->mesh_data->data, total_size);
4431 #if MESH_DEBUG
4432   {
4433     struct GNUNET_MESH_Multicast *mc;
4434     struct GNUNET_MessageHeader *mh;
4435
4436     mh = buf;
4437     if (ntohs (mh->type) == GNUNET_MESSAGE_TYPE_MESH_MULTICAST)
4438     {
4439       mc = (struct GNUNET_MESH_Multicast *) mh;
4440       mh = (struct GNUNET_MessageHeader *) &mc[1];
4441       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4442                   " multicast, payload type %s\n",
4443                   GNUNET_MESH_DEBUG_M2S (ntohs (mh->type)));
4444       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4445                   " multicast, payload size %u\n", ntohs (mh->size));
4446     }
4447     else
4448     {
4449       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " type %s\n",
4450                   GNUNET_MESH_DEBUG_M2S (ntohs (mh->type)));
4451     }
4452   }
4453 #endif
4454   data_descriptor_decrement_rc (info->mesh_data);
4455   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "freeing info...\n");
4456   GNUNET_free (info);
4457   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "return %u\n", total_size);
4458   return total_size;
4459 }
4460
4461
4462 /**
4463  * Creates a path ack message in buf and frees all unused resources.
4464  *
4465  * @param cls closure (MeshTransmissionDescriptor)
4466  * @param size number of bytes available in buf
4467  * @param buf where the callee should write the message
4468  * @return number of bytes written to buf
4469  */
4470 static size_t
4471 send_core_path_ack (void *cls, size_t size, void *buf)
4472 {
4473   struct MeshTransmissionDescriptor *info = cls;
4474   struct GNUNET_MESH_PathACK *msg = buf;
4475
4476   GNUNET_assert (NULL != info);
4477   if (sizeof (struct GNUNET_MESH_PathACK) > size)
4478   {
4479     GNUNET_break (0);
4480     return 0;
4481   }
4482   msg->header.size = htons (sizeof (struct GNUNET_MESH_PathACK));
4483   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_ACK);
4484   GNUNET_PEER_resolve (info->origin->oid, &msg->oid);
4485   msg->tid = htonl (info->origin->tid);
4486   msg->peer_id = my_full_id;
4487
4488   GNUNET_free (info);
4489   /* TODO add signature */
4490
4491   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "PATH ACK sent!\n");
4492   return sizeof (struct GNUNET_MESH_PathACK);
4493 }
4494
4495
4496 /**
4497  * Free a transmission that was already queued with all resources
4498  * associated to the request.
4499  *
4500  * @param queue Queue handler to cancel.
4501  * @param clear_cls Is it necessary to free associated cls?
4502  */
4503 static void
4504 queue_destroy (struct MeshPeerQueue *queue, int clear_cls)
4505 {
4506   struct MeshTransmissionDescriptor *dd;
4507   struct MeshPathInfo *path_info;
4508
4509   if (GNUNET_YES == clear_cls)
4510   {
4511     switch (queue->type)
4512     {
4513     case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
4514     case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
4515     case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
4516         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   type payload\n");
4517         dd = queue->cls;
4518         data_descriptor_decrement_rc (dd->mesh_data);
4519         break;
4520     case GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE:
4521         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   type create path\n");
4522         path_info = queue->cls;
4523         path_destroy (path_info->path);
4524         break;
4525     default:
4526         GNUNET_break (0);
4527         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4528                     "   type %u unknown!\n",
4529                     queue->type);
4530     }
4531     GNUNET_free_non_null (queue->cls);
4532   }
4533   GNUNET_CONTAINER_DLL_remove (queue->peer->queue_head,
4534                                queue->peer->queue_tail,
4535                                queue);
4536   GNUNET_free (queue);
4537 }
4538
4539
4540 /**
4541  * @brief Get the next transmittable message from the queue.
4542  *
4543  * This will be the head, except in the case of being a data packet
4544  * not allowed by the destination peer.
4545  *
4546  * @param peer Destination peer.
4547  *
4548  * @return The next viable MeshPeerQueue element to send to that peer.
4549  *         NULL when there are no transmittable messages.
4550  */
4551 struct MeshPeerQueue *
4552 queue_get_next (const struct MeshPeerInfo *peer)
4553 {
4554   struct MeshPeerQueue *q;
4555   struct MeshTunnel *t;
4556   struct MeshTransmissionDescriptor *info;
4557   struct MeshTunnelChildInfo *cinfo;
4558   struct GNUNET_MESH_Unicast *ucast;
4559   struct GNUNET_MESH_ToOrigin *to_orig;
4560   struct GNUNET_MESH_Multicast *mcast;
4561   struct GNUNET_PeerIdentity id;
4562   uint32_t pid;
4563   uint32_t ack;
4564
4565   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   selecting message\n");
4566   for (q = peer->queue_head; NULL != q; q = q->next)
4567   {
4568     t = q->tunnel;
4569     info = q->cls;
4570     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4571                 "*********     %s\n",
4572                 GNUNET_MESH_DEBUG_M2S(q->type));
4573     switch (q->type)
4574     {
4575       case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
4576         ucast = (struct GNUNET_MESH_Unicast *) info->mesh_data->data;
4577         pid = ntohl (ucast->pid);
4578         GNUNET_PEER_resolve (info->peer->id, &id);
4579         cinfo = tunnel_get_neighbor_fc(t, &id);
4580         ack = cinfo->fwd_ack;
4581         break;
4582       case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
4583         to_orig = (struct GNUNET_MESH_ToOrigin *) info->mesh_data->data;
4584         pid = ntohl (to_orig->pid);
4585         ack = t->bck_ack;
4586         break;
4587       case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
4588         mcast = (struct GNUNET_MESH_Multicast *) info->mesh_data->data;
4589         if (GNUNET_MESSAGE_TYPE_MESH_MULTICAST != ntohs(mcast->header.type)) 
4590         {
4591           // Not a multicast payload: multicast control traffic (destroy, etc)
4592           return q;
4593         }
4594         pid = ntohl (mcast->pid);
4595         GNUNET_PEER_resolve (info->peer->id, &id);
4596         cinfo = tunnel_get_neighbor_fc(t, &id);
4597         ack = cinfo->fwd_ack;
4598         break;
4599       default:
4600         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4601                     "*********   OK!\n");
4602         return q;
4603     }
4604         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4605                     "*********     ACK: %u, PID: %u\n",
4606                     ack, pid);
4607     if (GNUNET_NO == GMC_is_pid_bigger(pid, ack))
4608     {
4609       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4610                   "*********   OK!\n");
4611       return q;
4612     }
4613     else
4614     {
4615       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4616                   "*********     NEXT!\n");
4617     }
4618   }
4619   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4620                 "*********   nothing found\n");
4621   return NULL;
4622 }
4623
4624
4625 /**
4626   * Core callback to write a queued packet to core buffer
4627   *
4628   * @param cls Closure (peer info).
4629   * @param size Number of bytes available in buf.
4630   * @param buf Where the to write the message.
4631   *
4632   * @return number of bytes written to buf
4633   */
4634 static size_t
4635 queue_send (void *cls, size_t size, void *buf)
4636 {
4637     struct MeshPeerInfo *peer = cls;
4638     struct GNUNET_MessageHeader *msg;
4639     struct MeshPeerQueue *queue;
4640     struct MeshTunnel *t;
4641     struct MeshTunnelChildInfo *cinfo;
4642     struct GNUNET_PeerIdentity dst_id;
4643     size_t data_size;
4644
4645     peer->core_transmit = NULL;
4646     
4647     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "********* Queue send\n");
4648     queue = queue_get_next(peer);
4649
4650     /* Queue has no internal mesh traffic not sendable payload */
4651     if (NULL == queue)
4652     {
4653       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   not ready, return\n");
4654       if (NULL == peer->queue_head)
4655         GNUNET_break(0); // Should've been canceled
4656       return 0;
4657     }
4658     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   not empty\n");
4659
4660     GNUNET_PEER_resolve (peer->id, &dst_id);
4661     /* Check if buffer size is enough for the message */
4662     if (queue->size > size)
4663     {
4664
4665
4666         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4667                     "*********   not enough room, reissue\n");
4668         peer->core_transmit =
4669             GNUNET_CORE_notify_transmit_ready(core_handle,
4670                                               0,
4671                                               0,
4672                                               GNUNET_TIME_UNIT_FOREVER_REL,
4673                                               &dst_id,
4674                                               queue->size,
4675                                               &queue_send,
4676                                               peer);
4677         return 0;
4678     }
4679     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   size ok\n");
4680
4681     t = queue->tunnel;
4682     if (GNUNET_MESSAGE_TYPE_MESH_UNICAST == queue->type)
4683     {
4684       t->fwd_queue_n--;
4685       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4686                   "*********   unicast: t->q (%u/%u)\n",
4687                   t->fwd_queue_n, t->fwd_queue_max);
4688     }
4689     else if (GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN == queue->type)
4690     {
4691       t->bck_queue_n--;
4692       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   to origin\n");
4693     }
4694
4695     /* Fill buf */
4696     switch (queue->type)
4697     {
4698       case 0:
4699       case GNUNET_MESSAGE_TYPE_MESH_ACK:
4700       case GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN:
4701       case GNUNET_MESSAGE_TYPE_MESH_PATH_DESTROY:
4702         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4703                     "*********   raw: %s\n",
4704                     GNUNET_MESH_DEBUG_M2S (queue->type));
4705         /* Fall through */
4706       case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
4707       case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
4708         data_size = send_core_data_raw (queue->cls, size, buf);
4709         msg = (struct GNUNET_MessageHeader *) buf;
4710         switch (ntohs (msg->type)) // Type of preconstructed message
4711         {
4712           case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
4713             tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_UNICAST);
4714             break;
4715           case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
4716             tunnel_send_bck_ack(t, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN);
4717             break;
4718           default:
4719               break;
4720         }
4721         break;
4722       case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
4723         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   multicast\n");
4724         data_size = send_core_data_multicast(queue->cls, size, buf);
4725         // FIXME fc substract when? depending on the tunnel conf.
4726         // t->fwd_queue_n--;
4727         tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
4728         break;
4729       case GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE:
4730         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   path create\n");
4731         data_size = send_core_path_create(queue->cls, size, buf);
4732         break;
4733       case GNUNET_MESSAGE_TYPE_MESH_PATH_ACK:
4734         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   path ack\n");
4735         data_size = send_core_path_ack(queue->cls, size, buf);
4736         break;
4737       default:
4738         GNUNET_break (0);
4739         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4740                     "*********   type unknown: %u\n",
4741                     queue->type);
4742         data_size = 0;
4743     }
4744     switch (queue->type)
4745     {
4746       case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
4747       case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
4748       case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
4749         cinfo = tunnel_get_neighbor_fc(t, &dst_id);
4750         if (cinfo->send_buffer[cinfo->send_buffer_start] != queue)
4751         {
4752           GNUNET_break(0);
4753           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4754                       "at pos %u (%p) != %p\n",
4755                       cinfo->send_buffer_start,
4756                       cinfo->send_buffer[cinfo->send_buffer_start],
4757                       queue);
4758         }
4759         GNUNET_break(cinfo->send_buffer_n > 0);
4760         cinfo->send_buffer[cinfo->send_buffer_start] = NULL;
4761         cinfo->send_buffer_n--;
4762         cinfo->send_buffer_start++;
4763         cinfo->send_buffer_start %= t->fwd_queue_max;
4764         break;
4765       default:
4766         break;
4767     }
4768
4769     /* Free queue, but cls was freed by send_core_* */
4770     queue_destroy (queue, GNUNET_NO);
4771
4772     if (GNUNET_YES == t->destroy && 0 == t->fwd_queue_n)
4773     {
4774       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********  destroying tunnel!\n");
4775       tunnel_destroy (t);
4776     }
4777
4778     /* If more data in queue, send next */
4779     if (NULL != peer->queue_head)
4780     {
4781         struct GNUNET_PeerIdentity id;
4782
4783         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   more data!\n");
4784         GNUNET_PEER_resolve (peer->id, &id);
4785         peer->core_transmit =
4786             GNUNET_CORE_notify_transmit_ready(core_handle,
4787                                               0,
4788                                               0,
4789                                               GNUNET_TIME_UNIT_FOREVER_REL,
4790                                               &id,
4791                                               peer->queue_head->size,
4792                                               &queue_send,
4793                                               peer);
4794     }
4795     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   return %d\n", data_size);
4796     return data_size;
4797 }
4798
4799
4800 /**
4801  * Queue and pass message to core when possible.
4802  *
4803  * @param cls Closure (type dependant).
4804  * @param type Type of the message, 0 for a raw message.
4805  * @param size Size of the message.
4806  * @param dst Neighbor to send message to.
4807  * @param t Tunnel this message belongs to.
4808  */
4809 static void
4810 queue_add (void *cls, uint16_t type, size_t size,
4811            struct MeshPeerInfo *dst, struct MeshTunnel *t)
4812 {
4813   struct MeshPeerQueue *queue;
4814   struct MeshTunnelChildInfo *cinfo;
4815   struct GNUNET_PeerIdentity id;
4816   unsigned int *max;
4817   unsigned int *n;
4818   unsigned int i;
4819
4820   n = NULL;
4821   if (GNUNET_MESSAGE_TYPE_MESH_UNICAST == type ||
4822       GNUNET_MESSAGE_TYPE_MESH_MULTICAST == type)
4823   {
4824     n = &t->fwd_queue_n;
4825     max = &t->fwd_queue_max;
4826   }
4827   else if (GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN == type)
4828   {
4829     n = &t->bck_queue_n;
4830     max = &t->bck_queue_max;
4831   }
4832   if (NULL != n) {
4833     if (*n >= *max)
4834     {
4835       if (NULL == t->owner)
4836         GNUNET_break_op(0);       // TODO: kill connection?
4837       else
4838         GNUNET_break(0);
4839       GNUNET_STATISTICS_update(stats, "# messages dropped (buffer full)",
4840                                1, GNUNET_NO);
4841       return;                       // Drop message
4842     }
4843     (*n)++;
4844   }
4845   queue = GNUNET_malloc (sizeof (struct MeshPeerQueue));
4846   queue->cls = cls;
4847   queue->type = type;
4848   queue->size = size;
4849   queue->peer = dst;
4850   queue->tunnel = t;
4851   GNUNET_CONTAINER_DLL_insert_tail (dst->queue_head, dst->queue_tail, queue);
4852   GNUNET_PEER_resolve (dst->id, &id);
4853   if (NULL == dst->core_transmit)
4854   {
4855       dst->core_transmit =
4856           GNUNET_CORE_notify_transmit_ready(core_handle,
4857                                             0,
4858                                             0,
4859                                             GNUNET_TIME_UNIT_FOREVER_REL,
4860                                             &id,
4861                                             size,
4862                                             &queue_send,
4863                                             dst);
4864   }
4865   if (NULL == n) // Is this internal mesh traffic?
4866     return;
4867
4868   // It's payload, keep track of buffer per peer.
4869   cinfo = tunnel_get_neighbor_fc(t, &id);
4870   i = (cinfo->send_buffer_start + cinfo->send_buffer_n) % t->fwd_queue_max;
4871   if (NULL != cinfo->send_buffer[i])
4872   {
4873     GNUNET_break (cinfo->send_buffer_n == t->fwd_queue_max); // aka i == start
4874     queue_destroy(cinfo->send_buffer[cinfo->send_buffer_start], GNUNET_YES);
4875     cinfo->send_buffer_start++;
4876     cinfo->send_buffer_start %= t->fwd_queue_max;
4877     cinfo->send_buffer_n--;
4878   }
4879   cinfo->send_buffer[i] = queue;
4880   cinfo->send_buffer_n++;
4881   if (cinfo->send_buffer_n > t->fwd_queue_max)
4882   {
4883     GNUNET_break (0);
4884     cinfo->send_buffer_n = t->fwd_queue_max;
4885   }
4886 }
4887
4888
4889 /******************************************************************************/
4890 /********************      MESH NETWORK HANDLERS     **************************/
4891 /******************************************************************************/
4892
4893
4894 /**
4895  * Core handler for path creation
4896  *
4897  * @param cls closure
4898  * @param message message
4899  * @param peer peer identity this notification is about
4900  * @param atsi performance data
4901  * @param atsi_count number of records in 'atsi'
4902  *
4903  * @return GNUNET_OK to keep the connection open,
4904  *         GNUNET_SYSERR to close it (signal serious error)
4905  */
4906 static int
4907 handle_mesh_path_create (void *cls, const struct GNUNET_PeerIdentity *peer,
4908                          const struct GNUNET_MessageHeader *message,
4909                          const struct GNUNET_ATS_Information *atsi,
4910                          unsigned int atsi_count)
4911 {
4912   unsigned int own_pos;
4913   uint16_t size;
4914   uint16_t i;
4915   MESH_TunnelNumber tid;
4916   struct GNUNET_MESH_ManipulatePath *msg;
4917   struct GNUNET_PeerIdentity *pi;
4918   struct GNUNET_HashCode hash;
4919   struct MeshPeerPath *path;
4920   struct MeshPeerInfo *dest_peer_info;
4921   struct MeshPeerInfo *orig_peer_info;
4922   struct MeshTunnel *t;
4923
4924   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4925               "Received a path create msg [%s]\n",
4926               GNUNET_i2s (&my_full_id));
4927   size = ntohs (message->size);
4928   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
4929   {
4930     GNUNET_break_op (0);
4931     return GNUNET_OK;
4932   }
4933
4934   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
4935   if (size % sizeof (struct GNUNET_PeerIdentity))
4936   {
4937     GNUNET_break_op (0);
4938     return GNUNET_OK;
4939   }
4940   size /= sizeof (struct GNUNET_PeerIdentity);
4941   if (size < 2)
4942   {
4943     GNUNET_break_op (0);
4944     return GNUNET_OK;
4945   }
4946   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
4947   msg = (struct GNUNET_MESH_ManipulatePath *) message;
4948
4949   tid = ntohl (msg->tid);
4950   pi = (struct GNUNET_PeerIdentity *) &msg[1];
4951   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4952               "    path is for tunnel %s [%X].\n", GNUNET_i2s (pi), tid);
4953   t = tunnel_get (pi, tid);
4954   if (NULL == t) // FIXME only for INCOMING tunnels?
4955   {
4956     uint32_t opt;
4957
4958     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating tunnel\n");
4959     t = tunnel_new (GNUNET_PEER_intern (pi), tid, NULL, 0);
4960     if (NULL == t)
4961     {
4962       // FIXME notify failure
4963       return GNUNET_OK;
4964     }
4965     opt = ntohl (msg->opt);
4966     t->speed_min = (0 != (opt & MESH_TUNNEL_OPT_SPEED_MIN)) ?
4967                    GNUNET_YES : GNUNET_NO;
4968     t->nobuffer = (0 != (opt & MESH_TUNNEL_OPT_NOBUFFER)) ?
4969                   GNUNET_YES : GNUNET_NO;
4970
4971     if (GNUNET_YES == t->nobuffer)
4972     {
4973       t->bck_queue_max = 1;
4974       t->fwd_queue_max = 1;
4975     }
4976
4977     // FIXME only assign a local tid if a local client is interested (on demand)
4978     while (NULL != tunnel_get_incoming (next_local_tid))
4979       next_local_tid = (next_local_tid + 1) | GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
4980     t->local_tid_dest = next_local_tid++;
4981     next_local_tid = next_local_tid | GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
4982     // FIXME end
4983
4984     tunnel_reset_timeout (t);
4985     GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
4986     if (GNUNET_OK !=
4987         GNUNET_CONTAINER_multihashmap_put (incoming_tunnels, &hash, t,
4988                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
4989     {
4990       tunnel_destroy (t);
4991       GNUNET_break (0);
4992       return GNUNET_OK;
4993     }
4994   }
4995   dest_peer_info =
4996       GNUNET_CONTAINER_multihashmap_get (peers, &pi[size - 1].hashPubKey);
4997   if (NULL == dest_peer_info)
4998   {
4999     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5000                 "  Creating PeerInfo for destination.\n");
5001     dest_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
5002     dest_peer_info->id = GNUNET_PEER_intern (&pi[size - 1]);
5003     GNUNET_CONTAINER_multihashmap_put (peers, &pi[size - 1].hashPubKey,
5004                                        dest_peer_info,
5005                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
5006   }
5007   orig_peer_info = GNUNET_CONTAINER_multihashmap_get (peers, &pi->hashPubKey);
5008   if (NULL == orig_peer_info)
5009   {
5010     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5011                 "  Creating PeerInfo for origin.\n");
5012     orig_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
5013     orig_peer_info->id = GNUNET_PEER_intern (pi);
5014     GNUNET_CONTAINER_multihashmap_put (peers, &pi->hashPubKey, orig_peer_info,
5015                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
5016   }
5017   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
5018   path = path_new (size);
5019   own_pos = 0;
5020   for (i = 0; i < size; i++)
5021   {
5022     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ... adding %s\n",
5023                 GNUNET_i2s (&pi[i]));
5024     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
5025     if (path->peers[i] == myid)
5026       own_pos = i;
5027   }
5028   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
5029   if (own_pos == 0)
5030   {
5031     /* cannot be self, must be 'not found' */
5032     /* create path: self not found in path through self */
5033     GNUNET_break_op (0);
5034     path_destroy (path);
5035     tunnel_destroy (t);
5036     return GNUNET_OK;
5037   }
5038   path_add_to_peers (path, GNUNET_NO);
5039   tunnel_add_path (t, path, own_pos);
5040   if (own_pos == size - 1)
5041   {
5042     /* It is for us! Send ack. */
5043     struct MeshTransmissionDescriptor *info;
5044
5045     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
5046     peer_info_add_path_to_origin (orig_peer_info, path, GNUNET_NO);
5047     if (NULL == t->peers)
5048     {
5049       /* New tunnel! Notify clients on data. */
5050       t->peers = GNUNET_CONTAINER_multihashmap_create (4);
5051     }
5052     GNUNET_break (GNUNET_SYSERR !=
5053                   GNUNET_CONTAINER_multihashmap_put (t->peers,
5054                                                      &my_full_id.hashPubKey,
5055                                                      peer_info_get
5056                                                      (&my_full_id),
5057                                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE));
5058     info = GNUNET_malloc (sizeof (struct MeshTransmissionDescriptor));
5059     info->origin = &t->id;
5060     info->peer = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
5061     GNUNET_assert (NULL != info->peer);
5062     queue_add(info,
5063               GNUNET_MESSAGE_TYPE_MESH_PATH_ACK,
5064               sizeof (struct GNUNET_MESH_PathACK),
5065               info->peer,
5066               t);
5067   }
5068   else
5069   {
5070     struct MeshPeerPath *path2;
5071
5072     /* It's for somebody else! Retransmit. */
5073     path2 = path_duplicate (path);
5074     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Retransmitting.\n");
5075     peer_info_add_path (dest_peer_info, path2, GNUNET_NO);
5076     path2 = path_duplicate (path);
5077     peer_info_add_path_to_origin (orig_peer_info, path2, GNUNET_NO);
5078     send_create_path (dest_peer_info, path, t);
5079   }
5080   return GNUNET_OK;
5081 }
5082
5083
5084 /**
5085  * Core handler for path destruction
5086  *
5087  * @param cls closure
5088  * @param message message
5089  * @param peer peer identity this notification is about
5090  * @param atsi performance data
5091  * @param atsi_count number of records in 'atsi'
5092  *
5093  * @return GNUNET_OK to keep the connection open,
5094  *         GNUNET_SYSERR to close it (signal serious error)
5095  */
5096 static int
5097 handle_mesh_path_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
5098                           const struct GNUNET_MessageHeader *message,
5099                           const struct GNUNET_ATS_Information *atsi,
5100                           unsigned int atsi_count)
5101 {
5102   struct GNUNET_MESH_ManipulatePath *msg;
5103   struct GNUNET_PeerIdentity *pi;
5104   struct MeshPeerPath *path;
5105   struct MeshTunnel *t;
5106   unsigned int own_pos;
5107   unsigned int i;
5108   size_t size;
5109
5110   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5111               "Received a PATH DESTROY msg from %s\n", GNUNET_i2s (peer));
5112   size = ntohs (message->size);
5113   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
5114   {
5115     GNUNET_break_op (0);
5116     return GNUNET_OK;
5117   }
5118
5119   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
5120   if (size % sizeof (struct GNUNET_PeerIdentity))
5121   {
5122     GNUNET_break_op (0);
5123     return GNUNET_OK;
5124   }
5125   size /= sizeof (struct GNUNET_PeerIdentity);
5126   if (size < 2)
5127   {
5128     GNUNET_break_op (0);
5129     return GNUNET_OK;
5130   }
5131   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
5132
5133   msg = (struct GNUNET_MESH_ManipulatePath *) message;
5134   pi = (struct GNUNET_PeerIdentity *) &msg[1];
5135   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5136               "    path is for tunnel %s [%X].\n", GNUNET_i2s (pi),
5137               msg->tid);
5138   t = tunnel_get (pi, ntohl (msg->tid));
5139   if (NULL == t)
5140   {
5141     /* TODO notify back: we don't know this tunnel */
5142     GNUNET_break_op (0);
5143     return GNUNET_OK;
5144   }
5145   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
5146   path = path_new (size);
5147   own_pos = 0;
5148   for (i = 0; i < size; i++)
5149   {
5150     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ... adding %s\n",
5151                 GNUNET_i2s (&pi[i]));
5152     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
5153     if (path->peers[i] == myid)
5154       own_pos = i;
5155   }
5156   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
5157   if (own_pos < path->length - 1)
5158     send_message (message, &pi[own_pos + 1], t);
5159   else
5160     send_client_tunnel_disconnect(t, NULL);
5161
5162   tunnel_delete_peer (t, path->peers[path->length - 1]);
5163   path_destroy (path);
5164   return GNUNET_OK;
5165 }
5166
5167
5168 /**
5169  * Core handler for notifications of broken paths
5170  *
5171  * @param cls closure
5172  * @param message message
5173  * @param peer peer identity this notification is about
5174  * @param atsi performance data
5175  * @param atsi_count number of records in 'atsi'
5176  *
5177  * @return GNUNET_OK to keep the connection open,
5178  *         GNUNET_SYSERR to close it (signal serious error)
5179  */
5180 static int
5181 handle_mesh_path_broken (void *cls, const struct GNUNET_PeerIdentity *peer,
5182                          const struct GNUNET_MessageHeader *message,
5183                          const struct GNUNET_ATS_Information *atsi,
5184                          unsigned int atsi_count)
5185 {
5186   struct GNUNET_MESH_PathBroken *msg;
5187   struct MeshTunnel *t;
5188
5189   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5190               "Received a PATH BROKEN msg from %s\n", GNUNET_i2s (peer));
5191   msg = (struct GNUNET_MESH_PathBroken *) message;
5192   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
5193               GNUNET_i2s (&msg->peer1));
5194   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
5195               GNUNET_i2s (&msg->peer2));
5196   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5197   if (NULL == t)
5198   {
5199     GNUNET_break_op (0);
5200     return GNUNET_OK;
5201   }
5202   tunnel_notify_connection_broken (t, GNUNET_PEER_search (&msg->peer1),
5203                                    GNUNET_PEER_search (&msg->peer2));
5204   return GNUNET_OK;
5205
5206 }
5207
5208
5209 /**
5210  * Core handler for tunnel destruction
5211  *
5212  * @param cls closure
5213  * @param message message
5214  * @param peer peer identity this notification is about
5215  * @param atsi performance data
5216  * @param atsi_count number of records in 'atsi'
5217  *
5218  * @return GNUNET_OK to keep the connection open,
5219  *         GNUNET_SYSERR to close it (signal serious error)
5220  */
5221 static int
5222 handle_mesh_tunnel_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
5223                             const struct GNUNET_MessageHeader *message,
5224                             const struct GNUNET_ATS_Information *atsi,
5225                             unsigned int atsi_count)
5226 {
5227   struct GNUNET_MESH_TunnelDestroy *msg;
5228   struct MeshTunnel *t;
5229
5230   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5231               "Got a TUNNEL DESTROY packet from %s\n", GNUNET_i2s (peer));
5232   msg = (struct GNUNET_MESH_TunnelDestroy *) message;
5233   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for tunnel %s [%u]\n",
5234               GNUNET_i2s (&msg->oid), ntohl (msg->tid));
5235   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5236   if (NULL == t)
5237   {
5238     /* Probably already got the message from another path,
5239      * destroyed the tunnel and retransmitted to children.
5240      * Safe to ignore.
5241      */
5242     GNUNET_STATISTICS_update (stats, "# control on unknown tunnel", 1, GNUNET_NO);
5243     return GNUNET_OK;
5244   }
5245   if (t->id.oid == myid)
5246   {
5247     GNUNET_break_op (0);
5248     return GNUNET_OK;
5249   }
5250   if (t->local_tid_dest >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
5251   {
5252     /* Tunnel was incoming, notify clients */
5253     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "INCOMING TUNNEL %X %X\n",
5254                 t->local_tid, t->local_tid_dest);
5255     send_clients_tunnel_destroy (t);
5256   }
5257   tunnel_send_destroy (t);
5258   t->destroy = GNUNET_YES;
5259   // TODO: add timeout to destroy the tunnel anyway
5260   return GNUNET_OK;
5261 }
5262
5263
5264 /**
5265  * Core handler for mesh network traffic going from the origin to a peer
5266  *
5267  * @param cls closure
5268  * @param peer peer identity this notification is about
5269  * @param message message
5270  * @param atsi performance data
5271  * @param atsi_count number of records in 'atsi'
5272  * @return GNUNET_OK to keep the connection open,
5273  *         GNUNET_SYSERR to close it (signal serious error)
5274  */
5275 static int
5276 handle_mesh_data_unicast (void *cls, const struct GNUNET_PeerIdentity *peer,
5277                           const struct GNUNET_MessageHeader *message,
5278                           const struct GNUNET_ATS_Information *atsi,
5279                           unsigned int atsi_count)
5280 {
5281   struct GNUNET_MESH_Unicast *msg;
5282   struct GNUNET_PeerIdentity *neighbor;
5283   struct MeshTunnelChildInfo *cinfo;
5284   struct MeshTunnel *t;
5285   GNUNET_PEER_Id dest_id;
5286   uint32_t pid;
5287   uint32_t ttl;
5288   size_t size;
5289
5290   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a unicast packet from %s\n",
5291               GNUNET_i2s (peer));
5292   /* Check size */
5293   size = ntohs (message->size);
5294   if (size <
5295       sizeof (struct GNUNET_MESH_Unicast) +
5296       sizeof (struct GNUNET_MessageHeader))
5297   {
5298     GNUNET_break (0);
5299     return GNUNET_OK;
5300   }
5301   msg = (struct GNUNET_MESH_Unicast *) message;
5302   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " of type %s\n",
5303               GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
5304   /* Check tunnel */
5305   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5306   if (NULL == t)
5307   {
5308     /* TODO notify back: we don't know this tunnel */
5309     GNUNET_STATISTICS_update (stats, "# data on unknown tunnel", 1, GNUNET_NO);
5310     GNUNET_break_op (0);
5311     return GNUNET_OK;
5312   }
5313   pid = ntohl (msg->pid);
5314   if (t->fwd_pid == pid)
5315   {
5316     GNUNET_STATISTICS_update (stats, "# duplicate PID drops", 1, GNUNET_NO);
5317     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5318                 " Already seen pid %u, DROPPING!\n", pid);
5319     return GNUNET_OK;
5320   }
5321   else
5322   {
5323     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5324                 " pid %u not seen yet, forwarding\n", pid);
5325   }
5326
5327   t->skip += (pid - t->fwd_pid) - 1;
5328   t->fwd_pid = pid;
5329
5330   if (GMC_is_pid_bigger (pid, t->last_fwd_ack))
5331   {
5332     GNUNET_STATISTICS_update (stats, "# unsolicited unicast", 1, GNUNET_NO);
5333     GNUNET_break_op (0);
5334     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5335                 "Received PID %u, ACK %u\n",
5336                 pid, t->last_fwd_ack);
5337     return GNUNET_OK;
5338   }
5339
5340   tunnel_reset_timeout (t);
5341   dest_id = GNUNET_PEER_search (&msg->destination);
5342   if (dest_id == myid)
5343   {
5344     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5345                 "  it's for us! sending to clients...\n");
5346     GNUNET_STATISTICS_update (stats, "# unicast received", 1, GNUNET_NO);
5347     send_subscribed_clients (message, &msg[1].header, t);
5348     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_UNICAST);
5349     return GNUNET_OK;
5350   }
5351   ttl = ntohl (msg->ttl);
5352   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ttl: %u\n", ttl);
5353   if (ttl == 0)
5354   {
5355     GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
5356     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
5357     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5358     return GNUNET_OK;
5359   }
5360   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5361               "  not for us, retransmitting...\n");
5362
5363   neighbor = tree_get_first_hop (t->tree, dest_id);
5364   cinfo = tunnel_get_neighbor_fc (t, neighbor);
5365   cinfo->pid = pid;
5366   GNUNET_CONTAINER_multihashmap_iterate (t->children_fc,
5367                                          &tunnel_add_skip,
5368                                          &neighbor);
5369   if (GNUNET_YES == t->nobuffer &&
5370       GNUNET_YES == GMC_is_pid_bigger (pid, cinfo->fwd_ack))
5371   {
5372     GNUNET_STATISTICS_update (stats, "# unsolicited unicast", 1, GNUNET_NO);
5373     GNUNET_break_op (0);
5374     return GNUNET_OK;
5375   }
5376   send_message (message, neighbor, t);
5377   GNUNET_STATISTICS_update (stats, "# unicast forwarded", 1, GNUNET_NO);
5378   return GNUNET_OK;
5379 }
5380
5381
5382 /**
5383  * Core handler for mesh network traffic going from the origin to all peers
5384  *
5385  * @param cls closure
5386  * @param message message
5387  * @param peer peer identity this notification is about
5388  * @param atsi performance data
5389  * @param atsi_count number of records in 'atsi'
5390  * @return GNUNET_OK to keep the connection open,
5391  *         GNUNET_SYSERR to close it (signal serious error)
5392  *
5393  * TODO: Check who we got this from, to validate route.
5394  */
5395 static int
5396 handle_mesh_data_multicast (void *cls, const struct GNUNET_PeerIdentity *peer,
5397                             const struct GNUNET_MessageHeader *message,
5398                             const struct GNUNET_ATS_Information *atsi,
5399                             unsigned int atsi_count)
5400 {
5401   struct GNUNET_MESH_Multicast *msg;
5402   struct MeshTunnel *t;
5403   size_t size;
5404   uint32_t pid;
5405
5406   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a multicast packet from %s\n",
5407               GNUNET_i2s (peer));
5408   size = ntohs (message->size);
5409   if (sizeof (struct GNUNET_MESH_Multicast) +
5410       sizeof (struct GNUNET_MessageHeader) > size)
5411   {
5412     GNUNET_break_op (0);
5413     return GNUNET_OK;
5414   }
5415   msg = (struct GNUNET_MESH_Multicast *) message;
5416   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5417
5418   if (NULL == t)
5419   {
5420     /* TODO notify that we dont know that tunnel */
5421     GNUNET_STATISTICS_update (stats, "# data on unknown tunnel", 1, GNUNET_NO);
5422     GNUNET_break_op (0);
5423     return GNUNET_OK;
5424   }
5425   pid = ntohl (msg->pid);
5426   if (t->fwd_pid == pid)
5427   {
5428     /* already seen this packet, drop */
5429     GNUNET_STATISTICS_update (stats, "# duplicate PID drops", 1, GNUNET_NO);
5430     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5431                 " Already seen pid %u, DROPPING!\n", pid);
5432     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5433     return GNUNET_OK;
5434   }
5435   else
5436   {
5437     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5438                 " pid %u not seen yet, forwarding\n", pid);
5439   }
5440   t->skip += (pid - t->fwd_pid) - 1;
5441   t->fwd_pid = pid;
5442   tunnel_reset_timeout (t);
5443
5444   /* Transmit to locally interested clients */
5445   if (NULL != t->peers &&
5446       GNUNET_CONTAINER_multihashmap_contains (t->peers, &my_full_id.hashPubKey))
5447   {
5448     GNUNET_STATISTICS_update (stats, "# multicast received", 1, GNUNET_NO);
5449     send_subscribed_clients (message, &msg[1].header, t);
5450     tunnel_send_fwd_ack(t, GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
5451   }
5452   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ttl: %u\n", ntohl (msg->ttl));
5453   if (ntohl (msg->ttl) == 0)
5454   {
5455     GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
5456     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
5457     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5458     return GNUNET_OK;
5459   }
5460   GNUNET_STATISTICS_update (stats, "# multicast forwarded", 1, GNUNET_NO);
5461   tunnel_send_multicast (t, message, GNUNET_NO);
5462   return GNUNET_OK;
5463 }
5464
5465
5466 /**
5467  * Core handler for mesh network traffic toward the owner of a tunnel
5468  *
5469  * @param cls closure
5470  * @param message message
5471  * @param peer peer identity this notification is about
5472  * @param atsi performance data
5473  * @param atsi_count number of records in 'atsi'
5474  *
5475  * @return GNUNET_OK to keep the connection open,
5476  *         GNUNET_SYSERR to close it (signal serious error)
5477  */
5478 static int
5479 handle_mesh_data_to_orig (void *cls, const struct GNUNET_PeerIdentity *peer,
5480                           const struct GNUNET_MessageHeader *message,
5481                           const struct GNUNET_ATS_Information *atsi,
5482                           unsigned int atsi_count)
5483 {
5484   struct GNUNET_MESH_ToOrigin *msg;
5485   struct GNUNET_PeerIdentity id;
5486   struct MeshPeerInfo *peer_info;
5487   struct MeshTunnel *t;
5488   size_t size;
5489
5490
5491   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a ToOrigin packet from %s\n",
5492               GNUNET_i2s (peer));
5493   size = ntohs (message->size);
5494   if (size < sizeof (struct GNUNET_MESH_ToOrigin) +     /* Payload must be */
5495       sizeof (struct GNUNET_MessageHeader))     /* at least a header */
5496   {
5497     GNUNET_break_op (0);
5498     return GNUNET_OK;
5499   }
5500   msg = (struct GNUNET_MESH_ToOrigin *) message;
5501   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " of type %s\n",
5502               GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
5503   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5504
5505   if (NULL == t)
5506   {
5507     /* TODO notify that we dont know this tunnel (whom)? */
5508     GNUNET_STATISTICS_update (stats, "# data on unknown tunnel", 1, GNUNET_NO);
5509     GNUNET_break_op (0);
5510     return GNUNET_OK;
5511   }
5512
5513   if (NULL != t->owner)
5514   {
5515     char cbuf[size];
5516     struct GNUNET_MESH_ToOrigin *copy;
5517
5518     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5519                 "  it's for us! sending to clients...\n");
5520     /* TODO signature verification */
5521     memcpy (cbuf, message, size);
5522     copy = (struct GNUNET_MESH_ToOrigin *) cbuf;
5523     copy->tid = htonl (t->local_tid);
5524     GNUNET_STATISTICS_update (stats, "# to origin received", 1, GNUNET_NO);
5525     GNUNET_SERVER_notification_context_unicast (nc, t->owner->handle,
5526                                                 &copy->header, GNUNET_NO);
5527     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN);
5528     return GNUNET_OK;
5529   }
5530   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5531               "  not for us, retransmitting...\n");
5532
5533   peer_info = peer_info_get (&msg->oid);
5534   if (NULL == peer_info)
5535   {
5536     /* unknown origin of tunnel */
5537     GNUNET_break (0);
5538     return GNUNET_OK;
5539   }
5540   GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &id);
5541   send_message (message, &id, t);
5542   GNUNET_STATISTICS_update (stats, "# to origin forwarded", 1, GNUNET_NO);
5543
5544   return GNUNET_OK;
5545 }
5546
5547
5548 /**
5549  * Core handler for mesh network traffic point-to-point acks.
5550  *
5551  * @param cls closure
5552  * @param message message
5553  * @param peer peer identity this notification is about
5554  * @param atsi performance data
5555  * @param atsi_count number of records in 'atsi'
5556  *
5557  * @return GNUNET_OK to keep the connection open,
5558  *         GNUNET_SYSERR to close it (signal serious error)
5559  */
5560 static int
5561 handle_mesh_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
5562                  const struct GNUNET_MessageHeader *message,
5563                  const struct GNUNET_ATS_Information *atsi,
5564                  unsigned int atsi_count)
5565 {
5566   struct GNUNET_MESH_ACK *msg;
5567   struct MeshTunnel *t;
5568   uint32_t ack;
5569
5570   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got an ACK packet from %s!\n",
5571               GNUNET_i2s (peer));
5572   msg = (struct GNUNET_MESH_ACK *) message;
5573
5574   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5575
5576   if (NULL == t)
5577   {
5578     /* TODO notify that we dont know this tunnel (whom)? */
5579     GNUNET_STATISTICS_update (stats, "# ack on unknown tunnel", 1, GNUNET_NO);
5580     GNUNET_break_op (0);
5581     return GNUNET_OK;
5582   }
5583   ack = ntohl (msg->pid);
5584
5585   /* Is this a forward or backward ACK? */
5586   if (tree_get_predecessor(t->tree) != GNUNET_PEER_search(peer))
5587   {
5588     struct MeshTunnelChildInfo *cinfo;
5589
5590     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  FWD ACK\n");
5591     cinfo = tunnel_get_neighbor_fc (t, peer);
5592     cinfo->fwd_ack = ack;
5593     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5594     tunnel_unlock_fwd_queues (t);
5595   }
5596   else
5597   {
5598     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  BCK ACK\n");
5599     t->bck_ack = ack;
5600     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5601     tunnel_unlock_bck_queue (t);
5602   }
5603   return GNUNET_OK;
5604 }
5605
5606
5607 /**
5608  * Core handler for path ACKs
5609  *
5610  * @param cls closure
5611  * @param message message
5612  * @param peer peer identity this notification is about
5613  * @param atsi performance data
5614  * @param atsi_count number of records in 'atsi'
5615  *
5616  * @return GNUNET_OK to keep the connection open,
5617  *         GNUNET_SYSERR to close it (signal serious error)
5618  */
5619 static int
5620 handle_mesh_path_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
5621                       const struct GNUNET_MessageHeader *message,
5622                       const struct GNUNET_ATS_Information *atsi,
5623                       unsigned int atsi_count)
5624 {
5625   struct GNUNET_MESH_PathACK *msg;
5626   struct GNUNET_PeerIdentity id;
5627   struct MeshPeerInfo *peer_info;
5628   struct MeshPeerPath *p;
5629   struct MeshTunnel *t;
5630
5631   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a path ACK msg [%s]\n",
5632               GNUNET_i2s (&my_full_id));
5633   msg = (struct GNUNET_MESH_PathACK *) message;
5634   t = tunnel_get (&msg->oid, ntohl(msg->tid));
5635   if (NULL == t)
5636   {
5637     /* TODO notify that we don't know the tunnel */
5638     GNUNET_STATISTICS_update (stats, "# control on unknown tunnel", 1, GNUNET_NO);
5639     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  don't know the tunnel %s [%X]!\n",
5640                 GNUNET_i2s (&msg->oid), ntohl(msg->tid));
5641     return GNUNET_OK;
5642   }
5643   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %s [%X]\n",
5644               GNUNET_i2s (&msg->oid), ntohl(msg->tid));
5645
5646   peer_info = peer_info_get (&msg->peer_id);
5647   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by peer %s\n",
5648               GNUNET_i2s (&msg->peer_id));
5649   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  via peer %s\n",
5650               GNUNET_i2s (peer));
5651
5652   if (NULL != t->regex_ctx && t->regex_ctx->info->peer == peer_info->id)
5653   {
5654     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5655                 "connect_by_string completed, stopping search\n");
5656     regex_cancel_search (t->regex_ctx);
5657     t->regex_ctx = NULL;
5658   }
5659
5660   /* Add paths to peers? */
5661   p = tree_get_path_to_peer (t->tree, peer_info->id);
5662   if (NULL != p)
5663   {
5664     path_add_to_peers (p, GNUNET_YES);
5665     path_destroy (p);
5666   }
5667   else
5668   {
5669     GNUNET_break (0);
5670   }
5671
5672   /* Message for us? */
5673   if (0 == memcmp (&msg->oid, &my_full_id, sizeof (struct GNUNET_PeerIdentity)))
5674   {
5675     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
5676     if (NULL == t->owner)
5677     {
5678       GNUNET_break_op (0);
5679       return GNUNET_OK;
5680     }
5681     if (NULL != t->dht_get_type)
5682     {
5683       GNUNET_DHT_get_stop (t->dht_get_type);
5684       t->dht_get_type = NULL;
5685     }
5686     if (tree_get_status (t->tree, peer_info->id) != MESH_PEER_READY)
5687     {
5688       tree_set_status (t->tree, peer_info->id, MESH_PEER_READY);
5689       send_client_peer_connected (t, peer_info->id);
5690     }
5691     return GNUNET_OK;
5692   }
5693
5694   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5695               "  not for us, retransmitting...\n");
5696   GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &id);
5697   peer_info = peer_info_get (&msg->oid);
5698   if (NULL == peer_info)
5699   {
5700     /* If we know the tunnel, we should DEFINITELY know the peer */
5701     GNUNET_break (0);
5702     return GNUNET_OK;
5703   }
5704   send_message (message, &id, t);
5705   return GNUNET_OK;
5706 }
5707
5708
5709 /**
5710  * Functions to handle messages from core
5711  */
5712 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
5713   {&handle_mesh_path_create, GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE, 0},
5714   {&handle_mesh_path_destroy, GNUNET_MESSAGE_TYPE_MESH_PATH_DESTROY, 0},
5715   {&handle_mesh_path_broken, GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN,
5716    sizeof (struct GNUNET_MESH_PathBroken)},
5717   {&handle_mesh_tunnel_destroy, GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY,
5718    sizeof (struct GNUNET_MESH_TunnelDestroy)},
5719   {&handle_mesh_data_unicast, GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
5720   {&handle_mesh_data_multicast, GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
5721   {&handle_mesh_data_to_orig, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
5722   {&handle_mesh_ack, GNUNET_MESSAGE_TYPE_MESH_ACK,
5723     sizeof (struct GNUNET_MESH_ACK)},
5724   {&handle_mesh_path_ack, GNUNET_MESSAGE_TYPE_MESH_PATH_ACK,
5725    sizeof (struct GNUNET_MESH_PathACK)},
5726   {NULL, 0, 0}
5727 };
5728
5729
5730
5731 /******************************************************************************/
5732 /****************       MESH LOCAL HANDLER HELPERS      ***********************/
5733 /******************************************************************************/
5734
5735 /**
5736  * deregister_app: iterator for removing each application registered by a client
5737  *
5738  * @param cls closure
5739  * @param key the hash of the application id (used to access the hashmap)
5740  * @param value the value stored at the key (client)
5741  *
5742  * @return GNUNET_OK on success
5743  */
5744 static int
5745 deregister_app (void *cls, const struct GNUNET_HashCode * key, void *value)
5746 {
5747   struct GNUNET_CONTAINER_MultiHashMap *h = cls;
5748   GNUNET_break (GNUNET_YES ==
5749                 GNUNET_CONTAINER_multihashmap_remove (h, key, value));
5750   return GNUNET_OK;
5751 }
5752
5753 #if LATER
5754 /**
5755  * notify_client_connection_failure: notify a client that the connection to the
5756  * requested remote peer is not possible (for instance, no route found)
5757  * Function called when the socket is ready to queue more data. "buf" will be
5758  * NULL and "size" zero if the socket was closed for writing in the meantime.
5759  *
5760  * @param cls closure
5761  * @param size number of bytes available in buf
5762  * @param buf where the callee should write the message
5763  * @return number of bytes written to buf
5764  */
5765 static size_t
5766 notify_client_connection_failure (void *cls, size_t size, void *buf)
5767 {
5768   int size_needed;
5769   struct MeshPeerInfo *peer_info;
5770   struct GNUNET_MESH_PeerControl *msg;
5771   struct GNUNET_PeerIdentity id;
5772
5773   if (0 == size && NULL == buf)
5774   {
5775     // TODO retry? cancel?
5776     return 0;
5777   }
5778
5779   size_needed = sizeof (struct GNUNET_MESH_PeerControl);
5780   peer_info = (struct MeshPeerInfo *) cls;
5781   msg = (struct GNUNET_MESH_PeerControl *) buf;
5782   msg->header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
5783   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DISCONNECTED);
5784 //     msg->tunnel_id = htonl(peer_info->t->tid);
5785   GNUNET_PEER_resolve (peer_info->id, &id);
5786   memcpy (&msg->peer, &id, sizeof (struct GNUNET_PeerIdentity));
5787
5788   return size_needed;
5789 }
5790 #endif
5791
5792
5793 /**
5794  * Send keepalive packets for a peer
5795  *
5796  * @param cls Closure (tunnel for which to send the keepalive).
5797  * @param tc Notification context.
5798  *
5799  * TODO: implement explicit multicast keepalive?
5800  */
5801 static void
5802 path_refresh (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
5803 {
5804   struct MeshTunnel *t = cls;
5805   struct GNUNET_MessageHeader *payload;
5806   struct GNUNET_MESH_Multicast *msg;
5807   size_t size =
5808       sizeof (struct GNUNET_MESH_Multicast) +
5809       sizeof (struct GNUNET_MessageHeader);
5810   char cbuf[size];
5811
5812   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
5813   {
5814     return;
5815   }
5816   t->path_refresh_task = GNUNET_SCHEDULER_NO_TASK;
5817
5818   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5819               "sending keepalive for tunnel %d\n", t->id.tid);
5820
5821   msg = (struct GNUNET_MESH_Multicast *) cbuf;
5822   msg->header.size = htons (size);
5823   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
5824   // FIXME: change type to != MULTICAST
5825   msg->oid = my_full_id;
5826   msg->tid = htonl (t->id.tid);
5827   msg->ttl = htonl (default_ttl);
5828   msg->pid = htonl (t->fwd_pid + 1);
5829   t->fwd_pid++;
5830   payload = (struct GNUNET_MessageHeader *) &msg[1];
5831   payload->size = htons (sizeof (struct GNUNET_MessageHeader));
5832   payload->type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE);
5833   tunnel_send_multicast (t, &msg->header, GNUNET_YES);
5834
5835   t->path_refresh_task =
5836       GNUNET_SCHEDULER_add_delayed (refresh_path_time, &path_refresh, t);
5837   return;
5838 }
5839
5840
5841 /**
5842  * Function to process paths received for a new peer addition. The recorded
5843  * paths form the initial tunnel, which can be optimized later.
5844  * Called on each result obtained for the DHT search.
5845  *
5846  * @param cls closure
5847  * @param exp when will this value expire
5848  * @param key key of the result
5849  * @param get_path path of the get request
5850  * @param get_path_length lenght of get_path
5851  * @param put_path path of the put request
5852  * @param put_path_length length of the put_path
5853  * @param type type of the result
5854  * @param size number of bytes in data
5855  * @param data pointer to the result data
5856  *
5857  * TODO: re-issue the request after certain time? cancel after X results?
5858  */
5859 static void
5860 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
5861                     const struct GNUNET_HashCode * key,
5862                     const struct GNUNET_PeerIdentity *get_path,
5863                     unsigned int get_path_length,
5864                     const struct GNUNET_PeerIdentity *put_path,
5865                     unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
5866                     size_t size, const void *data)
5867 {
5868   struct MeshPathInfo *path_info = cls;
5869   struct MeshPeerPath *p;
5870   struct GNUNET_PeerIdentity pi;
5871   int i;
5872
5873   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got results from DHT!\n");
5874   GNUNET_PEER_resolve (path_info->peer->id, &pi);
5875   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for %s\n", GNUNET_i2s (&pi));
5876
5877   p = path_build_from_dht (get_path, get_path_length, put_path,
5878                            put_path_length);
5879   path_add_to_peers (p, GNUNET_NO);
5880   path_destroy(p);
5881   for (i = 0; i < path_info->peer->ntunnels; i++)
5882   {
5883     tunnel_add_peer (path_info->peer->tunnels[i], path_info->peer);
5884     peer_info_connect (path_info->peer, path_info->t);
5885   }
5886
5887   return;
5888 }
5889
5890
5891 /**
5892  * Function to process paths received for a new peer addition. The recorded
5893  * paths form the initial tunnel, which can be optimized later.
5894  * Called on each result obtained for the DHT search.
5895  *
5896  * @param cls closure
5897  * @param exp when will this value expire
5898  * @param key key of the result
5899  * @param get_path path of the get request
5900  * @param get_path_length lenght of get_path
5901  * @param put_path path of the put request
5902  * @param put_path_length length of the put_path
5903  * @param type type of the result
5904  * @param size number of bytes in data
5905  * @param data pointer to the result data
5906  */
5907 static void
5908 dht_get_type_handler (void *cls, struct GNUNET_TIME_Absolute exp,
5909                       const struct GNUNET_HashCode * key,
5910                       const struct GNUNET_PeerIdentity *get_path,
5911                       unsigned int get_path_length,
5912                       const struct GNUNET_PeerIdentity *put_path,
5913                       unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
5914                       size_t size, const void *data)
5915 {
5916   const struct PBlock *pb = data;
5917   const struct GNUNET_PeerIdentity *pi = &pb->id;
5918   struct MeshTunnel *t = cls;
5919   struct MeshPeerInfo *peer_info;
5920   struct MeshPeerPath *p;
5921
5922   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got type DHT result!\n");
5923   if (size != sizeof (struct PBlock))
5924   {
5925     GNUNET_break_op (0);
5926     return;
5927   }
5928   if (ntohl(pb->type) != t->type)
5929   {
5930     GNUNET_break_op (0);
5931     return;
5932   }
5933   GNUNET_assert (NULL != t->owner);
5934   peer_info = peer_info_get (pi);
5935   (void) GNUNET_CONTAINER_multihashmap_put (t->peers, &pi->hashPubKey,
5936                                             peer_info,
5937                                             GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
5938
5939   p = path_build_from_dht (get_path, get_path_length, put_path,
5940                            put_path_length);
5941   path_add_to_peers (p, GNUNET_NO);
5942   path_destroy(p);
5943   tunnel_add_peer (t, peer_info);
5944   peer_info_connect (peer_info, t);
5945 }
5946
5947
5948 /**
5949  * Function to process DHT string to regex matching.
5950  * Called on each result obtained for the DHT search.
5951  *
5952  * @param cls closure (search context)
5953  * @param exp when will this value expire
5954  * @param key key of the result
5955  * @param get_path path of the get request (not used)
5956  * @param get_path_length lenght of get_path (not used)
5957  * @param put_path path of the put request (not used)
5958  * @param put_path_length length of the put_path (not used)
5959  * @param type type of the result
5960  * @param size number of bytes in data
5961  * @param data pointer to the result data
5962  */
5963 static void
5964 dht_get_string_accept_handler (void *cls, struct GNUNET_TIME_Absolute exp,
5965                                const struct GNUNET_HashCode * key,
5966                                const struct GNUNET_PeerIdentity *get_path,
5967                                unsigned int get_path_length,
5968                                const struct GNUNET_PeerIdentity *put_path,
5969                                unsigned int put_path_length,
5970                                enum GNUNET_BLOCK_Type type,
5971                                size_t size, const void *data)
5972 {
5973   const struct MeshRegexAccept *block = data;
5974   struct MeshRegexSearchContext *ctx = cls;
5975   struct MeshRegexSearchInfo *info = ctx->info;
5976   struct MeshPeerPath *p;
5977   struct MeshPeerInfo *peer_info;
5978
5979   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got regex results from DHT!\n");
5980   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for %s\n", info->description);
5981
5982   peer_info = peer_info_get(&block->id);
5983   p = path_build_from_dht (get_path, get_path_length, put_path,
5984                            put_path_length);
5985   path_add_to_peers (p, GNUNET_NO);
5986   path_destroy(p);
5987
5988   tunnel_add_peer (info->t, peer_info);
5989   peer_info_connect (peer_info, info->t);
5990   if (0 == info->peer)
5991   {
5992     info->peer = peer_info->id;
5993   }
5994   else
5995   {
5996     GNUNET_array_append (info->peers, info->n_peers, peer_info->id);
5997   }
5998
5999   info->timeout = GNUNET_SCHEDULER_add_delayed (connect_timeout,
6000                                                 &regex_connect_timeout,
6001                                                 info);
6002
6003   return;
6004 }
6005
6006
6007 /**
6008  * Function to process DHT string to regex matching.
6009  * Called on each result obtained for the DHT search.
6010  *
6011  * @param cls closure (search context)
6012  * @param exp when will this value expire
6013  * @param key key of the result
6014  * @param get_path path of the get request (not used)
6015  * @param get_path_length lenght of get_path (not used)
6016  * @param put_path path of the put request (not used)
6017  * @param put_path_length length of the put_path (not used)
6018  * @param type type of the result
6019  * @param size number of bytes in data
6020  * @param data pointer to the result data
6021  *
6022  * TODO: re-issue the request after certain time? cancel after X results?
6023  */
6024 static void
6025 dht_get_string_handler (void *cls, struct GNUNET_TIME_Absolute exp,
6026                         const struct GNUNET_HashCode * key,
6027                         const struct GNUNET_PeerIdentity *get_path,
6028                         unsigned int get_path_length,
6029                         const struct GNUNET_PeerIdentity *put_path,
6030                         unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
6031                         size_t size, const void *data)
6032 {
6033   const struct MeshRegexBlock *block = data;
6034   struct MeshRegexSearchContext *ctx = cls;
6035   struct MeshRegexSearchInfo *info = ctx->info;
6036   void *copy;
6037   size_t len;
6038
6039   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6040               "DHT GET STRING RETURNED RESULTS\n");
6041   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6042               "  key: %s\n", GNUNET_h2s (key));
6043
6044   copy = GNUNET_malloc (size);
6045   memcpy (copy, data, size);
6046   GNUNET_break (GNUNET_OK ==
6047                 GNUNET_CONTAINER_multihashmap_put(info->dht_get_results, key, copy,
6048                                                   GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
6049   len = ntohl (block->n_proof);
6050   {
6051     char proof[len + 1];
6052
6053     memcpy (proof, &block[1], len);
6054     proof[len] = '\0';
6055     if (GNUNET_OK != GNUNET_REGEX_check_proof (proof, key))
6056     {
6057       GNUNET_break_op (0);
6058       return;
6059     }
6060   }
6061   len = strlen (info->description);
6062   if (len == ctx->position) // String processed
6063   {
6064     if (GNUNET_YES == ntohl (block->accepting))
6065     {
6066       regex_find_path(key, ctx);
6067     }
6068     else
6069     {
6070       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  block not accepting!\n");
6071       // FIXME REGEX this block not successful, wait for more? start timeout?
6072     }
6073     return;
6074   }
6075   GNUNET_break (GNUNET_OK ==
6076                 GNUNET_MESH_regex_block_iterate (block, size,
6077                                                  &regex_edge_iterator, ctx));
6078   return;
6079 }
6080
6081 /******************************************************************************/
6082 /*********************       MESH LOCAL HANDLES      **************************/
6083 /******************************************************************************/
6084
6085
6086 /**
6087  * Handler for client disconnection
6088  *
6089  * @param cls closure
6090  * @param client identification of the client; NULL
6091  *        for the last call when the server is destroyed
6092  */
6093 static void
6094 handle_local_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
6095 {
6096   struct MeshClient *c;
6097   struct MeshClient *next;
6098   unsigned int i;
6099
6100   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client disconnected\n");
6101   if (client == NULL)
6102   {
6103     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   (SERVER DOWN)\n");
6104     return;
6105   }
6106   c = clients;
6107   while (NULL != c)
6108   {
6109     if (c->handle != client)
6110     {
6111       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ... searching\n");
6112       c = c->next;
6113       continue;
6114     }
6115     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "matching client found (%u)\n",
6116                 c->id);
6117     GNUNET_SERVER_client_drop (c->handle);
6118     c->shutting_down = GNUNET_YES;
6119     GNUNET_assert (NULL != c->own_tunnels);
6120     GNUNET_assert (NULL != c->incoming_tunnels);
6121     GNUNET_CONTAINER_multihashmap_iterate (c->own_tunnels,
6122                                            &tunnel_destroy_iterator, c);
6123     GNUNET_CONTAINER_multihashmap_iterate (c->incoming_tunnels,
6124                                            &tunnel_destroy_iterator, c);
6125     GNUNET_CONTAINER_multihashmap_iterate (c->ignore_tunnels,
6126                                            &tunnel_destroy_iterator, c);
6127     GNUNET_CONTAINER_multihashmap_destroy (c->own_tunnels);
6128     GNUNET_CONTAINER_multihashmap_destroy (c->incoming_tunnels);
6129     GNUNET_CONTAINER_multihashmap_destroy (c->ignore_tunnels);
6130
6131     /* deregister clients applications */
6132     if (NULL != c->apps)
6133     {
6134       GNUNET_CONTAINER_multihashmap_iterate (c->apps, &deregister_app, c->apps);
6135       GNUNET_CONTAINER_multihashmap_destroy (c->apps);
6136     }
6137     if (0 == GNUNET_CONTAINER_multihashmap_size (applications) &&
6138         GNUNET_SCHEDULER_NO_TASK != announce_applications_task)
6139     {
6140       GNUNET_SCHEDULER_cancel (announce_applications_task);
6141       announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
6142     }
6143     if (NULL != c->types)
6144       GNUNET_CONTAINER_multihashmap_destroy (c->types);
6145     for (i = 0; i < c->n_regex; i++)
6146     {
6147       GNUNET_free (c->regexes[i]);
6148     }
6149     GNUNET_free_non_null (c->regexes);
6150     if (GNUNET_SCHEDULER_NO_TASK != c->regex_announce_task)
6151       GNUNET_SCHEDULER_cancel (c->regex_announce_task);
6152     next = c->next;
6153     GNUNET_CONTAINER_DLL_remove (clients, clients_tail, c);
6154     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  CLIENT FREE at %p\n", c);
6155     GNUNET_free (c);
6156     GNUNET_STATISTICS_update (stats, "# clients", -1, GNUNET_NO);
6157     c = next;
6158   }
6159   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   done!\n");
6160   return;
6161 }
6162
6163
6164 /**
6165  * Handler for new clients
6166  *
6167  * @param cls closure
6168  * @param client identification of the client
6169  * @param message the actual message, which includes messages the client wants
6170  */
6171 static void
6172 handle_local_new_client (void *cls, struct GNUNET_SERVER_Client *client,
6173                          const struct GNUNET_MessageHeader *message)
6174 {
6175   struct GNUNET_MESH_ClientConnect *cc_msg;
6176   struct MeshClient *c;
6177   GNUNET_MESH_ApplicationType *a;
6178   unsigned int size;
6179   uint16_t ntypes;
6180   uint16_t *t;
6181   uint16_t napps;
6182   uint16_t i;
6183
6184   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client connected\n");
6185   /* Check data sanity */
6186   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_ClientConnect);
6187   cc_msg = (struct GNUNET_MESH_ClientConnect *) message;
6188   ntypes = ntohs (cc_msg->types);
6189   napps = ntohs (cc_msg->applications);
6190   if (size !=
6191       ntypes * sizeof (uint16_t) + napps * sizeof (GNUNET_MESH_ApplicationType))
6192   {
6193     GNUNET_break (0);
6194     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6195     return;
6196   }
6197
6198   /* Create new client structure */
6199   c = GNUNET_malloc (sizeof (struct MeshClient));
6200   c->id = next_client_id++;
6201   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  CLIENT NEW %u\n", c->id);
6202   c->handle = client;
6203   GNUNET_SERVER_client_keep (client);
6204   a = (GNUNET_MESH_ApplicationType *) &cc_msg[1];
6205   if (napps > 0)
6206   {
6207     GNUNET_MESH_ApplicationType at;
6208     struct GNUNET_HashCode hc;
6209
6210     c->apps = GNUNET_CONTAINER_multihashmap_create (napps);
6211     for (i = 0; i < napps; i++)
6212     {
6213       at = ntohl (a[i]);
6214       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  app type: %u\n", at);
6215       GNUNET_CRYPTO_hash (&at, sizeof (at), &hc);
6216       /* store in clients hashmap */
6217       GNUNET_CONTAINER_multihashmap_put (c->apps, &hc, (void *) (long) at,
6218                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
6219       /* store in global hashmap, for announcements */
6220       GNUNET_CONTAINER_multihashmap_put (applications, &hc, c,
6221                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
6222     }
6223     if (GNUNET_SCHEDULER_NO_TASK == announce_applications_task)
6224       announce_applications_task =
6225           GNUNET_SCHEDULER_add_now (&announce_applications, NULL);
6226
6227   }
6228   if (ntypes > 0)
6229   {
6230     uint16_t u16;
6231     struct GNUNET_HashCode hc;
6232
6233     t = (uint16_t *) & a[napps];
6234     c->types = GNUNET_CONTAINER_multihashmap_create (ntypes);
6235     for (i = 0; i < ntypes; i++)
6236     {
6237       u16 = ntohs (t[i]);
6238       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  msg type: %u\n", u16);
6239       GNUNET_CRYPTO_hash (&u16, sizeof (u16), &hc);
6240
6241       /* store in clients hashmap */
6242       GNUNET_CONTAINER_multihashmap_put (c->types, &hc, c,
6243                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
6244       /* store in global hashmap */
6245       GNUNET_CONTAINER_multihashmap_put (types, &hc, c,
6246                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
6247     }
6248   }
6249   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6250               " client has %u+%u subscriptions\n", napps, ntypes);
6251
6252   GNUNET_CONTAINER_DLL_insert (clients, clients_tail, c);
6253   c->own_tunnels = GNUNET_CONTAINER_multihashmap_create (32);
6254   c->incoming_tunnels = GNUNET_CONTAINER_multihashmap_create (32);
6255   c->ignore_tunnels = GNUNET_CONTAINER_multihashmap_create (32);
6256   GNUNET_SERVER_notification_context_add (nc, client);
6257   GNUNET_STATISTICS_update (stats, "# clients", 1, GNUNET_NO);
6258
6259   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6260   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client processed\n");
6261 }
6262
6263
6264 /**
6265  * Handler for clients announcing available services by a regular expression.
6266  *
6267  * @param cls closure
6268  * @param client identification of the client
6269  * @param message the actual message, which includes messages the client wants
6270  */
6271 static void
6272 handle_local_announce_regex (void *cls, struct GNUNET_SERVER_Client *client,
6273                              const struct GNUNET_MessageHeader *message)
6274 {
6275   struct MeshClient *c;
6276   char *regex;
6277   size_t len;
6278
6279   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "announce regex started\n");
6280
6281   /* Sanity check for client registration */
6282   if (NULL == (c = client_get (client)))
6283   {
6284     GNUNET_break (0);
6285     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6286     return;
6287   }
6288   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6289
6290   len = ntohs (message->size) - sizeof(struct GNUNET_MessageHeader);
6291   regex = GNUNET_malloc (len + 1);
6292   memcpy (regex, &message[1], len);
6293   regex[len] = '\0';
6294   GNUNET_array_append (c->regexes, c->n_regex, regex);
6295   if (GNUNET_SCHEDULER_NO_TASK == c->regex_announce_task)
6296   {
6297     c->regex_announce_task = GNUNET_SCHEDULER_add_now(&announce_regex, c);
6298   }
6299   else
6300   {
6301     regex_put(regex);
6302   }
6303   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6304   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "announce regex processed\n");
6305 }
6306
6307
6308 /**
6309  * Handler for requests of new tunnels
6310  *
6311  * @param cls closure
6312  * @param client identification of the client
6313  * @param message the actual message
6314  */
6315 static void
6316 handle_local_tunnel_create (void *cls, struct GNUNET_SERVER_Client *client,
6317                             const struct GNUNET_MessageHeader *message)
6318 {
6319   struct GNUNET_MESH_TunnelMessage *t_msg;
6320   struct MeshTunnel *t;
6321   struct MeshClient *c;
6322   MESH_TunnelNumber tid;
6323
6324   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new tunnel requested\n");
6325
6326   /* Sanity check for client registration */
6327   if (NULL == (c = client_get (client)))
6328   {
6329     GNUNET_break (0);
6330     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6331     return;
6332   }
6333   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6334
6335   /* Message sanity check */
6336   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
6337   {
6338     GNUNET_break (0);
6339     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6340     return;
6341   }
6342
6343   t_msg = (struct GNUNET_MESH_TunnelMessage *) message;
6344   /* Sanity check for tunnel numbering */
6345   tid = ntohl (t_msg->tunnel_id);
6346   if (0 == (tid & GNUNET_MESH_LOCAL_TUNNEL_ID_CLI))
6347   {
6348     GNUNET_break (0);
6349     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6350     return;
6351   }
6352   /* Sanity check for duplicate tunnel IDs */
6353   if (NULL != tunnel_get_by_local_id (c, tid))
6354   {
6355     GNUNET_break (0);
6356     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6357     return;
6358   }
6359
6360   while (NULL != tunnel_get_by_pi (myid, next_tid))
6361     next_tid = (next_tid + 1) & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
6362   t = tunnel_new (myid, next_tid++, c, tid);
6363   if (NULL == t)
6364   {
6365     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Tunnel creation failed.\n");
6366     GNUNET_break (0);
6367     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6368     return;
6369   }
6370   next_tid = next_tid & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
6371   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CREATED TUNNEL %s [%x] (%x)\n",
6372               GNUNET_i2s (&my_full_id), t->id.tid, t->local_tid);
6373   t->peers = GNUNET_CONTAINER_multihashmap_create (32);
6374
6375   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new tunnel created\n");
6376   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6377   return;
6378 }
6379
6380
6381 /**
6382  * Handler for requests of deleting tunnels
6383  *
6384  * @param cls closure
6385  * @param client identification of the client
6386  * @param message the actual message
6387  */
6388 static void
6389 handle_local_tunnel_destroy (void *cls, struct GNUNET_SERVER_Client *client,
6390                              const struct GNUNET_MessageHeader *message)
6391 {
6392   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
6393   struct MeshClient *c;
6394   struct MeshTunnel *t;
6395   MESH_TunnelNumber tid;
6396
6397   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6398               "Got a DESTROY TUNNEL from client!\n");
6399
6400   /* Sanity check for client registration */
6401   if (NULL == (c = client_get (client)))
6402   {
6403     GNUNET_break (0);
6404     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6405     return;
6406   }
6407   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6408
6409   /* Message sanity check */
6410   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
6411   {
6412     GNUNET_break (0);
6413     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6414     return;
6415   }
6416
6417   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
6418
6419   /* Retrieve tunnel */
6420   tid = ntohl (tunnel_msg->tunnel_id);
6421   t = tunnel_get_by_local_id(c, tid);
6422   if (NULL == t)
6423   {
6424     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  tunnel %X not found\n", tid);
6425     GNUNET_break (0);
6426     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6427     return;
6428   }
6429   if (c != t->owner || tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
6430   {
6431     client_ignore_tunnel (c, t);
6432 #if 0
6433     // TODO: when to destroy incoming tunnel?
6434     if (t->nclients == 0)
6435     {
6436       GNUNET_assert (GNUNET_YES ==
6437                      GNUNET_CONTAINER_multihashmap_remove (incoming_tunnels,
6438                                                            &hash, t));
6439       GNUNET_assert (GNUNET_YES ==
6440                      GNUNET_CONTAINER_multihashmap_remove (t->peers,
6441                                                            &my_full_id.hashPubKey,
6442                                                            t));
6443     }
6444 #endif
6445     GNUNET_SERVER_receive_done (client, GNUNET_OK);
6446     return;
6447   }
6448   send_client_tunnel_disconnect(t, c);
6449   client_delete_tunnel(c, t);
6450
6451   /* Don't try to ACK the client about the tunnel_destroy multicast packet */
6452   t->owner = NULL;
6453   tunnel_send_destroy (t);
6454   t->destroy = GNUNET_YES;
6455   // The tunnel will be destroyed when the last message is transmitted.
6456   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6457   return;
6458 }
6459
6460
6461 /**
6462  * Handler for requests of seeting tunnel's speed.
6463  *
6464  * @param cls Closure (unused).
6465  * @param client Identification of the client.
6466  * @param message The actual message.
6467  */
6468 static void
6469 handle_local_tunnel_speed (void *cls, struct GNUNET_SERVER_Client *client,
6470                            const struct GNUNET_MessageHeader *message)
6471 {
6472   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
6473   struct MeshClient *c;
6474   struct MeshTunnel *t;
6475   MESH_TunnelNumber tid;
6476
6477   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6478               "Got a SPEED request from client!\n");
6479
6480   /* Sanity check for client registration */
6481   if (NULL == (c = client_get (client)))
6482   {
6483     GNUNET_break (0);
6484     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6485     return;
6486   }
6487
6488   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6489
6490   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
6491
6492   /* Retrieve tunnel */
6493   tid = ntohl (tunnel_msg->tunnel_id);
6494   t = tunnel_get_by_local_id(c, tid);
6495   if (NULL == t)
6496   {
6497     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  tunnel %X not found\n", tid);
6498     GNUNET_break (0);
6499     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6500     return;
6501   }
6502
6503   switch (ntohs(message->type))
6504   {
6505       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MIN:
6506           t->speed_min = GNUNET_YES;
6507           break;
6508       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MAX:
6509           t->speed_min = GNUNET_NO;
6510           break;
6511       default:
6512           GNUNET_break (0);
6513   }
6514   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6515 }
6516
6517
6518 /**
6519  * Handler for requests of seeting tunnel's buffering policy.
6520  *
6521  * @param cls Closure (unused).
6522  * @param client Identification of the client.
6523  * @param message The actual message.
6524  */
6525 static void
6526 handle_local_tunnel_buffer (void *cls, struct GNUNET_SERVER_Client *client,
6527                             const struct GNUNET_MessageHeader *message)
6528 {
6529   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
6530   struct MeshClient *c;
6531   struct MeshTunnel *t;
6532   MESH_TunnelNumber tid;
6533
6534   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6535               "Got a BUFFER request from client!\n");
6536
6537   /* Sanity check for client registration */
6538   if (NULL == (c = client_get (client)))
6539   {
6540     GNUNET_break (0);
6541     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6542     return;
6543   }
6544   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6545
6546   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
6547
6548   /* Retrieve tunnel */
6549   tid = ntohl (tunnel_msg->tunnel_id);
6550   t = tunnel_get_by_local_id(c, tid);
6551   if (NULL == t)
6552   {
6553     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  tunnel %X not found\n", tid);
6554     GNUNET_break (0);
6555     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6556     return;
6557   }
6558
6559   switch (ntohs(message->type))
6560   {
6561       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_BUFFER:
6562           t->nobuffer = GNUNET_NO;
6563           break;
6564       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_NOBUFFER:
6565           t->nobuffer = GNUNET_YES;
6566           break;
6567       default:
6568           GNUNET_break (0);
6569   }
6570
6571   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6572 }
6573
6574
6575 /**
6576  * Handler for connection requests to new peers
6577  *
6578  * @param cls closure
6579  * @param client identification of the client
6580  * @param message the actual message (PeerControl)
6581  */
6582 static void
6583 handle_local_connect_add (void *cls, struct GNUNET_SERVER_Client *client,
6584                           const struct GNUNET_MessageHeader *message)
6585 {
6586   struct GNUNET_MESH_PeerControl *peer_msg;
6587   struct MeshPeerInfo *peer_info;
6588   struct MeshClient *c;
6589   struct MeshTunnel *t;
6590   MESH_TunnelNumber tid;
6591
6592   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got connection request\n");
6593   /* Sanity check for client registration */
6594   if (NULL == (c = client_get (client)))
6595   {
6596     GNUNET_break (0);
6597     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6598     return;
6599   }
6600   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6601
6602   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
6603
6604   /* Sanity check for message size */
6605   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
6606   {
6607     GNUNET_break (0);
6608     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6609     return;
6610   }
6611
6612   /* Tunnel exists? */
6613   tid = ntohl (peer_msg->tunnel_id);
6614   t = tunnel_get_by_local_id (c, tid);
6615   if (NULL == t)
6616   {
6617     GNUNET_break (0);
6618     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6619     return;
6620   }
6621
6622   /* Does client own tunnel? */
6623   if (t->owner->handle != client)
6624   {
6625     GNUNET_break (0);
6626     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6627     return;
6628   }
6629   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "     for %s\n",
6630               GNUNET_i2s (&peer_msg->peer));
6631   peer_info = peer_info_get (&peer_msg->peer);
6632
6633   tunnel_add_peer (t, peer_info);
6634   peer_info_connect (peer_info, t);
6635
6636   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6637   return;
6638 }
6639
6640
6641 /**
6642  * Handler for disconnection requests of peers in a tunnel
6643  *
6644  * @param cls closure
6645  * @param client identification of the client
6646  * @param message the actual message (PeerControl)
6647  */
6648 static void
6649 handle_local_connect_del (void *cls, struct GNUNET_SERVER_Client *client,
6650                           const struct GNUNET_MessageHeader *message)
6651 {
6652   struct GNUNET_MESH_PeerControl *peer_msg;
6653   struct MeshPeerInfo *peer_info;
6654   struct MeshClient *c;
6655   struct MeshTunnel *t;
6656   MESH_TunnelNumber tid;
6657
6658   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a PEER DEL request\n");
6659   /* Sanity check for client registration */
6660   if (NULL == (c = client_get (client)))
6661   {
6662     GNUNET_break (0);
6663     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6664     return;
6665   }
6666   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6667
6668   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
6669
6670   /* Sanity check for message size */
6671   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
6672   {
6673     GNUNET_break (0);
6674     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6675     return;
6676   }
6677
6678   /* Tunnel exists? */
6679   tid = ntohl (peer_msg->tunnel_id);
6680   t = tunnel_get_by_local_id (c, tid);
6681   if (NULL == t)
6682   {
6683     GNUNET_break (0);
6684     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6685     return;
6686   }
6687   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", t->id.tid);
6688
6689   /* Does client own tunnel? */
6690   if (t->owner->handle != client)
6691   {
6692     GNUNET_break (0);
6693     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6694     return;
6695   }
6696
6697   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for peer %s\n",
6698               GNUNET_i2s (&peer_msg->peer));
6699   /* Is the peer in the tunnel? */
6700   peer_info =
6701       GNUNET_CONTAINER_multihashmap_get (t->peers, &peer_msg->peer.hashPubKey);
6702   if (NULL == peer_info)
6703   {
6704     GNUNET_break (0);
6705     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6706     return;
6707   }
6708
6709   /* Ok, delete peer from tunnel */
6710   GNUNET_CONTAINER_multihashmap_remove_all (t->peers,
6711                                             &peer_msg->peer.hashPubKey);
6712
6713   send_destroy_path (t, peer_info->id);
6714   tunnel_delete_peer (t, peer_info->id);
6715   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6716   return;
6717 }
6718
6719 /**
6720  * Handler for blacklist requests of peers in a tunnel
6721  *
6722  * @param cls closure
6723  * @param client identification of the client
6724  * @param message the actual message (PeerControl)
6725  * 
6726  * FIXME implement DHT block bloomfilter
6727  */
6728 static void
6729 handle_local_blacklist (void *cls, struct GNUNET_SERVER_Client *client,
6730                           const struct GNUNET_MessageHeader *message)
6731 {
6732   struct GNUNET_MESH_PeerControl *peer_msg;
6733   struct MeshClient *c;
6734   struct MeshTunnel *t;
6735   MESH_TunnelNumber tid;
6736
6737   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a PEER BLACKLIST request\n");
6738   /* Sanity check for client registration */
6739   if (NULL == (c = client_get (client)))
6740   {
6741     GNUNET_break (0);
6742     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6743     return;
6744   }
6745   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6746
6747   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
6748
6749   /* Sanity check for message size */
6750   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
6751   {
6752     GNUNET_break (0);
6753     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6754     return;
6755   }
6756
6757   /* Tunnel exists? */
6758   tid = ntohl (peer_msg->tunnel_id);
6759   t = tunnel_get_by_local_id (c, tid);
6760   if (NULL == t)
6761   {
6762     GNUNET_break (0);
6763     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6764     return;
6765   }
6766   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", t->id.tid);
6767
6768   GNUNET_array_append(t->blacklisted, t->nblacklisted,
6769                       GNUNET_PEER_intern(&peer_msg->peer));
6770 }
6771
6772
6773 /**
6774  * Handler for unblacklist requests of peers in a tunnel
6775  *
6776  * @param cls closure
6777  * @param client identification of the client
6778  * @param message the actual message (PeerControl)
6779  */
6780 static void
6781 handle_local_unblacklist (void *cls, struct GNUNET_SERVER_Client *client,
6782                           const struct GNUNET_MessageHeader *message)
6783 {
6784   struct GNUNET_MESH_PeerControl *peer_msg;
6785   struct MeshClient *c;
6786   struct MeshTunnel *t;
6787   MESH_TunnelNumber tid;
6788   GNUNET_PEER_Id pid;
6789   unsigned int i;
6790
6791   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a PEER UNBLACKLIST request\n");
6792   /* Sanity check for client registration */
6793   if (NULL == (c = client_get (client)))
6794   {
6795     GNUNET_break (0);
6796     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6797     return;
6798   }
6799   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6800
6801   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
6802
6803   /* Sanity check for message size */
6804   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
6805   {
6806     GNUNET_break (0);
6807     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6808     return;
6809   }
6810
6811   /* Tunnel exists? */
6812   tid = ntohl (peer_msg->tunnel_id);
6813   t = tunnel_get_by_local_id (c, tid);
6814   if (NULL == t)
6815   {
6816     GNUNET_break (0);
6817     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6818     return;
6819   }
6820   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", t->id.tid);
6821
6822   /* if peer is not known, complain */
6823   pid = GNUNET_PEER_search (&peer_msg->peer);
6824   if (0 == pid)
6825   {
6826     GNUNET_break (0);
6827     return;
6828   }
6829
6830   /* search and remove from list */
6831   for (i = 0; i < t->nblacklisted; i++)
6832   {
6833     if (t->blacklisted[i] == pid)
6834     {
6835       t->blacklisted[i] = t->blacklisted[t->nblacklisted - 1];
6836       GNUNET_array_grow (t->blacklisted, t->nblacklisted, t->nblacklisted - 1);
6837       return;
6838     }
6839   }
6840
6841   /* if peer hasn't been blacklisted, complain */
6842   GNUNET_break (0);
6843 }
6844
6845
6846 /**
6847  * Handler for connection requests to new peers by type
6848  *
6849  * @param cls closure
6850  * @param client identification of the client
6851  * @param message the actual message (ConnectPeerByType)
6852  */
6853 static void
6854 handle_local_connect_by_type (void *cls, struct GNUNET_SERVER_Client *client,
6855                               const struct GNUNET_MessageHeader *message)
6856 {
6857   struct GNUNET_MESH_ConnectPeerByType *connect_msg;
6858   struct MeshClient *c;
6859   struct MeshTunnel *t;
6860   struct GNUNET_HashCode hash;
6861   MESH_TunnelNumber tid;
6862
6863   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got connect by type request\n");
6864   /* Sanity check for client registration */
6865   if (NULL == (c = client_get (client)))
6866   {
6867     GNUNET_break (0);
6868     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6869     return;
6870   }
6871   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6872
6873   connect_msg = (struct GNUNET_MESH_ConnectPeerByType *) message;
6874
6875   /* Sanity check for message size */
6876   if (sizeof (struct GNUNET_MESH_ConnectPeerByType) !=
6877       ntohs (connect_msg->header.size))
6878   {
6879     GNUNET_break (0);
6880     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6881     return;
6882   }
6883
6884   /* Tunnel exists? */
6885   tid = ntohl (connect_msg->tunnel_id);
6886   t = tunnel_get_by_local_id (c, tid);
6887   if (NULL == t)
6888   {
6889     GNUNET_break (0);
6890     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6891     return;
6892   }
6893
6894   /* Does client own tunnel? */
6895   if (t->owner->handle != client)
6896   {
6897     GNUNET_break (0);
6898     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6899     return;
6900   }
6901
6902   /* Do WE have the service? */
6903   t->type = ntohl (connect_msg->type);
6904   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " type requested: %u\n", t->type);
6905   GNUNET_CRYPTO_hash (&t->type, sizeof (GNUNET_MESH_ApplicationType), &hash);
6906   if (GNUNET_CONTAINER_multihashmap_contains (applications, &hash) ==
6907       GNUNET_YES)
6908   {
6909     /* Yes! Fast forward, add ourselves to the tunnel and send the
6910      * good news to the client, and alert the destination client of
6911      * an incoming tunnel.
6912      *
6913      * FIXME send a path create to self, avoid code duplication
6914      */
6915     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " available locally\n");
6916     GNUNET_CONTAINER_multihashmap_put (t->peers, &my_full_id.hashPubKey,
6917                                        peer_info_get (&my_full_id),
6918                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
6919
6920     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " notifying client\n");
6921     send_client_peer_connected (t, myid);
6922     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Done\n");
6923     GNUNET_SERVER_receive_done (client, GNUNET_OK);
6924
6925     t->local_tid_dest = next_local_tid++;
6926     GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
6927     GNUNET_CONTAINER_multihashmap_put (incoming_tunnels, &hash, t,
6928                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
6929
6930     return;
6931   }
6932   /* Ok, lets find a peer offering the service */
6933   if (NULL != t->dht_get_type)
6934   {
6935     GNUNET_DHT_get_stop (t->dht_get_type);
6936   }
6937   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " looking in DHT for %s\n",
6938               GNUNET_h2s (&hash));
6939   t->dht_get_type =
6940       GNUNET_DHT_get_start (dht_handle, 
6941                             GNUNET_BLOCK_TYPE_MESH_PEER_BY_TYPE,
6942                             &hash,
6943                             dht_replication_level,
6944                             GNUNET_DHT_RO_RECORD_ROUTE |
6945                             GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
6946                             NULL, 0,
6947                             &dht_get_type_handler, t);
6948
6949   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6950   return;
6951 }
6952
6953
6954 /**
6955  * Handler for connection requests to new peers by a string service description.
6956  *
6957  * @param cls closure
6958  * @param client identification of the client
6959  * @param message the actual message, which includes messages the client wants
6960  */
6961 static void
6962 handle_local_connect_by_string (void *cls, struct GNUNET_SERVER_Client *client,
6963                                 const struct GNUNET_MessageHeader *message)
6964 {
6965   struct GNUNET_MESH_ConnectPeerByString *msg;
6966   struct MeshRegexSearchContext *ctx;
6967   struct MeshRegexSearchInfo *info;
6968   struct GNUNET_DHT_GetHandle *get_h;
6969   struct GNUNET_HashCode key;
6970   struct MeshTunnel *t;
6971   struct MeshClient *c;
6972   MESH_TunnelNumber tid;
6973   const char *string;
6974   size_t size;
6975   size_t len;
6976   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6977               "Connect by string started\n");
6978   msg = (struct GNUNET_MESH_ConnectPeerByString *) message;
6979   size = htons (message->size);
6980
6981   /* Sanity check for client registration */
6982   if (NULL == (c = client_get (client)))
6983   {
6984     GNUNET_break (0);
6985     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6986     return;
6987   }
6988   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6989
6990   /* Message size sanity check */
6991   if (sizeof(struct GNUNET_MESH_ConnectPeerByString) >= size)
6992   {
6993     GNUNET_break (0);
6994     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6995     return;
6996   }
6997
6998   /* Tunnel exists? */
6999   tid = ntohl (msg->tunnel_id);
7000   t = tunnel_get_by_local_id (c, tid);
7001   if (NULL == t)
7002   {
7003     GNUNET_break (0);
7004     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7005     return;
7006   }
7007
7008   /* Does client own tunnel? */
7009   if (t->owner->handle != client)
7010   {
7011     GNUNET_break (0);
7012     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7013     return;
7014   }
7015
7016   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7017               "  on tunnel %s [%u]\n",
7018               GNUNET_i2s(&my_full_id),
7019               t->id.tid);
7020
7021   /* Only one connect_by_string allowed at the same time! */
7022   /* FIXME: allow more, return handle at api level to cancel, document */
7023   if (NULL != t->regex_ctx)
7024   {
7025     GNUNET_break (0);
7026     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7027     return;
7028   }
7029
7030   /* Find string itself */
7031   len = size - sizeof(struct GNUNET_MESH_ConnectPeerByString);
7032   string = (const char *) &msg[1];
7033
7034   /* Initialize context */
7035   size = GNUNET_REGEX_get_first_key(string, len, &key);
7036   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7037               "  consumed %u bits out of %u\n", size, len);
7038   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7039               "  looking for %s\n", GNUNET_h2s (&key));
7040
7041   info = GNUNET_malloc (sizeof (struct MeshRegexSearchInfo));
7042   info->t = t;
7043   info->description = GNUNET_malloc (len + 1);
7044   memcpy (info->description, string, len);
7045   info->description[len] = '\0';
7046   info->dht_get_handles = GNUNET_CONTAINER_multihashmap_create(32);
7047   info->dht_get_results = GNUNET_CONTAINER_multihashmap_create(32);
7048   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   string: %s\n", info->description);
7049
7050   ctx = GNUNET_malloc (sizeof (struct MeshRegexSearchContext));
7051   ctx->position = size;
7052   ctx->info = info;
7053   t->regex_ctx = ctx;
7054
7055   GNUNET_array_append (info->contexts, info->n_contexts, ctx);
7056
7057   /* Start search in DHT */
7058   get_h = GNUNET_DHT_get_start (dht_handle,    /* handle */
7059                                 GNUNET_BLOCK_TYPE_MESH_REGEX, /* type */
7060                                 &key,     /* key to search */
7061                                 dht_replication_level, /* replication level */
7062                                 GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
7063                                 NULL,       /* xquery */ // FIXME BLOOMFILTER
7064                                 0,     /* xquery bits */ // FIXME BLOOMFILTER SIZE
7065                                 &dht_get_string_handler, ctx);
7066
7067   GNUNET_break (GNUNET_OK ==
7068                 GNUNET_CONTAINER_multihashmap_put(info->dht_get_handles,
7069                                                   &key,
7070                                                   get_h,
7071                                                   GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
7072
7073   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7074   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "connect by string processed\n");
7075 }
7076
7077
7078 /**
7079  * Handler for client traffic directed to one peer
7080  *
7081  * @param cls closure
7082  * @param client identification of the client
7083  * @param message the actual message
7084  */
7085 static void
7086 handle_local_unicast (void *cls, struct GNUNET_SERVER_Client *client,
7087                       const struct GNUNET_MessageHeader *message)
7088 {
7089   struct MeshClient *c;
7090   struct MeshTunnel *t;
7091   struct MeshPeerInfo *pi;
7092   struct GNUNET_MESH_Unicast *data_msg;
7093   MESH_TunnelNumber tid;
7094   size_t size;
7095
7096   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7097               "Got a unicast request from a client!\n");
7098
7099   /* Sanity check for client registration */
7100   if (NULL == (c = client_get (client)))
7101   {
7102     GNUNET_break (0);
7103     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7104     return;
7105   }
7106   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7107
7108   data_msg = (struct GNUNET_MESH_Unicast *) message;
7109
7110   /* Sanity check for message size */
7111   size = ntohs (message->size);
7112   if (sizeof (struct GNUNET_MESH_Unicast) +
7113       sizeof (struct GNUNET_MessageHeader) > size)
7114   {
7115     GNUNET_break (0);
7116     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7117     return;
7118   }
7119
7120   /* Tunnel exists? */
7121   tid = ntohl (data_msg->tid);
7122   t = tunnel_get_by_local_id (c, tid);
7123   if (NULL == t)
7124   {
7125     GNUNET_break (0);
7126     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7127     return;
7128   }
7129
7130   /*  Is it a local tunnel? Then, does client own the tunnel? */
7131   if (t->owner->handle != client)
7132   {
7133     GNUNET_break (0);
7134     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7135     return;
7136   }
7137
7138   pi = GNUNET_CONTAINER_multihashmap_get (t->peers,
7139                                           &data_msg->destination.hashPubKey);
7140   /* Is the selected peer in the tunnel? */
7141   if (NULL == pi)
7142   {
7143     GNUNET_break (0);
7144     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7145     return;
7146   }
7147
7148   /* PID should be as expected */
7149   if (ntohl (data_msg->pid) != t->fwd_pid + 1)
7150   {
7151     GNUNET_break (0);
7152     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7153               "Unicast PID, expected %u, got %u\n",
7154               t->fwd_pid + 1, ntohl (data_msg->pid));
7155     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7156     return;
7157   }
7158
7159   /* Ok, everything is correct, send the message
7160    * (pretend we got it from a mesh peer)
7161    */
7162   {
7163     /* Work around const limitation */
7164     char buf[ntohs (message->size)] GNUNET_ALIGN;
7165     struct GNUNET_MESH_Unicast *copy;
7166
7167     copy = (struct GNUNET_MESH_Unicast *) buf;
7168     memcpy (buf, data_msg, size);
7169     copy->oid = my_full_id;
7170     copy->tid = htonl (t->id.tid);
7171     copy->ttl = htonl (default_ttl);
7172     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7173                 "  calling generic handler...\n");
7174     handle_mesh_data_unicast (NULL, &my_full_id, &copy->header, NULL, 0);
7175   }
7176   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "receive done OK\n");
7177   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7178
7179   return;
7180 }
7181
7182
7183 /**
7184  * Handler for client traffic directed to the origin
7185  *
7186  * @param cls closure
7187  * @param client identification of the client
7188  * @param message the actual message
7189  */
7190 static void
7191 handle_local_to_origin (void *cls, struct GNUNET_SERVER_Client *client,
7192                         const struct GNUNET_MessageHeader *message)
7193 {
7194   struct GNUNET_MESH_ToOrigin *data_msg;
7195   struct MeshTunnelClientInfo *clinfo;
7196   struct MeshClient *c;
7197   struct MeshTunnel *t;
7198   MESH_TunnelNumber tid;
7199   size_t size;
7200
7201   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7202               "Got a ToOrigin request from a client!\n");
7203   /* Sanity check for client registration */
7204   if (NULL == (c = client_get (client)))
7205   {
7206     GNUNET_break (0);
7207     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7208     return;
7209   }
7210   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7211
7212   data_msg = (struct GNUNET_MESH_ToOrigin *) message;
7213
7214   /* Sanity check for message size */
7215   size = ntohs (message->size);
7216   if (sizeof (struct GNUNET_MESH_ToOrigin) +
7217       sizeof (struct GNUNET_MessageHeader) > size)
7218   {
7219     GNUNET_break (0);
7220     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7221     return;
7222   }
7223
7224   /* Tunnel exists? */
7225   tid = ntohl (data_msg->tid);
7226   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", tid);
7227   if (tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
7228   {
7229     GNUNET_break (0);
7230     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7231     return;
7232   }
7233   t = tunnel_get_by_local_id (c, tid);
7234   if (NULL == t)
7235   {
7236     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Tunnel %X unknown.\n", tid);
7237     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  for client %u.\n", c->id);
7238     GNUNET_break (0);
7239     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7240     return;
7241   }
7242
7243   /*  It should be sent by someone who has this as incoming tunnel. */
7244   if (GNUNET_NO == client_knows_tunnel (c, t))
7245   {
7246     GNUNET_break (0);
7247     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7248     return;
7249   }
7250
7251   /* PID should be as expected */
7252   clinfo = tunnel_get_client_fc (t, c);
7253   if (ntohl (data_msg->pid) != clinfo->bck_pid + 1)
7254   {
7255     GNUNET_break (0);
7256     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7257                 "To Origin PID, expected %u, got %u\n",
7258                 clinfo->bck_pid + 1,
7259                 ntohl (data_msg->pid));
7260     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7261     return;
7262   }
7263
7264   /* Ok, everything is correct, send the message
7265    * (pretend we got it from a mesh peer)
7266    */
7267   clinfo->bck_pid++;
7268   {
7269     char buf[ntohs (message->size)] GNUNET_ALIGN;
7270     struct GNUNET_MESH_ToOrigin *copy;
7271
7272     /* Work around const limitation */
7273     copy = (struct GNUNET_MESH_ToOrigin *) buf;
7274     memcpy (buf, data_msg, size);
7275     GNUNET_PEER_resolve (t->id.oid, &copy->oid);
7276     copy->tid = htonl (t->id.tid);
7277     copy->ttl = htonl (default_ttl);
7278     if (ntohl (copy->pid) != (t->bck_pid + 1))
7279     {
7280       GNUNET_break (0);
7281       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7282                   "To Origin PID, expected %u, got %u\n",
7283                   t->bck_pid + 1,
7284                   ntohl (copy->pid));
7285       return;
7286     }
7287     t->bck_pid++;
7288     copy->sender = my_full_id;
7289     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7290                 "  calling generic handler...\n");
7291     handle_mesh_data_to_orig (NULL, &my_full_id, &copy->header, NULL, 0);
7292   }
7293   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7294
7295   return;
7296 }
7297
7298
7299 /**
7300  * Handler for client traffic directed to all peers in a tunnel
7301  *
7302  * @param cls closure
7303  * @param client identification of the client
7304  * @param message the actual message
7305  */
7306 static void
7307 handle_local_multicast (void *cls, struct GNUNET_SERVER_Client *client,
7308                         const struct GNUNET_MessageHeader *message)
7309 {
7310   struct MeshClient *c;
7311   struct MeshTunnel *t;
7312   struct GNUNET_MESH_Multicast *data_msg;
7313   MESH_TunnelNumber tid;
7314
7315   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7316               "Got a multicast request from a client!\n");
7317
7318   /* Sanity check for client registration */
7319   if (NULL == (c = client_get (client)))
7320   {
7321     GNUNET_break (0);
7322     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7323     return;
7324   }
7325   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7326
7327   data_msg = (struct GNUNET_MESH_Multicast *) message;
7328
7329   /* Sanity check for message size */
7330   if (sizeof (struct GNUNET_MESH_Multicast) +
7331       sizeof (struct GNUNET_MessageHeader) > ntohs (data_msg->header.size))
7332   {
7333     GNUNET_break (0);
7334     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7335     return;
7336   }
7337
7338   /* Tunnel exists? */
7339   tid = ntohl (data_msg->tid);
7340   t = tunnel_get_by_local_id (c, tid);
7341   if (NULL == t)
7342   {
7343     GNUNET_break (0);
7344     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Tunnel %X unknown.\n", tid);
7345     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  for client %u.\n", c->id);
7346     GNUNET_break (0);
7347     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7348     return;
7349   }
7350
7351   /* Does client own tunnel? */
7352   if (t->owner->handle != client)
7353   {
7354     GNUNET_break (0);
7355     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7356     return;
7357   }
7358
7359   /* PID should be as expected */
7360   if (ntohl (data_msg->pid) != t->fwd_pid + 1)
7361   {
7362     GNUNET_break (0);
7363     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7364               "Multicast PID, expected %u, got %u\n",
7365               t->fwd_pid + 1, ntohl (data_msg->pid));
7366     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7367     return;
7368   }
7369
7370   {
7371     char buf[ntohs (message->size)] GNUNET_ALIGN;
7372     struct GNUNET_MESH_Multicast *copy;
7373
7374     copy = (struct GNUNET_MESH_Multicast *) buf;
7375     memcpy (buf, message, ntohs (message->size));
7376     copy->oid = my_full_id;
7377     copy->tid = htonl (t->id.tid);
7378     copy->ttl = htonl (default_ttl);
7379     GNUNET_assert (ntohl (copy->pid) == (t->fwd_pid + 1));
7380     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7381                 "  calling generic handler...\n");
7382     handle_mesh_data_multicast (client, &my_full_id, &copy->header, NULL, 0);
7383   }
7384
7385   /* receive done gets called when last copy is sent to a neighbor */
7386   return;
7387 }
7388
7389
7390 /**
7391  * Handler for client's ACKs for payload traffic.
7392  *
7393  * @param cls Closure (unused).
7394  * @param client Identification of the client.
7395  * @param message The actual message.
7396  */
7397 static void
7398 handle_local_ack (void *cls, struct GNUNET_SERVER_Client *client,
7399                   const struct GNUNET_MessageHeader *message)
7400 {
7401   struct GNUNET_MESH_LocalAck *msg;
7402   struct MeshTunnel *t;
7403   struct MeshClient *c;
7404   MESH_TunnelNumber tid;
7405   uint32_t ack;
7406
7407   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a local ACK\n");
7408   /* Sanity check for client registration */
7409   if (NULL == (c = client_get (client)))
7410   {
7411     GNUNET_break (0);
7412     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7413     return;
7414   }
7415   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7416
7417   msg = (struct GNUNET_MESH_LocalAck *) message;
7418
7419   /* Tunnel exists? */
7420   tid = ntohl (msg->tunnel_id);
7421   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", tid);
7422   t = tunnel_get_by_local_id (c, tid);
7423   if (NULL == t)
7424   {
7425     GNUNET_break (0);
7426     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Tunnel %X unknown.\n", tid);
7427     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  for client %u.\n", c->id);
7428     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7429     return;
7430   }
7431
7432   ack = ntohl (msg->max_pid);
7433   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ack %u\n", ack);
7434
7435   /* Does client own tunnel? I.E: Is this and ACK for BCK traffic? */
7436   if (NULL != t->owner && t->owner->handle == client)
7437   {
7438     /* The client owns the tunnel, ACK is for data to_origin, send BCK ACK. */
7439     t->bck_ack = ack;
7440     tunnel_send_bck_ack(t, GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
7441   }
7442   else
7443   {
7444     /* The client doesn't own the tunnel, this ACK is for FWD traffic. */
7445     tunnel_set_client_fwd_ack (t, c, ack);
7446     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
7447   }
7448
7449   GNUNET_SERVER_receive_done (client, GNUNET_OK);  
7450
7451   return;
7452 }
7453
7454
7455 /**
7456  * Functions to handle messages from clients
7457  */
7458 static struct GNUNET_SERVER_MessageHandler client_handlers[] = {
7459   {&handle_local_new_client, NULL,
7460    GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT, 0},
7461   {&handle_local_announce_regex, NULL,
7462    GNUNET_MESSAGE_TYPE_MESH_LOCAL_ANNOUNCE_REGEX, 0},
7463   {&handle_local_tunnel_create, NULL,
7464    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE,
7465    sizeof (struct GNUNET_MESH_TunnelMessage)},
7466   {&handle_local_tunnel_destroy, NULL,
7467    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY,
7468    sizeof (struct GNUNET_MESH_TunnelMessage)},
7469   {&handle_local_tunnel_speed, NULL,
7470    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MIN,
7471    sizeof (struct GNUNET_MESH_TunnelMessage)},
7472   {&handle_local_tunnel_speed, NULL,
7473    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MAX,
7474    sizeof (struct GNUNET_MESH_TunnelMessage)},
7475   {&handle_local_tunnel_buffer, NULL,
7476    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_BUFFER,
7477    sizeof (struct GNUNET_MESH_TunnelMessage)},
7478   {&handle_local_tunnel_buffer, NULL,
7479    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_NOBUFFER,
7480    sizeof (struct GNUNET_MESH_TunnelMessage)},
7481   {&handle_local_connect_add, NULL,
7482    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD,
7483    sizeof (struct GNUNET_MESH_PeerControl)},
7484   {&handle_local_connect_del, NULL,
7485    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL,
7486    sizeof (struct GNUNET_MESH_PeerControl)},
7487   {&handle_local_blacklist, NULL,
7488    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_BLACKLIST,
7489    sizeof (struct GNUNET_MESH_PeerControl)},
7490   {&handle_local_unblacklist, NULL,
7491    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_UNBLACKLIST,
7492    sizeof (struct GNUNET_MESH_PeerControl)},
7493   {&handle_local_connect_by_type, NULL,
7494    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_TYPE,
7495    sizeof (struct GNUNET_MESH_ConnectPeerByType)},
7496   {&handle_local_connect_by_string, NULL,
7497    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_STRING, 0},
7498   {&handle_local_unicast, NULL,
7499    GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
7500   {&handle_local_to_origin, NULL,
7501    GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
7502   {&handle_local_multicast, NULL,
7503    GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
7504   {&handle_local_ack, NULL,
7505    GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK,
7506    sizeof (struct GNUNET_MESH_LocalAck)},
7507   {NULL, NULL, 0, 0}
7508 };
7509
7510
7511 /**
7512  * To be called on core init/fail.
7513  *
7514  * @param cls service closure
7515  * @param server handle to the server for this service
7516  * @param identity the public identity of this peer
7517  */
7518 static void
7519 core_init (void *cls, struct GNUNET_CORE_Handle *server,
7520            const struct GNUNET_PeerIdentity *identity)
7521 {
7522   static int i = 0;
7523   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Core init\n");
7524   core_handle = server;
7525   if (0 != memcmp (identity, &my_full_id, sizeof (my_full_id)) ||
7526       NULL == server)
7527   {
7528     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Wrong CORE service\n"));
7529     GNUNET_SCHEDULER_shutdown (); // Try gracefully
7530     if (10 < i++)
7531       GNUNET_abort(); // Try harder
7532   }
7533   return;
7534 }
7535
7536
7537 /**
7538  * Method called whenever a given peer connects.
7539  *
7540  * @param cls closure
7541  * @param peer peer identity this notification is about
7542  * @param atsi performance data for the connection
7543  * @param atsi_count number of records in 'atsi'
7544  */
7545 static void
7546 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
7547               const struct GNUNET_ATS_Information *atsi,
7548               unsigned int atsi_count)
7549 {
7550   struct MeshPeerInfo *peer_info;
7551   struct MeshPeerPath *path;
7552
7553   DEBUG_CONN ("Peer connected\n");
7554   DEBUG_CONN ("     %s\n", GNUNET_i2s (&my_full_id));
7555   peer_info = peer_info_get (peer);
7556   if (myid == peer_info->id)
7557   {
7558     DEBUG_CONN ("     (self)\n");
7559     return;
7560   }
7561   else
7562   {
7563     DEBUG_CONN ("     %s\n", GNUNET_i2s (peer));
7564   }
7565   path = path_new (2);
7566   path->peers[0] = myid;
7567   path->peers[1] = peer_info->id;
7568   GNUNET_PEER_change_rc (myid, 1);
7569   GNUNET_PEER_change_rc (peer_info->id, 1);
7570   peer_info_add_path (peer_info, path, GNUNET_YES);
7571   GNUNET_STATISTICS_update (stats, "# peers", 1, GNUNET_NO);
7572   return;
7573 }
7574
7575
7576 /**
7577  * Method called whenever a peer disconnects.
7578  *
7579  * @param cls closure
7580  * @param peer peer identity this notification is about
7581  */
7582 static void
7583 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
7584 {
7585   struct MeshPeerInfo *pi;
7586   struct MeshPeerQueue *q;
7587   struct MeshPeerQueue *n;
7588
7589   DEBUG_CONN ("Peer disconnected\n");
7590   pi = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
7591   if (NULL == pi)
7592   {
7593     GNUNET_break (0);
7594     return;
7595   }
7596   q = pi->queue_head;
7597   while (NULL != q)
7598   {
7599       n = q->next;
7600       if (q->peer == pi)
7601       {
7602         /* try to reroute this traffic instead */
7603         queue_destroy(q, GNUNET_YES);
7604       }
7605       q = n;
7606   }
7607   peer_info_remove_path (pi, pi->id, myid);
7608   if (myid == pi->id)
7609   {
7610     DEBUG_CONN ("     (self)\n");
7611   }
7612   GNUNET_STATISTICS_update (stats, "# peers", -1, GNUNET_NO);
7613   return;
7614 }
7615
7616
7617 /******************************************************************************/
7618 /************************      MAIN FUNCTIONS      ****************************/
7619 /******************************************************************************/
7620
7621 /**
7622  * Iterator over tunnel hash map entries to destroy the tunnel during shutdown.
7623  *
7624  * @param cls closure
7625  * @param key current key code
7626  * @param value value in the hash map
7627  * @return GNUNET_YES if we should continue to iterate,
7628  *         GNUNET_NO if not.
7629  */
7630 static int
7631 shutdown_tunnel (void *cls, const struct GNUNET_HashCode * key, void *value)
7632 {
7633   struct MeshTunnel *t = value;
7634
7635   tunnel_destroy (t);
7636   return GNUNET_YES;
7637 }
7638
7639 /**
7640  * Iterator over peer hash map entries to destroy the tunnel during shutdown.
7641  *
7642  * @param cls closure
7643  * @param key current key code
7644  * @param value value in the hash map
7645  * @return GNUNET_YES if we should continue to iterate,
7646  *         GNUNET_NO if not.
7647  */
7648 static int
7649 shutdown_peer (void *cls, const struct GNUNET_HashCode * key, void *value)
7650 {
7651   struct MeshPeerInfo *p = value;
7652   struct MeshPeerQueue *q;
7653   struct MeshPeerQueue *n;
7654
7655   q = p->queue_head;
7656   while (NULL != q)
7657   {
7658       n = q->next;
7659       if (q->peer == p)
7660       {
7661         queue_destroy(q, GNUNET_YES);
7662       }
7663       q = n;
7664   }
7665   peer_info_destroy (p);
7666   return GNUNET_YES;
7667 }
7668
7669 /**
7670  * Task run during shutdown.
7671  *
7672  * @param cls unused
7673  * @param tc unused
7674  */
7675 static void
7676 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
7677 {
7678   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shutting down\n");
7679
7680   if (core_handle != NULL)
7681   {
7682     GNUNET_CORE_disconnect (core_handle);
7683     core_handle = NULL;
7684   }
7685   GNUNET_CONTAINER_multihashmap_iterate (tunnels, &shutdown_tunnel, NULL);
7686   GNUNET_CONTAINER_multihashmap_iterate (peers, &shutdown_peer, NULL);
7687   if (dht_handle != NULL)
7688   {
7689     GNUNET_DHT_disconnect (dht_handle);
7690     dht_handle = NULL;
7691   }
7692   if (nc != NULL)
7693   {
7694     GNUNET_SERVER_notification_context_destroy (nc);
7695     nc = NULL;
7696   }
7697   if (GNUNET_SCHEDULER_NO_TASK != announce_id_task)
7698   {
7699     GNUNET_SCHEDULER_cancel (announce_id_task);
7700     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
7701   }
7702   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shut down\n");
7703 }
7704
7705 /**
7706  * Process mesh requests.
7707  *
7708  * @param cls closure
7709  * @param server the initialized server
7710  * @param c configuration to use
7711  */
7712 static void
7713 run (void *cls, struct GNUNET_SERVER_Handle *server,
7714      const struct GNUNET_CONFIGURATION_Handle *c)
7715 {
7716   struct MeshPeerInfo *peer;
7717   struct MeshPeerPath *p;
7718   char *keyfile;
7719
7720   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "starting to run\n");
7721   server_handle = server;
7722   core_handle = GNUNET_CORE_connect (c, /* Main configuration */
7723                                      NULL,      /* Closure passed to MESH functions */
7724                                      &core_init,        /* Call core_init once connected */
7725                                      &core_connect,     /* Handle connects */
7726                                      &core_disconnect,  /* remove peers on disconnects */
7727                                      NULL,      /* Don't notify about all incoming messages */
7728                                      GNUNET_NO, /* For header only in notification */
7729                                      NULL,      /* Don't notify about all outbound messages */
7730                                      GNUNET_NO, /* For header-only out notification */
7731                                      core_handlers);    /* Register these handlers */
7732
7733   if (core_handle == NULL)
7734   {
7735     GNUNET_break (0);
7736     GNUNET_SCHEDULER_shutdown ();
7737     return;
7738   }
7739
7740   if (GNUNET_OK !=
7741       GNUNET_CONFIGURATION_get_value_filename (c, "GNUNETD", "HOSTKEY",
7742                                                &keyfile))
7743   {
7744     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7745                 _
7746                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7747                 "hostkey");
7748     GNUNET_SCHEDULER_shutdown ();
7749     return;
7750   }
7751
7752   if (GNUNET_OK !=
7753       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "REFRESH_PATH_TIME",
7754                                            &refresh_path_time))
7755   {
7756     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7757                 _
7758                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7759                 "refresh path time");
7760     GNUNET_SCHEDULER_shutdown ();
7761     return;
7762   }
7763
7764   if (GNUNET_OK !=
7765       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "APP_ANNOUNCE_TIME",
7766                                            &app_announce_time))
7767   {
7768     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7769                 _
7770                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7771                 "app announce time");
7772     GNUNET_SCHEDULER_shutdown ();
7773     return;
7774   }
7775
7776   if (GNUNET_OK !=
7777       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "ID_ANNOUNCE_TIME",
7778                                            &id_announce_time))
7779   {
7780     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7781                 _
7782                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7783                 "id announce time");
7784     GNUNET_SCHEDULER_shutdown ();
7785     return;
7786   }
7787
7788   if (GNUNET_OK !=
7789       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "UNACKNOWLEDGED_WAIT",
7790                                            &unacknowledged_wait_time))
7791   {
7792     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7793                 _
7794                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7795                 "unacknowledged wait time");
7796     GNUNET_SCHEDULER_shutdown ();
7797     return;
7798   }
7799
7800   if (GNUNET_OK !=
7801       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "CONNECT_TIMEOUT",
7802                                            &connect_timeout))
7803   {
7804     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7805                 _
7806                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7807                 "connect timeout");
7808     GNUNET_SCHEDULER_shutdown ();
7809     return;
7810   }
7811
7812   if (GNUNET_OK !=
7813       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_MSGS_QUEUE",
7814                                              &max_msgs_queue))
7815   {
7816     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7817                 _
7818                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7819                 "max msgs queue");
7820     GNUNET_SCHEDULER_shutdown ();
7821     return;
7822   }
7823
7824   if (GNUNET_OK !=
7825       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_TUNNELS",
7826                                              &max_tunnels))
7827   {
7828     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7829                 _
7830                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7831                 "max tunnels");
7832     GNUNET_SCHEDULER_shutdown ();
7833     return;
7834   }
7835
7836   if (GNUNET_OK !=
7837       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DEFAULT_TTL",
7838                                              &default_ttl))
7839   {
7840     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7841                 _
7842                 ("Mesh service is lacking key configuration settings (%s). Using default (%u).\n"),
7843                 "default ttl", 64);
7844     default_ttl = 64;
7845   }
7846
7847   if (GNUNET_OK !=
7848       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DHT_REPLICATION_LEVEL",
7849                                              &dht_replication_level))
7850   {
7851     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7852                 _
7853                 ("Mesh service is lacking key configuration settings (%s). Using default (%u).\n"),
7854                 "dht replication level", 10);
7855     dht_replication_level = 10;
7856   }
7857
7858   
7859   my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
7860   GNUNET_free (keyfile);
7861   if (my_private_key == NULL)
7862   {
7863     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7864                 _("Mesh service could not access hostkey.  Exiting.\n"));
7865     GNUNET_SCHEDULER_shutdown ();
7866     return;
7867   }
7868   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
7869   GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
7870                       &my_full_id.hashPubKey);
7871   myid = GNUNET_PEER_intern (&my_full_id);
7872   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
7873               "Mesh for peer [%s] starting\n",
7874               GNUNET_i2s(&my_full_id));
7875
7876 //   transport_handle = GNUNET_TRANSPORT_connect(c,
7877 //                                               &my_full_id,
7878 //                                               NULL,
7879 //                                               NULL,
7880 //                                               NULL,
7881 //                                               NULL);
7882
7883   dht_handle = GNUNET_DHT_connect (c, 64);
7884   if (dht_handle == NULL)
7885   {
7886     GNUNET_break (0);
7887   }
7888
7889   stats = GNUNET_STATISTICS_create ("mesh", c);
7890
7891
7892   next_tid = 0;
7893   next_local_tid = GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
7894
7895   tunnels = GNUNET_CONTAINER_multihashmap_create (32);
7896   incoming_tunnels = GNUNET_CONTAINER_multihashmap_create (32);
7897   peers = GNUNET_CONTAINER_multihashmap_create (32);
7898   applications = GNUNET_CONTAINER_multihashmap_create (32);
7899   types = GNUNET_CONTAINER_multihashmap_create (32);
7900
7901   GNUNET_SERVER_add_handlers (server_handle, client_handlers);
7902   nc = GNUNET_SERVER_notification_context_create (server_handle, 1);
7903   GNUNET_SERVER_disconnect_notify (server_handle,
7904                                    &handle_local_client_disconnect, NULL);
7905
7906
7907   clients = NULL;
7908   clients_tail = NULL;
7909   next_client_id = 0;
7910
7911   announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
7912   announce_id_task = GNUNET_SCHEDULER_add_now (&announce_id, cls);
7913
7914   /* Create a peer_info for the local peer */
7915   peer = peer_info_get (&my_full_id);
7916   p = path_new (1);
7917   p->peers[0] = myid;
7918   GNUNET_PEER_change_rc (myid, 1);
7919   peer_info_add_path (peer, p, GNUNET_YES);
7920
7921   /* Scheduled the task to clean up when shutdown is called */
7922   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
7923                                 NULL);
7924
7925   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "end of run()\n");
7926 }
7927
7928 /**
7929  * The main function for the mesh service.
7930  *
7931  * @param argc number of arguments from the command line
7932  * @param argv command line arguments
7933  * @return 0 ok, 1 on error
7934  */
7935 int
7936 main (int argc, char *const *argv)
7937 {
7938   int ret;
7939
7940   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main()\n");
7941   ret =
7942       (GNUNET_OK ==
7943        GNUNET_SERVICE_run (argc, argv, "mesh", GNUNET_SERVICE_OPTION_NONE, &run,
7944                            NULL)) ? 0 : 1;
7945   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main() END\n");
7946
7947   INTERVAL_SHOW;
7948
7949   return ret;
7950 }