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