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