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