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