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