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