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