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