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