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