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