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