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