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