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