b8ff58e310750505607ac34ed78e7ddd9ec98310
[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     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4995                 "  speed_min: %d, nobuffer:%d\n",
4996                 t->speed_min, t->nobuffer);
4997
4998     if (GNUNET_YES == t->nobuffer)
4999     {
5000       t->bck_queue_max = 1;
5001       t->fwd_queue_max = 1;
5002     }
5003
5004     // FIXME only assign a local tid if a local client is interested (on demand)
5005     while (NULL != tunnel_get_incoming (next_local_tid))
5006       next_local_tid = (next_local_tid + 1) | GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
5007     t->local_tid_dest = next_local_tid++;
5008     next_local_tid = next_local_tid | GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
5009     // FIXME end
5010
5011     tunnel_reset_timeout (t);
5012     GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
5013     if (GNUNET_OK !=
5014         GNUNET_CONTAINER_multihashmap_put (incoming_tunnels, &hash, t,
5015                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
5016     {
5017       tunnel_destroy (t);
5018       GNUNET_break (0);
5019       return GNUNET_OK;
5020     }
5021   }
5022   dest_peer_info =
5023       GNUNET_CONTAINER_multihashmap_get (peers, &pi[size - 1].hashPubKey);
5024   if (NULL == dest_peer_info)
5025   {
5026     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5027                 "  Creating PeerInfo for destination.\n");
5028     dest_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
5029     dest_peer_info->id = GNUNET_PEER_intern (&pi[size - 1]);
5030     GNUNET_CONTAINER_multihashmap_put (peers, &pi[size - 1].hashPubKey,
5031                                        dest_peer_info,
5032                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
5033   }
5034   orig_peer_info = GNUNET_CONTAINER_multihashmap_get (peers, &pi->hashPubKey);
5035   if (NULL == orig_peer_info)
5036   {
5037     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5038                 "  Creating PeerInfo for origin.\n");
5039     orig_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
5040     orig_peer_info->id = GNUNET_PEER_intern (pi);
5041     GNUNET_CONTAINER_multihashmap_put (peers, &pi->hashPubKey, orig_peer_info,
5042                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
5043   }
5044   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
5045   path = path_new (size);
5046   own_pos = 0;
5047   for (i = 0; i < size; i++)
5048   {
5049     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ... adding %s\n",
5050                 GNUNET_i2s (&pi[i]));
5051     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
5052     if (path->peers[i] == myid)
5053       own_pos = i;
5054   }
5055   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
5056   if (own_pos == 0)
5057   {
5058     /* cannot be self, must be 'not found' */
5059     /* create path: self not found in path through self */
5060     GNUNET_break_op (0);
5061     path_destroy (path);
5062     tunnel_destroy (t);
5063     return GNUNET_OK;
5064   }
5065   path_add_to_peers (path, GNUNET_NO);
5066   tunnel_add_path (t, path, own_pos);
5067   if (own_pos == size - 1)
5068   {
5069     /* It is for us! Send ack. */
5070     struct MeshTransmissionDescriptor *info;
5071
5072     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
5073     peer_info_add_path_to_origin (orig_peer_info, path, GNUNET_NO);
5074     if (NULL == t->peers)
5075     {
5076       /* New tunnel! Notify clients on data. */
5077       t->peers = GNUNET_CONTAINER_multihashmap_create (4);
5078     }
5079     GNUNET_break (GNUNET_SYSERR !=
5080                   GNUNET_CONTAINER_multihashmap_put (t->peers,
5081                                                      &my_full_id.hashPubKey,
5082                                                      peer_info_get
5083                                                      (&my_full_id),
5084                                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE));
5085     info = GNUNET_malloc (sizeof (struct MeshTransmissionDescriptor));
5086     info->origin = &t->id;
5087     info->peer = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
5088     GNUNET_assert (NULL != info->peer);
5089     queue_add(info,
5090               GNUNET_MESSAGE_TYPE_MESH_PATH_ACK,
5091               sizeof (struct GNUNET_MESH_PathACK),
5092               info->peer,
5093               t);
5094   }
5095   else
5096   {
5097     struct MeshPeerPath *path2;
5098
5099     /* It's for somebody else! Retransmit. */
5100     path2 = path_duplicate (path);
5101     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Retransmitting.\n");
5102     peer_info_add_path (dest_peer_info, path2, GNUNET_NO);
5103     path2 = path_duplicate (path);
5104     peer_info_add_path_to_origin (orig_peer_info, path2, GNUNET_NO);
5105     send_create_path (dest_peer_info, path, t);
5106   }
5107   return GNUNET_OK;
5108 }
5109
5110
5111 /**
5112  * Core handler for path destruction
5113  *
5114  * @param cls closure
5115  * @param message message
5116  * @param peer peer identity this notification is about
5117  * @param atsi performance data
5118  * @param atsi_count number of records in 'atsi'
5119  *
5120  * @return GNUNET_OK to keep the connection open,
5121  *         GNUNET_SYSERR to close it (signal serious error)
5122  */
5123 static int
5124 handle_mesh_path_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
5125                           const struct GNUNET_MessageHeader *message,
5126                           const struct GNUNET_ATS_Information *atsi,
5127                           unsigned int atsi_count)
5128 {
5129   struct GNUNET_MESH_ManipulatePath *msg;
5130   struct GNUNET_PeerIdentity *pi;
5131   struct MeshPeerPath *path;
5132   struct MeshTunnel *t;
5133   unsigned int own_pos;
5134   unsigned int i;
5135   size_t size;
5136
5137   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5138               "Received a PATH DESTROY msg from %s\n", GNUNET_i2s (peer));
5139   size = ntohs (message->size);
5140   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
5141   {
5142     GNUNET_break_op (0);
5143     return GNUNET_OK;
5144   }
5145
5146   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
5147   if (size % sizeof (struct GNUNET_PeerIdentity))
5148   {
5149     GNUNET_break_op (0);
5150     return GNUNET_OK;
5151   }
5152   size /= sizeof (struct GNUNET_PeerIdentity);
5153   if (size < 2)
5154   {
5155     GNUNET_break_op (0);
5156     return GNUNET_OK;
5157   }
5158   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
5159
5160   msg = (struct GNUNET_MESH_ManipulatePath *) message;
5161   pi = (struct GNUNET_PeerIdentity *) &msg[1];
5162   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5163               "    path is for tunnel %s [%X].\n", GNUNET_i2s (pi),
5164               msg->tid);
5165   t = tunnel_get (pi, ntohl (msg->tid));
5166   if (NULL == t)
5167   {
5168     /* TODO notify back: we don't know this tunnel */
5169     GNUNET_break_op (0);
5170     return GNUNET_OK;
5171   }
5172   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
5173   path = path_new (size);
5174   own_pos = 0;
5175   for (i = 0; i < size; i++)
5176   {
5177     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ... adding %s\n",
5178                 GNUNET_i2s (&pi[i]));
5179     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
5180     if (path->peers[i] == myid)
5181       own_pos = i;
5182   }
5183   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
5184   if (own_pos < path->length - 1)
5185     send_message (message, &pi[own_pos + 1], t);
5186   else
5187     send_client_tunnel_disconnect(t, NULL);
5188
5189   tunnel_delete_peer (t, path->peers[path->length - 1]);
5190   path_destroy (path);
5191   return GNUNET_OK;
5192 }
5193
5194
5195 /**
5196  * Core handler for notifications of broken paths
5197  *
5198  * @param cls closure
5199  * @param message message
5200  * @param peer peer identity this notification is about
5201  * @param atsi performance data
5202  * @param atsi_count number of records in 'atsi'
5203  *
5204  * @return GNUNET_OK to keep the connection open,
5205  *         GNUNET_SYSERR to close it (signal serious error)
5206  */
5207 static int
5208 handle_mesh_path_broken (void *cls, const struct GNUNET_PeerIdentity *peer,
5209                          const struct GNUNET_MessageHeader *message,
5210                          const struct GNUNET_ATS_Information *atsi,
5211                          unsigned int atsi_count)
5212 {
5213   struct GNUNET_MESH_PathBroken *msg;
5214   struct MeshTunnel *t;
5215
5216   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5217               "Received a PATH BROKEN msg from %s\n", GNUNET_i2s (peer));
5218   msg = (struct GNUNET_MESH_PathBroken *) message;
5219   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
5220               GNUNET_i2s (&msg->peer1));
5221   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
5222               GNUNET_i2s (&msg->peer2));
5223   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5224   if (NULL == t)
5225   {
5226     GNUNET_break_op (0);
5227     return GNUNET_OK;
5228   }
5229   tunnel_notify_connection_broken (t, GNUNET_PEER_search (&msg->peer1),
5230                                    GNUNET_PEER_search (&msg->peer2));
5231   return GNUNET_OK;
5232
5233 }
5234
5235
5236 /**
5237  * Core handler for tunnel destruction
5238  *
5239  * @param cls closure
5240  * @param message message
5241  * @param peer peer identity this notification is about
5242  * @param atsi performance data
5243  * @param atsi_count number of records in 'atsi'
5244  *
5245  * @return GNUNET_OK to keep the connection open,
5246  *         GNUNET_SYSERR to close it (signal serious error)
5247  */
5248 static int
5249 handle_mesh_tunnel_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
5250                             const struct GNUNET_MessageHeader *message,
5251                             const struct GNUNET_ATS_Information *atsi,
5252                             unsigned int atsi_count)
5253 {
5254   struct GNUNET_MESH_TunnelDestroy *msg;
5255   struct MeshTunnel *t;
5256
5257   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5258               "Got a TUNNEL DESTROY packet from %s\n", GNUNET_i2s (peer));
5259   msg = (struct GNUNET_MESH_TunnelDestroy *) message;
5260   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for tunnel %s [%u]\n",
5261               GNUNET_i2s (&msg->oid), ntohl (msg->tid));
5262   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5263   if (NULL == t)
5264   {
5265     /* Probably already got the message from another path,
5266      * destroyed the tunnel and retransmitted to children.
5267      * Safe to ignore.
5268      */
5269     GNUNET_STATISTICS_update (stats, "# control on unknown tunnel", 1, GNUNET_NO);
5270     return GNUNET_OK;
5271   }
5272   if (t->id.oid == myid)
5273   {
5274     GNUNET_break_op (0);
5275     return GNUNET_OK;
5276   }
5277   if (t->local_tid_dest >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
5278   {
5279     /* Tunnel was incoming, notify clients */
5280     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "INCOMING TUNNEL %X %X\n",
5281                 t->local_tid, t->local_tid_dest);
5282     send_clients_tunnel_destroy (t);
5283   }
5284   tunnel_send_destroy (t);
5285   t->destroy = GNUNET_YES;
5286   // TODO: add timeout to destroy the tunnel anyway
5287   return GNUNET_OK;
5288 }
5289
5290
5291 /**
5292  * Core handler for mesh network traffic going from the origin to a peer
5293  *
5294  * @param cls closure
5295  * @param peer peer identity this notification is about
5296  * @param message message
5297  * @param atsi performance data
5298  * @param atsi_count number of records in 'atsi'
5299  * @return GNUNET_OK to keep the connection open,
5300  *         GNUNET_SYSERR to close it (signal serious error)
5301  */
5302 static int
5303 handle_mesh_data_unicast (void *cls, const struct GNUNET_PeerIdentity *peer,
5304                           const struct GNUNET_MessageHeader *message,
5305                           const struct GNUNET_ATS_Information *atsi,
5306                           unsigned int atsi_count)
5307 {
5308   struct GNUNET_MESH_Unicast *msg;
5309   struct GNUNET_PeerIdentity *neighbor;
5310   struct MeshTunnelChildInfo *cinfo;
5311   struct MeshTunnel *t;
5312   GNUNET_PEER_Id dest_id;
5313   uint32_t pid;
5314   uint32_t ttl;
5315   size_t size;
5316
5317   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a unicast packet from %s\n",
5318               GNUNET_i2s (peer));
5319   /* Check size */
5320   size = ntohs (message->size);
5321   if (size <
5322       sizeof (struct GNUNET_MESH_Unicast) +
5323       sizeof (struct GNUNET_MessageHeader))
5324   {
5325     GNUNET_break (0);
5326     return GNUNET_OK;
5327   }
5328   msg = (struct GNUNET_MESH_Unicast *) message;
5329   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " of type %s\n",
5330               GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
5331   /* Check tunnel */
5332   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5333   if (NULL == t)
5334   {
5335     /* TODO notify back: we don't know this tunnel */
5336     GNUNET_STATISTICS_update (stats, "# data on unknown tunnel", 1, GNUNET_NO);
5337     GNUNET_break_op (0);
5338     return GNUNET_OK;
5339   }
5340   pid = ntohl (msg->pid);
5341   if (t->fwd_pid == pid)
5342   {
5343     GNUNET_STATISTICS_update (stats, "# duplicate PID drops", 1, GNUNET_NO);
5344     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5345                 " Already seen pid %u, DROPPING!\n", pid);
5346     return GNUNET_OK;
5347   }
5348   else
5349   {
5350     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5351                 " pid %u not seen yet, forwarding\n", pid);
5352   }
5353
5354   t->skip += (pid - t->fwd_pid) - 1;
5355   t->fwd_pid = pid;
5356
5357   if (GMC_is_pid_bigger (pid, t->last_fwd_ack))
5358   {
5359     GNUNET_STATISTICS_update (stats, "# unsolicited unicast", 1, GNUNET_NO);
5360     GNUNET_break_op (0);
5361     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5362                 "Received PID %u, ACK %u\n",
5363                 pid, t->last_fwd_ack);
5364     return GNUNET_OK;
5365   }
5366
5367   tunnel_reset_timeout (t);
5368   dest_id = GNUNET_PEER_search (&msg->destination);
5369   if (dest_id == myid)
5370   {
5371     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5372                 "  it's for us! sending to clients...\n");
5373     GNUNET_STATISTICS_update (stats, "# unicast received", 1, GNUNET_NO);
5374     send_subscribed_clients (message, &msg[1].header, t);
5375     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_UNICAST);
5376     return GNUNET_OK;
5377   }
5378   ttl = ntohl (msg->ttl);
5379   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ttl: %u\n", ttl);
5380   if (ttl == 0)
5381   {
5382     GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
5383     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
5384     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5385     return GNUNET_OK;
5386   }
5387   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5388               "  not for us, retransmitting...\n");
5389
5390   neighbor = tree_get_first_hop (t->tree, dest_id);
5391   cinfo = tunnel_get_neighbor_fc (t, neighbor);
5392   cinfo->pid = pid;
5393   GNUNET_CONTAINER_multihashmap_iterate (t->children_fc,
5394                                          &tunnel_add_skip,
5395                                          &neighbor);
5396   if (GNUNET_YES == t->nobuffer &&
5397       GNUNET_YES == GMC_is_pid_bigger (pid, cinfo->fwd_ack))
5398   {
5399     GNUNET_STATISTICS_update (stats, "# unsolicited unicast", 1, GNUNET_NO);
5400     GNUNET_break_op (0);
5401     return GNUNET_OK;
5402   }
5403   send_message (message, neighbor, t);
5404   GNUNET_STATISTICS_update (stats, "# unicast forwarded", 1, GNUNET_NO);
5405   return GNUNET_OK;
5406 }
5407
5408
5409 /**
5410  * Core handler for mesh network traffic going from the origin to all peers
5411  *
5412  * @param cls closure
5413  * @param message message
5414  * @param peer peer identity this notification is about
5415  * @param atsi performance data
5416  * @param atsi_count number of records in 'atsi'
5417  * @return GNUNET_OK to keep the connection open,
5418  *         GNUNET_SYSERR to close it (signal serious error)
5419  *
5420  * TODO: Check who we got this from, to validate route.
5421  */
5422 static int
5423 handle_mesh_data_multicast (void *cls, const struct GNUNET_PeerIdentity *peer,
5424                             const struct GNUNET_MessageHeader *message,
5425                             const struct GNUNET_ATS_Information *atsi,
5426                             unsigned int atsi_count)
5427 {
5428   struct GNUNET_MESH_Multicast *msg;
5429   struct MeshTunnel *t;
5430   size_t size;
5431   uint32_t pid;
5432
5433   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a multicast packet from %s\n",
5434               GNUNET_i2s (peer));
5435   size = ntohs (message->size);
5436   if (sizeof (struct GNUNET_MESH_Multicast) +
5437       sizeof (struct GNUNET_MessageHeader) > size)
5438   {
5439     GNUNET_break_op (0);
5440     return GNUNET_OK;
5441   }
5442   msg = (struct GNUNET_MESH_Multicast *) message;
5443   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5444
5445   if (NULL == t)
5446   {
5447     /* TODO notify that we dont know that tunnel */
5448     GNUNET_STATISTICS_update (stats, "# data on unknown tunnel", 1, GNUNET_NO);
5449     GNUNET_break_op (0);
5450     return GNUNET_OK;
5451   }
5452   pid = ntohl (msg->pid);
5453   if (t->fwd_pid == pid)
5454   {
5455     /* already seen this packet, drop */
5456     GNUNET_STATISTICS_update (stats, "# duplicate PID drops", 1, GNUNET_NO);
5457     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5458                 " Already seen pid %u, DROPPING!\n", pid);
5459     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5460     return GNUNET_OK;
5461   }
5462   else
5463   {
5464     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5465                 " pid %u not seen yet, forwarding\n", pid);
5466   }
5467   t->skip += (pid - t->fwd_pid) - 1;
5468   t->fwd_pid = pid;
5469   tunnel_reset_timeout (t);
5470
5471   /* Transmit to locally interested clients */
5472   if (NULL != t->peers &&
5473       GNUNET_CONTAINER_multihashmap_contains (t->peers, &my_full_id.hashPubKey))
5474   {
5475     GNUNET_STATISTICS_update (stats, "# multicast received", 1, GNUNET_NO);
5476     send_subscribed_clients (message, &msg[1].header, t);
5477     tunnel_send_fwd_ack(t, GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
5478   }
5479   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ttl: %u\n", ntohl (msg->ttl));
5480   if (ntohl (msg->ttl) == 0)
5481   {
5482     GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
5483     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
5484     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5485     return GNUNET_OK;
5486   }
5487   GNUNET_STATISTICS_update (stats, "# multicast forwarded", 1, GNUNET_NO);
5488   tunnel_send_multicast (t, message, GNUNET_NO);
5489   return GNUNET_OK;
5490 }
5491
5492
5493 /**
5494  * Core handler for mesh network traffic toward the owner of a tunnel
5495  *
5496  * @param cls closure
5497  * @param message message
5498  * @param peer peer identity this notification is about
5499  * @param atsi performance data
5500  * @param atsi_count number of records in 'atsi'
5501  *
5502  * @return GNUNET_OK to keep the connection open,
5503  *         GNUNET_SYSERR to close it (signal serious error)
5504  */
5505 static int
5506 handle_mesh_data_to_orig (void *cls, const struct GNUNET_PeerIdentity *peer,
5507                           const struct GNUNET_MessageHeader *message,
5508                           const struct GNUNET_ATS_Information *atsi,
5509                           unsigned int atsi_count)
5510 {
5511   struct GNUNET_MESH_ToOrigin *msg;
5512   struct GNUNET_PeerIdentity id;
5513   struct MeshPeerInfo *peer_info;
5514   struct MeshTunnel *t;
5515   size_t size;
5516
5517
5518   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a ToOrigin packet from %s\n",
5519               GNUNET_i2s (peer));
5520   size = ntohs (message->size);
5521   if (size < sizeof (struct GNUNET_MESH_ToOrigin) +     /* Payload must be */
5522       sizeof (struct GNUNET_MessageHeader))     /* at least a header */
5523   {
5524     GNUNET_break_op (0);
5525     return GNUNET_OK;
5526   }
5527   msg = (struct GNUNET_MESH_ToOrigin *) message;
5528   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " of type %s\n",
5529               GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
5530   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5531
5532   if (NULL == t)
5533   {
5534     /* TODO notify that we dont know this tunnel (whom)? */
5535     GNUNET_STATISTICS_update (stats, "# data on unknown tunnel", 1, GNUNET_NO);
5536     GNUNET_break_op (0);
5537     return GNUNET_OK;
5538   }
5539
5540   if (NULL != t->owner)
5541   {
5542     char cbuf[size];
5543     struct GNUNET_MESH_ToOrigin *copy;
5544
5545     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5546                 "  it's for us! sending to clients...\n");
5547     /* TODO signature verification */
5548     memcpy (cbuf, message, size);
5549     copy = (struct GNUNET_MESH_ToOrigin *) cbuf;
5550     copy->tid = htonl (t->local_tid);
5551     GNUNET_STATISTICS_update (stats, "# to origin received", 1, GNUNET_NO);
5552     GNUNET_SERVER_notification_context_unicast (nc, t->owner->handle,
5553                                                 &copy->header, GNUNET_NO);
5554     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN);
5555     return GNUNET_OK;
5556   }
5557   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5558               "  not for us, retransmitting...\n");
5559
5560   peer_info = peer_info_get (&msg->oid);
5561   if (NULL == peer_info)
5562   {
5563     /* unknown origin of tunnel */
5564     GNUNET_break (0);
5565     return GNUNET_OK;
5566   }
5567   GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &id);
5568   send_message (message, &id, t);
5569   GNUNET_STATISTICS_update (stats, "# to origin forwarded", 1, GNUNET_NO);
5570
5571   return GNUNET_OK;
5572 }
5573
5574
5575 /**
5576  * Core handler for mesh network traffic point-to-point acks.
5577  *
5578  * @param cls closure
5579  * @param message message
5580  * @param peer peer identity this notification is about
5581  * @param atsi performance data
5582  * @param atsi_count number of records in 'atsi'
5583  *
5584  * @return GNUNET_OK to keep the connection open,
5585  *         GNUNET_SYSERR to close it (signal serious error)
5586  */
5587 static int
5588 handle_mesh_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
5589                  const struct GNUNET_MessageHeader *message,
5590                  const struct GNUNET_ATS_Information *atsi,
5591                  unsigned int atsi_count)
5592 {
5593   struct GNUNET_MESH_ACK *msg;
5594   struct MeshTunnel *t;
5595   uint32_t ack;
5596
5597   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got an ACK packet from %s!\n",
5598               GNUNET_i2s (peer));
5599   msg = (struct GNUNET_MESH_ACK *) message;
5600
5601   t = tunnel_get (&msg->oid, ntohl (msg->tid));
5602
5603   if (NULL == t)
5604   {
5605     /* TODO notify that we dont know this tunnel (whom)? */
5606     GNUNET_STATISTICS_update (stats, "# ack on unknown tunnel", 1, GNUNET_NO);
5607     GNUNET_break_op (0);
5608     return GNUNET_OK;
5609   }
5610   ack = ntohl (msg->pid);
5611
5612   /* Is this a forward or backward ACK? */
5613   if (tree_get_predecessor(t->tree) != GNUNET_PEER_search(peer))
5614   {
5615     struct MeshTunnelChildInfo *cinfo;
5616
5617     debug_bck_ack++;
5618     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  FWD ACK\n");
5619     cinfo = tunnel_get_neighbor_fc (t, peer);
5620     cinfo->fwd_ack = ack;
5621     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5622     tunnel_unlock_fwd_queues (t);
5623   }
5624   else
5625   {
5626     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  BCK ACK\n");
5627     t->bck_ack = ack;
5628     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
5629     tunnel_unlock_bck_queue (t);
5630   }
5631   return GNUNET_OK;
5632 }
5633
5634
5635 /**
5636  * Core handler for path ACKs
5637  *
5638  * @param cls closure
5639  * @param message message
5640  * @param peer peer identity this notification is about
5641  * @param atsi performance data
5642  * @param atsi_count number of records in 'atsi'
5643  *
5644  * @return GNUNET_OK to keep the connection open,
5645  *         GNUNET_SYSERR to close it (signal serious error)
5646  */
5647 static int
5648 handle_mesh_path_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
5649                       const struct GNUNET_MessageHeader *message,
5650                       const struct GNUNET_ATS_Information *atsi,
5651                       unsigned int atsi_count)
5652 {
5653   struct GNUNET_MESH_PathACK *msg;
5654   struct GNUNET_PeerIdentity id;
5655   struct MeshPeerInfo *peer_info;
5656   struct MeshPeerPath *p;
5657   struct MeshTunnel *t;
5658
5659   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a path ACK msg [%s]\n",
5660               GNUNET_i2s (&my_full_id));
5661   msg = (struct GNUNET_MESH_PathACK *) message;
5662   t = tunnel_get (&msg->oid, ntohl(msg->tid));
5663   if (NULL == t)
5664   {
5665     /* TODO notify that we don't know the tunnel */
5666     GNUNET_STATISTICS_update (stats, "# control on unknown tunnel", 1, GNUNET_NO);
5667     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  don't know the tunnel %s [%X]!\n",
5668                 GNUNET_i2s (&msg->oid), ntohl(msg->tid));
5669     return GNUNET_OK;
5670   }
5671   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %s [%X]\n",
5672               GNUNET_i2s (&msg->oid), ntohl(msg->tid));
5673
5674   peer_info = peer_info_get (&msg->peer_id);
5675   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by peer %s\n",
5676               GNUNET_i2s (&msg->peer_id));
5677   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  via peer %s\n",
5678               GNUNET_i2s (peer));
5679
5680   if (NULL != t->regex_ctx && t->regex_ctx->info->peer == peer_info->id)
5681   {
5682     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5683                 "connect_by_string completed, stopping search\n");
5684     regex_cancel_search (t->regex_ctx);
5685     t->regex_ctx = NULL;
5686   }
5687
5688   /* Add paths to peers? */
5689   p = tree_get_path_to_peer (t->tree, peer_info->id);
5690   if (NULL != p)
5691   {
5692     path_add_to_peers (p, GNUNET_YES);
5693     path_destroy (p);
5694   }
5695   else
5696   {
5697     GNUNET_break (0);
5698   }
5699
5700   /* Message for us? */
5701   if (0 == memcmp (&msg->oid, &my_full_id, sizeof (struct GNUNET_PeerIdentity)))
5702   {
5703     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
5704     if (NULL == t->owner)
5705     {
5706       GNUNET_break_op (0);
5707       return GNUNET_OK;
5708     }
5709     if (NULL != t->dht_get_type)
5710     {
5711       GNUNET_DHT_get_stop (t->dht_get_type);
5712       t->dht_get_type = NULL;
5713     }
5714     if (tree_get_status (t->tree, peer_info->id) != MESH_PEER_READY)
5715     {
5716       tree_set_status (t->tree, peer_info->id, MESH_PEER_READY);
5717       send_client_peer_connected (t, peer_info->id);
5718     }
5719     return GNUNET_OK;
5720   }
5721
5722   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5723               "  not for us, retransmitting...\n");
5724   GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &id);
5725   peer_info = peer_info_get (&msg->oid);
5726   if (NULL == peer_info)
5727   {
5728     /* If we know the tunnel, we should DEFINITELY know the peer */
5729     GNUNET_break (0);
5730     return GNUNET_OK;
5731   }
5732   send_message (message, &id, t);
5733   return GNUNET_OK;
5734 }
5735
5736
5737 /**
5738  * Functions to handle messages from core
5739  */
5740 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
5741   {&handle_mesh_path_create, GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE, 0},
5742   {&handle_mesh_path_destroy, GNUNET_MESSAGE_TYPE_MESH_PATH_DESTROY, 0},
5743   {&handle_mesh_path_broken, GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN,
5744    sizeof (struct GNUNET_MESH_PathBroken)},
5745   {&handle_mesh_tunnel_destroy, GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY,
5746    sizeof (struct GNUNET_MESH_TunnelDestroy)},
5747   {&handle_mesh_data_unicast, GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
5748   {&handle_mesh_data_multicast, GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
5749   {&handle_mesh_data_to_orig, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
5750   {&handle_mesh_ack, GNUNET_MESSAGE_TYPE_MESH_ACK,
5751     sizeof (struct GNUNET_MESH_ACK)},
5752   {&handle_mesh_path_ack, GNUNET_MESSAGE_TYPE_MESH_PATH_ACK,
5753    sizeof (struct GNUNET_MESH_PathACK)},
5754   {NULL, 0, 0}
5755 };
5756
5757
5758
5759 /******************************************************************************/
5760 /****************       MESH LOCAL HANDLER HELPERS      ***********************/
5761 /******************************************************************************/
5762
5763 /**
5764  * deregister_app: iterator for removing each application registered by a client
5765  *
5766  * @param cls closure
5767  * @param key the hash of the application id (used to access the hashmap)
5768  * @param value the value stored at the key (client)
5769  *
5770  * @return GNUNET_OK on success
5771  */
5772 static int
5773 deregister_app (void *cls, const struct GNUNET_HashCode * key, void *value)
5774 {
5775   struct GNUNET_CONTAINER_MultiHashMap *h = cls;
5776   GNUNET_break (GNUNET_YES ==
5777                 GNUNET_CONTAINER_multihashmap_remove (h, key, value));
5778   return GNUNET_OK;
5779 }
5780
5781 #if LATER
5782 /**
5783  * notify_client_connection_failure: notify a client that the connection to the
5784  * requested remote peer is not possible (for instance, no route found)
5785  * Function called when the socket is ready to queue more data. "buf" will be
5786  * NULL and "size" zero if the socket was closed for writing in the meantime.
5787  *
5788  * @param cls closure
5789  * @param size number of bytes available in buf
5790  * @param buf where the callee should write the message
5791  * @return number of bytes written to buf
5792  */
5793 static size_t
5794 notify_client_connection_failure (void *cls, size_t size, void *buf)
5795 {
5796   int size_needed;
5797   struct MeshPeerInfo *peer_info;
5798   struct GNUNET_MESH_PeerControl *msg;
5799   struct GNUNET_PeerIdentity id;
5800
5801   if (0 == size && NULL == buf)
5802   {
5803     // TODO retry? cancel?
5804     return 0;
5805   }
5806
5807   size_needed = sizeof (struct GNUNET_MESH_PeerControl);
5808   peer_info = (struct MeshPeerInfo *) cls;
5809   msg = (struct GNUNET_MESH_PeerControl *) buf;
5810   msg->header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
5811   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DISCONNECTED);
5812 //     msg->tunnel_id = htonl(peer_info->t->tid);
5813   GNUNET_PEER_resolve (peer_info->id, &id);
5814   memcpy (&msg->peer, &id, sizeof (struct GNUNET_PeerIdentity));
5815
5816   return size_needed;
5817 }
5818 #endif
5819
5820
5821 /**
5822  * Send keepalive packets for a peer
5823  *
5824  * @param cls Closure (tunnel for which to send the keepalive).
5825  * @param tc Notification context.
5826  *
5827  * TODO: implement explicit multicast keepalive?
5828  */
5829 static void
5830 path_refresh (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
5831 {
5832   struct MeshTunnel *t = cls;
5833   struct GNUNET_MessageHeader *payload;
5834   struct GNUNET_MESH_Multicast *msg;
5835   size_t size =
5836       sizeof (struct GNUNET_MESH_Multicast) +
5837       sizeof (struct GNUNET_MessageHeader);
5838   char cbuf[size];
5839
5840   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
5841   {
5842     return;
5843   }
5844   t->path_refresh_task = GNUNET_SCHEDULER_NO_TASK;
5845
5846   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5847               "sending keepalive for tunnel %d\n", t->id.tid);
5848
5849   msg = (struct GNUNET_MESH_Multicast *) cbuf;
5850   msg->header.size = htons (size);
5851   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
5852   // FIXME: change type to != MULTICAST
5853   msg->oid = my_full_id;
5854   msg->tid = htonl (t->id.tid);
5855   msg->ttl = htonl (default_ttl);
5856   msg->pid = htonl (t->fwd_pid + 1);
5857   t->fwd_pid++;
5858   payload = (struct GNUNET_MessageHeader *) &msg[1];
5859   payload->size = htons (sizeof (struct GNUNET_MessageHeader));
5860   payload->type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE);
5861   tunnel_send_multicast (t, &msg->header, GNUNET_YES);
5862
5863   t->path_refresh_task =
5864       GNUNET_SCHEDULER_add_delayed (refresh_path_time, &path_refresh, t);
5865   return;
5866 }
5867
5868
5869 /**
5870  * Function to process paths received for a new peer addition. The recorded
5871  * paths form the initial tunnel, which can be optimized later.
5872  * Called on each result obtained for the DHT search.
5873  *
5874  * @param cls closure
5875  * @param exp when will this value expire
5876  * @param key key of the result
5877  * @param get_path path of the get request
5878  * @param get_path_length lenght of get_path
5879  * @param put_path path of the put request
5880  * @param put_path_length length of the put_path
5881  * @param type type of the result
5882  * @param size number of bytes in data
5883  * @param data pointer to the result data
5884  *
5885  * TODO: re-issue the request after certain time? cancel after X results?
5886  */
5887 static void
5888 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
5889                     const struct GNUNET_HashCode * key,
5890                     const struct GNUNET_PeerIdentity *get_path,
5891                     unsigned int get_path_length,
5892                     const struct GNUNET_PeerIdentity *put_path,
5893                     unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
5894                     size_t size, const void *data)
5895 {
5896   struct MeshPathInfo *path_info = cls;
5897   struct MeshPeerPath *p;
5898   struct GNUNET_PeerIdentity pi;
5899   int i;
5900
5901   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got results from DHT!\n");
5902   GNUNET_PEER_resolve (path_info->peer->id, &pi);
5903   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for %s\n", GNUNET_i2s (&pi));
5904
5905   p = path_build_from_dht (get_path, get_path_length, put_path,
5906                            put_path_length);
5907   path_add_to_peers (p, GNUNET_NO);
5908   path_destroy(p);
5909   for (i = 0; i < path_info->peer->ntunnels; i++)
5910   {
5911     tunnel_add_peer (path_info->peer->tunnels[i], path_info->peer);
5912     peer_info_connect (path_info->peer, path_info->t);
5913   }
5914
5915   return;
5916 }
5917
5918
5919 /**
5920  * Function to process paths received for a new peer addition. The recorded
5921  * paths form the initial tunnel, which can be optimized later.
5922  * Called on each result obtained for the DHT search.
5923  *
5924  * @param cls closure
5925  * @param exp when will this value expire
5926  * @param key key of the result
5927  * @param get_path path of the get request
5928  * @param get_path_length lenght of get_path
5929  * @param put_path path of the put request
5930  * @param put_path_length length of the put_path
5931  * @param type type of the result
5932  * @param size number of bytes in data
5933  * @param data pointer to the result data
5934  */
5935 static void
5936 dht_get_type_handler (void *cls, struct GNUNET_TIME_Absolute exp,
5937                       const struct GNUNET_HashCode * key,
5938                       const struct GNUNET_PeerIdentity *get_path,
5939                       unsigned int get_path_length,
5940                       const struct GNUNET_PeerIdentity *put_path,
5941                       unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
5942                       size_t size, const void *data)
5943 {
5944   const struct PBlock *pb = data;
5945   const struct GNUNET_PeerIdentity *pi = &pb->id;
5946   struct MeshTunnel *t = cls;
5947   struct MeshPeerInfo *peer_info;
5948   struct MeshPeerPath *p;
5949
5950   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got type DHT result!\n");
5951   if (size != sizeof (struct PBlock))
5952   {
5953     GNUNET_break_op (0);
5954     return;
5955   }
5956   if (ntohl(pb->type) != t->type)
5957   {
5958     GNUNET_break_op (0);
5959     return;
5960   }
5961   GNUNET_assert (NULL != t->owner);
5962   peer_info = peer_info_get (pi);
5963   (void) GNUNET_CONTAINER_multihashmap_put (t->peers, &pi->hashPubKey,
5964                                             peer_info,
5965                                             GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
5966
5967   p = path_build_from_dht (get_path, get_path_length, put_path,
5968                            put_path_length);
5969   path_add_to_peers (p, GNUNET_NO);
5970   path_destroy(p);
5971   tunnel_add_peer (t, peer_info);
5972   peer_info_connect (peer_info, t);
5973 }
5974
5975
5976 /**
5977  * Function to process DHT string to regex matching.
5978  * Called on each result obtained for the DHT search.
5979  *
5980  * @param cls closure (search context)
5981  * @param exp when will this value expire
5982  * @param key key of the result
5983  * @param get_path path of the get request (not used)
5984  * @param get_path_length lenght of get_path (not used)
5985  * @param put_path path of the put request (not used)
5986  * @param put_path_length length of the put_path (not used)
5987  * @param type type of the result
5988  * @param size number of bytes in data
5989  * @param data pointer to the result data
5990  */
5991 static void
5992 dht_get_string_accept_handler (void *cls, struct GNUNET_TIME_Absolute exp,
5993                                const struct GNUNET_HashCode * key,
5994                                const struct GNUNET_PeerIdentity *get_path,
5995                                unsigned int get_path_length,
5996                                const struct GNUNET_PeerIdentity *put_path,
5997                                unsigned int put_path_length,
5998                                enum GNUNET_BLOCK_Type type,
5999                                size_t size, const void *data)
6000 {
6001   const struct MeshRegexAccept *block = data;
6002   struct MeshRegexSearchContext *ctx = cls;
6003   struct MeshRegexSearchInfo *info = ctx->info;
6004   struct MeshPeerPath *p;
6005   struct MeshPeerInfo *peer_info;
6006
6007   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got regex results from DHT!\n");
6008   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for %s\n", info->description);
6009
6010   peer_info = peer_info_get(&block->id);
6011   p = path_build_from_dht (get_path, get_path_length, put_path,
6012                            put_path_length);
6013   path_add_to_peers (p, GNUNET_NO);
6014   path_destroy(p);
6015
6016   tunnel_add_peer (info->t, peer_info);
6017   peer_info_connect (peer_info, info->t);
6018   if (0 == info->peer)
6019   {
6020     info->peer = peer_info->id;
6021   }
6022   else
6023   {
6024     GNUNET_array_append (info->peers, info->n_peers, peer_info->id);
6025   }
6026
6027   info->timeout = GNUNET_SCHEDULER_add_delayed (connect_timeout,
6028                                                 &regex_connect_timeout,
6029                                                 info);
6030
6031   return;
6032 }
6033
6034
6035 /**
6036  * Function to process DHT string to regex matching.
6037  * Called on each result obtained for the DHT search.
6038  *
6039  * @param cls closure (search context)
6040  * @param exp when will this value expire
6041  * @param key key of the result
6042  * @param get_path path of the get request (not used)
6043  * @param get_path_length lenght of get_path (not used)
6044  * @param put_path path of the put request (not used)
6045  * @param put_path_length length of the put_path (not used)
6046  * @param type type of the result
6047  * @param size number of bytes in data
6048  * @param data pointer to the result data
6049  *
6050  * TODO: re-issue the request after certain time? cancel after X results?
6051  */
6052 static void
6053 dht_get_string_handler (void *cls, struct GNUNET_TIME_Absolute exp,
6054                         const struct GNUNET_HashCode * key,
6055                         const struct GNUNET_PeerIdentity *get_path,
6056                         unsigned int get_path_length,
6057                         const struct GNUNET_PeerIdentity *put_path,
6058                         unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
6059                         size_t size, const void *data)
6060 {
6061   const struct MeshRegexBlock *block = data;
6062   struct MeshRegexSearchContext *ctx = cls;
6063   struct MeshRegexSearchInfo *info = ctx->info;
6064   void *copy;
6065   size_t len;
6066
6067   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6068               "DHT GET STRING RETURNED RESULTS\n");
6069   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6070               "  key: %s\n", GNUNET_h2s (key));
6071
6072   copy = GNUNET_malloc (size);
6073   memcpy (copy, data, size);
6074   GNUNET_break (GNUNET_OK ==
6075                 GNUNET_CONTAINER_multihashmap_put(info->dht_get_results, key, copy,
6076                                                   GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
6077   len = ntohl (block->n_proof);
6078   {
6079     char proof[len + 1];
6080
6081     memcpy (proof, &block[1], len);
6082     proof[len] = '\0';
6083     if (GNUNET_OK != GNUNET_REGEX_check_proof (proof, key))
6084     {
6085       GNUNET_break_op (0);
6086       return;
6087     }
6088   }
6089   len = strlen (info->description);
6090   if (len == ctx->position) // String processed
6091   {
6092     if (GNUNET_YES == ntohl (block->accepting))
6093     {
6094       regex_find_path(key, ctx);
6095     }
6096     else
6097     {
6098       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  block not accepting!\n");
6099       // FIXME REGEX this block not successful, wait for more? start timeout?
6100     }
6101     return;
6102   }
6103   GNUNET_break (GNUNET_OK ==
6104                 GNUNET_MESH_regex_block_iterate (block, size,
6105                                                  &regex_edge_iterator, ctx));
6106   return;
6107 }
6108
6109 /******************************************************************************/
6110 /*********************       MESH LOCAL HANDLES      **************************/
6111 /******************************************************************************/
6112
6113
6114 /**
6115  * Handler for client disconnection
6116  *
6117  * @param cls closure
6118  * @param client identification of the client; NULL
6119  *        for the last call when the server is destroyed
6120  */
6121 static void
6122 handle_local_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
6123 {
6124   struct MeshClient *c;
6125   struct MeshClient *next;
6126   unsigned int i;
6127
6128   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client disconnected\n");
6129   if (client == NULL)
6130   {
6131     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   (SERVER DOWN)\n");
6132     return;
6133   }
6134   c = clients;
6135   while (NULL != c)
6136   {
6137     if (c->handle != client)
6138     {
6139       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ... searching\n");
6140       c = c->next;
6141       continue;
6142     }
6143     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "matching client found (%u)\n",
6144                 c->id);
6145     GNUNET_SERVER_client_drop (c->handle);
6146     c->shutting_down = GNUNET_YES;
6147     GNUNET_assert (NULL != c->own_tunnels);
6148     GNUNET_assert (NULL != c->incoming_tunnels);
6149     GNUNET_CONTAINER_multihashmap_iterate (c->own_tunnels,
6150                                            &tunnel_destroy_iterator, c);
6151     GNUNET_CONTAINER_multihashmap_iterate (c->incoming_tunnels,
6152                                            &tunnel_destroy_iterator, c);
6153     GNUNET_CONTAINER_multihashmap_iterate (c->ignore_tunnels,
6154                                            &tunnel_destroy_iterator, c);
6155     GNUNET_CONTAINER_multihashmap_destroy (c->own_tunnels);
6156     GNUNET_CONTAINER_multihashmap_destroy (c->incoming_tunnels);
6157     GNUNET_CONTAINER_multihashmap_destroy (c->ignore_tunnels);
6158
6159     /* deregister clients applications */
6160     if (NULL != c->apps)
6161     {
6162       GNUNET_CONTAINER_multihashmap_iterate (c->apps, &deregister_app, c->apps);
6163       GNUNET_CONTAINER_multihashmap_destroy (c->apps);
6164     }
6165     if (0 == GNUNET_CONTAINER_multihashmap_size (applications) &&
6166         GNUNET_SCHEDULER_NO_TASK != announce_applications_task)
6167     {
6168       GNUNET_SCHEDULER_cancel (announce_applications_task);
6169       announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
6170     }
6171     if (NULL != c->types)
6172       GNUNET_CONTAINER_multihashmap_destroy (c->types);
6173     for (i = 0; i < c->n_regex; i++)
6174     {
6175       GNUNET_free (c->regexes[i]);
6176     }
6177     GNUNET_free_non_null (c->regexes);
6178     if (GNUNET_SCHEDULER_NO_TASK != c->regex_announce_task)
6179       GNUNET_SCHEDULER_cancel (c->regex_announce_task);
6180     next = c->next;
6181     GNUNET_CONTAINER_DLL_remove (clients, clients_tail, c);
6182     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  CLIENT FREE at %p\n", c);
6183     GNUNET_free (c);
6184     GNUNET_STATISTICS_update (stats, "# clients", -1, GNUNET_NO);
6185     c = next;
6186   }
6187   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   done!\n");
6188   return;
6189 }
6190
6191
6192 /**
6193  * Handler for new clients
6194  *
6195  * @param cls closure
6196  * @param client identification of the client
6197  * @param message the actual message, which includes messages the client wants
6198  */
6199 static void
6200 handle_local_new_client (void *cls, struct GNUNET_SERVER_Client *client,
6201                          const struct GNUNET_MessageHeader *message)
6202 {
6203   struct GNUNET_MESH_ClientConnect *cc_msg;
6204   struct MeshClient *c;
6205   GNUNET_MESH_ApplicationType *a;
6206   unsigned int size;
6207   uint16_t ntypes;
6208   uint16_t *t;
6209   uint16_t napps;
6210   uint16_t i;
6211
6212   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client connected\n");
6213   /* Check data sanity */
6214   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_ClientConnect);
6215   cc_msg = (struct GNUNET_MESH_ClientConnect *) message;
6216   ntypes = ntohs (cc_msg->types);
6217   napps = ntohs (cc_msg->applications);
6218   if (size !=
6219       ntypes * sizeof (uint16_t) + napps * sizeof (GNUNET_MESH_ApplicationType))
6220   {
6221     GNUNET_break (0);
6222     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6223     return;
6224   }
6225
6226   /* Create new client structure */
6227   c = GNUNET_malloc (sizeof (struct MeshClient));
6228   c->id = next_client_id++;
6229   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  CLIENT NEW %u\n", c->id);
6230   c->handle = client;
6231   GNUNET_SERVER_client_keep (client);
6232   a = (GNUNET_MESH_ApplicationType *) &cc_msg[1];
6233   if (napps > 0)
6234   {
6235     GNUNET_MESH_ApplicationType at;
6236     struct GNUNET_HashCode hc;
6237
6238     c->apps = GNUNET_CONTAINER_multihashmap_create (napps);
6239     for (i = 0; i < napps; i++)
6240     {
6241       at = ntohl (a[i]);
6242       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  app type: %u\n", at);
6243       GNUNET_CRYPTO_hash (&at, sizeof (at), &hc);
6244       /* store in clients hashmap */
6245       GNUNET_CONTAINER_multihashmap_put (c->apps, &hc, (void *) (long) at,
6246                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
6247       /* store in global hashmap, for announcements */
6248       GNUNET_CONTAINER_multihashmap_put (applications, &hc, c,
6249                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
6250     }
6251     if (GNUNET_SCHEDULER_NO_TASK == announce_applications_task)
6252       announce_applications_task =
6253           GNUNET_SCHEDULER_add_now (&announce_applications, NULL);
6254
6255   }
6256   if (ntypes > 0)
6257   {
6258     uint16_t u16;
6259     struct GNUNET_HashCode hc;
6260
6261     t = (uint16_t *) & a[napps];
6262     c->types = GNUNET_CONTAINER_multihashmap_create (ntypes);
6263     for (i = 0; i < ntypes; i++)
6264     {
6265       u16 = ntohs (t[i]);
6266       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  msg type: %u\n", u16);
6267       GNUNET_CRYPTO_hash (&u16, sizeof (u16), &hc);
6268
6269       /* store in clients hashmap */
6270       GNUNET_CONTAINER_multihashmap_put (c->types, &hc, c,
6271                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
6272       /* store in global hashmap */
6273       GNUNET_CONTAINER_multihashmap_put (types, &hc, c,
6274                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
6275     }
6276   }
6277   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6278               " client has %u+%u subscriptions\n", napps, ntypes);
6279
6280   GNUNET_CONTAINER_DLL_insert (clients, clients_tail, c);
6281   c->own_tunnels = GNUNET_CONTAINER_multihashmap_create (32);
6282   c->incoming_tunnels = GNUNET_CONTAINER_multihashmap_create (32);
6283   c->ignore_tunnels = GNUNET_CONTAINER_multihashmap_create (32);
6284   GNUNET_SERVER_notification_context_add (nc, client);
6285   GNUNET_STATISTICS_update (stats, "# clients", 1, GNUNET_NO);
6286
6287   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6288   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client processed\n");
6289 }
6290
6291
6292 /**
6293  * Handler for clients announcing available services by a regular expression.
6294  *
6295  * @param cls closure
6296  * @param client identification of the client
6297  * @param message the actual message, which includes messages the client wants
6298  */
6299 static void
6300 handle_local_announce_regex (void *cls, struct GNUNET_SERVER_Client *client,
6301                              const struct GNUNET_MessageHeader *message)
6302 {
6303   struct MeshClient *c;
6304   char *regex;
6305   size_t len;
6306
6307   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "announce regex started\n");
6308
6309   /* Sanity check for client registration */
6310   if (NULL == (c = client_get (client)))
6311   {
6312     GNUNET_break (0);
6313     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6314     return;
6315   }
6316   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6317
6318   len = ntohs (message->size) - sizeof(struct GNUNET_MessageHeader);
6319   regex = GNUNET_malloc (len + 1);
6320   memcpy (regex, &message[1], len);
6321   regex[len] = '\0';
6322   GNUNET_array_append (c->regexes, c->n_regex, regex);
6323   if (GNUNET_SCHEDULER_NO_TASK == c->regex_announce_task)
6324   {
6325     c->regex_announce_task = GNUNET_SCHEDULER_add_now(&announce_regex, c);
6326   }
6327   else
6328   {
6329     regex_put(regex);
6330   }
6331   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6332   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "announce regex processed\n");
6333 }
6334
6335
6336 /**
6337  * Handler for requests of new tunnels
6338  *
6339  * @param cls closure
6340  * @param client identification of the client
6341  * @param message the actual message
6342  */
6343 static void
6344 handle_local_tunnel_create (void *cls, struct GNUNET_SERVER_Client *client,
6345                             const struct GNUNET_MessageHeader *message)
6346 {
6347   struct GNUNET_MESH_TunnelMessage *t_msg;
6348   struct MeshTunnel *t;
6349   struct MeshClient *c;
6350   MESH_TunnelNumber tid;
6351
6352   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new tunnel requested\n");
6353
6354   /* Sanity check for client registration */
6355   if (NULL == (c = client_get (client)))
6356   {
6357     GNUNET_break (0);
6358     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6359     return;
6360   }
6361   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6362
6363   /* Message sanity check */
6364   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
6365   {
6366     GNUNET_break (0);
6367     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6368     return;
6369   }
6370
6371   t_msg = (struct GNUNET_MESH_TunnelMessage *) message;
6372   /* Sanity check for tunnel numbering */
6373   tid = ntohl (t_msg->tunnel_id);
6374   if (0 == (tid & GNUNET_MESH_LOCAL_TUNNEL_ID_CLI))
6375   {
6376     GNUNET_break (0);
6377     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6378     return;
6379   }
6380   /* Sanity check for duplicate tunnel IDs */
6381   if (NULL != tunnel_get_by_local_id (c, tid))
6382   {
6383     GNUNET_break (0);
6384     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6385     return;
6386   }
6387
6388   while (NULL != tunnel_get_by_pi (myid, next_tid))
6389     next_tid = (next_tid + 1) & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
6390   t = tunnel_new (myid, next_tid++, c, tid);
6391   if (NULL == t)
6392   {
6393     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Tunnel creation failed.\n");
6394     GNUNET_break (0);
6395     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6396     return;
6397   }
6398   next_tid = next_tid & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
6399   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CREATED TUNNEL %s [%x] (%x)\n",
6400               GNUNET_i2s (&my_full_id), t->id.tid, t->local_tid);
6401   t->peers = GNUNET_CONTAINER_multihashmap_create (32);
6402
6403   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new tunnel created\n");
6404   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6405   return;
6406 }
6407
6408
6409 /**
6410  * Handler for requests of deleting tunnels
6411  *
6412  * @param cls closure
6413  * @param client identification of the client
6414  * @param message the actual message
6415  */
6416 static void
6417 handle_local_tunnel_destroy (void *cls, struct GNUNET_SERVER_Client *client,
6418                              const struct GNUNET_MessageHeader *message)
6419 {
6420   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
6421   struct MeshClient *c;
6422   struct MeshTunnel *t;
6423   MESH_TunnelNumber tid;
6424
6425   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6426               "Got a DESTROY TUNNEL from client!\n");
6427
6428   /* Sanity check for client registration */
6429   if (NULL == (c = client_get (client)))
6430   {
6431     GNUNET_break (0);
6432     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6433     return;
6434   }
6435   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6436
6437   /* Message sanity check */
6438   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
6439   {
6440     GNUNET_break (0);
6441     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6442     return;
6443   }
6444
6445   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
6446
6447   /* Retrieve tunnel */
6448   tid = ntohl (tunnel_msg->tunnel_id);
6449   t = tunnel_get_by_local_id(c, tid);
6450   if (NULL == t)
6451   {
6452     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  tunnel %X not found\n", tid);
6453     GNUNET_break (0);
6454     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6455     return;
6456   }
6457   if (c != t->owner || tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
6458   {
6459     client_ignore_tunnel (c, t);
6460 #if 0
6461     // TODO: when to destroy incoming tunnel?
6462     if (t->nclients == 0)
6463     {
6464       GNUNET_assert (GNUNET_YES ==
6465                      GNUNET_CONTAINER_multihashmap_remove (incoming_tunnels,
6466                                                            &hash, t));
6467       GNUNET_assert (GNUNET_YES ==
6468                      GNUNET_CONTAINER_multihashmap_remove (t->peers,
6469                                                            &my_full_id.hashPubKey,
6470                                                            t));
6471     }
6472 #endif
6473     GNUNET_SERVER_receive_done (client, GNUNET_OK);
6474     return;
6475   }
6476   send_client_tunnel_disconnect(t, c);
6477   client_delete_tunnel(c, t);
6478
6479   /* Don't try to ACK the client about the tunnel_destroy multicast packet */
6480   t->owner = NULL;
6481   tunnel_send_destroy (t);
6482   t->destroy = GNUNET_YES;
6483   // The tunnel will be destroyed when the last message is transmitted.
6484   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6485   return;
6486 }
6487
6488
6489 /**
6490  * Handler for requests of seeting tunnel's speed.
6491  *
6492  * @param cls Closure (unused).
6493  * @param client Identification of the client.
6494  * @param message The actual message.
6495  */
6496 static void
6497 handle_local_tunnel_speed (void *cls, struct GNUNET_SERVER_Client *client,
6498                            const struct GNUNET_MessageHeader *message)
6499 {
6500   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
6501   struct MeshClient *c;
6502   struct MeshTunnel *t;
6503   MESH_TunnelNumber tid;
6504
6505   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6506               "Got a SPEED request from client!\n");
6507
6508   /* Sanity check for client registration */
6509   if (NULL == (c = client_get (client)))
6510   {
6511     GNUNET_break (0);
6512     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6513     return;
6514   }
6515
6516   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6517
6518   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
6519
6520   /* Retrieve tunnel */
6521   tid = ntohl (tunnel_msg->tunnel_id);
6522   t = tunnel_get_by_local_id(c, tid);
6523   if (NULL == t)
6524   {
6525     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  tunnel %X not found\n", tid);
6526     GNUNET_break (0);
6527     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6528     return;
6529   }
6530
6531   switch (ntohs(message->type))
6532   {
6533       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MIN:
6534           t->speed_min = GNUNET_YES;
6535           break;
6536       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MAX:
6537           t->speed_min = GNUNET_NO;
6538           break;
6539       default:
6540           GNUNET_break (0);
6541   }
6542   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6543 }
6544
6545
6546 /**
6547  * Handler for requests of seeting tunnel's buffering policy.
6548  *
6549  * @param cls Closure (unused).
6550  * @param client Identification of the client.
6551  * @param message The actual message.
6552  */
6553 static void
6554 handle_local_tunnel_buffer (void *cls, struct GNUNET_SERVER_Client *client,
6555                             const struct GNUNET_MessageHeader *message)
6556 {
6557   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
6558   struct MeshClient *c;
6559   struct MeshTunnel *t;
6560   MESH_TunnelNumber tid;
6561
6562   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
6563               "Got a BUFFER request from client!\n");
6564
6565   /* Sanity check for client registration */
6566   if (NULL == (c = client_get (client)))
6567   {
6568     GNUNET_break (0);
6569     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6570     return;
6571   }
6572   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6573
6574   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
6575
6576   /* Retrieve tunnel */
6577   tid = ntohl (tunnel_msg->tunnel_id);
6578   t = tunnel_get_by_local_id(c, tid);
6579   if (NULL == t)
6580   {
6581     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  tunnel %X not found\n", tid);
6582     GNUNET_break (0);
6583     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6584     return;
6585   }
6586
6587   switch (ntohs(message->type))
6588   {
6589       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_BUFFER:
6590           t->nobuffer = GNUNET_NO;
6591           break;
6592       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_NOBUFFER:
6593           t->nobuffer = GNUNET_YES;
6594           break;
6595       default:
6596           GNUNET_break (0);
6597   }
6598
6599   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6600 }
6601
6602
6603 /**
6604  * Handler for connection requests to new peers
6605  *
6606  * @param cls closure
6607  * @param client identification of the client
6608  * @param message the actual message (PeerControl)
6609  */
6610 static void
6611 handle_local_connect_add (void *cls, struct GNUNET_SERVER_Client *client,
6612                           const struct GNUNET_MessageHeader *message)
6613 {
6614   struct GNUNET_MESH_PeerControl *peer_msg;
6615   struct MeshPeerInfo *peer_info;
6616   struct MeshClient *c;
6617   struct MeshTunnel *t;
6618   MESH_TunnelNumber tid;
6619
6620   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got connection request\n");
6621   /* Sanity check for client registration */
6622   if (NULL == (c = client_get (client)))
6623   {
6624     GNUNET_break (0);
6625     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6626     return;
6627   }
6628   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6629
6630   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
6631
6632   /* Sanity check for message size */
6633   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
6634   {
6635     GNUNET_break (0);
6636     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6637     return;
6638   }
6639
6640   /* Tunnel exists? */
6641   tid = ntohl (peer_msg->tunnel_id);
6642   t = tunnel_get_by_local_id (c, tid);
6643   if (NULL == t)
6644   {
6645     GNUNET_break (0);
6646     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6647     return;
6648   }
6649
6650   /* Does client own tunnel? */
6651   if (t->owner->handle != client)
6652   {
6653     GNUNET_break (0);
6654     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6655     return;
6656   }
6657   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "     for %s\n",
6658               GNUNET_i2s (&peer_msg->peer));
6659   peer_info = peer_info_get (&peer_msg->peer);
6660
6661   tunnel_add_peer (t, peer_info);
6662   peer_info_connect (peer_info, t);
6663
6664   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6665   return;
6666 }
6667
6668
6669 /**
6670  * Handler for disconnection requests of peers in a tunnel
6671  *
6672  * @param cls closure
6673  * @param client identification of the client
6674  * @param message the actual message (PeerControl)
6675  */
6676 static void
6677 handle_local_connect_del (void *cls, struct GNUNET_SERVER_Client *client,
6678                           const struct GNUNET_MessageHeader *message)
6679 {
6680   struct GNUNET_MESH_PeerControl *peer_msg;
6681   struct MeshPeerInfo *peer_info;
6682   struct MeshClient *c;
6683   struct MeshTunnel *t;
6684   MESH_TunnelNumber tid;
6685
6686   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a PEER DEL request\n");
6687   /* Sanity check for client registration */
6688   if (NULL == (c = client_get (client)))
6689   {
6690     GNUNET_break (0);
6691     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6692     return;
6693   }
6694   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6695
6696   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
6697
6698   /* Sanity check for message size */
6699   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
6700   {
6701     GNUNET_break (0);
6702     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6703     return;
6704   }
6705
6706   /* Tunnel exists? */
6707   tid = ntohl (peer_msg->tunnel_id);
6708   t = tunnel_get_by_local_id (c, tid);
6709   if (NULL == t)
6710   {
6711     GNUNET_break (0);
6712     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6713     return;
6714   }
6715   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", t->id.tid);
6716
6717   /* Does client own tunnel? */
6718   if (t->owner->handle != client)
6719   {
6720     GNUNET_break (0);
6721     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6722     return;
6723   }
6724
6725   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for peer %s\n",
6726               GNUNET_i2s (&peer_msg->peer));
6727   /* Is the peer in the tunnel? */
6728   peer_info =
6729       GNUNET_CONTAINER_multihashmap_get (t->peers, &peer_msg->peer.hashPubKey);
6730   if (NULL == peer_info)
6731   {
6732     GNUNET_break (0);
6733     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6734     return;
6735   }
6736
6737   /* Ok, delete peer from tunnel */
6738   GNUNET_CONTAINER_multihashmap_remove_all (t->peers,
6739                                             &peer_msg->peer.hashPubKey);
6740
6741   send_destroy_path (t, peer_info->id);
6742   tunnel_delete_peer (t, peer_info->id);
6743   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6744   return;
6745 }
6746
6747 /**
6748  * Handler for blacklist requests of peers in a tunnel
6749  *
6750  * @param cls closure
6751  * @param client identification of the client
6752  * @param message the actual message (PeerControl)
6753  * 
6754  * FIXME implement DHT block bloomfilter
6755  */
6756 static void
6757 handle_local_blacklist (void *cls, struct GNUNET_SERVER_Client *client,
6758                           const struct GNUNET_MessageHeader *message)
6759 {
6760   struct GNUNET_MESH_PeerControl *peer_msg;
6761   struct MeshClient *c;
6762   struct MeshTunnel *t;
6763   MESH_TunnelNumber tid;
6764
6765   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a PEER BLACKLIST request\n");
6766   /* Sanity check for client registration */
6767   if (NULL == (c = client_get (client)))
6768   {
6769     GNUNET_break (0);
6770     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6771     return;
6772   }
6773   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6774
6775   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
6776
6777   /* Sanity check for message size */
6778   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
6779   {
6780     GNUNET_break (0);
6781     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6782     return;
6783   }
6784
6785   /* Tunnel exists? */
6786   tid = ntohl (peer_msg->tunnel_id);
6787   t = tunnel_get_by_local_id (c, tid);
6788   if (NULL == t)
6789   {
6790     GNUNET_break (0);
6791     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6792     return;
6793   }
6794   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", t->id.tid);
6795
6796   GNUNET_array_append(t->blacklisted, t->nblacklisted,
6797                       GNUNET_PEER_intern(&peer_msg->peer));
6798 }
6799
6800
6801 /**
6802  * Handler for unblacklist requests of peers in a tunnel
6803  *
6804  * @param cls closure
6805  * @param client identification of the client
6806  * @param message the actual message (PeerControl)
6807  */
6808 static void
6809 handle_local_unblacklist (void *cls, struct GNUNET_SERVER_Client *client,
6810                           const struct GNUNET_MessageHeader *message)
6811 {
6812   struct GNUNET_MESH_PeerControl *peer_msg;
6813   struct MeshClient *c;
6814   struct MeshTunnel *t;
6815   MESH_TunnelNumber tid;
6816   GNUNET_PEER_Id pid;
6817   unsigned int i;
6818
6819   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a PEER UNBLACKLIST request\n");
6820   /* Sanity check for client registration */
6821   if (NULL == (c = client_get (client)))
6822   {
6823     GNUNET_break (0);
6824     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6825     return;
6826   }
6827   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6828
6829   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
6830
6831   /* Sanity check for message size */
6832   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
6833   {
6834     GNUNET_break (0);
6835     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6836     return;
6837   }
6838
6839   /* Tunnel exists? */
6840   tid = ntohl (peer_msg->tunnel_id);
6841   t = tunnel_get_by_local_id (c, tid);
6842   if (NULL == t)
6843   {
6844     GNUNET_break (0);
6845     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6846     return;
6847   }
6848   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", t->id.tid);
6849
6850   /* if peer is not known, complain */
6851   pid = GNUNET_PEER_search (&peer_msg->peer);
6852   if (0 == pid)
6853   {
6854     GNUNET_break (0);
6855     return;
6856   }
6857
6858   /* search and remove from list */
6859   for (i = 0; i < t->nblacklisted; i++)
6860   {
6861     if (t->blacklisted[i] == pid)
6862     {
6863       t->blacklisted[i] = t->blacklisted[t->nblacklisted - 1];
6864       GNUNET_array_grow (t->blacklisted, t->nblacklisted, t->nblacklisted - 1);
6865       return;
6866     }
6867   }
6868
6869   /* if peer hasn't been blacklisted, complain */
6870   GNUNET_break (0);
6871 }
6872
6873
6874 /**
6875  * Handler for connection requests to new peers by type
6876  *
6877  * @param cls closure
6878  * @param client identification of the client
6879  * @param message the actual message (ConnectPeerByType)
6880  */
6881 static void
6882 handle_local_connect_by_type (void *cls, struct GNUNET_SERVER_Client *client,
6883                               const struct GNUNET_MessageHeader *message)
6884 {
6885   struct GNUNET_MESH_ConnectPeerByType *connect_msg;
6886   struct MeshClient *c;
6887   struct MeshTunnel *t;
6888   struct GNUNET_HashCode hash;
6889   MESH_TunnelNumber tid;
6890
6891   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got connect by type request\n");
6892   /* Sanity check for client registration */
6893   if (NULL == (c = client_get (client)))
6894   {
6895     GNUNET_break (0);
6896     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6897     return;
6898   }
6899   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
6900
6901   connect_msg = (struct GNUNET_MESH_ConnectPeerByType *) message;
6902
6903   /* Sanity check for message size */
6904   if (sizeof (struct GNUNET_MESH_ConnectPeerByType) !=
6905       ntohs (connect_msg->header.size))
6906   {
6907     GNUNET_break (0);
6908     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6909     return;
6910   }
6911
6912   /* Tunnel exists? */
6913   tid = ntohl (connect_msg->tunnel_id);
6914   t = tunnel_get_by_local_id (c, tid);
6915   if (NULL == t)
6916   {
6917     GNUNET_break (0);
6918     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6919     return;
6920   }
6921
6922   /* Does client own tunnel? */
6923   if (t->owner->handle != client)
6924   {
6925     GNUNET_break (0);
6926     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
6927     return;
6928   }
6929
6930   /* Do WE have the service? */
6931   t->type = ntohl (connect_msg->type);
6932   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " type requested: %u\n", t->type);
6933   GNUNET_CRYPTO_hash (&t->type, sizeof (GNUNET_MESH_ApplicationType), &hash);
6934   if (GNUNET_CONTAINER_multihashmap_contains (applications, &hash) ==
6935       GNUNET_YES)
6936   {
6937     /* Yes! Fast forward, add ourselves to the tunnel and send the
6938      * good news to the client, and alert the destination client of
6939      * an incoming tunnel.
6940      *
6941      * FIXME send a path create to self, avoid code duplication
6942      */
6943     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " available locally\n");
6944     GNUNET_CONTAINER_multihashmap_put (t->peers, &my_full_id.hashPubKey,
6945                                        peer_info_get (&my_full_id),
6946                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
6947
6948     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " notifying client\n");
6949     send_client_peer_connected (t, myid);
6950     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Done\n");
6951     GNUNET_SERVER_receive_done (client, GNUNET_OK);
6952
6953     t->local_tid_dest = next_local_tid++;
6954     GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
6955     GNUNET_CONTAINER_multihashmap_put (incoming_tunnels, &hash, t,
6956                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
6957
6958     return;
6959   }
6960   /* Ok, lets find a peer offering the service */
6961   if (NULL != t->dht_get_type)
6962   {
6963     GNUNET_DHT_get_stop (t->dht_get_type);
6964   }
6965   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " looking in DHT for %s\n",
6966               GNUNET_h2s (&hash));
6967   t->dht_get_type =
6968       GNUNET_DHT_get_start (dht_handle, 
6969                             GNUNET_BLOCK_TYPE_MESH_PEER_BY_TYPE,
6970                             &hash,
6971                             dht_replication_level,
6972                             GNUNET_DHT_RO_RECORD_ROUTE |
6973                             GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
6974                             NULL, 0,
6975                             &dht_get_type_handler, t);
6976
6977   GNUNET_SERVER_receive_done (client, GNUNET_OK);
6978   return;
6979 }
6980
6981
6982 /**
6983  * Handler for connection requests to new peers by a string service description.
6984  *
6985  * @param cls closure
6986  * @param client identification of the client
6987  * @param message the actual message, which includes messages the client wants
6988  */
6989 static void
6990 handle_local_connect_by_string (void *cls, struct GNUNET_SERVER_Client *client,
6991                                 const struct GNUNET_MessageHeader *message)
6992 {
6993   struct GNUNET_MESH_ConnectPeerByString *msg;
6994   struct MeshRegexSearchContext *ctx;
6995   struct MeshRegexSearchInfo *info;
6996   struct GNUNET_DHT_GetHandle *get_h;
6997   struct GNUNET_HashCode key;
6998   struct MeshTunnel *t;
6999   struct MeshClient *c;
7000   MESH_TunnelNumber tid;
7001   const char *string;
7002   size_t size;
7003   size_t len;
7004   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7005               "Connect by string started\n");
7006   msg = (struct GNUNET_MESH_ConnectPeerByString *) message;
7007   size = htons (message->size);
7008
7009   /* Sanity check for client registration */
7010   if (NULL == (c = client_get (client)))
7011   {
7012     GNUNET_break (0);
7013     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7014     return;
7015   }
7016   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7017
7018   /* Message size sanity check */
7019   if (sizeof(struct GNUNET_MESH_ConnectPeerByString) >= size)
7020   {
7021     GNUNET_break (0);
7022     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7023     return;
7024   }
7025
7026   /* Tunnel exists? */
7027   tid = ntohl (msg->tunnel_id);
7028   t = tunnel_get_by_local_id (c, tid);
7029   if (NULL == t)
7030   {
7031     GNUNET_break (0);
7032     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7033     return;
7034   }
7035
7036   /* Does client own tunnel? */
7037   if (t->owner->handle != client)
7038   {
7039     GNUNET_break (0);
7040     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7041     return;
7042   }
7043
7044   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7045               "  on tunnel %s [%u]\n",
7046               GNUNET_i2s(&my_full_id),
7047               t->id.tid);
7048
7049   /* Only one connect_by_string allowed at the same time! */
7050   /* FIXME: allow more, return handle at api level to cancel, document */
7051   if (NULL != t->regex_ctx)
7052   {
7053     GNUNET_break (0);
7054     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7055     return;
7056   }
7057
7058   /* Find string itself */
7059   len = size - sizeof(struct GNUNET_MESH_ConnectPeerByString);
7060   string = (const char *) &msg[1];
7061
7062   /* Initialize context */
7063   size = GNUNET_REGEX_get_first_key(string, len, &key);
7064   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7065               "  consumed %u bits out of %u\n", size, len);
7066   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7067               "  looking for %s\n", GNUNET_h2s (&key));
7068
7069   info = GNUNET_malloc (sizeof (struct MeshRegexSearchInfo));
7070   info->t = t;
7071   info->description = GNUNET_malloc (len + 1);
7072   memcpy (info->description, string, len);
7073   info->description[len] = '\0';
7074   info->dht_get_handles = GNUNET_CONTAINER_multihashmap_create(32);
7075   info->dht_get_results = GNUNET_CONTAINER_multihashmap_create(32);
7076   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   string: %s\n", info->description);
7077
7078   ctx = GNUNET_malloc (sizeof (struct MeshRegexSearchContext));
7079   ctx->position = size;
7080   ctx->info = info;
7081   t->regex_ctx = ctx;
7082
7083   GNUNET_array_append (info->contexts, info->n_contexts, ctx);
7084
7085   /* Start search in DHT */
7086   get_h = GNUNET_DHT_get_start (dht_handle,    /* handle */
7087                                 GNUNET_BLOCK_TYPE_MESH_REGEX, /* type */
7088                                 &key,     /* key to search */
7089                                 dht_replication_level, /* replication level */
7090                                 GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
7091                                 NULL,       /* xquery */ // FIXME BLOOMFILTER
7092                                 0,     /* xquery bits */ // FIXME BLOOMFILTER SIZE
7093                                 &dht_get_string_handler, ctx);
7094
7095   GNUNET_break (GNUNET_OK ==
7096                 GNUNET_CONTAINER_multihashmap_put(info->dht_get_handles,
7097                                                   &key,
7098                                                   get_h,
7099                                                   GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
7100
7101   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7102   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "connect by string processed\n");
7103 }
7104
7105
7106 /**
7107  * Handler for client traffic directed to one peer
7108  *
7109  * @param cls closure
7110  * @param client identification of the client
7111  * @param message the actual message
7112  */
7113 static void
7114 handle_local_unicast (void *cls, struct GNUNET_SERVER_Client *client,
7115                       const struct GNUNET_MessageHeader *message)
7116 {
7117   struct MeshClient *c;
7118   struct MeshTunnel *t;
7119   struct MeshPeerInfo *pi;
7120   struct GNUNET_MESH_Unicast *data_msg;
7121   MESH_TunnelNumber tid;
7122   size_t size;
7123
7124   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7125               "Got a unicast request from a client!\n");
7126
7127   /* Sanity check for client registration */
7128   if (NULL == (c = client_get (client)))
7129   {
7130     GNUNET_break (0);
7131     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7132     return;
7133   }
7134   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7135
7136   data_msg = (struct GNUNET_MESH_Unicast *) message;
7137
7138   /* Sanity check for message size */
7139   size = ntohs (message->size);
7140   if (sizeof (struct GNUNET_MESH_Unicast) +
7141       sizeof (struct GNUNET_MessageHeader) > size)
7142   {
7143     GNUNET_break (0);
7144     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7145     return;
7146   }
7147
7148   /* Tunnel exists? */
7149   tid = ntohl (data_msg->tid);
7150   t = tunnel_get_by_local_id (c, tid);
7151   if (NULL == t)
7152   {
7153     GNUNET_break (0);
7154     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7155     return;
7156   }
7157
7158   /*  Is it a local tunnel? Then, does client own the tunnel? */
7159   if (t->owner->handle != client)
7160   {
7161     GNUNET_break (0);
7162     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7163     return;
7164   }
7165
7166   pi = GNUNET_CONTAINER_multihashmap_get (t->peers,
7167                                           &data_msg->destination.hashPubKey);
7168   /* Is the selected peer in the tunnel? */
7169   if (NULL == pi)
7170   {
7171     GNUNET_break (0);
7172     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7173     return;
7174   }
7175
7176   /* PID should be as expected */
7177   if (ntohl (data_msg->pid) != t->fwd_pid + 1)
7178   {
7179     GNUNET_break (0);
7180     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7181               "Unicast PID, expected %u, got %u\n",
7182               t->fwd_pid + 1, ntohl (data_msg->pid));
7183     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7184     return;
7185   }
7186
7187   /* Ok, everything is correct, send the message
7188    * (pretend we got it from a mesh peer)
7189    */
7190   {
7191     /* Work around const limitation */
7192     char buf[ntohs (message->size)] GNUNET_ALIGN;
7193     struct GNUNET_MESH_Unicast *copy;
7194
7195     copy = (struct GNUNET_MESH_Unicast *) buf;
7196     memcpy (buf, data_msg, size);
7197     copy->oid = my_full_id;
7198     copy->tid = htonl (t->id.tid);
7199     copy->ttl = htonl (default_ttl);
7200     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7201                 "  calling generic handler...\n");
7202     handle_mesh_data_unicast (NULL, &my_full_id, &copy->header, NULL, 0);
7203   }
7204   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "receive done OK\n");
7205   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7206
7207   return;
7208 }
7209
7210
7211 /**
7212  * Handler for client traffic directed to the origin
7213  *
7214  * @param cls closure
7215  * @param client identification of the client
7216  * @param message the actual message
7217  */
7218 static void
7219 handle_local_to_origin (void *cls, struct GNUNET_SERVER_Client *client,
7220                         const struct GNUNET_MessageHeader *message)
7221 {
7222   struct GNUNET_MESH_ToOrigin *data_msg;
7223   struct MeshTunnelClientInfo *clinfo;
7224   struct MeshClient *c;
7225   struct MeshTunnel *t;
7226   MESH_TunnelNumber tid;
7227   size_t size;
7228
7229   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7230               "Got a ToOrigin request from a client!\n");
7231   /* Sanity check for client registration */
7232   if (NULL == (c = client_get (client)))
7233   {
7234     GNUNET_break (0);
7235     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7236     return;
7237   }
7238   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7239
7240   data_msg = (struct GNUNET_MESH_ToOrigin *) message;
7241
7242   /* Sanity check for message size */
7243   size = ntohs (message->size);
7244   if (sizeof (struct GNUNET_MESH_ToOrigin) +
7245       sizeof (struct GNUNET_MessageHeader) > size)
7246   {
7247     GNUNET_break (0);
7248     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7249     return;
7250   }
7251
7252   /* Tunnel exists? */
7253   tid = ntohl (data_msg->tid);
7254   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", tid);
7255   if (tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
7256   {
7257     GNUNET_break (0);
7258     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7259     return;
7260   }
7261   t = tunnel_get_by_local_id (c, tid);
7262   if (NULL == t)
7263   {
7264     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Tunnel %X unknown.\n", tid);
7265     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  for client %u.\n", c->id);
7266     GNUNET_break (0);
7267     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7268     return;
7269   }
7270
7271   /*  It should be sent by someone who has this as incoming tunnel. */
7272   if (GNUNET_NO == client_knows_tunnel (c, t))
7273   {
7274     GNUNET_break (0);
7275     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7276     return;
7277   }
7278
7279   /* PID should be as expected */
7280   clinfo = tunnel_get_client_fc (t, c);
7281   if (ntohl (data_msg->pid) != clinfo->bck_pid + 1)
7282   {
7283     GNUNET_break (0);
7284     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7285                 "To Origin PID, expected %u, got %u\n",
7286                 clinfo->bck_pid + 1,
7287                 ntohl (data_msg->pid));
7288     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7289     return;
7290   }
7291
7292   /* Ok, everything is correct, send the message
7293    * (pretend we got it from a mesh peer)
7294    */
7295   clinfo->bck_pid++;
7296   {
7297     char buf[ntohs (message->size)] GNUNET_ALIGN;
7298     struct GNUNET_MESH_ToOrigin *copy;
7299
7300     /* Work around const limitation */
7301     copy = (struct GNUNET_MESH_ToOrigin *) buf;
7302     memcpy (buf, data_msg, size);
7303     GNUNET_PEER_resolve (t->id.oid, &copy->oid);
7304     copy->tid = htonl (t->id.tid);
7305     copy->ttl = htonl (default_ttl);
7306     if (ntohl (copy->pid) != (t->bck_pid + 1))
7307     {
7308       GNUNET_break (0);
7309       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7310                   "To Origin PID, expected %u, got %u\n",
7311                   t->bck_pid + 1,
7312                   ntohl (copy->pid));
7313       return;
7314     }
7315     t->bck_pid++;
7316     copy->sender = my_full_id;
7317     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7318                 "  calling generic handler...\n");
7319     handle_mesh_data_to_orig (NULL, &my_full_id, &copy->header, NULL, 0);
7320   }
7321   GNUNET_SERVER_receive_done (client, GNUNET_OK);
7322
7323   return;
7324 }
7325
7326
7327 /**
7328  * Handler for client traffic directed to all peers in a tunnel
7329  *
7330  * @param cls closure
7331  * @param client identification of the client
7332  * @param message the actual message
7333  */
7334 static void
7335 handle_local_multicast (void *cls, struct GNUNET_SERVER_Client *client,
7336                         const struct GNUNET_MessageHeader *message)
7337 {
7338   struct MeshClient *c;
7339   struct MeshTunnel *t;
7340   struct GNUNET_MESH_Multicast *data_msg;
7341   MESH_TunnelNumber tid;
7342
7343   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7344               "Got a multicast request from a client!\n");
7345
7346   /* Sanity check for client registration */
7347   if (NULL == (c = client_get (client)))
7348   {
7349     GNUNET_break (0);
7350     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7351     return;
7352   }
7353   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7354
7355   data_msg = (struct GNUNET_MESH_Multicast *) message;
7356
7357   /* Sanity check for message size */
7358   if (sizeof (struct GNUNET_MESH_Multicast) +
7359       sizeof (struct GNUNET_MessageHeader) > ntohs (data_msg->header.size))
7360   {
7361     GNUNET_break (0);
7362     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7363     return;
7364   }
7365
7366   /* Tunnel exists? */
7367   tid = ntohl (data_msg->tid);
7368   t = tunnel_get_by_local_id (c, tid);
7369   if (NULL == t)
7370   {
7371     GNUNET_break (0);
7372     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Tunnel %X unknown.\n", tid);
7373     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  for client %u.\n", c->id);
7374     GNUNET_break (0);
7375     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7376     return;
7377   }
7378
7379   /* Does client own tunnel? */
7380   if (t->owner->handle != client)
7381   {
7382     GNUNET_break (0);
7383     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7384     return;
7385   }
7386
7387   /* PID should be as expected */
7388   if (ntohl (data_msg->pid) != t->fwd_pid + 1)
7389   {
7390     GNUNET_break (0);
7391     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7392               "Multicast PID, expected %u, got %u\n",
7393               t->fwd_pid + 1, ntohl (data_msg->pid));
7394     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7395     return;
7396   }
7397
7398   {
7399     char buf[ntohs (message->size)] GNUNET_ALIGN;
7400     struct GNUNET_MESH_Multicast *copy;
7401
7402     copy = (struct GNUNET_MESH_Multicast *) buf;
7403     memcpy (buf, message, ntohs (message->size));
7404     copy->oid = my_full_id;
7405     copy->tid = htonl (t->id.tid);
7406     copy->ttl = htonl (default_ttl);
7407     GNUNET_assert (ntohl (copy->pid) == (t->fwd_pid + 1));
7408     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
7409                 "  calling generic handler...\n");
7410     handle_mesh_data_multicast (client, &my_full_id, &copy->header, NULL, 0);
7411   }
7412
7413   /* receive done gets called when last copy is sent to a neighbor */
7414   return;
7415 }
7416
7417
7418 /**
7419  * Handler for client's ACKs for payload traffic.
7420  *
7421  * @param cls Closure (unused).
7422  * @param client Identification of the client.
7423  * @param message The actual message.
7424  */
7425 static void
7426 handle_local_ack (void *cls, struct GNUNET_SERVER_Client *client,
7427                   const struct GNUNET_MessageHeader *message)
7428 {
7429   struct GNUNET_MESH_LocalAck *msg;
7430   struct MeshTunnel *t;
7431   struct MeshClient *c;
7432   MESH_TunnelNumber tid;
7433   uint32_t ack;
7434
7435   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a local ACK\n");
7436   /* Sanity check for client registration */
7437   if (NULL == (c = client_get (client)))
7438   {
7439     GNUNET_break (0);
7440     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7441     return;
7442   }
7443   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
7444
7445   msg = (struct GNUNET_MESH_LocalAck *) message;
7446
7447   /* Tunnel exists? */
7448   tid = ntohl (msg->tunnel_id);
7449   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", tid);
7450   t = tunnel_get_by_local_id (c, tid);
7451   if (NULL == t)
7452   {
7453     GNUNET_break (0);
7454     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Tunnel %X unknown.\n", tid);
7455     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  for client %u.\n", c->id);
7456     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
7457     return;
7458   }
7459
7460   ack = ntohl (msg->max_pid);
7461   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ack %u\n", ack);
7462
7463   /* Does client own tunnel? I.E: Is this and ACK for BCK traffic? */
7464   if (NULL != t->owner && t->owner->handle == client)
7465   {
7466     /* The client owns the tunnel, ACK is for data to_origin, send BCK ACK. */
7467     t->bck_ack = ack;
7468     tunnel_send_bck_ack(t, GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
7469   }
7470   else
7471   {
7472     /* The client doesn't own the tunnel, this ACK is for FWD traffic. */
7473     tunnel_set_client_fwd_ack (t, c, ack);
7474     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
7475   }
7476
7477   GNUNET_SERVER_receive_done (client, GNUNET_OK);  
7478
7479   return;
7480 }
7481
7482
7483 /**
7484  * Functions to handle messages from clients
7485  */
7486 static struct GNUNET_SERVER_MessageHandler client_handlers[] = {
7487   {&handle_local_new_client, NULL,
7488    GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT, 0},
7489   {&handle_local_announce_regex, NULL,
7490    GNUNET_MESSAGE_TYPE_MESH_LOCAL_ANNOUNCE_REGEX, 0},
7491   {&handle_local_tunnel_create, NULL,
7492    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE,
7493    sizeof (struct GNUNET_MESH_TunnelMessage)},
7494   {&handle_local_tunnel_destroy, NULL,
7495    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY,
7496    sizeof (struct GNUNET_MESH_TunnelMessage)},
7497   {&handle_local_tunnel_speed, NULL,
7498    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MIN,
7499    sizeof (struct GNUNET_MESH_TunnelMessage)},
7500   {&handle_local_tunnel_speed, NULL,
7501    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_MAX,
7502    sizeof (struct GNUNET_MESH_TunnelMessage)},
7503   {&handle_local_tunnel_buffer, NULL,
7504    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_BUFFER,
7505    sizeof (struct GNUNET_MESH_TunnelMessage)},
7506   {&handle_local_tunnel_buffer, NULL,
7507    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_NOBUFFER,
7508    sizeof (struct GNUNET_MESH_TunnelMessage)},
7509   {&handle_local_connect_add, NULL,
7510    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD,
7511    sizeof (struct GNUNET_MESH_PeerControl)},
7512   {&handle_local_connect_del, NULL,
7513    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL,
7514    sizeof (struct GNUNET_MESH_PeerControl)},
7515   {&handle_local_blacklist, NULL,
7516    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_BLACKLIST,
7517    sizeof (struct GNUNET_MESH_PeerControl)},
7518   {&handle_local_unblacklist, NULL,
7519    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_UNBLACKLIST,
7520    sizeof (struct GNUNET_MESH_PeerControl)},
7521   {&handle_local_connect_by_type, NULL,
7522    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_TYPE,
7523    sizeof (struct GNUNET_MESH_ConnectPeerByType)},
7524   {&handle_local_connect_by_string, NULL,
7525    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_STRING, 0},
7526   {&handle_local_unicast, NULL,
7527    GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
7528   {&handle_local_to_origin, NULL,
7529    GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
7530   {&handle_local_multicast, NULL,
7531    GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
7532   {&handle_local_ack, NULL,
7533    GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK,
7534    sizeof (struct GNUNET_MESH_LocalAck)},
7535   {NULL, NULL, 0, 0}
7536 };
7537
7538
7539 /**
7540  * To be called on core init/fail.
7541  *
7542  * @param cls service closure
7543  * @param server handle to the server for this service
7544  * @param identity the public identity of this peer
7545  */
7546 static void
7547 core_init (void *cls, struct GNUNET_CORE_Handle *server,
7548            const struct GNUNET_PeerIdentity *identity)
7549 {
7550   static int i = 0;
7551   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Core init\n");
7552   core_handle = server;
7553   if (0 != memcmp (identity, &my_full_id, sizeof (my_full_id)) ||
7554       NULL == server)
7555   {
7556     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Wrong CORE service\n"));
7557     GNUNET_SCHEDULER_shutdown (); // Try gracefully
7558     if (10 < i++)
7559       GNUNET_abort(); // Try harder
7560   }
7561   return;
7562 }
7563
7564
7565 /**
7566  * Method called whenever a given peer connects.
7567  *
7568  * @param cls closure
7569  * @param peer peer identity this notification is about
7570  * @param atsi performance data for the connection
7571  * @param atsi_count number of records in 'atsi'
7572  */
7573 static void
7574 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
7575               const struct GNUNET_ATS_Information *atsi,
7576               unsigned int atsi_count)
7577 {
7578   struct MeshPeerInfo *peer_info;
7579   struct MeshPeerPath *path;
7580
7581   DEBUG_CONN ("Peer connected\n");
7582   DEBUG_CONN ("     %s\n", GNUNET_i2s (&my_full_id));
7583   peer_info = peer_info_get (peer);
7584   if (myid == peer_info->id)
7585   {
7586     DEBUG_CONN ("     (self)\n");
7587     return;
7588   }
7589   else
7590   {
7591     DEBUG_CONN ("     %s\n", GNUNET_i2s (peer));
7592   }
7593   path = path_new (2);
7594   path->peers[0] = myid;
7595   path->peers[1] = peer_info->id;
7596   GNUNET_PEER_change_rc (myid, 1);
7597   GNUNET_PEER_change_rc (peer_info->id, 1);
7598   peer_info_add_path (peer_info, path, GNUNET_YES);
7599   GNUNET_STATISTICS_update (stats, "# peers", 1, GNUNET_NO);
7600   return;
7601 }
7602
7603
7604 /**
7605  * Method called whenever a peer disconnects.
7606  *
7607  * @param cls closure
7608  * @param peer peer identity this notification is about
7609  */
7610 static void
7611 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
7612 {
7613   struct MeshPeerInfo *pi;
7614   struct MeshPeerQueue *q;
7615   struct MeshPeerQueue *n;
7616
7617   DEBUG_CONN ("Peer disconnected\n");
7618   pi = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
7619   if (NULL == pi)
7620   {
7621     GNUNET_break (0);
7622     return;
7623   }
7624   q = pi->queue_head;
7625   while (NULL != q)
7626   {
7627       n = q->next;
7628       if (q->peer == pi)
7629       {
7630         /* try to reroute this traffic instead */
7631         queue_destroy(q, GNUNET_YES);
7632       }
7633       q = n;
7634   }
7635   peer_info_remove_path (pi, pi->id, myid);
7636   if (myid == pi->id)
7637   {
7638     DEBUG_CONN ("     (self)\n");
7639   }
7640   GNUNET_STATISTICS_update (stats, "# peers", -1, GNUNET_NO);
7641   return;
7642 }
7643
7644
7645 /******************************************************************************/
7646 /************************      MAIN FUNCTIONS      ****************************/
7647 /******************************************************************************/
7648
7649 /**
7650  * Iterator over tunnel hash map entries to destroy the tunnel during shutdown.
7651  *
7652  * @param cls closure
7653  * @param key current key code
7654  * @param value value in the hash map
7655  * @return GNUNET_YES if we should continue to iterate,
7656  *         GNUNET_NO if not.
7657  */
7658 static int
7659 shutdown_tunnel (void *cls, const struct GNUNET_HashCode * key, void *value)
7660 {
7661   struct MeshTunnel *t = value;
7662
7663   tunnel_destroy (t);
7664   return GNUNET_YES;
7665 }
7666
7667 /**
7668  * Iterator over peer hash map entries to destroy the tunnel during shutdown.
7669  *
7670  * @param cls closure
7671  * @param key current key code
7672  * @param value value in the hash map
7673  * @return GNUNET_YES if we should continue to iterate,
7674  *         GNUNET_NO if not.
7675  */
7676 static int
7677 shutdown_peer (void *cls, const struct GNUNET_HashCode * key, void *value)
7678 {
7679   struct MeshPeerInfo *p = value;
7680   struct MeshPeerQueue *q;
7681   struct MeshPeerQueue *n;
7682
7683   q = p->queue_head;
7684   while (NULL != q)
7685   {
7686       n = q->next;
7687       if (q->peer == p)
7688       {
7689         queue_destroy(q, GNUNET_YES);
7690       }
7691       q = n;
7692   }
7693   peer_info_destroy (p);
7694   return GNUNET_YES;
7695 }
7696
7697 /**
7698  * Task run during shutdown.
7699  *
7700  * @param cls unused
7701  * @param tc unused
7702  */
7703 static void
7704 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
7705 {
7706   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shutting down\n");
7707
7708   if (core_handle != NULL)
7709   {
7710     GNUNET_CORE_disconnect (core_handle);
7711     core_handle = NULL;
7712   }
7713   GNUNET_CONTAINER_multihashmap_iterate (tunnels, &shutdown_tunnel, NULL);
7714   GNUNET_CONTAINER_multihashmap_iterate (peers, &shutdown_peer, NULL);
7715   if (dht_handle != NULL)
7716   {
7717     GNUNET_DHT_disconnect (dht_handle);
7718     dht_handle = NULL;
7719   }
7720   if (nc != NULL)
7721   {
7722     GNUNET_SERVER_notification_context_destroy (nc);
7723     nc = NULL;
7724   }
7725   if (GNUNET_SCHEDULER_NO_TASK != announce_id_task)
7726   {
7727     GNUNET_SCHEDULER_cancel (announce_id_task);
7728     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
7729   }
7730   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shut down\n");
7731 }
7732
7733 /**
7734  * Process mesh requests.
7735  *
7736  * @param cls closure
7737  * @param server the initialized server
7738  * @param c configuration to use
7739  */
7740 static void
7741 run (void *cls, struct GNUNET_SERVER_Handle *server,
7742      const struct GNUNET_CONFIGURATION_Handle *c)
7743 {
7744   struct MeshPeerInfo *peer;
7745   struct MeshPeerPath *p;
7746   char *keyfile;
7747
7748   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "starting to run\n");
7749   server_handle = server;
7750   core_handle = GNUNET_CORE_connect (c, /* Main configuration */
7751                                      NULL,      /* Closure passed to MESH functions */
7752                                      &core_init,        /* Call core_init once connected */
7753                                      &core_connect,     /* Handle connects */
7754                                      &core_disconnect,  /* remove peers on disconnects */
7755                                      NULL,      /* Don't notify about all incoming messages */
7756                                      GNUNET_NO, /* For header only in notification */
7757                                      NULL,      /* Don't notify about all outbound messages */
7758                                      GNUNET_NO, /* For header-only out notification */
7759                                      core_handlers);    /* Register these handlers */
7760
7761   if (core_handle == NULL)
7762   {
7763     GNUNET_break (0);
7764     GNUNET_SCHEDULER_shutdown ();
7765     return;
7766   }
7767
7768   if (GNUNET_OK !=
7769       GNUNET_CONFIGURATION_get_value_filename (c, "GNUNETD", "HOSTKEY",
7770                                                &keyfile))
7771   {
7772     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7773                 _
7774                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7775                 "hostkey");
7776     GNUNET_SCHEDULER_shutdown ();
7777     return;
7778   }
7779
7780   if (GNUNET_OK !=
7781       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "REFRESH_PATH_TIME",
7782                                            &refresh_path_time))
7783   {
7784     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7785                 _
7786                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7787                 "refresh path time");
7788     GNUNET_SCHEDULER_shutdown ();
7789     return;
7790   }
7791
7792   if (GNUNET_OK !=
7793       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "APP_ANNOUNCE_TIME",
7794                                            &app_announce_time))
7795   {
7796     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7797                 _
7798                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7799                 "app announce time");
7800     GNUNET_SCHEDULER_shutdown ();
7801     return;
7802   }
7803
7804   if (GNUNET_OK !=
7805       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "ID_ANNOUNCE_TIME",
7806                                            &id_announce_time))
7807   {
7808     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7809                 _
7810                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7811                 "id announce time");
7812     GNUNET_SCHEDULER_shutdown ();
7813     return;
7814   }
7815
7816   if (GNUNET_OK !=
7817       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "UNACKNOWLEDGED_WAIT",
7818                                            &unacknowledged_wait_time))
7819   {
7820     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7821                 _
7822                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7823                 "unacknowledged wait time");
7824     GNUNET_SCHEDULER_shutdown ();
7825     return;
7826   }
7827
7828   if (GNUNET_OK !=
7829       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "CONNECT_TIMEOUT",
7830                                            &connect_timeout))
7831   {
7832     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7833                 _
7834                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7835                 "connect timeout");
7836     GNUNET_SCHEDULER_shutdown ();
7837     return;
7838   }
7839
7840   if (GNUNET_OK !=
7841       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_MSGS_QUEUE",
7842                                              &max_msgs_queue))
7843   {
7844     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7845                 _
7846                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7847                 "max msgs queue");
7848     GNUNET_SCHEDULER_shutdown ();
7849     return;
7850   }
7851
7852   if (GNUNET_OK !=
7853       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_TUNNELS",
7854                                              &max_tunnels))
7855   {
7856     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7857                 _
7858                 ("Mesh service is lacking key configuration settings (%s).  Exiting.\n"),
7859                 "max tunnels");
7860     GNUNET_SCHEDULER_shutdown ();
7861     return;
7862   }
7863
7864   if (GNUNET_OK !=
7865       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DEFAULT_TTL",
7866                                              &default_ttl))
7867   {
7868     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7869                 _
7870                 ("Mesh service is lacking key configuration settings (%s). Using default (%u).\n"),
7871                 "default ttl", 64);
7872     default_ttl = 64;
7873   }
7874
7875   if (GNUNET_OK !=
7876       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DHT_REPLICATION_LEVEL",
7877                                              &dht_replication_level))
7878   {
7879     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
7880                 _
7881                 ("Mesh service is lacking key configuration settings (%s). Using default (%u).\n"),
7882                 "dht replication level", 10);
7883     dht_replication_level = 10;
7884   }
7885
7886   
7887   my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
7888   GNUNET_free (keyfile);
7889   if (my_private_key == NULL)
7890   {
7891     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
7892                 _("Mesh service could not access hostkey.  Exiting.\n"));
7893     GNUNET_SCHEDULER_shutdown ();
7894     return;
7895   }
7896   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
7897   GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
7898                       &my_full_id.hashPubKey);
7899   myid = GNUNET_PEER_intern (&my_full_id);
7900   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
7901               "Mesh for peer [%s] starting\n",
7902               GNUNET_i2s(&my_full_id));
7903
7904 //   transport_handle = GNUNET_TRANSPORT_connect(c,
7905 //                                               &my_full_id,
7906 //                                               NULL,
7907 //                                               NULL,
7908 //                                               NULL,
7909 //                                               NULL);
7910
7911   dht_handle = GNUNET_DHT_connect (c, 64);
7912   if (dht_handle == NULL)
7913   {
7914     GNUNET_break (0);
7915   }
7916
7917   stats = GNUNET_STATISTICS_create ("mesh", c);
7918
7919
7920   next_tid = 0;
7921   next_local_tid = GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
7922
7923   tunnels = GNUNET_CONTAINER_multihashmap_create (32);
7924   incoming_tunnels = GNUNET_CONTAINER_multihashmap_create (32);
7925   peers = GNUNET_CONTAINER_multihashmap_create (32);
7926   applications = GNUNET_CONTAINER_multihashmap_create (32);
7927   types = GNUNET_CONTAINER_multihashmap_create (32);
7928
7929   GNUNET_SERVER_add_handlers (server_handle, client_handlers);
7930   nc = GNUNET_SERVER_notification_context_create (server_handle, 1);
7931   GNUNET_SERVER_disconnect_notify (server_handle,
7932                                    &handle_local_client_disconnect, NULL);
7933
7934
7935   clients = NULL;
7936   clients_tail = NULL;
7937   next_client_id = 0;
7938
7939   announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
7940   announce_id_task = GNUNET_SCHEDULER_add_now (&announce_id, cls);
7941
7942   /* Create a peer_info for the local peer */
7943   peer = peer_info_get (&my_full_id);
7944   p = path_new (1);
7945   p->peers[0] = myid;
7946   GNUNET_PEER_change_rc (myid, 1);
7947   peer_info_add_path (peer, p, GNUNET_YES);
7948
7949   /* Scheduled the task to clean up when shutdown is called */
7950   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
7951                                 NULL);
7952
7953   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "end of run()\n");
7954 }
7955
7956 /**
7957  * The main function for the mesh service.
7958  *
7959  * @param argc number of arguments from the command line
7960  * @param argv command line arguments
7961  * @return 0 ok, 1 on error
7962  */
7963 int
7964 main (int argc, char *const *argv)
7965 {
7966   int ret;
7967
7968   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main()\n");
7969   ret =
7970       (GNUNET_OK ==
7971        GNUNET_SERVICE_run (argc, argv, "mesh", GNUNET_SERVICE_OPTION_NONE, &run,
7972                            NULL)) ? 0 : 1;
7973   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main() END\n");
7974
7975   INTERVAL_SHOW;
7976
7977   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
7978               "Mesh for peer [%s] FWD ACKs %u, BCK ACKs %u\n",
7979               GNUNET_i2s(&my_full_id), debug_fwd_ack, debug_bck_ack);
7980   
7981
7982   return ret;
7983 }