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