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