3252d2703d78a951be985956f98fe979378b15af
[oweals/gnunet.git] / src / mesh / gnunet-service-mesh-new.c
1 /*
2      This file is part of GNUnet.
3      (C) 2001-2012 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file mesh/gnunet-service-mesh.c
23  * @brief GNUnet MESH service
24  * @author Bartlomiej Polot
25  *
26  * STRUCTURE:
27  * - DATA STRUCTURES
28  * - GLOBAL VARIABLES
29  * - GENERAL HELPERS
30  * - PERIODIC FUNCTIONS
31  * - MESH NETWORK HANDLER HELPERS
32  * - MESH NETWORK HANDLES
33  * - MESH LOCAL HANDLER HELPERS
34  * - MESH LOCAL HANDLES
35  * - MAIN FUNCTIONS (main & run)
36  *
37  * TODO:
38  * - error reporting (CREATE/CHANGE/ADD/DEL?) -- new message!
39  * - partial disconnect reporting -- same as error reporting?
40  * - add ping message
41  * - relay corking down to core
42  * - set ttl relative to tree depth
43  * - Add data ACK count in path ACK
44  * - Make common GNUNET_MESH_Data header for unicast, to_orig, multicast
45  * TODO END
46  */
47
48 #include "platform.h"
49 #include "mesh2.h"
50 #include "mesh2_protocol.h"
51 #include "mesh_tunnel_tree.h"
52 #include "block_mesh.h"
53 #include "gnunet_dht_service.h"
54 #include "gnunet_statistics_service.h"
55
56 #define MESH_BLOOM_SIZE         128
57
58 #define MESH_DEBUG_DHT          GNUNET_NO
59 #define MESH_DEBUG_CONNECTION   GNUNET_NO
60 #define MESH_DEBUG_TIMING       __LINUX__ && GNUNET_NO
61
62 #define MESH_MAX_POLL_TIME      GNUNET_TIME_relative_multiply (\
63                                   GNUNET_TIME_UNIT_MINUTES,\
64                                   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 containing info about a queued transmission to this peer
113  */
114 struct MeshPeerQueue
115 {
116     /**
117       * DLL next
118       */
119   struct MeshPeerQueue *next;
120
121     /**
122       * DLL previous
123       */
124   struct MeshPeerQueue *prev;
125
126     /**
127      * Peer this transmission is directed to.
128      */
129   struct MeshPeerInfo *peer;
130
131     /**
132      * Tunnel this message belongs to.
133      */
134   struct MeshTunnel *tunnel;
135
136     /**
137      * Pointer to info stucture used as cls.
138      */
139   void *cls;
140
141     /**
142      * Type of message
143      */
144   uint16_t type;
145
146     /**
147      * Size of the message
148      */
149   size_t size;
150 };
151
152
153 /**
154  * Struct containing all info possibly needed to build a package when called
155  * back by core.
156  */
157 struct MeshTransmissionDescriptor
158 {
159     /** ID of the tunnel this packet travels in */
160   struct MESH_TunnelID *origin;
161
162     /** Who was this message being sent to */
163   struct MeshPeerInfo *peer;
164
165     /** Ultimate destination of the packet */
166   GNUNET_PEER_Id destination;
167
168   /** Tunnel it belongs to. */
169   struct MeshTunnel *t;
170   
171   /** Size of the data. */
172   size_t data_len;
173   
174   /** Data itself */
175   void *data;
176 };
177
178
179 /**
180  * Struct containing all information regarding a given peer
181  */
182 struct MeshPeerInfo
183 {
184     /**
185      * ID of the peer
186      */
187   GNUNET_PEER_Id id;
188
189     /**
190      * Last time we heard from this peer
191      */
192   struct GNUNET_TIME_Absolute last_contact;
193
194     /**
195      * Number of attempts to reconnect so far
196      */
197   int n_reconnect_attempts;
198
199     /**
200      * Paths to reach the peer, ordered by ascending hop count
201      */
202   struct MeshPeerPath *path_head;
203
204     /**
205      * Paths to reach the peer, ordered by ascending hop count
206      */
207   struct MeshPeerPath *path_tail;
208
209     /**
210      * Handle to stop the DHT search for a path to this peer
211      */
212   struct GNUNET_DHT_GetHandle *dhtget;
213
214     /**
215      * Array of tunnels this peer is the target of.
216      * Most probably a small amount, therefore not a hashmap.
217      * When the path to the peer changes, notify these tunnels to let them
218      * re-adjust their path trees.
219      */
220   struct MeshTunnel **tunnels;
221
222     /**
223      * Number of tunnels this peers participates in
224      */
225   unsigned int ntunnels;
226
227    /**
228     * Transmission queue to core DLL head
229     */
230   struct MeshPeerQueue *queue_head;
231
232    /**
233     * Transmission queue to core DLL tail
234     */
235    struct MeshPeerQueue *queue_tail;
236
237    /**
238     * How many messages are in the queue to this peer.
239     */
240    unsigned int queue_n;
241
242    /**
243     * Handle to for queued transmissions
244     */
245   struct GNUNET_CORE_TransmitHandle *core_transmit;
246 };
247
248
249 /**
250  * Struct to encapsulate all the Flow Control information to a peer in the
251  * context of a tunnel: Same peer in different tunnels will have independent
252  * flow control structures, allowing to choke/free tunnels according to its
253  * own criteria.
254  */
255 struct MeshFlowControl
256 {
257   /**
258    * ID of the last packet sent towards the peer.
259    */
260   uint32_t last_pid_sent;
261
262   /**
263    * ID of the last packet received from the peer.
264    */
265   uint32_t last_pid_recv;
266
267   /**
268    * Last ACK sent to the peer (peer can't send more than this PID).
269    */
270   uint32_t last_ack_sent;
271
272   /**
273    * Last ACK sent towards the origin (for traffic towards leaf node).
274    */
275   uint32_t last_ack_recv;
276
277   /**
278    * How many messages are in the queue towards this peer.
279    */
280   uint32_t queue_n;
281
282   /**
283    * Task to poll the peer in case of a lost ACK causes stall.
284    */
285   GNUNET_SCHEDULER_TaskIdentifier poll_task;
286
287   /**
288    * How frequently to poll for ACKs.
289    */
290   struct GNUNET_TIME_Relative poll_time;
291
292   /**
293    * On which tunnel to poll.
294    * Using an explicit poll_ctx would not help memory wise,
295    * since the allocated context would have to be stored in the
296    * fc struct in order to free it upon cancelling poll_task.
297    */
298   struct MeshTunnel *t;
299 };
300
301
302 /**
303  * Globally unique tunnel identification (owner + number)
304  * DO NOT USE OVER THE NETWORK
305  */
306 struct MESH_TunnelID
307 {
308     /**
309      * Node that owns the tunnel
310      */
311   GNUNET_PEER_Id oid;
312
313     /**
314      * Tunnel number to differentiate all the tunnels owned by the node oid
315      * ( tid < GNUNET_MESH_LOCAL_TUNNEL_ID_CLI )
316      */
317   MESH_TunnelNumber tid;
318 };
319
320
321 /**
322  * Struct containing all information regarding a tunnel
323  * For an intermediate node the improtant info used will be:
324  * - id        Tunnel unique identification
325  * - paths[0]  To know where to send it next
326  * - metainfo: ready, speeds, accounting
327  */
328 struct MeshTunnel
329 {
330     /**
331      * Tunnel ID
332      */
333   struct MESH_TunnelID id;
334
335     /**
336      * Local tunnel number ( >= GNUNET_MESH_LOCAL_TUNNEL_ID_CLI or 0 )
337      */
338   MESH_TunnelNumber local_tid;
339
340     /**
341      * Local tunnel number for local destination clients (incoming number)
342      * ( >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV or 0). All clients share the same
343      * number.
344      */
345   MESH_TunnelNumber local_tid_dest;
346
347     /**
348      * Is the tunnel bufferless (minimum latency)?
349      */
350   int nobuffer;
351
352     /**
353      * Force sending ACK? Flag to allow duplicate ACK on POLL.
354      */
355   int force_ack;
356
357     /**
358      * How many messages do we accept in the forward queue.
359      */
360   unsigned int queue_max;
361
362     /**
363      * Last time the tunnel was used
364      */
365   struct GNUNET_TIME_Absolute timestamp;
366
367     /**
368      * Destination of the tunnel.
369      */
370   GNUNET_PEER_Id dest;
371
372     /**
373      * Next hop in the tunnel.
374      */
375   GNUNET_PEER_Id next_hop;
376
377     /**
378      * Previous hop in the tunnel.
379      */
380   GNUNET_PEER_Id prev_hop;
381
382     /**
383      * Flow control information about @c next_hop.
384      */
385   struct MeshFlowControl next_fc;
386
387   /**
388    * Flow control information about @c prev_hop.
389    */
390   struct MeshFlowControl prev_fc;
391
392     /**
393      * Client owner of the tunnel, if any
394      */
395   struct MeshClient *owner;
396
397     /**
398      * Task to keep the used paths alive at the owner,
399      * time tunnel out on all the other peers.
400      */
401   GNUNET_SCHEDULER_TaskIdentifier maintenance_task;
402
403     /**
404      * Clients that have been informed about and want to stay in the tunnel.
405      */
406   struct MeshClient **clients;
407
408     /**
409      * Flow control info for each client.
410      */
411   struct MeshTunnelClientInfo *clients_fc;
412
413     /**
414      * Number of elements in clients/clients_fc
415      */
416   unsigned int nclients;
417
418     /**
419      * Clients that have been informed but requested to leave the tunnel.
420      */
421   struct MeshClient **ignore;
422
423     /**
424      * Number of elements in clients
425      */
426   unsigned int nignore;
427
428     /**
429      * Path being used for the tunnel.
430      */
431   struct MeshPeerPath *path;
432
433     /**
434      * Flag to signal the destruction of the tunnel.
435      * If this is set GNUNET_YES the tunnel will be destroyed
436      * when the queue is empty.
437      */
438   int destroy;
439
440     /**
441      * Total messages pending for this tunnels, payload or not.
442      */
443   unsigned int pending_messages;
444
445     /**
446      * If the tunnel is empty, destoy it.
447      */
448   GNUNET_SCHEDULER_TaskIdentifier delayed_destroy;
449 };
450
451
452 /**
453  * Info about a leaf client of a tunnel, needed to perform flow control.
454  */
455 struct MeshTunnelClientInfo
456 {
457   /**
458    * PID of the last packet sent to the client (FWD).
459    */
460   uint32_t fwd_pid;
461
462   /**
463    * PID of the last packet received from the client (BCK).
464    */
465   uint32_t bck_pid;
466
467   /**
468    * Maximum PID allowed (FWD ACK received).
469    */
470   uint32_t fwd_ack;
471   
472   /**
473    * Last ACK sent to that child (BCK ACK).
474    */
475   uint32_t bck_ack;
476 };
477
478
479 /**
480  * Struct containing information about a client of the service
481  */
482 struct MeshClient
483 {
484     /**
485      * Linked list next
486      */
487   struct MeshClient *next;
488
489     /**
490      * Linked list prev
491      */
492   struct MeshClient *prev;
493
494     /**
495      * Tunnels that belong to this client, indexed by local id
496      */
497   struct GNUNET_CONTAINER_MultiHashMap *own_tunnels;
498
499    /**
500      * Tunnels this client has accepted, indexed by incoming local id
501      */
502   struct GNUNET_CONTAINER_MultiHashMap *incoming_tunnels;
503
504    /**
505      * Tunnels this client has rejected, indexed by incoming local id
506      */
507   struct GNUNET_CONTAINER_MultiHashMap *ignore_tunnels;
508     /**
509      * Handle to communicate with the client
510      */
511   struct GNUNET_SERVER_Client *handle;
512
513     /**
514      * Messages that this client has declared interest in
515      */
516   struct GNUNET_CONTAINER_MultiHashMap *types;
517
518     /**
519      * Whether the client is active or shutting down (don't send confirmations
520      * to a client that is shutting down.
521      */
522   int shutting_down;
523
524     /**
525      * ID of the client, mainly for debug messages
526      */
527   unsigned int id;
528
529 };
530
531
532 /******************************************************************************/
533 /************************      DEBUG FUNCTIONS     ****************************/
534 /******************************************************************************/
535
536 #if MESH_DEBUG
537 /**
538  * GNUNET_SCHEDULER_Task for printing a message after some operation is done
539  * @param cls string to print
540  * @param success  GNUNET_OK if the PUT was transmitted,
541  *                GNUNET_NO on timeout,
542  *                GNUNET_SYSERR on disconnect from service
543  *                after the PUT message was transmitted
544  *                (so we don't know if it was received or not)
545  */
546
547 #if 0
548 static void
549 mesh_debug (void *cls, int success)
550 {
551   char *s = cls;
552
553   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "%s (%d)\n", s, success);
554 }
555 #endif
556
557 unsigned int debug_fwd_ack;
558 unsigned int debug_bck_ack;
559
560 #endif
561
562 /******************************************************************************/
563 /***********************      GLOBAL VARIABLES     ****************************/
564 /******************************************************************************/
565
566 /************************** Configuration parameters **************************/
567
568 /**
569  * How often to send tunnel keepalives. Tunnels timeout after 4 missed.
570  */
571 static struct GNUNET_TIME_Relative refresh_path_time;
572
573 /**
574  * How often to PUT own ID in the DHT.
575  */
576 static struct GNUNET_TIME_Relative id_announce_time;
577
578 /**
579  * Maximum time allowed to connect to a peer found by string.
580  */
581 static struct GNUNET_TIME_Relative connect_timeout;
582
583 /**
584  * Default TTL for payload packets.
585  */
586 static unsigned long long default_ttl;
587
588 /**
589  * DHT replication level, see DHT API: GNUNET_DHT_get_start, GNUNET_DHT_put.
590  */
591 static unsigned long long dht_replication_level;
592
593 /**
594  * How many tunnels are we willing to maintain.
595  * Local tunnels are always allowed, even if there are more tunnels than max.
596  */
597 static unsigned long long max_tunnels;
598
599 /**
600  * How many messages *in total* are we willing to queue, divided by number of 
601  * tunnels to get tunnel queue size.
602  */
603 static unsigned long long max_msgs_queue;
604
605 /**
606  * How many peers do we want to remember?
607  */
608 static unsigned long long max_peers;
609
610
611 /*************************** Static global variables **************************/
612
613 /**
614  * Hostkey generation context
615  */
616 static struct GNUNET_CRYPTO_EccKeyGenerationContext *keygen;
617
618 /**
619  * DLL with all the clients, head.
620  */
621 static struct MeshClient *clients_head;
622
623 /**
624  * DLL with all the clients, tail.
625  */
626 static struct MeshClient *clients_tail;
627
628 /**
629  * Tunnels known, indexed by MESH_TunnelID (MeshTunnel).
630  */
631 static struct GNUNET_CONTAINER_MultiHashMap *tunnels;
632
633 /**
634  * Number of tunnels known.
635  */
636 static unsigned long long n_tunnels;
637
638 /**
639  * Tunnels incoming, indexed by MESH_TunnelNumber
640  * (which is greater than GNUNET_MESH_LOCAL_TUNNEL_ID_SERV).
641  */
642 static struct GNUNET_CONTAINER_MultiHashMap *incoming_tunnels;
643
644 /**
645  * Peers known, indexed by PeerIdentity (MeshPeerInfo).
646  */
647 static struct GNUNET_CONTAINER_MultiHashMap *peers;
648
649 /*
650  * Handle to communicate with transport
651  */
652 // static struct GNUNET_TRANSPORT_Handle *transport_handle;
653
654 /**
655  * Handle to communicate with core.
656  */
657 static struct GNUNET_CORE_Handle *core_handle;
658
659 /**
660  * Handle to use DHT.
661  */
662 static struct GNUNET_DHT_Handle *dht_handle;
663
664 /**
665  * Handle to server.
666  */
667 static struct GNUNET_SERVER_Handle *server_handle;
668
669 /**
670  * Handle to the statistics service.
671  */
672 static struct GNUNET_STATISTICS_Handle *stats;
673
674 /**
675  * Notification context, to send messages to local clients.
676  */
677 static struct GNUNET_SERVER_NotificationContext *nc;
678
679 /**
680  * Local peer own ID (memory efficient handle).
681  */
682 static GNUNET_PEER_Id myid;
683
684 /**
685  * Local peer own ID (full value).
686  */
687 static struct GNUNET_PeerIdentity my_full_id;
688
689 /**
690  * Own private key.
691  */
692 static struct GNUNET_CRYPTO_EccPrivateKey *my_private_key;
693
694 /**
695  * Own public key.
696  */
697 static struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded my_public_key;
698
699 /**
700  * Tunnel ID for the next created tunnel (global tunnel number).
701  */
702 static MESH_TunnelNumber next_tid;
703
704 /**
705  * Tunnel ID for the next incoming tunnel (local tunnel number).
706  */
707 static MESH_TunnelNumber next_local_tid;
708
709 /**
710  * All message types clients of this peer are interested in.
711  */
712 static struct GNUNET_CONTAINER_MultiHashMap *types;
713
714 /**
715  * Task to periodically announce itself in the network.
716  */
717 GNUNET_SCHEDULER_TaskIdentifier announce_id_task;
718
719 /**
720  * Next ID to assign to a client.
721  */
722 unsigned int next_client_id;
723
724
725 /******************************************************************************/
726 /***********************         DECLARATIONS        **************************/
727 /******************************************************************************/
728
729 /**
730  * Function to process paths received for a new peer addition. The recorded
731  * paths form the initial tunnel, which can be optimized later.
732  * Called on each result obtained for the DHT search.
733  *
734  * @param cls closure
735  * @param exp when will this value expire
736  * @param key key of the result
737  * @param type type of the result
738  * @param size number of bytes in data
739  * @param data pointer to the result data
740  */
741 static void
742 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
743                     const struct GNUNET_HashCode * key,
744                     const struct GNUNET_PeerIdentity *get_path,
745                     unsigned int get_path_length,
746                     const struct GNUNET_PeerIdentity *put_path,
747                     unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
748                     size_t size, const void *data);
749
750
751 /**
752  * Retrieve the MeshPeerInfo stucture associated with the peer, create one
753  * and insert it in the appropiate structures if the peer is not known yet.
754  *
755  * @param peer Full identity of the peer.
756  *
757  * @return Existing or newly created peer info.
758  */
759 static struct MeshPeerInfo *
760 peer_get (const struct GNUNET_PeerIdentity *peer);
761
762
763 /**
764  * Retrieve the MeshPeerInfo stucture associated with the peer, create one
765  * and insert it in the appropiate structures if the peer is not known yet.
766  *
767  * @param peer Short identity of the peer.
768  *
769  * @return Existing or newly created peer info.
770  */
771 static struct MeshPeerInfo *
772 peer_get_short (const GNUNET_PEER_Id peer);
773
774
775 /**
776  * Build a PeerPath from the paths returned from the DHT, reversing the paths
777  * to obtain a local peer -> destination path and interning the peer ids.
778  *
779  * @return Newly allocated and created path
780  */
781 static struct MeshPeerPath *
782 path_build_from_dht (const struct GNUNET_PeerIdentity *get_path,
783                      unsigned int get_path_length,
784                      const struct GNUNET_PeerIdentity *put_path,
785                      unsigned int put_path_length);
786
787
788 /**
789  * Adds a path to the peer_infos of all the peers in the path
790  *
791  * @param p Path to process.
792  * @param confirmed Whether we know if the path works or not.
793  */
794 static void
795 path_add_to_peers (struct MeshPeerPath *p, int confirmed);
796
797
798
799 /**
800  * Search for a tunnel by global ID using full PeerIdentities.
801  *
802  * @param oid owner of the tunnel.
803  * @param tid global tunnel number.
804  *
805  * @return tunnel handler, NULL if doesn't exist.
806  */
807 static struct MeshTunnel *
808 tunnel_get (const struct GNUNET_PeerIdentity *oid, MESH_TunnelNumber tid);
809
810
811 /**
812  * Delete an active client from the tunnel.
813  *
814  * @param t Tunnel.
815  * @param c Client.
816  */
817 static void
818 tunnel_delete_active_client (struct MeshTunnel *t, const struct MeshClient *c);
819
820 /**
821  * Notify a tunnel that a connection has broken that affects at least
822  * some of its peers.
823  *
824  * @param t Tunnel affected.
825  * @param p1 Peer that got disconnected from p2.
826  * @param p2 Peer that got disconnected from p1.
827  *
828  * @return Short ID of the peer disconnected (either p1 or p2).
829  *         0 if the tunnel remained unaffected.
830  */
831 static GNUNET_PEER_Id
832 tunnel_notify_connection_broken (struct MeshTunnel *t, GNUNET_PEER_Id p1,
833                                  GNUNET_PEER_Id p2);
834
835
836 /**
837  * Get the current ack value for a tunnel, for data going from root to leaves,
838  * taking in account the tunnel mode and the status of all children and clients.
839  *
840  * @param t Tunnel.
841  *
842  * @return Maximum PID allowed.
843  */
844 static uint32_t
845 tunnel_get_fwd_ack (struct MeshTunnel *t);
846
847
848 /**
849  * Add a client to a tunnel, initializing all needed data structures.
850  * 
851  * @param t Tunnel to which add the client.
852  * @param c Client which to add to the tunnel.
853  */
854 static void
855 tunnel_add_client (struct MeshTunnel *t, struct MeshClient *c);
856
857
858 /**
859  * Use the given path for the tunnel.
860  * 
861  * @param t Tunnel to update.
862  * @param p Path to use.
863  */
864 static void
865 tunnel_use_path (struct MeshTunnel *t, struct MeshPeerPath *p);
866
867 /**
868  * @brief Queue and pass message to core when possible.
869  * 
870  * If type is payload (UNICAST, TO_ORIGIN, MULTICAST) checks for queue status
871  * and accounts for it. In case the queue is full, the message is dropped and
872  * a break issued.
873  * 
874  * Otherwise, message is treated as internal and allowed to go regardless of 
875  * queue status.
876  *
877  * @param cls Closure (@c type dependant). It will be used by queue_send to
878  *            build the message to be sent if not already prebuilt.
879  * @param type Type of the message, 0 for a raw message.
880  * @param size Size of the message.
881  * @param dst Neighbor to send message to.
882  * @param t Tunnel this message belongs to.
883  */
884 static void
885 queue_add (void *cls, uint16_t type, size_t size,
886            struct MeshPeerInfo *dst, struct MeshTunnel *t);
887
888
889 /**
890  * Free a transmission that was already queued with all resources
891  * associated to the request.
892  *
893  * @param queue Queue handler to cancel.
894  * @param clear_cls Is it necessary to free associated cls?
895  */
896 static void
897 queue_destroy (struct MeshPeerQueue *queue, int clear_cls);
898
899
900 /**
901  * @brief Get the next transmittable message from the queue.
902  *
903  * This will be the head, except in the case of being a data packet
904  * not allowed by the destination peer.
905  *
906  * @param peer Destination peer.
907  *
908  * @return The next viable MeshPeerQueue element to send to that peer.
909  *         NULL when there are no transmittable messages.
910  */
911 struct MeshPeerQueue *
912 queue_get_next (const struct MeshPeerInfo *peer);
913
914
915 /**
916  * Core callback to write a queued packet to core buffer
917  *
918  * @param cls Closure (peer info).
919  * @param size Number of bytes available in buf.
920  * @param buf Where the to write the message.
921  *
922  * @return number of bytes written to buf
923  */
924 static size_t
925 queue_send (void *cls, size_t size, void *buf);
926
927
928 /******************************************************************************/
929 /************************    PERIODIC FUNCTIONS    ****************************/
930 /******************************************************************************/
931
932 /**
933  * Periodically announce self id in the DHT
934  *
935  * @param cls closure
936  * @param tc task context
937  */
938 static void
939 announce_id (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
940 {
941   struct PBlock block;
942
943   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
944   {
945     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
946     return;
947   }
948   /* TODO
949    * - Set data expiration in function of X
950    * - Adapt X to churn
951    */
952   DEBUG_DHT ("DHT_put for ID %s started.\n", GNUNET_i2s (&my_full_id));
953
954   block.id = my_full_id;
955   block.type = htonl (0);
956   GNUNET_DHT_put (dht_handle,   /* DHT handle */
957                   &my_full_id.hashPubKey,       /* Key to use */
958                   dht_replication_level,     /* Replication level */
959                   GNUNET_DHT_RO_RECORD_ROUTE | GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,    /* DHT options */
960                   GNUNET_BLOCK_TYPE_MESH_PEER,       /* Block type */
961                   sizeof (block),  /* Size of the data */
962                   (const char *) &block, /* Data itself */
963                   GNUNET_TIME_UNIT_FOREVER_ABS,  /* Data expiration */
964                   GNUNET_TIME_UNIT_FOREVER_REL, /* Retry time */
965                   NULL,         /* Continuation */
966                   NULL);        /* Continuation closure */
967   announce_id_task =
968       GNUNET_SCHEDULER_add_delayed (id_announce_time, &announce_id, cls);
969 }
970
971
972 /******************************************************************************/
973 /******************      GENERAL HELPER FUNCTIONS      ************************/
974 /******************************************************************************/
975
976
977 /**
978  * Check if client has registered with the service and has not disconnected
979  *
980  * @param client the client to check
981  *
982  * @return non-NULL if client exists in the global DLL
983  */
984 static struct MeshClient *
985 client_get (struct GNUNET_SERVER_Client *client)
986 {
987   struct MeshClient *c;
988
989   c = clients_head;
990   while (NULL != c)
991   {
992     if (c->handle == client)
993       return c;
994     c = c->next;
995   }
996   return NULL;
997 }
998
999
1000 /**
1001  * Checks if a given client has subscribed to certain message type
1002  *
1003  * @param message_type Type of message to check
1004  * @param c Client to check
1005  *
1006  * @return GNUNET_YES or GNUNET_NO, depending on subscription status
1007  * 
1008  * FIXME: use of crypto_hash slows it down
1009  *  The hash function alone takes 8-10us out of the ~55us for the whole
1010  * process of retransmitting the message from one local client to another.
1011  * Find faster implementation!
1012  */
1013 static int
1014 client_is_subscribed (uint16_t message_type, struct MeshClient *c)
1015 {
1016   struct GNUNET_HashCode hc;
1017
1018   if (NULL == c->types)
1019     return GNUNET_NO;
1020
1021   GNUNET_CRYPTO_hash (&message_type, sizeof (uint16_t), &hc);
1022   return GNUNET_CONTAINER_multihashmap_contains (c->types, &hc);
1023 }
1024
1025
1026 /**
1027  * Check whether client wants traffic from a tunnel.
1028  *
1029  * @param c Client to check.
1030  * @param t Tunnel to be found.
1031  *
1032  * @return GNUNET_YES if client knows tunnel.
1033  * 
1034  * TODO look in client hashmap
1035  */
1036 static int
1037 client_wants_tunnel (struct MeshClient *c, struct MeshTunnel *t)
1038 {
1039   unsigned int i;
1040
1041   for (i = 0; i < t->nclients; i++)
1042     if (t->clients[i] == c)
1043       return GNUNET_YES;
1044   return GNUNET_NO;
1045 }
1046
1047
1048 /**
1049  * Check whether client has been informed about a tunnel.
1050  *
1051  * @param c Client to check.
1052  * @param t Tunnel to be found.
1053  *
1054  * @return GNUNET_YES if client knows tunnel.
1055  * 
1056  * TODO look in client hashmap
1057  */
1058 static int
1059 client_knows_tunnel (struct MeshClient *c, struct MeshTunnel *t)
1060 {
1061   unsigned int i;
1062
1063   for (i = 0; i < t->nignore; i++)
1064     if (t->ignore[i] == c)
1065       return GNUNET_YES;
1066   return client_wants_tunnel(c, t);
1067 }
1068
1069
1070 /**
1071  * Marks a client as uninterested in traffic from the tunnel, updating both
1072  * client and tunnel to reflect this.
1073  *
1074  * @param c Client that doesn't want traffic anymore.
1075  * @param t Tunnel which should be ignored.
1076  *
1077  * FIXME when to delete an incoming tunnel?
1078  */
1079 static void
1080 client_ignore_tunnel (struct MeshClient *c, struct MeshTunnel *t)
1081 {
1082   struct GNUNET_HashCode hash;
1083
1084   GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
1085   GNUNET_break (GNUNET_YES ==
1086                 GNUNET_CONTAINER_multihashmap_remove (c->incoming_tunnels,
1087                                                       &hash, t));
1088   GNUNET_break (GNUNET_YES ==
1089                 GNUNET_CONTAINER_multihashmap_put (c->ignore_tunnels, &hash, t,
1090                                                    GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
1091   tunnel_delete_active_client (t, c);
1092   GNUNET_array_append (t->ignore, t->nignore, c);
1093 }
1094
1095
1096 /**
1097  * Deletes a tunnel from a client (either owner or destination). To be used on
1098  * tunnel destroy, otherwise, use client_ignore_tunnel.
1099  *
1100  * @param c Client whose tunnel to delete.
1101  * @param t Tunnel which should be deleted.
1102  */
1103 static void
1104 client_delete_tunnel (struct MeshClient *c, struct MeshTunnel *t)
1105 {
1106   struct GNUNET_HashCode hash;
1107
1108   if (c == t->owner)
1109   {
1110     GNUNET_CRYPTO_hash(&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
1111     GNUNET_assert (GNUNET_YES ==
1112                    GNUNET_CONTAINER_multihashmap_remove (c->own_tunnels,
1113                                                          &hash,
1114                                                          t));
1115   }
1116   else
1117   {
1118     GNUNET_CRYPTO_hash(&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
1119     // FIXME XOR?
1120     GNUNET_assert (GNUNET_YES ==
1121                    GNUNET_CONTAINER_multihashmap_remove (c->incoming_tunnels,
1122                                                          &hash,
1123                                                          t) ||
1124                    GNUNET_YES ==
1125                    GNUNET_CONTAINER_multihashmap_remove (c->ignore_tunnels,
1126                                                          &hash,
1127                                                          t));
1128   }
1129 }
1130
1131
1132 /**
1133  * Send the message to all clients that have subscribed to its type
1134  *
1135  * @param msg Pointer to the message itself
1136  * @param payload Pointer to the payload of the message.
1137  * @param t The tunnel to whose clients this message goes.
1138  * 
1139  * @return number of clients this message was sent to
1140  */
1141 static unsigned int
1142 send_subscribed_clients (const struct GNUNET_MessageHeader *msg,
1143                          const struct GNUNET_MessageHeader *payload,
1144                          struct MeshTunnel *t)
1145 {
1146   struct MeshClient *c;
1147   MESH_TunnelNumber *tid;
1148   unsigned int count;
1149   uint16_t type;
1150   char cbuf[htons (msg->size)];
1151
1152   type = ntohs (payload->type);
1153   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending to clients...\n");
1154   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "message of type %s\n",
1155               GNUNET_MESH_DEBUG_M2S (type));
1156
1157   memcpy (cbuf, msg, sizeof (cbuf));
1158   switch (htons (msg->type))
1159   {
1160     struct GNUNET_MESH_Unicast *uc;
1161     struct GNUNET_MESH_ToOrigin *to;
1162
1163     case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
1164       uc = (struct GNUNET_MESH_Unicast *) cbuf;
1165       tid = &uc->tid;
1166       break;
1167     case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
1168       to = (struct GNUNET_MESH_ToOrigin *) cbuf;
1169       tid = &to->tid;
1170       break;
1171     default:
1172       GNUNET_break (0);
1173       return 0;
1174   }
1175
1176   for (count = 0, c = clients_head; c != NULL; c = c->next)
1177   {
1178     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   client %u\n", c->id);
1179     if (client_is_subscribed (type, c))
1180     {
1181       if (htons (msg->type) == GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN)
1182       {
1183         if (c != t->owner)
1184           continue;
1185         *tid = htonl (t->local_tid);
1186       }
1187       else
1188       {
1189         if (GNUNET_NO == client_knows_tunnel (c, t))
1190         {
1191           /* This client doesn't know the tunnel */
1192           struct GNUNET_MESH_TunnelNotification tmsg;
1193           struct GNUNET_HashCode hash;
1194
1195           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "     sending tunnel create\n");
1196           tmsg.header.size = htons (sizeof (tmsg));
1197           tmsg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE);
1198           GNUNET_PEER_resolve (t->id.oid, &tmsg.peer);
1199           tmsg.tunnel_id = htonl (t->local_tid_dest);
1200           tmsg.opt = 0;
1201           if (GNUNET_YES == t->nobuffer)
1202             tmsg.opt |= MESH_TUNNEL_OPT_NOBUFFER;
1203           GNUNET_SERVER_notification_context_unicast (nc, c->handle,
1204                                                       &tmsg.header, GNUNET_NO);
1205           tunnel_add_client (t, c);
1206           GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber),
1207                               &hash);
1208           GNUNET_break (GNUNET_OK == GNUNET_CONTAINER_multihashmap_put (
1209                                        c->incoming_tunnels, &hash, t,
1210                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
1211         }
1212         *tid = htonl (t->local_tid_dest);
1213       }
1214
1215       /* Check if the client wants to get traffic from the tunnel */
1216       if (GNUNET_NO == client_wants_tunnel(c, t))
1217         continue;
1218       count++;
1219       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "     sending\n");
1220       GNUNET_SERVER_notification_context_unicast (nc, c->handle,
1221                                                   (struct GNUNET_MessageHeader
1222                                                    *) cbuf, GNUNET_NO);
1223     }
1224   }
1225
1226   return count;
1227 }
1228
1229
1230 /**
1231  * Notify all clients (not depending on registration status) that the incoming
1232  * tunnel is no longer valid.
1233  *
1234  * @param t Tunnel that was destroyed.
1235  */
1236 static void
1237 send_clients_tunnel_destroy (struct MeshTunnel *t)
1238 {
1239   struct GNUNET_MESH_TunnelMessage msg;
1240
1241   msg.header.size = htons (sizeof (msg));
1242   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY);
1243   msg.tunnel_id = htonl (t->local_tid_dest);
1244   GNUNET_SERVER_notification_context_broadcast (nc, &msg.header, GNUNET_NO);
1245 }
1246
1247
1248 /**
1249  * Notify clients of tunnel disconnections, if needed.
1250  * In case the origin disconnects, the destination clients get a tunnel destroy
1251  * notification. If the last destination disconnects (only one remaining client
1252  * in tunnel), the origin gets a (local ID) peer disconnected.
1253  * Note that the function must be called BEFORE removing the client from
1254  * the tunnel.
1255  *
1256  * @param t Tunnel that was destroyed.
1257  * @param c Client that disconnected.
1258  */
1259 static void
1260 send_client_tunnel_disconnect (struct MeshTunnel *t, struct MeshClient *c)
1261 {
1262   unsigned int i;
1263
1264   if (c == t->owner)
1265   {
1266     struct GNUNET_MESH_TunnelMessage msg;
1267
1268     msg.header.size = htons (sizeof (msg));
1269     msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY);
1270     msg.tunnel_id = htonl (t->local_tid_dest);
1271     for (i = 0; i < t->nclients; i++)
1272       GNUNET_SERVER_notification_context_unicast (nc, t->clients[i]->handle,
1273                                                   &msg.header, GNUNET_NO);
1274   }
1275   // FIXME when to disconnect an incoming tunnel?
1276 }
1277
1278
1279 /**
1280  * Iterator over all the peers to remove the oldest not-used entry.
1281  *
1282  * @param cls Closure (unsued).
1283  * @param key ID of the peer.
1284  * @param value Peer_Info of the peer.
1285  *
1286  * FIXME implement
1287  */
1288 static int
1289 peer_info_timeout (void *cls,
1290                    const struct GNUNET_HashCode *key,
1291                    void *value)
1292 {
1293   return GNUNET_YES;
1294 }
1295
1296 /**
1297  * Retrieve the MeshPeerInfo stucture associated with the peer, create one
1298  * and insert it in the appropiate structures if the peer is not known yet.
1299  *
1300  * @param peer Full identity of the peer.
1301  *
1302  * @return Existing or newly created peer info.
1303  */
1304 static struct MeshPeerInfo *
1305 peer_get (const struct GNUNET_PeerIdentity *peer)
1306 {
1307   struct MeshPeerInfo *peer_info;
1308
1309   peer_info = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
1310   if (NULL == peer_info)
1311   {
1312     peer_info =
1313         (struct MeshPeerInfo *) GNUNET_malloc (sizeof (struct MeshPeerInfo));
1314     if (GNUNET_CONTAINER_multihashmap_size (peers) > max_peers)
1315     {
1316       GNUNET_CONTAINER_multihashmap_iterate (peers,
1317                                              &peer_info_timeout,
1318                                              NULL);
1319     }
1320     GNUNET_CONTAINER_multihashmap_put (peers, &peer->hashPubKey, peer_info,
1321                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
1322     peer_info->id = GNUNET_PEER_intern (peer);
1323   }
1324   peer_info->last_contact = GNUNET_TIME_absolute_get();
1325
1326   return peer_info;
1327 }
1328
1329
1330 /**
1331  * Retrieve the MeshPeerInfo stucture associated with the peer, create one
1332  * and insert it in the appropiate structures if the peer is not known yet.
1333  *
1334  * @param peer Short identity of the peer.
1335  *
1336  * @return Existing or newly created peer info.
1337  */
1338 static struct MeshPeerInfo *
1339 peer_get_short (const GNUNET_PEER_Id peer)
1340 {
1341   struct GNUNET_PeerIdentity id;
1342
1343   GNUNET_PEER_resolve (peer, &id);
1344   return peer_get (&id);
1345 }
1346
1347
1348 /**
1349  * Choose the best path towards a peer considering the tunnel properties.
1350  * 
1351  * @param peer The destination peer.
1352  * @param t The tunnel the path is for.
1353  *
1354  * @return Best current known path towards the peer, if any.
1355  */
1356 static struct MeshPeerPath *
1357 peer_get_best_path (const struct MeshPeerInfo *peer, const struct MeshTunnel *t)
1358 {
1359   struct MeshPeerPath *best_p;
1360   struct MeshPeerPath *p;
1361   unsigned int best_cost;
1362   unsigned int cost;
1363
1364   best_p = p = peer->path_head;
1365   best_cost = cost = p->length;
1366   while (NULL != p)
1367   {
1368     if ((cost = p->length) < best_cost)
1369     {
1370       best_cost = cost;
1371       best_p = p;
1372     }
1373         p = p->next;
1374   }
1375   return best_p;
1376 }
1377
1378
1379 /**
1380  * Remove the tunnel from the list of tunnels to which a peer is target.
1381  *
1382  * @param peer PeerInfo of the peer.
1383  * @param t Tunnel to remove.
1384  */
1385 static void
1386 peer_remove_tunnel (struct MeshPeerInfo *peer, struct MeshTunnel *t)
1387 {
1388   unsigned int i;
1389
1390   for (i = 0; i < peer->ntunnels; i++)
1391   {
1392     if (0 ==
1393         memcmp (&peer->tunnels[i]->id, &t->id, sizeof (struct MESH_TunnelID)))
1394     {
1395       peer->ntunnels--;
1396       peer->tunnels[i] = peer->tunnels[peer->ntunnels];
1397       peer->tunnels = 
1398         GNUNET_realloc (peer->tunnels, 
1399                         peer->ntunnels * sizeof(struct MeshTunnel *));
1400       return;
1401     }
1402   }
1403 }
1404
1405
1406 /**
1407   * Core callback to write a pre-constructed data packet to core buffer
1408   *
1409   * @param cls Closure (MeshTransmissionDescriptor with data in "data" member).
1410   * @param size Number of bytes available in buf.
1411   * @param buf Where the to write the message.
1412   *
1413   * @return number of bytes written to buf
1414   */
1415 static size_t
1416 send_core_data_raw (void *cls, size_t size, void *buf)
1417 {
1418   struct MeshTransmissionDescriptor *info = cls;
1419   struct GNUNET_MessageHeader *msg;
1420   size_t total_size;
1421
1422   GNUNET_assert (NULL != info);
1423   msg = (struct GNUNET_MessageHeader *) info->data;
1424   total_size = ntohs (msg->size);
1425
1426   if (total_size > size)
1427   {
1428     GNUNET_break (0);
1429     return 0;
1430   }
1431   memcpy (buf, msg, total_size);
1432   GNUNET_free (info->data);
1433   GNUNET_free (info);
1434   return total_size;
1435 }
1436
1437
1438 /**
1439  * Sends an already built message to a peer, properly registrating
1440  * all used resources.
1441  *
1442  * @param message Message to send. Function makes a copy of it.
1443  * @param peer Short ID of the neighbor whom to send the message.
1444  * @param t Tunnel on which this message is transmitted.
1445  */
1446 static void
1447 send_prebuilt_message (const struct GNUNET_MessageHeader *message,
1448                        GNUNET_PEER_Id peer,
1449                        struct MeshTunnel *t)
1450 {
1451   struct MeshTransmissionDescriptor *info;
1452   struct GNUNET_PeerIdentity id;
1453   struct MeshPeerInfo *neighbor;
1454   struct MeshPeerPath *p;
1455   size_t size;
1456   uint16_t type;
1457
1458 //   GNUNET_TRANSPORT_try_connect(); FIXME use?
1459
1460   if (0 == peer)
1461     return;
1462
1463   size = ntohs (message->size);
1464   info = GNUNET_malloc (sizeof (struct MeshTransmissionDescriptor));
1465   info->data = GNUNET_malloc (size);
1466   memcpy (info->data, message, size);
1467   type = ntohs(message->type);
1468   switch (type)
1469   {
1470     struct GNUNET_MESH_Unicast *m;
1471     struct GNUNET_MESH_ToOrigin *to;
1472
1473     case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
1474       m = (struct GNUNET_MESH_Unicast *) info->data;
1475       m->ttl = htonl (ntohl (m->ttl) - 1);
1476       break;
1477     case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
1478       to = (struct GNUNET_MESH_ToOrigin *) info->data;
1479       t->prev_fc.last_pid_sent++; /* FIXME per hop? */
1480       to->pid = htonl (t->prev_fc.last_pid_sent);
1481   }
1482   info->data_len = size;
1483   GNUNET_PEER_resolve (peer, &id);
1484   neighbor = peer_get (&id);
1485   for (p = neighbor->path_head; NULL != p; p = p->next)
1486   {
1487     if (2 >= p->length)
1488     {
1489       break;
1490     }
1491   }
1492   if (NULL == p)
1493   {
1494 #if MESH_DEBUG
1495     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1496                 "  %s IS NOT DIRECTLY CONNECTED\n",
1497                 GNUNET_i2s(&id));
1498     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1499                 "  PATHS TO %s:\n",
1500                 GNUNET_i2s(&id));
1501     for (p = neighbor->path_head; NULL != p; p = p->next)
1502     {
1503       struct GNUNET_PeerIdentity debug_id;
1504       unsigned int i;
1505
1506       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1507                   "    path with %u hops through:\n",
1508                   p->length);
1509       for (i = 0; i < p->length; i++)
1510       {
1511         GNUNET_PEER_resolve(p->peers[i], &debug_id);
1512         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1513                     "      hop %u: %s\n",
1514                     i, GNUNET_i2s(&debug_id));
1515       }
1516     }
1517 #endif
1518     GNUNET_break (0); // FIXME sometimes fails (testing disconnect?)
1519     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1520                     " no direct connection to %s\n",
1521                     GNUNET_i2s (&id));
1522     GNUNET_free (info->data);
1523     GNUNET_free (info);
1524     return;
1525   }
1526   info->peer = neighbor;
1527   if (GNUNET_MESSAGE_TYPE_MESH_PATH_ACK == type)
1528     type = 0;
1529   queue_add (info,
1530              type,
1531              size,
1532              neighbor,
1533              t);
1534 }
1535
1536
1537 /**
1538  * Sends a CREATE PATH message for a path to a peer, properly registrating
1539  * all used resources.
1540  *
1541  * @param peer PeerInfo of the final peer for whom this path is being created.
1542  * @param p Path itself.
1543  * @param t Tunnel for which the path is created.
1544  */
1545 static void
1546 send_create_path (struct MeshPeerInfo *peer, struct MeshPeerPath *p,
1547                   struct MeshTunnel *t)
1548 {
1549   struct MeshPeerInfo *neighbor;
1550
1551   if (NULL == p)
1552   {
1553     GNUNET_break (0);
1554     return;
1555   }
1556
1557   neighbor = peer_get_short (t->next_hop);
1558   queue_add (t,
1559              GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE,
1560              sizeof (struct GNUNET_MESH_ManipulatePath) +
1561                 (p->length * sizeof (struct GNUNET_PeerIdentity)),
1562              neighbor,
1563              t);
1564 }
1565
1566
1567 /**
1568  * Sends a PATH ACK message in reponse to a received PATH_CREATE directed to us.
1569  *
1570  * @param t Tunnel which to confirm.
1571  */
1572 static void
1573 send_path_ack (struct MeshTunnel *t) 
1574 {
1575   struct MeshTransmissionDescriptor *info;
1576   struct GNUNET_PeerIdentity id;
1577
1578   GNUNET_PEER_resolve (t->prev_hop, &id);
1579   info = GNUNET_malloc (sizeof (struct MeshTransmissionDescriptor));
1580   info->origin = &t->id;
1581   info->peer = GNUNET_CONTAINER_multihashmap_get (peers, &id.hashPubKey);
1582   GNUNET_assert (NULL != info->peer);
1583
1584   queue_add (info,
1585              GNUNET_MESSAGE_TYPE_MESH_PATH_ACK,
1586              sizeof (struct GNUNET_MESH_PathACK),
1587              info->peer,
1588              t);
1589 }
1590
1591
1592 /**
1593  * Try to establish a new connection to this peer in the fiven tunnel.
1594  * If the peer doesn't have any path to it yet, try to get one.
1595  * If the peer already has some path, send a CREATE PATH towards it.
1596  *
1597  * @param peer PeerInfo of the peer.
1598  * @param t Tunnel for which to create the path, if possible.
1599  */
1600 static void
1601 peer_connect (struct MeshPeerInfo *peer, struct MeshTunnel *t)
1602 {
1603   struct MeshPeerPath *p;
1604
1605   if (NULL != peer->path_head)
1606   {
1607     p = peer_get_best_path (peer, t);
1608     tunnel_use_path (t, p);
1609     send_create_path (peer, p, t);
1610   }
1611   else if (NULL == peer->dhtget)
1612   {
1613     struct GNUNET_PeerIdentity id;
1614
1615     GNUNET_PEER_resolve (peer->id, &id);
1616     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1617                 "  Starting DHT GET for peer %s\n", GNUNET_i2s (&id));
1618     peer->dhtget = GNUNET_DHT_get_start (dht_handle,    /* handle */
1619                                          GNUNET_BLOCK_TYPE_MESH_PEER, /* type */
1620                                          &id.hashPubKey,     /* key to search */
1621                                          dht_replication_level, /* replication level */
1622                                          GNUNET_DHT_RO_RECORD_ROUTE |
1623                                          GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
1624                                          NULL,       /* xquery */
1625                                          0,     /* xquery bits */
1626                                          &dht_get_id_handler, peer);
1627   }
1628   /* Otherwise, there is no path but the DHT get is already started. */
1629 }
1630
1631
1632 /**
1633  * Destroy the peer_info and free any allocated resources linked to it
1634  *
1635  * @param pi The peer_info to destroy.
1636  *
1637  * @return GNUNET_OK on success
1638  */
1639 static int
1640 peer_info_destroy (struct MeshPeerInfo *pi)
1641 {
1642   struct GNUNET_PeerIdentity id;
1643   struct MeshPeerPath *p;
1644   struct MeshPeerPath *nextp;
1645
1646   GNUNET_PEER_resolve (pi->id, &id);
1647   GNUNET_PEER_change_rc (pi->id, -1);
1648
1649   if (GNUNET_YES !=
1650       GNUNET_CONTAINER_multihashmap_remove (peers, &id.hashPubKey, pi))
1651   {
1652     GNUNET_break (0);
1653     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1654                 "removing peer %s, not in hashmap\n", GNUNET_i2s (&id));
1655   }
1656   if (NULL != pi->dhtget)
1657   {
1658     GNUNET_DHT_get_stop (pi->dhtget);
1659   }
1660   p = pi->path_head;
1661   while (NULL != p)
1662   {
1663     nextp = p->next;
1664     GNUNET_CONTAINER_DLL_remove (pi->path_head, pi->path_tail, p);
1665     path_destroy (p);
1666     p = nextp;
1667   }
1668   GNUNET_free (pi);
1669   return GNUNET_OK;
1670 }
1671
1672
1673 /**
1674  * Remove all paths that rely on a direct connection between p1 and p2
1675  * from the peer itself and notify all tunnels about it.
1676  *
1677  * @param peer PeerInfo of affected peer.
1678  * @param p1 GNUNET_PEER_Id of one peer.
1679  * @param p2 GNUNET_PEER_Id of another peer that was connected to the first and
1680  *           no longer is.
1681  *
1682  * TODO: optimize (see below)
1683  */
1684 static void
1685 peer_remove_path (struct MeshPeerInfo *peer, GNUNET_PEER_Id p1,
1686                        GNUNET_PEER_Id p2)
1687 {
1688   struct MeshPeerPath *p;
1689   struct MeshPeerPath *next;
1690   struct MeshPeerInfo *peer_d;
1691   GNUNET_PEER_Id d;
1692   unsigned int destroyed;
1693   unsigned int i;
1694
1695   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "peer_info_remove_path\n");
1696   destroyed = 0;
1697   for (p = peer->path_head; NULL != p; p = next)
1698   {
1699     next = p->next;
1700     for (i = 0; i < (p->length - 1); i++)
1701     {
1702       if ((p->peers[i] == p1 && p->peers[i + 1] == p2) ||
1703           (p->peers[i] == p2 && p->peers[i + 1] == p1))
1704       {
1705         GNUNET_CONTAINER_DLL_remove (peer->path_head, peer->path_tail, p);
1706         path_destroy (p);
1707         destroyed++;
1708         break;
1709       }
1710     }
1711   }
1712   if (0 == destroyed)
1713     return;
1714
1715   for (i = 0; i < peer->ntunnels; i++)
1716   {
1717     d = tunnel_notify_connection_broken (peer->tunnels[i], p1, p2);
1718     if (0 == d)
1719       continue;
1720
1721     peer_d = peer_get_short (d);
1722     next = peer_get_best_path (peer_d, peer->tunnels[i]);
1723     tunnel_use_path (peer->tunnels[i], next);
1724     peer_connect (peer_d, peer->tunnels[i]);
1725   }
1726   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "peer_info_remove_path END\n");
1727 }
1728
1729
1730 /**
1731  * Add the path to the peer and update the path used to reach it in case this
1732  * is the shortest.
1733  *
1734  * @param peer_info Destination peer to add the path to.
1735  * @param path New path to add. Last peer must be the peer in arg 1.
1736  *             Path will be either used of freed if already known.
1737  * @param trusted Do we trust that this path is real?
1738  */
1739 void
1740 peer_info_add_path (struct MeshPeerInfo *peer_info, struct MeshPeerPath *path,
1741                     int trusted)
1742 {
1743   struct MeshPeerPath *aux;
1744   unsigned int l;
1745   unsigned int l2;
1746
1747   if ((NULL == peer_info) || (NULL == path))
1748   {
1749     GNUNET_break (0);
1750     path_destroy (path);
1751     return;
1752   }
1753   if (path->peers[path->length - 1] != peer_info->id)
1754   {
1755     GNUNET_break (0);
1756     path_destroy (path);
1757     return;
1758   }
1759   if (path->length <= 2 && GNUNET_NO == trusted)
1760   {
1761     /* Only allow CORE to tell us about direct paths */
1762     path_destroy (path);
1763     return;
1764   }
1765   GNUNET_assert (peer_info->id == path->peers[path->length - 1]);
1766   for (l = 1; l < path->length; l++)
1767   {
1768     if (path->peers[l] == myid)
1769     {
1770       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shortening path by %u\n", l);
1771       for (l2 = 0; l2 < path->length - l; l2++)
1772       {
1773         path->peers[l2] = path->peers[l + l2];
1774       }
1775       path->length -= l;
1776       l = 1;
1777       path->peers =
1778           GNUNET_realloc (path->peers, path->length * sizeof (GNUNET_PEER_Id));
1779     }
1780   }
1781 #if MESH_DEBUG
1782   {
1783     struct GNUNET_PeerIdentity id;
1784
1785     GNUNET_PEER_resolve (peer_info->id, &id);
1786     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "adding path [%u] to peer %s\n",
1787                 path->length, GNUNET_i2s (&id));
1788   }
1789 #endif
1790   l = path_get_length (path);
1791   if (0 == l)
1792   {
1793     GNUNET_free (path);
1794     return;
1795   }
1796
1797   GNUNET_assert (peer_info->id == path->peers[path->length - 1]);
1798   for (aux = peer_info->path_head; aux != NULL; aux = aux->next)
1799   {
1800     l2 = path_get_length (aux);
1801     if (l2 > l)
1802     {
1803       GNUNET_CONTAINER_DLL_insert_before (peer_info->path_head,
1804                                           peer_info->path_tail, aux, path);
1805       return;
1806     }
1807     else
1808     {
1809       if (l2 == l && memcmp (path->peers, aux->peers, l) == 0)
1810       {
1811         path_destroy (path);
1812         return;
1813       }
1814     }
1815   }
1816   GNUNET_CONTAINER_DLL_insert_tail (peer_info->path_head, peer_info->path_tail,
1817                                     path);
1818   return;
1819 }
1820
1821
1822 /**
1823  * Add the path to the origin peer and update the path used to reach it in case
1824  * this is the shortest.
1825  * The path is given in peer_info -> destination, therefore we turn the path
1826  * upside down first.
1827  *
1828  * @param peer_info Peer to add the path to, being the origin of the path.
1829  * @param path New path to add after being inversed.
1830  * @param trusted Do we trust that this path is real?
1831  */
1832 static void
1833 peer_info_add_path_to_origin (struct MeshPeerInfo *peer_info,
1834                               struct MeshPeerPath *path, int trusted)
1835 {
1836   path_invert (path);
1837   peer_info_add_path (peer_info, path, trusted);
1838 }
1839
1840
1841 /**
1842  * Function called if the connection to the peer has been stalled for a while,
1843  * possibly due to a missed ACK. Poll the peer about its ACK status.
1844  *
1845  * @param cls Closure (poll ctx).
1846  * @param tc TaskContext.
1847  */
1848 static void
1849 tunnel_poll (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1850 {
1851   struct MeshFlowControl *fc = cls;
1852   struct GNUNET_MESH_Poll msg;
1853   struct MeshTunnel *t = fc->t;
1854   GNUNET_PEER_Id peer;
1855
1856   fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
1857   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1858   {
1859     return;
1860   }
1861
1862   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_POLL);
1863   msg.header.size = htons (sizeof (msg));
1864   msg.tid = htonl (t->id.tid);
1865   GNUNET_PEER_resolve (t->id.oid, &msg.oid);
1866   msg.last_ack = htonl (fc->last_ack_recv);
1867
1868   if (fc == &t->prev_fc)
1869   {
1870     peer = t->prev_hop;
1871   }
1872   else
1873   {
1874     peer = t->next_hop;
1875   }
1876   send_prebuilt_message (&msg.header, peer, t);
1877   fc->poll_time = GNUNET_TIME_STD_BACKOFF (fc->poll_time);
1878   fc->poll_task = GNUNET_SCHEDULER_add_delayed (fc->poll_time,
1879                                                 &tunnel_poll, fc);
1880 }
1881
1882
1883 /**
1884  * Build a PeerPath from the paths returned from the DHT, reversing the paths
1885  * to obtain a local peer -> destination path and interning the peer ids.
1886  *
1887  * @return Newly allocated and created path
1888  */
1889 static struct MeshPeerPath *
1890 path_build_from_dht (const struct GNUNET_PeerIdentity *get_path,
1891                      unsigned int get_path_length,
1892                      const struct GNUNET_PeerIdentity *put_path,
1893                      unsigned int put_path_length)
1894 {
1895   struct MeshPeerPath *p;
1896   GNUNET_PEER_Id id;
1897   int i;
1898
1899   p = path_new (1);
1900   p->peers[0] = myid;
1901   GNUNET_PEER_change_rc (myid, 1);
1902   i = get_path_length;
1903   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   GET has %d hops.\n", i);
1904   for (i--; i >= 0; i--)
1905   {
1906     id = GNUNET_PEER_intern (&get_path[i]);
1907     if (p->length > 0 && id == p->peers[p->length - 1])
1908     {
1909       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   Optimizing 1 hop out.\n");
1910       GNUNET_PEER_change_rc (id, -1);
1911     }
1912     else
1913     {
1914       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   Adding from GET: %s.\n",
1915                   GNUNET_i2s (&get_path[i]));
1916       p->length++;
1917       p->peers = GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * p->length);
1918       p->peers[p->length - 1] = id;
1919     }
1920   }
1921   i = put_path_length;
1922   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   PUT has %d hops.\n", i);
1923   for (i--; i >= 0; i--)
1924   {
1925     id = GNUNET_PEER_intern (&put_path[i]);
1926     if (id == myid)
1927     {
1928       /* PUT path went through us, so discard the path up until now and start
1929        * from here to get a much shorter (and loop-free) path.
1930        */
1931       path_destroy (p);
1932       p = path_new (0);
1933     }
1934     if (p->length > 0 && id == p->peers[p->length - 1])
1935     {
1936       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   Optimizing 1 hop out.\n");
1937       GNUNET_PEER_change_rc (id, -1);
1938     }
1939     else
1940     {
1941       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   Adding from PUT: %s.\n",
1942                   GNUNET_i2s (&put_path[i]));
1943       p->length++;
1944       p->peers = GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * p->length);
1945       p->peers[p->length - 1] = id;
1946     }
1947   }
1948 #if MESH_DEBUG
1949   if (get_path_length > 0)
1950     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   (first of GET: %s)\n",
1951                 GNUNET_i2s (&get_path[0]));
1952   if (put_path_length > 0)
1953     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   (first of PUT: %s)\n",
1954                 GNUNET_i2s (&put_path[0]));
1955   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   In total: %d hops\n",
1956               p->length);
1957   for (i = 0; i < p->length; i++)
1958   {
1959     struct GNUNET_PeerIdentity peer_id;
1960
1961     GNUNET_PEER_resolve (p->peers[i], &peer_id);
1962     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "       %u: %s\n", p->peers[i],
1963                 GNUNET_i2s (&peer_id));
1964   }
1965 #endif
1966   return p;
1967 }
1968
1969
1970 /**
1971  * Adds a path to the peer_infos of all the peers in the path
1972  *
1973  * @param p Path to process.
1974  * @param confirmed Whether we know if the path works or not.
1975  */
1976 static void
1977 path_add_to_peers (struct MeshPeerPath *p, int confirmed)
1978 {
1979   unsigned int i;
1980
1981   /* TODO: invert and add */
1982   for (i = 0; i < p->length && p->peers[i] != myid; i++) /* skip'em */ ;
1983   for (i++; i < p->length; i++)
1984   {
1985     struct MeshPeerInfo *aux;
1986     struct MeshPeerPath *copy;
1987
1988     aux = peer_get_short (p->peers[i]);
1989     copy = path_duplicate (p);
1990     copy->length = i + 1;
1991     peer_info_add_path (aux, copy, GNUNET_NO);
1992   }
1993 }
1994
1995
1996 /**
1997  * Send keepalive packets for a peer
1998  *
1999  * @param cls Closure (tunnel for which to send the keepalive).
2000  * @param tc Notification context.
2001  */
2002 static void
2003 path_refresh (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
2004
2005
2006 /**
2007  * Search for a tunnel among the incoming tunnels
2008  *
2009  * @param tid the local id of the tunnel
2010  *
2011  * @return tunnel handler, NULL if doesn't exist
2012  */
2013 static struct MeshTunnel *
2014 tunnel_get_incoming (MESH_TunnelNumber tid)
2015 {
2016   struct GNUNET_HashCode hash;
2017
2018   GNUNET_assert (tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV);
2019   GNUNET_CRYPTO_hash (&tid, sizeof (MESH_TunnelNumber), &hash);
2020   return GNUNET_CONTAINER_multihashmap_get (incoming_tunnels, &hash);
2021 }
2022
2023
2024 /**
2025  * Search for a tunnel among the tunnels for a client
2026  *
2027  * @param c the client whose tunnels to search in
2028  * @param tid the local id of the tunnel
2029  *
2030  * @return tunnel handler, NULL if doesn't exist
2031  */
2032 static struct MeshTunnel *
2033 tunnel_get_by_local_id (struct MeshClient *c, MESH_TunnelNumber tid)
2034 {
2035   if (tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
2036   {
2037     return tunnel_get_incoming (tid);
2038   }
2039   else
2040   {
2041     struct GNUNET_HashCode hash;
2042
2043     GNUNET_CRYPTO_hash (&tid, sizeof (MESH_TunnelNumber), &hash);
2044     return GNUNET_CONTAINER_multihashmap_get (c->own_tunnels, &hash);
2045   }
2046 }
2047
2048
2049 /**
2050  * Search for a tunnel by global ID using PEER_ID
2051  *
2052  * @param pi owner of the tunnel
2053  * @param tid global tunnel number
2054  *
2055  * @return tunnel handler, NULL if doesn't exist
2056  */
2057 static struct MeshTunnel *
2058 tunnel_get_by_pi (GNUNET_PEER_Id pi, MESH_TunnelNumber tid)
2059 {
2060   struct MESH_TunnelID id;
2061   struct GNUNET_HashCode hash;
2062
2063   id.oid = pi;
2064   id.tid = tid;
2065
2066   GNUNET_CRYPTO_hash (&id, sizeof (struct MESH_TunnelID), &hash);
2067   return GNUNET_CONTAINER_multihashmap_get (tunnels, &hash);
2068 }
2069
2070
2071 /**
2072  * Search for a tunnel by global ID using full PeerIdentities
2073  *
2074  * @param oid owner of the tunnel
2075  * @param tid global tunnel number
2076  *
2077  * @return tunnel handler, NULL if doesn't exist
2078  */
2079 static struct MeshTunnel *
2080 tunnel_get (const struct GNUNET_PeerIdentity *oid, MESH_TunnelNumber tid)
2081 {
2082   return tunnel_get_by_pi (GNUNET_PEER_search (oid), tid);
2083 }
2084
2085
2086 /**
2087  * Delete an active client from the tunnel.
2088  * 
2089  * @param t Tunnel.
2090  * @param c Client.
2091  */
2092 static void
2093 tunnel_delete_active_client (struct MeshTunnel *t, const struct MeshClient *c)
2094 {
2095   unsigned int i;
2096
2097   for (i = 0; i < t->nclients; i++)
2098   {
2099     if (t->clients[i] == c)
2100     {
2101       t->clients[i] = t->clients[t->nclients - 1];
2102       t->clients_fc[i] = t->clients_fc[t->nclients - 1];
2103       GNUNET_array_grow (t->clients, t->nclients, t->nclients - 1);
2104       t->nclients++;
2105       GNUNET_array_grow (t->clients_fc, t->nclients, t->nclients - 1);
2106       break;
2107     }
2108   }
2109 }
2110
2111
2112 /**
2113  * Delete an ignored client from the tunnel.
2114  * 
2115  * @param t Tunnel.
2116  * @param c Client.
2117  */
2118 static void
2119 tunnel_delete_ignored_client (struct MeshTunnel *t, const struct MeshClient *c)
2120 {
2121   unsigned int i;
2122
2123   for (i = 0; i < t->nignore; i++)
2124   {
2125     if (t->ignore[i] == c)
2126     {
2127       t->ignore[i] = t->ignore[t->nignore - 1];
2128       GNUNET_array_grow (t->ignore, t->nignore, t->nignore - 1);
2129       break;
2130     }
2131   }
2132 }
2133
2134
2135 /**
2136  * Delete a client from the tunnel. It should be only done on
2137  * client disconnection, otherwise use client_ignore_tunnel.
2138  * 
2139  * @param t Tunnel.
2140  * @param c Client.
2141  */
2142 static void
2143 tunnel_delete_client (struct MeshTunnel *t, const struct MeshClient *c)
2144 {
2145   tunnel_delete_ignored_client (t, c);
2146   tunnel_delete_active_client (t, c);
2147 }
2148
2149 /* FIXME check initial values */
2150 static void
2151 tunnel_add_client (struct MeshTunnel *t, struct MeshClient *c)
2152 {
2153   struct MeshTunnelClientInfo clinfo;
2154
2155   GNUNET_array_append (t->clients, t->nclients, c);
2156   clinfo.fwd_ack = t->prev_fc.last_pid_recv + 1;
2157   clinfo.fwd_pid = t->prev_fc.last_pid_recv;
2158   clinfo.bck_ack = t->nobuffer ? 1 : INITIAL_WINDOW_SIZE - 1;
2159   clinfo.bck_pid = (uint32_t) -1; /* Expected next: 0 */
2160   t->nclients--; /* Double append */
2161   GNUNET_array_append (t->clients_fc, t->nclients, clinfo);
2162 }
2163
2164
2165 static void
2166 tunnel_use_path (struct MeshTunnel *t, struct MeshPeerPath *p)
2167 {
2168   unsigned int i;
2169
2170   for (i = 0; i < p->length; i++)
2171   {
2172     if (p->peers[i] == myid)
2173       break;
2174   }
2175   if (i > p->length - 1)
2176   {
2177     GNUNET_break (0);
2178     return;
2179   }
2180
2181   if (i < p->length - 1)
2182     t->next_hop = p->peers[i + 1];
2183   else
2184     t->next_hop = 0;
2185   if (0 < i)
2186     t->prev_hop = p->peers[i - 1];
2187   else
2188     t->prev_hop = 0;
2189
2190   if (NULL != t->path)
2191     path_destroy (t->path);
2192   t->path = path_duplicate (p);
2193   if (GNUNET_SCHEDULER_NO_TASK == t->maintenance_task)
2194     t->maintenance_task =
2195         GNUNET_SCHEDULER_add_delayed (refresh_path_time, &path_refresh, t);
2196 }
2197
2198
2199 /**
2200  * Notifies a tunnel that a connection has broken that affects at least
2201  * some of its peers. Sends a notification towards the root of the tree.
2202  * In case the peer is the owner of the tree, notifies the client that owns
2203  * the tunnel and tries to reconnect.
2204  *
2205  * @param t Tunnel affected.
2206  * @param p1 Peer that got disconnected from p2.
2207  * @param p2 Peer that got disconnected from p1.
2208  *
2209  * @return Short ID of the peer disconnected (either p1 or p2).
2210  *         0 if the tunnel remained unaffected.
2211  */
2212 static GNUNET_PEER_Id
2213 tunnel_notify_connection_broken (struct MeshTunnel *t, GNUNET_PEER_Id p1,
2214                                  GNUNET_PEER_Id p2)
2215 {
2216 //   if (myid != p1 && myid != p2) FIXME
2217 //   {
2218 //     return;
2219 //   }
2220 // 
2221 //   if (tree_get_predecessor (t->tree) != 0)
2222 //   {
2223 //     /* We are the peer still connected, notify owner of the disconnection. */
2224 //     struct GNUNET_MESH_PathBroken msg;
2225 //     struct GNUNET_PeerIdentity neighbor;
2226 // 
2227 //     msg.header.size = htons (sizeof (msg));
2228 //     msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN);
2229 //     GNUNET_PEER_resolve (t->id.oid, &msg.oid);
2230 //     msg.tid = htonl (t->id.tid);
2231 //     msg.peer1 = my_full_id;
2232 //     GNUNET_PEER_resolve (pid, &msg.peer2);
2233 //     GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &neighbor);
2234 //     send_prebuilt_message (&msg.header, &neighbor, t);
2235 //   }
2236   return 0;
2237 }
2238
2239
2240 /**
2241  * Get the Flow Control info of a client.
2242  * 
2243  * @param t Tunnel on which to look.
2244  * @param c Client whose ACK to get.
2245  * 
2246  * @return ACK value.
2247  */
2248 static struct MeshTunnelClientInfo *
2249 tunnel_get_client_fc (struct MeshTunnel *t,
2250                       struct MeshClient *c)
2251 {
2252   unsigned int i;
2253
2254   for (i = 0; i < t->nclients; i++)
2255   {
2256     if (t->clients[i] != c)
2257       continue;
2258     return &t->clients_fc[i];
2259   }
2260   GNUNET_assert (0);
2261   return NULL; // avoid compiler / coverity complaints
2262 }
2263
2264
2265 /**
2266  * Set the FWD ACK value of a client in a particular tunnel.
2267  * 
2268  * @param t Tunnel affected.
2269  * @param c Client whose ACK to set.
2270  * @param ack ACK value.
2271  */
2272 static void
2273 tunnel_set_client_fwd_ack (struct MeshTunnel *t,
2274                            struct MeshClient *c, 
2275                            uint32_t ack)
2276 {
2277   unsigned int i;
2278
2279   for (i = 0; i < t->nclients; i++)
2280   {
2281     if (t->clients[i] != c)
2282       continue;
2283     t->clients_fc[i].fwd_ack = ack;
2284     return;
2285   }
2286   GNUNET_break (0);
2287 }
2288
2289
2290 /**
2291  * Get the highest ACK value of all clients in a particular tunnel,
2292  * according to the buffering/speed settings.
2293  * 
2294  * @param t Tunnel on which to look.
2295  * 
2296  * @return Corresponding ACK value (max uint32_t).
2297  *         If no clients are suscribed, -1LL.
2298  */
2299 static int64_t
2300 tunnel_get_clients_fwd_ack (struct MeshTunnel *t)
2301 {
2302   unsigned int i;
2303   int64_t ack;
2304
2305   if (0 == t->nclients)
2306   {
2307     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2308                 "  tunnel has no clients, no FWD ACK\n");
2309     return -1LL;
2310   }
2311
2312   for (ack = -1LL, i = 0; i < t->nclients; i++)
2313   {
2314     if (-1LL == ack ||
2315         GNUNET_YES == GMC_is_pid_bigger (ack, t->clients_fc[i].fwd_ack))
2316     {
2317       ack = t->clients_fc[i].fwd_ack;
2318     }
2319   }
2320
2321   if (GNUNET_YES == t->nobuffer &&
2322       GMC_is_pid_bigger(ack, t->prev_fc.last_pid_recv))
2323     ack = (uint32_t) t->prev_fc.last_pid_recv + 1; // Might overflow, it's ok.
2324
2325   return (uint32_t) ack;
2326 }
2327
2328
2329 /** FIXME
2330  * Get the current fwd ack value for a tunnel, taking in account the tunnel
2331  * mode and the status of all children nodes.
2332  *
2333  * @param t Tunnel.
2334  *
2335  * @return Maximum PID allowed.
2336  */
2337 static uint32_t
2338 tunnel_get_fwd_ack (struct MeshTunnel *t)
2339 {
2340   uint32_t ack;
2341   uint32_t buffer_free;
2342   int64_t client_ack;
2343
2344   buffer_free = t->queue_max - t->next_fc.queue_n;
2345   client_ack = tunnel_get_clients_fwd_ack (t);
2346   if (GNUNET_YES == t->nobuffer)
2347   {
2348     ack = t->prev_fc.last_ack_sent;
2349   }
2350   else
2351   {
2352     ack = t->prev_fc.last_ack_sent + buffer_free; // Overflow? OK!
2353   }
2354   if (-1LL == client_ack)
2355   {
2356     client_ack = ack;
2357   }
2358   /* FIXME check */
2359   ack = GMC_max_pid ((uint32_t) client_ack, ack);
2360
2361   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2362               "c %u, bf %u, cl %lld, ACK: %u\n",
2363               t->prev_fc.last_ack_sent, buffer_free, client_ack, ack);
2364   return ack;
2365 }
2366
2367
2368 /**
2369  * Build a local ACK message and send it to a local client.
2370  * 
2371  * @param t Tunnel on which to send the ACK.
2372  * @param c Client to whom send the ACK.
2373  * @param ack Value of the ACK.
2374  */
2375 static void
2376 send_local_ack (struct MeshTunnel *t, struct MeshClient *c, uint32_t ack)
2377 {
2378   struct GNUNET_MESH_LocalAck msg;
2379
2380   msg.header.size = htons (sizeof (msg));
2381   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
2382   msg.tunnel_id = htonl (t->owner == c ? t->local_tid : t->local_tid_dest);
2383   msg.max_pid = htonl (ack); 
2384   GNUNET_SERVER_notification_context_unicast(nc,
2385                                               c->handle,
2386                                               &msg.header,
2387                                               GNUNET_NO);
2388 }
2389
2390 /**
2391  * Build an ACK message and queue it to send to the given peer.
2392  * 
2393  * @param t Tunnel on which to send the ACK.
2394  * @param peer Peer to whom send the ACK.
2395  * @param ack Value of the ACK.
2396  */
2397 static void
2398 send_ack (struct MeshTunnel *t, GNUNET_PEER_Id peer,  uint32_t ack)
2399 {
2400   struct GNUNET_MESH_ACK msg;
2401
2402   GNUNET_PEER_resolve (t->id.oid, &msg.oid);
2403   msg.header.size = htons (sizeof (msg));
2404   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_ACK);
2405   msg.pid = htonl (ack);
2406   msg.tid = htonl (t->id.tid);
2407
2408   send_prebuilt_message (&msg.header, peer, t);
2409 }
2410
2411
2412 /**
2413  * Notify a the owner of a tunnel about how many more
2414  * payload packages will we accept on a given tunnel.
2415  *
2416  * @param t Tunnel on which to send the ACK.
2417  */
2418 static void
2419 tunnel_send_client_fwd_ack (struct MeshTunnel *t)
2420 {
2421   uint32_t ack;
2422
2423   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2424               "Sending client FWD ACK on tunnel %X\n",
2425               t->local_tid);
2426
2427   ack = tunnel_get_fwd_ack (t);
2428
2429   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ack %u\n", ack);
2430   if (t->prev_fc.last_ack_sent == ack)
2431   {
2432     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " same as last, not sending!\n");
2433     return;
2434   }
2435
2436   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " sending!\n");
2437   t->prev_fc.last_ack_sent = ack;
2438   send_local_ack (t, t->owner, ack);
2439 }
2440
2441
2442 /**
2443  * Send an ACK informing the predecessor about the available buffer space.
2444  * In case there is no predecessor, inform the owning client.
2445  * If buffering is off, send only on behalf of children or self if endpoint.
2446  * If buffering is on, send when sent to children and buffer space is free.
2447  * Note that although the name is fwd_ack, the FWD mean forward *traffic*,
2448  * the ACK itself goes "back" (towards root).
2449  * 
2450  * @param t Tunnel on which to send the ACK.
2451  * @param type Type of message that triggered the ACK transmission.
2452  */
2453 static void
2454 tunnel_send_fwd_ack (struct MeshTunnel *t, uint16_t type)
2455 {
2456   uint32_t ack;
2457
2458   if (NULL != t->owner)
2459   {
2460     tunnel_send_client_fwd_ack (t);
2461     return;
2462   }
2463   /* Is it after unicast retransmission? */
2464   switch (type)
2465   {
2466     case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
2467       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2468                   "ACK due to FWD DATA retransmission\n");
2469       if (GNUNET_YES == t->nobuffer)
2470       {
2471         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending ACK, nobuffer\n");
2472         return;
2473       }
2474       break;
2475     case GNUNET_MESSAGE_TYPE_MESH_ACK:
2476     case GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK:
2477       break;
2478     case GNUNET_MESSAGE_TYPE_MESH_POLL:
2479       t->force_ack = GNUNET_YES;
2480       break;
2481     default:
2482       GNUNET_break (0);
2483   }
2484
2485   /* Check if we need to transmit the ACK */
2486   if (t->queue_max > t->next_fc.queue_n * 4 &&
2487       GMC_is_pid_bigger(t->prev_fc.last_ack_sent, t->prev_fc.last_pid_recv) &&
2488       GNUNET_NO == t->force_ack)
2489   {
2490     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending ACK, buffer free\n");
2491     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2492                 "  t->qmax: %u, t->qn: %u\n",
2493                 t->queue_max, t->next_fc.queue_n);
2494     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2495                 "  t->pid: %u, t->ack: %u\n",
2496                 t->prev_fc.last_pid_recv, t->prev_fc.last_ack_sent);
2497     return;
2498   }
2499
2500   /* Ok, ACK might be necessary, what PID to ACK? */
2501   ack = tunnel_get_fwd_ack (t);
2502   if (ack == t->prev_fc.last_ack_sent && GNUNET_NO == t->force_ack)
2503   {
2504     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending FWD ACK, not ready\n");
2505     return;
2506   }
2507
2508   t->prev_fc.last_ack_sent = ack;
2509   send_ack (t, t->prev_hop, ack);
2510   debug_fwd_ack++;
2511   t->force_ack = GNUNET_NO;
2512 }
2513
2514
2515 /**
2516  * Send a child node a BCK ACK to allow him to send more to_origin data.
2517  *
2518  * @param t Tunnel.
2519  * @param id Id of the child node.
2520  */
2521 static void
2522 tunnel_send_mesh_bck_ack (struct MeshTunnel *t,
2523                            GNUNET_PEER_Id peer)
2524 {
2525   uint32_t ack = 0; // FIXME
2526
2527   ack = t->next_fc.last_pid_recv + t->queue_max - t->prev_fc.queue_n;
2528
2529   if (t->next_fc.last_ack_sent == ack && GNUNET_NO == t->force_ack)
2530   {
2531     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2532                 "    Not sending ACK, not needed\n");
2533     return;
2534   }
2535   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2536               "    Sending BCK ACK %u (last sent: %u)\n",
2537               ack, t->next_fc.last_ack_sent);
2538   t->next_fc.last_ack_sent = ack;
2539
2540   send_ack (t, peer, ack);
2541 }
2542
2543
2544 /**
2545  * @brief Send BCK ACKs to clients to allow them more to_origin traffic
2546  * 
2547  * Iterates over all clients and sends BCK ACKs to the ones that need it.
2548  *
2549  * FIXME fc: what happens if we have 2 clients but q_size is 1?
2550  *           - implement a size 1 buffer in each client_fc AND children_fc
2551  *           to hold at least 1 message per "child".
2552  *             problem: violates no buffer policy
2553  *           - ack 0 and make "children" poll for transmission slots
2554  *             problem: big overhead, extra latency even in low traffic
2555  *                      settings
2556  * 
2557  * @param t Tunnel on which to send the BCK ACKs.
2558  */
2559 static void
2560 tunnel_send_clients_bck_ack (struct MeshTunnel *t)
2561 {
2562   unsigned int i;
2563   unsigned int tunnel_delta;
2564
2565   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Sending BCK ACK to clients\n");
2566
2567   tunnel_delta = t->queue_max - t->next_fc.queue_n;
2568   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   tunnel delta: %u\n", tunnel_delta);
2569
2570   /* Find client whom to allow to send to origin (with lowest buffer space) */
2571   for (i = 0; i < t->nclients; i++)
2572   {
2573     struct MeshTunnelClientInfo *clinfo;
2574     unsigned int delta;
2575
2576     clinfo = &t->clients_fc[i];
2577     delta = clinfo->bck_ack - clinfo->bck_pid;
2578     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    client %u delta: %u\n",
2579          t->clients[i]->id, delta);
2580
2581     if ((GNUNET_NO == t->nobuffer && tunnel_delta > delta) ||
2582         (GNUNET_YES == t->nobuffer && 0 == delta))
2583     {
2584       uint32_t ack;
2585
2586       ack = clinfo->bck_pid;
2587       ack += t->nobuffer ? 1 : tunnel_delta;
2588       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2589                   "    sending ack to client %u: %u\n",
2590                   t->clients[i]->id, ack);
2591       send_local_ack (t, t->clients[i], ack);
2592       clinfo->bck_ack = ack;
2593     }
2594     else
2595     {
2596       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2597                   "    not sending ack to client %u (td %u, d %u)\n",
2598                   t->clients[i]->id, tunnel_delta, delta);
2599     }
2600   }
2601 }
2602
2603
2604 /**
2605  * Send an ACK informing the children nodes and destination clients about
2606  * the available buffer space.
2607  * If buffering is off, send only on behalf of root (can be self).
2608  * If buffering is on, send when sent to predecessor and buffer space is free.
2609  * Note that although the name is bck_ack, the BCK mean backwards *traffic*,
2610  * the ACK itself goes "forward" (towards children/clients).
2611  * 
2612  * @param t Tunnel on which to send the ACK.
2613  * @param type Type of message that triggered the ACK transmission.
2614  */
2615 static void
2616 tunnel_send_bck_ack (struct MeshTunnel *t, uint16_t type)
2617 {
2618   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2619               "Sending BCK ACK on tunnel %u [%u] due to %s\n",
2620               t->id.oid, t->id.tid, GNUNET_MESH_DEBUG_M2S(type));
2621   /* Is it after data to_origin retransmission? */
2622   switch (type)
2623   {
2624     case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
2625       if (GNUNET_YES == t->nobuffer)
2626       {
2627         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2628                     "    Not sending ACK, nobuffer\n");
2629         return;
2630       }
2631       break;
2632     case GNUNET_MESSAGE_TYPE_MESH_ACK:
2633     case GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK:
2634       break;
2635     case GNUNET_MESSAGE_TYPE_MESH_POLL:
2636       t->force_ack = GNUNET_YES;
2637       break;
2638     default:
2639       GNUNET_break (0);
2640   }
2641
2642   tunnel_send_clients_bck_ack (t);
2643     tunnel_send_mesh_bck_ack (t, t->next_hop);
2644   t->force_ack = GNUNET_NO;
2645 }
2646
2647
2648 /**
2649  * @brief Re-initiate traffic to this peer if necessary.
2650  *
2651  * Check if there is traffic queued towards this peer
2652  * and the core transmit handle is NULL (traffic was stalled).
2653  * If so, call core tmt rdy.
2654  *
2655  * @param peer_id Short ID of peer to which initiate traffic.
2656  */
2657 static void
2658 peer_unlock_queue(GNUNET_PEER_Id peer_id)
2659 {
2660   struct MeshPeerInfo *peer;
2661   struct GNUNET_PeerIdentity id;
2662   struct MeshPeerQueue *q;
2663   size_t size;
2664
2665   peer = peer_get_short (peer_id);
2666   if (NULL != peer->core_transmit)
2667     return;
2668
2669   q = queue_get_next (peer);
2670   if (NULL == q)
2671   {
2672     /* Might br multicast traffic already sent to this particular peer but
2673      * not to other children in this tunnel.
2674      * This way t->queue_n would be > 0 but the queue of this particular peer
2675      * would be empty.
2676      */
2677     return;
2678   }
2679   size = q->size;
2680   GNUNET_PEER_resolve (peer->id, &id);
2681   peer->core_transmit =
2682         GNUNET_CORE_notify_transmit_ready(core_handle,
2683                                           0,
2684                                           0,
2685                                           GNUNET_TIME_UNIT_FOREVER_REL,
2686                                           &id,
2687                                           size,
2688                                           &queue_send,
2689                                           peer);
2690         return;
2691 }
2692
2693
2694 /**
2695  * Send a message to all peers in this tunnel that the tunnel is no longer
2696  * valid.
2697  *
2698  * @param t The tunnel whose peers to notify.
2699  */
2700 static void
2701 tunnel_send_destroy (struct MeshTunnel *t)
2702 {
2703   struct GNUNET_MESH_TunnelDestroy msg;
2704   struct GNUNET_PeerIdentity id;
2705
2706   msg.header.size = htons (sizeof (msg));
2707   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY);
2708   GNUNET_PEER_resolve (t->id.oid, &msg.oid);
2709   msg.tid = htonl (t->id.tid);
2710   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2711               "  sending tunnel destroy for tunnel: %s [%X]\n",
2712               GNUNET_i2s (&msg.oid), t->id.tid);
2713
2714   if (0 != t->next_hop)
2715   {
2716     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  child: %u\n", t->next_hop);
2717     GNUNET_PEER_resolve (t->next_hop, &id);
2718     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2719                 "  sending forward to %s\n",
2720                 GNUNET_i2s (&id));
2721     send_prebuilt_message (&msg.header, t->next_hop, t);
2722   }
2723   if (0 != t->prev_hop)
2724   {
2725     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  parent: %u\n", t->prev_hop);
2726     GNUNET_PEER_resolve (t->prev_hop, &id);
2727     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2728                 "  sending back to %s\n",
2729                 GNUNET_i2s (&id));
2730     send_prebuilt_message (&msg.header, t->prev_hop, t);
2731   }
2732 }
2733
2734
2735 /**
2736  * Cancel all transmissions towards a neighbor that belongs to a certain tunnel.
2737  *
2738  * @param t Tunnel which to cancel.
2739  * @param neighbor Short ID of the neighbor to whom cancel the transmissions.
2740  */
2741 static void
2742 peer_cancel_queues (GNUNET_PEER_Id neighbor, struct MeshTunnel *t)
2743 {
2744   struct MeshPeerInfo *peer_info;
2745   struct MeshPeerQueue *pq;
2746   struct MeshPeerQueue *next;
2747
2748   peer_info = peer_get_short (neighbor);
2749   for (pq = peer_info->queue_head; NULL != pq; pq = next)
2750   {
2751     next = pq->next;
2752     if (pq->tunnel == t)
2753     {
2754       if (GNUNET_MESSAGE_TYPE_MESH_UNICAST == pq->type ||
2755           GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN == pq->type)
2756       {
2757         // Should have been removed on destroy children
2758         GNUNET_break (0);
2759       }
2760       queue_destroy (pq, GNUNET_YES);
2761     }
2762   }
2763   if (NULL == peer_info->queue_head && NULL != peer_info->core_transmit)
2764   {
2765     GNUNET_CORE_notify_transmit_ready_cancel(peer_info->core_transmit);
2766     peer_info->core_transmit = NULL;
2767   }
2768 }
2769
2770
2771 /**
2772  * Destroy the tunnel and free any allocated resources linked to it.
2773  *
2774  * @param t the tunnel to destroy
2775  *
2776  * @return GNUNET_OK on success
2777  */
2778 static int
2779 tunnel_destroy (struct MeshTunnel *t)
2780 {
2781   struct MeshClient *c;
2782   struct GNUNET_HashCode hash;
2783   unsigned int i;
2784   int r;
2785
2786   if (NULL == t)
2787     return GNUNET_OK;
2788
2789   r = GNUNET_OK;
2790   c = t->owner;
2791 #if MESH_DEBUG
2792   {
2793     struct GNUNET_PeerIdentity id;
2794
2795     GNUNET_PEER_resolve (t->id.oid, &id);
2796     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s [%x]\n",
2797                 GNUNET_i2s (&id), t->id.tid);
2798     if (NULL != c)
2799       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
2800   }
2801 #endif
2802
2803   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
2804   if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_remove (tunnels, &hash, t))
2805   {
2806     GNUNET_break (0);
2807     r = GNUNET_SYSERR;
2808   }
2809
2810   if (NULL != c)
2811   {
2812     GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
2813     if (GNUNET_YES !=
2814         GNUNET_CONTAINER_multihashmap_remove (c->own_tunnels, &hash, t))
2815     {
2816       GNUNET_break (0);
2817       r = GNUNET_SYSERR;
2818     }
2819   }
2820
2821   GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
2822   for (i = 0; i < t->nclients; i++)
2823   {
2824     c = t->clients[i];
2825     if (GNUNET_YES !=
2826           GNUNET_CONTAINER_multihashmap_remove (c->incoming_tunnels, &hash, t))
2827     {
2828       GNUNET_break (0);
2829       r = GNUNET_SYSERR;
2830     }
2831   }
2832   for (i = 0; i < t->nignore; i++)
2833   {
2834     c = t->ignore[i];
2835     if (GNUNET_YES !=
2836           GNUNET_CONTAINER_multihashmap_remove (c->ignore_tunnels, &hash, t))
2837     {
2838       GNUNET_break (0);
2839       r = GNUNET_SYSERR;
2840     }
2841   }
2842
2843   (void) GNUNET_CONTAINER_multihashmap_remove (incoming_tunnels, &hash, t);
2844   GNUNET_free_non_null (t->clients);
2845   GNUNET_free_non_null (t->ignore);
2846   GNUNET_free_non_null (t->clients_fc);
2847
2848   peer_cancel_queues (t->next_hop, t);
2849   peer_cancel_queues (t->prev_hop, t);
2850
2851   if (GNUNET_SCHEDULER_NO_TASK != t->maintenance_task)
2852     GNUNET_SCHEDULER_cancel (t->maintenance_task);
2853
2854   n_tunnels--;
2855   GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
2856   GNUNET_free (t);
2857   return r;
2858 }
2859
2860 #define TUNNEL_DESTROY_EMPTY_TIME GNUNET_TIME_UNIT_MILLISECONDS
2861
2862 /**
2863  * Tunnel is empty: destroy it.
2864  * 
2865  * @param cls Closure (Tunnel).
2866  * @param tc TaskContext. 
2867  */
2868 static void
2869 tunnel_destroy_empty_delayed (void *cls,
2870                               const struct GNUNET_SCHEDULER_TaskContext *tc)
2871 {
2872   struct MeshTunnel *t = cls;
2873
2874   t->delayed_destroy = GNUNET_SCHEDULER_NO_TASK;
2875   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2876     return;
2877
2878   if (0 != t->nclients)
2879     return;
2880
2881   #if MESH_DEBUG
2882   {
2883     struct GNUNET_PeerIdentity id;
2884
2885     GNUNET_PEER_resolve (t->id.oid, &id);
2886     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2887                 "executing destruction of empty tunnel %s [%X]\n",
2888                 GNUNET_i2s (&id), t->id.tid);
2889   }
2890   #endif
2891
2892   tunnel_send_destroy (t);
2893   if (0 == t->pending_messages)
2894     tunnel_destroy (t);
2895   else
2896     t->destroy = GNUNET_YES;
2897 }
2898
2899
2900 /**
2901  * Schedule tunnel destruction if is empty and no new traffic comes in a time.
2902  * 
2903  * @param t Tunnel to destroy if empty.
2904  */
2905 static void
2906 tunnel_destroy_empty (struct MeshTunnel *t)
2907 {
2908   if (GNUNET_SCHEDULER_NO_TASK != t->delayed_destroy || 
2909       0 != t->nclients)
2910   {
2911     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "%u %u\n",
2912                 t->delayed_destroy, t->nclients);
2913     return;
2914   }
2915
2916   #if MESH_DEBUG
2917   {
2918     struct GNUNET_PeerIdentity id;
2919
2920     GNUNET_PEER_resolve (t->id.oid, &id);
2921     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2922                 "scheduling destruction of empty tunnel %s [%X]\n",
2923                 GNUNET_i2s (&id), t->id.tid);
2924   }
2925   #endif
2926
2927   t->delayed_destroy =
2928       GNUNET_SCHEDULER_add_delayed (TUNNEL_DESTROY_EMPTY_TIME,
2929                                     &tunnel_destroy_empty_delayed,
2930                                     t);
2931 }
2932
2933
2934 /**
2935  * Create a new tunnel
2936  * 
2937  * @param owner Who is the owner of the tunnel (short ID).
2938  * @param tid Tunnel Number of the tunnel.
2939  * @param client Clients that owns the tunnel, NULL for foreign tunnels.
2940  * @param local Tunnel Number for the tunnel, for the client point of view.
2941  * 
2942  * @return A new initialized tunnel. NULL on error.
2943  */
2944 static struct MeshTunnel *
2945 tunnel_new (GNUNET_PEER_Id owner,
2946             MESH_TunnelNumber tid,
2947             struct MeshClient *client,
2948             MESH_TunnelNumber local)
2949 {
2950   struct MeshTunnel *t;
2951   struct GNUNET_HashCode hash;
2952
2953   if (n_tunnels >= max_tunnels && NULL == client)
2954     return NULL;
2955
2956   t = GNUNET_malloc (sizeof (struct MeshTunnel));
2957   t->id.oid = owner;
2958   t->id.tid = tid;
2959   t->queue_max = (max_msgs_queue / max_tunnels) + 1;
2960   t->owner = client;
2961   t->next_fc.last_pid_sent = (uint32_t) -1; /* Next (expected) = 0 */
2962   t->next_fc.last_pid_recv = (uint32_t) -1;
2963   t->prev_fc.last_pid_sent = (uint32_t) -1;
2964   t->prev_fc.last_pid_recv = (uint32_t) -1;
2965   t->next_fc.last_ack_sent = INITIAL_WINDOW_SIZE - 1;
2966   t->next_fc.last_ack_recv = INITIAL_WINDOW_SIZE - 1;
2967   t->prev_fc.last_ack_sent = INITIAL_WINDOW_SIZE - 1;
2968   t->prev_fc.last_ack_recv = INITIAL_WINDOW_SIZE - 1;
2969   t->local_tid = local;
2970   n_tunnels++;
2971   GNUNET_STATISTICS_update (stats, "# tunnels", 1, GNUNET_NO);
2972
2973   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
2974   if (GNUNET_OK !=
2975       GNUNET_CONTAINER_multihashmap_put (tunnels, &hash, t,
2976                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
2977   {
2978     GNUNET_break (0);
2979     tunnel_destroy (t);
2980     if (NULL != client)
2981     {
2982       GNUNET_break (0);
2983       GNUNET_SERVER_receive_done (client->handle, GNUNET_SYSERR);
2984     }
2985     return NULL;
2986   }
2987
2988   if (NULL != client)
2989   {
2990     GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
2991     if (GNUNET_OK !=
2992         GNUNET_CONTAINER_multihashmap_put (client->own_tunnels, &hash, t,
2993                                           GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
2994     {
2995       tunnel_destroy (t);
2996       GNUNET_break (0);
2997       GNUNET_SERVER_receive_done (client->handle, GNUNET_SYSERR);
2998       return NULL;
2999     }
3000   }
3001
3002   return t;
3003 }
3004
3005
3006
3007 /**
3008  * tunnel_destroy_iterator: iterator for deleting each tunnel that belongs to a
3009  * client when the client disconnects. If the client is not the owner, the
3010  * owner will get notified if no more clients are in the tunnel and the client
3011  * get removed from the tunnel's list.
3012  *
3013  * @param cls closure (client that is disconnecting)
3014  * @param key the hash of the local tunnel id (used to access the hashmap)
3015  * @param value the value stored at the key (tunnel to destroy)
3016  *
3017  * @return GNUNET_OK, keep iterating.
3018  */
3019 static int
3020 tunnel_destroy_iterator (void *cls,
3021                          const struct GNUNET_HashCode * key,
3022                          void *value)
3023 {
3024   struct MeshTunnel *t = value;
3025   struct MeshClient *c = cls;
3026
3027   send_client_tunnel_disconnect (t, c);
3028   if (c != t->owner)
3029   {
3030     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Client %u is destination.\n", c->id);
3031     tunnel_delete_client (t, c);
3032     client_delete_tunnel (c, t);
3033     tunnel_destroy_empty (t);
3034     return GNUNET_OK;
3035   }
3036   tunnel_send_destroy (t);
3037   t->owner = NULL;
3038   t->destroy = GNUNET_YES;
3039
3040   return GNUNET_OK;
3041 }
3042
3043
3044 /**
3045  * Timeout function, destroys tunnel if called
3046  *
3047  * @param cls Closure (tunnel to destroy).
3048  * @param tc TaskContext
3049  */
3050 static void
3051 tunnel_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3052 {
3053   struct MeshTunnel *t = cls;
3054   struct GNUNET_PeerIdentity id;
3055
3056   t->maintenance_task = GNUNET_SCHEDULER_NO_TASK;
3057   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
3058     return;
3059   GNUNET_PEER_resolve(t->id.oid, &id);
3060   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3061               "Tunnel %s [%X] timed out. Destroying.\n",
3062               GNUNET_i2s(&id), t->id.tid);
3063   send_clients_tunnel_destroy (t);
3064   tunnel_destroy (t);
3065 }
3066
3067 /**
3068  * Resets the tunnel timeout. Starts it if no timeout was running.
3069  *
3070  * @param t Tunnel whose timeout to reset.
3071  *
3072  * TODO use heap to improve efficiency of scheduler.
3073  */
3074 static void
3075 tunnel_reset_timeout (struct MeshTunnel *t)
3076 {
3077   if (GNUNET_SCHEDULER_NO_TASK != t->maintenance_task)
3078     GNUNET_SCHEDULER_cancel (t->maintenance_task);
3079   t->maintenance_task =
3080       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
3081                                     (refresh_path_time, 4), &tunnel_timeout, t);
3082 }
3083
3084
3085 /******************************************************************************/
3086 /****************      MESH NETWORK HANDLER HELPERS     ***********************/
3087 /******************************************************************************/
3088
3089 /**
3090  * Function to send a create path packet to a peer.
3091  *
3092  * @param cls closure
3093  * @param size number of bytes available in buf
3094  * @param buf where the callee should write the message
3095  * @return number of bytes written to buf
3096  */
3097 static size_t
3098 send_core_path_create (void *cls, size_t size, void *buf)
3099 {
3100   struct MeshTunnel *t = cls;
3101   struct GNUNET_MESH_ManipulatePath *msg;
3102   struct GNUNET_PeerIdentity *peer_ptr;
3103   struct MeshPeerPath *p = t->path;
3104   size_t size_needed;
3105   uint32_t opt;
3106   int i;
3107
3108   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CREATE PATH sending...\n");
3109   size_needed =
3110       sizeof (struct GNUNET_MESH_ManipulatePath) +
3111       p->length * sizeof (struct GNUNET_PeerIdentity);
3112
3113   if (size < size_needed || NULL == buf)
3114   {
3115     GNUNET_break (0);
3116     return 0;
3117   }
3118   msg = (struct GNUNET_MESH_ManipulatePath *) buf;
3119   msg->header.size = htons (size_needed);
3120   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE);
3121   msg->tid = ntohl (t->id.tid);
3122
3123   opt = 0;
3124   if (GNUNET_YES == t->nobuffer)
3125     opt |= MESH_TUNNEL_OPT_NOBUFFER;
3126   msg->opt = htonl(opt);
3127   msg->reserved = 0;
3128
3129   peer_ptr = (struct GNUNET_PeerIdentity *) &msg[1];
3130   for (i = 0; i < p->length; i++)
3131   {
3132     GNUNET_PEER_resolve (p->peers[i], peer_ptr++);
3133   }
3134
3135   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3136               "CREATE PATH (%u bytes long) sent!\n", size_needed);
3137   return size_needed;
3138 }
3139
3140
3141 /**
3142  * Creates a path ack message in buf and frees all unused resources.
3143  *
3144  * @param cls closure (MeshTransmissionDescriptor)
3145  * @param size number of bytes available in buf
3146  * @param buf where the callee should write the message
3147  * @return number of bytes written to buf
3148  */
3149 static size_t
3150 send_core_path_ack (void *cls, size_t size, void *buf)
3151 {
3152   struct MeshTransmissionDescriptor *info = cls;
3153   struct GNUNET_MESH_PathACK *msg = buf;
3154
3155   GNUNET_assert (NULL != info);
3156   if (sizeof (struct GNUNET_MESH_PathACK) > size)
3157   {
3158     GNUNET_break (0);
3159     return 0;
3160   }
3161   msg->header.size = htons (sizeof (struct GNUNET_MESH_PathACK));
3162   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_ACK);
3163   GNUNET_PEER_resolve (info->origin->oid, &msg->oid);
3164   msg->tid = htonl (info->origin->tid);
3165   msg->peer_id = my_full_id;
3166
3167   GNUNET_free (info);
3168   /* TODO add signature */
3169
3170   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "PATH ACK sent!\n");
3171   return sizeof (struct GNUNET_MESH_PathACK);
3172 }
3173
3174
3175 /**
3176  * Free a transmission that was already queued with all resources
3177  * associated to the request.
3178  *
3179  * @param queue Queue handler to cancel.
3180  * @param clear_cls Is it necessary to free associated cls?
3181  */
3182 static void
3183 queue_destroy (struct MeshPeerQueue *queue, int clear_cls)
3184 {
3185   struct MeshTransmissionDescriptor *dd;
3186 //   unsigned int max;
3187
3188   if (GNUNET_YES == clear_cls)
3189   {
3190     switch (queue->type)
3191     {
3192       case GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY:
3193         GNUNET_log (GNUNET_ERROR_TYPE_INFO, "   cancelling TUNNEL_DESTROY\n");
3194         GNUNET_break (GNUNET_YES == queue->tunnel->destroy);
3195         /* fall through */
3196       case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
3197       case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
3198       case GNUNET_MESSAGE_TYPE_MESH_ACK:
3199       case GNUNET_MESSAGE_TYPE_MESH_POLL:
3200       case GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE:
3201         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3202                     "   prebuilt message\n");
3203         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3204                     "   type %s\n",
3205                     GNUNET_MESH_DEBUG_M2S(queue->type));
3206         dd = queue->cls;
3207         GNUNET_free (dd->data);
3208         break;
3209       case GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE:
3210         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   type create path\n");
3211         break;
3212       default:
3213         GNUNET_break (0);
3214         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3215                     "   type %s unknown!\n",
3216                     GNUNET_MESH_DEBUG_M2S(queue->type));
3217     }
3218     GNUNET_free_non_null (queue->cls);
3219   }
3220   GNUNET_CONTAINER_DLL_remove (queue->peer->queue_head,
3221                                queue->peer->queue_tail,
3222                                queue);
3223
3224   /* Delete from child_fc in the appropiate tunnel */
3225 //   max = queue->tunnel->fwd_queue_max;
3226 //   GNUNET_PEER_resolve (queue->peer->id, &id);
3227 //   if (NULL != cinfo)
3228 //   { FIXME
3229 //     for (i = 0; i < cinfo->send_buffer_n; i++)
3230 //     {
3231 //       i2 = (cinfo->send_buffer_start + i) % max;
3232 //       if (cinfo->send_buffer[i2] == queue)
3233 //       {
3234 //         /* Found corresponding entry in the send_buffer. Move all others back. */
3235 //         unsigned int j;
3236 // 
3237 // 
3238 //         for (j = i, j2 = 0, j3 = 0; j < cinfo->send_buffer_n - 1; j++)
3239 //         {
3240 //           j2 = (cinfo->send_buffer_start + j) % max;
3241 //           j3 = (cinfo->send_buffer_start + j + 1) % max;
3242 //           cinfo->send_buffer[j2] = cinfo->send_buffer[j3];
3243 //         }
3244 // 
3245 //         cinfo->send_buffer[j3] = NULL;
3246 //         cinfo->send_buffer_n--;
3247 //       }
3248 //     }
3249 //   }
3250
3251   GNUNET_free (queue);
3252 }
3253
3254
3255 /**
3256  * @brief Get the next transmittable message from the queue.
3257  *
3258  * This will be the head, except in the case of being a data packet
3259  * not allowed by the destination peer.
3260  *
3261  * @param peer Destination peer.
3262  *
3263  * @return The next viable MeshPeerQueue element to send to that peer.
3264  *         NULL when there are no transmittable messages.
3265  */
3266 struct MeshPeerQueue *
3267 queue_get_next (const struct MeshPeerInfo *peer)
3268 {
3269   struct MeshPeerQueue *q;
3270  
3271   struct MeshTransmissionDescriptor *info;
3272 //   struct GNUNET_MESH_Unicast *ucast;
3273 //   struct GNUNET_MESH_ToOrigin *to_orig;
3274   struct GNUNET_PeerIdentity id;
3275 //   uint32_t pid;
3276 //   uint32_t ack; FIXME
3277
3278   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   selecting message\n");
3279   for (q = peer->queue_head; NULL != q; q = q->next)
3280   {
3281 //     t = q->tunnel;
3282     info = q->cls;
3283     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3284                 "*********     %s\n",
3285                 GNUNET_MESH_DEBUG_M2S(q->type));
3286     switch (q->type)
3287     {
3288       case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
3289 //         ucast = (struct GNUNET_MESH_Unicast *) info->mesh_data->data;
3290 //         pid = ntohl (ucast->pid);
3291         GNUNET_PEER_resolve (info->peer->id, &id);
3292 //         ack = cinfo->fwd_ack;
3293         break;
3294       case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
3295 //         to_orig = (struct GNUNET_MESH_ToOrigin *) info->mesh_data->data;
3296 //         pid = ntohl (to_orig->pid);
3297 //         ack = t->bck_ack;
3298         break;
3299       default:
3300         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3301                     "*********   OK!\n");
3302         return q;
3303     }
3304 //     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3305 //                 "*********     ACK: %u, PID: %u\n",
3306 //                 ack, pid);
3307 //     if (GNUNET_NO == GMC_is_pid_bigger(pid, ack))
3308 //     {
3309 //       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3310 //                   "*********   OK!\n");
3311 //       return q;
3312 //     }
3313 //     else
3314 //     {
3315 //       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3316 //                   "*********     NEXT!\n");
3317 //     }
3318   }
3319   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3320                 "*********   nothing found\n");
3321   return NULL;
3322 }
3323
3324
3325 static size_t
3326 queue_send (void *cls, size_t size, void *buf)
3327 {
3328     struct MeshPeerInfo *peer = cls;
3329     struct GNUNET_MessageHeader *msg;
3330     struct MeshPeerQueue *queue;
3331     struct MeshTunnel *t;
3332     struct GNUNET_PeerIdentity dst_id;
3333     struct MeshFlowControl *fc;
3334     size_t data_size;
3335
3336     peer->core_transmit = NULL;
3337
3338     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "********* Queue send\n");
3339     queue = queue_get_next (peer);
3340
3341     /* Queue has no internal mesh traffic nor sendable payload */
3342     if (NULL == queue)
3343     {
3344       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   not ready, return\n");
3345       if (NULL == peer->queue_head)
3346         GNUNET_break (0); /* Core tmt_rdy should've been canceled */
3347       return 0;
3348     }
3349     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   not empty\n");
3350
3351     GNUNET_PEER_resolve (peer->id, &dst_id);
3352     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3353                 "*********   towards %s\n",
3354                 GNUNET_i2s(&dst_id));
3355     /* Check if buffer size is enough for the message */
3356     if (queue->size > size)
3357     {
3358         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3359                     "*********   not enough room, reissue\n");
3360         peer->core_transmit =
3361             GNUNET_CORE_notify_transmit_ready (core_handle,
3362                                                0,
3363                                                0,
3364                                                GNUNET_TIME_UNIT_FOREVER_REL,
3365                                                &dst_id,
3366                                                queue->size,
3367                                                &queue_send,
3368                                                peer);
3369         return 0;
3370     }
3371     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   size ok\n");
3372
3373     t = queue->tunnel;
3374     GNUNET_assert (0 < t->pending_messages);
3375     t->pending_messages--;
3376     if (GNUNET_MESSAGE_TYPE_MESH_UNICAST == queue->type)
3377     {
3378       t->next_fc.queue_n--;
3379       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3380                   "*********   unicast: t->q (%u/%u)\n",
3381                   t->next_fc.queue_n, t->queue_max);
3382     }
3383     else if (GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN == queue->type)
3384     {
3385       t->prev_fc.queue_n--;
3386       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3387                   "*********   to orig: t->q (%u/%u)\n",
3388                   t->prev_fc.queue_n, t->queue_max);
3389     }
3390
3391     /* Fill buf */
3392     switch (queue->type)
3393     {
3394       case 0:
3395       case GNUNET_MESSAGE_TYPE_MESH_ACK:
3396       case GNUNET_MESSAGE_TYPE_MESH_POLL:
3397       case GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN:
3398       case GNUNET_MESSAGE_TYPE_MESH_PATH_DESTROY:
3399       case GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY:
3400       case GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE:
3401         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3402                     "*********   raw: %s\n",
3403                     GNUNET_MESH_DEBUG_M2S (queue->type));
3404         /* Fall through */
3405       case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
3406       case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
3407         data_size = send_core_data_raw (queue->cls, size, buf);
3408         msg = (struct GNUNET_MessageHeader *) buf;
3409         switch (ntohs (msg->type)) // Type of preconstructed message
3410         {
3411           case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
3412             tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_UNICAST);
3413             break;
3414           case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
3415             tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN);
3416             break;
3417           default:
3418               break;
3419         }
3420         break;
3421       case GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE:
3422         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   path create\n");
3423         data_size = send_core_path_create (queue->cls, size, buf);
3424         break;
3425       case GNUNET_MESSAGE_TYPE_MESH_PATH_ACK:
3426         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   path ack\n");
3427         data_size = send_core_path_ack (queue->cls, size, buf);
3428         break;
3429       default:
3430         GNUNET_break (0);
3431         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3432                     "*********   type unknown: %u\n",
3433                     queue->type);
3434         data_size = 0;
3435     }
3436     switch (queue->type)
3437     {
3438       case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
3439       case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
3440 //         if (cinfo->send_buffer[cinfo->send_buffer_start] != queue)
3441 //         { FIXME
3442 //           GNUNET_break (0);
3443 //           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3444 //                       "at pos %u (%p) != %p\n",
3445 //                       cinfo->send_buffer_start,
3446 //                       cinfo->send_buffer[cinfo->send_buffer_start],
3447 //                       queue);
3448 //         }
3449 //         if (cinfo->send_buffer_n > 0)
3450 //         {
3451 //           cinfo->send_buffer[cinfo->send_buffer_start] = NULL;
3452 //           cinfo->send_buffer_n--;
3453 //           cinfo->send_buffer_start++;
3454 //           cinfo->send_buffer_start %= t->fwd_queue_max;
3455 //         }
3456 //         else
3457 //         {
3458 //           GNUNET_break (0);
3459 //         }
3460         break;
3461       default:
3462         break;
3463     }
3464
3465     /* Free queue, but cls was freed by send_core_* */
3466     queue_destroy (queue, GNUNET_NO);
3467
3468     if (GNUNET_YES == t->destroy && 0 == t->pending_messages)
3469     {
3470       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********  destroying tunnel!\n");
3471       tunnel_destroy (t);
3472     }
3473
3474     /* If more data in queue, send next */
3475     queue = queue_get_next (peer);
3476     if (NULL != queue)
3477     {
3478         struct GNUNET_PeerIdentity id;
3479
3480         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   more data!\n");
3481         GNUNET_PEER_resolve (peer->id, &id);
3482         peer->core_transmit =
3483             GNUNET_CORE_notify_transmit_ready(core_handle,
3484                                               0,
3485                                               0,
3486                                               GNUNET_TIME_UNIT_FOREVER_REL,
3487                                               &id,
3488                                               queue->size,
3489                                               &queue_send,
3490                                               peer);
3491     }
3492     else
3493     {
3494       if (NULL != peer->queue_head)
3495       {
3496         GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3497                     "*********   %s stalled\n",
3498                     GNUNET_i2s(&my_full_id));
3499         if (peer->id == t->next_hop)
3500           fc = &t->next_fc;
3501         else
3502           fc = &t->prev_fc;
3503         if (GNUNET_SCHEDULER_NO_TASK == fc->poll_task)
3504         {
3505           fc->t = t;
3506           fc->poll_task = GNUNET_SCHEDULER_add_delayed (fc->poll_time,
3507                                                         &tunnel_poll, fc);
3508         }
3509       }
3510     }
3511     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   return %d\n", data_size);
3512     return data_size;
3513 }
3514
3515
3516 /**
3517  * @brief Queue and pass message to core when possible.
3518  * 
3519  * If type is payload (UNICAST, TO_ORIGIN) checks for queue status and
3520  * accounts for it. In case the queue is full, the message is dropped and
3521  * a break issued.
3522  * 
3523  * Otherwise, message is treated as internal and allowed to go regardless of 
3524  * queue status.
3525  *
3526  * @param cls Closure (@c type dependant). It will be used by queue_send to
3527  *            build the message to be sent if not already prebuilt.
3528  * @param type Type of the message, 0 for a raw message.
3529  * @param size Size of the message.
3530  * @param dst Neighbor to send message to.
3531  * @param t Tunnel this message belongs to.
3532  */
3533 static void
3534 queue_add (void *cls, uint16_t type, size_t size,
3535            struct MeshPeerInfo *dst, struct MeshTunnel *t)
3536 {
3537   struct MeshPeerQueue *queue;
3538   struct GNUNET_PeerIdentity id;
3539   unsigned int *n;
3540
3541   n = NULL;
3542   if (GNUNET_MESSAGE_TYPE_MESH_UNICAST == type)
3543   {
3544     n = &t->next_fc.queue_n;
3545   }
3546   else if (GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN == type)
3547   {
3548     n = &t->prev_fc.queue_n;
3549   }
3550   if (NULL != n)
3551   {
3552     if (*n >= t->queue_max)
3553     {
3554       GNUNET_break(0);
3555       GNUNET_STATISTICS_update(stats,
3556                                "# messages dropped (buffer full)",
3557                                1, GNUNET_NO);
3558       return; // Drop message
3559     }
3560     (*n)++;
3561   }
3562   queue = GNUNET_malloc (sizeof (struct MeshPeerQueue));
3563   queue->cls = cls;
3564   queue->type = type;
3565   queue->size = size;
3566   queue->peer = dst;
3567   queue->tunnel = t;
3568   GNUNET_CONTAINER_DLL_insert_tail (dst->queue_head, dst->queue_tail, queue);
3569   if (NULL == dst->core_transmit)
3570   {
3571     GNUNET_PEER_resolve (dst->id, &id);
3572     dst->core_transmit =
3573         GNUNET_CORE_notify_transmit_ready (core_handle,
3574                                            0,
3575                                            0,
3576                                            GNUNET_TIME_UNIT_FOREVER_REL,
3577                                            &id,
3578                                            size,
3579                                            &queue_send,
3580                                            dst);
3581   }
3582   t->pending_messages++;
3583 }
3584
3585
3586 /******************************************************************************/
3587 /********************      MESH NETWORK HANDLERS     **************************/
3588 /******************************************************************************/
3589
3590
3591 /**
3592  * Core handler for path creation
3593  *
3594  * @param cls closure
3595  * @param message message
3596  * @param peer peer identity this notification is about
3597  *
3598  * @return GNUNET_OK to keep the connection open,
3599  *         GNUNET_SYSERR to close it (signal serious error)
3600  */
3601 static int
3602 handle_mesh_path_create (void *cls, const struct GNUNET_PeerIdentity *peer,
3603                          const struct GNUNET_MessageHeader *message)
3604 {
3605   unsigned int own_pos;
3606   uint16_t size;
3607   uint16_t i;
3608   MESH_TunnelNumber tid;
3609   struct GNUNET_MESH_ManipulatePath *msg;
3610   struct GNUNET_PeerIdentity *pi;
3611   struct GNUNET_HashCode hash;
3612   struct MeshPeerPath *path;
3613   struct MeshPeerInfo *dest_peer_info;
3614   struct MeshPeerInfo *orig_peer_info;
3615   struct MeshTunnel *t;
3616
3617   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3618               "Received a path create msg [%s]\n",
3619               GNUNET_i2s (&my_full_id));
3620   size = ntohs (message->size);
3621   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
3622   {
3623     GNUNET_break_op (0);
3624     return GNUNET_OK;
3625   }
3626
3627   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
3628   if (size % sizeof (struct GNUNET_PeerIdentity))
3629   {
3630     GNUNET_break_op (0);
3631     return GNUNET_OK;
3632   }
3633   size /= sizeof (struct GNUNET_PeerIdentity);
3634   if (size < 2)
3635   {
3636     GNUNET_break_op (0);
3637     return GNUNET_OK;
3638   }
3639   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
3640   msg = (struct GNUNET_MESH_ManipulatePath *) message;
3641
3642   tid = ntohl (msg->tid);
3643   pi = (struct GNUNET_PeerIdentity *) &msg[1];
3644   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3645               "    path is for tunnel %s [%X].\n", GNUNET_i2s (pi), tid);
3646   t = tunnel_get (pi, tid);
3647   if (NULL == t) // FIXME only for INCOMING tunnels?
3648   {
3649     uint32_t opt;
3650
3651     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating tunnel\n");
3652     t = tunnel_new (GNUNET_PEER_intern (pi), tid, NULL, 0);
3653     if (NULL == t)
3654     {
3655       // FIXME notify failure
3656       return GNUNET_OK;
3657     }
3658     opt = ntohl (msg->opt);
3659     if (0 != (opt & MESH_TUNNEL_OPT_NOBUFFER))
3660     {
3661       t->nobuffer = GNUNET_YES;
3662       t->prev_fc.last_ack_sent = t->prev_fc.last_pid_recv + 1;
3663     }
3664     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  nobuffer:%d\n", t->nobuffer);
3665
3666     if (GNUNET_YES == t->nobuffer)
3667     {
3668       t->queue_max = 1;
3669     }
3670
3671     // FIXME only assign a local tid if a local client is interested (on demand)
3672     while (NULL != tunnel_get_incoming (next_local_tid))
3673       next_local_tid = (next_local_tid + 1) | GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
3674     t->local_tid_dest = next_local_tid++;
3675     next_local_tid = next_local_tid | GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
3676     // FIXME end
3677
3678     tunnel_reset_timeout (t);
3679     GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
3680     if (GNUNET_OK !=
3681         GNUNET_CONTAINER_multihashmap_put (incoming_tunnels, &hash, t,
3682                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
3683     {
3684       tunnel_destroy (t);
3685       GNUNET_break (0);
3686       return GNUNET_OK;
3687     }
3688   }
3689   dest_peer_info =
3690       GNUNET_CONTAINER_multihashmap_get (peers, &pi[size - 1].hashPubKey);
3691   if (NULL == dest_peer_info)
3692   {
3693     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3694                 "  Creating PeerInfo for destination.\n");
3695     dest_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
3696     dest_peer_info->id = GNUNET_PEER_intern (&pi[size - 1]);
3697     GNUNET_CONTAINER_multihashmap_put (peers, &pi[size - 1].hashPubKey,
3698                                        dest_peer_info,
3699                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3700   }
3701   orig_peer_info = GNUNET_CONTAINER_multihashmap_get (peers, &pi->hashPubKey);
3702   if (NULL == orig_peer_info)
3703   {
3704     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3705                 "  Creating PeerInfo for origin.\n");
3706     orig_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
3707     orig_peer_info->id = GNUNET_PEER_intern (pi);
3708     GNUNET_CONTAINER_multihashmap_put (peers, &pi->hashPubKey, orig_peer_info,
3709                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3710   }
3711   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
3712   path = path_new (size);
3713   own_pos = 0;
3714   for (i = 0; i < size; i++)
3715   {
3716     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ... adding %s\n",
3717                 GNUNET_i2s (&pi[i]));
3718     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
3719     if (path->peers[i] == myid)
3720       own_pos = i;
3721   }
3722   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
3723   if (own_pos == 0)
3724   {
3725     /* cannot be self, must be 'not found' */
3726     /* create path: self not found in path through self */
3727     GNUNET_break_op (0);
3728     path_destroy (path);
3729     tunnel_destroy (t);
3730     return GNUNET_OK;
3731   }
3732   path_add_to_peers (path, GNUNET_NO);
3733   t->prev_hop = path->peers[own_pos - 1];
3734   GNUNET_PEER_change_rc (t->prev_hop, 1);
3735   if (own_pos == size - 1)
3736   {
3737     /* It is for us! Send ack. */
3738     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
3739     peer_info_add_path_to_origin (orig_peer_info, path, GNUNET_NO);
3740     t->dest = myid;
3741     send_path_ack (t);
3742   }
3743   else
3744   {
3745     struct MeshPeerPath *path2;
3746
3747     t->next_hop = path->peers[own_pos + 1];
3748     GNUNET_PEER_change_rc(t->next_hop, 1);
3749
3750     /* It's for somebody else! Retransmit. */
3751     path2 = path_duplicate (path);
3752     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Retransmitting.\n");
3753     peer_info_add_path (dest_peer_info, path2, GNUNET_NO);
3754     path2 = path_duplicate (path);
3755     peer_info_add_path_to_origin (orig_peer_info, path2, GNUNET_NO);
3756     send_create_path (dest_peer_info, path, t);
3757   }
3758   return GNUNET_OK;
3759 }
3760
3761
3762 /**
3763  * Core handler for path destruction
3764  *
3765  * @param cls closure
3766  * @param message message
3767  * @param peer peer identity this notification is about
3768  *
3769  * @return GNUNET_OK to keep the connection open,
3770  *         GNUNET_SYSERR to close it (signal serious error)
3771  */
3772 static int
3773 handle_mesh_path_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
3774                           const struct GNUNET_MessageHeader *message)
3775 {
3776   struct GNUNET_MESH_ManipulatePath *msg;
3777   struct GNUNET_PeerIdentity *pi;
3778   struct MeshPeerPath *path;
3779   struct MeshTunnel *t;
3780   unsigned int own_pos;
3781   unsigned int i;
3782   size_t size;
3783
3784   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3785               "Received a PATH DESTROY msg from %s\n", GNUNET_i2s (peer));
3786   size = ntohs (message->size);
3787   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
3788   {
3789     GNUNET_break_op (0);
3790     return GNUNET_OK;
3791   }
3792
3793   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
3794   if (size % sizeof (struct GNUNET_PeerIdentity))
3795   {
3796     GNUNET_break_op (0);
3797     return GNUNET_OK;
3798   }
3799   size /= sizeof (struct GNUNET_PeerIdentity);
3800   if (size < 2)
3801   {
3802     GNUNET_break_op (0);
3803     return GNUNET_OK;
3804   }
3805   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
3806
3807   msg = (struct GNUNET_MESH_ManipulatePath *) message;
3808   pi = (struct GNUNET_PeerIdentity *) &msg[1];
3809   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3810               "    path is for tunnel %s [%X].\n", GNUNET_i2s (pi),
3811               msg->tid);
3812   t = tunnel_get (pi, ntohl (msg->tid));
3813   if (NULL == t)
3814   {
3815     /* TODO notify back: we don't know this tunnel */
3816     GNUNET_break_op (0);
3817     return GNUNET_OK;
3818   }
3819   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
3820   path = path_new (size);
3821   own_pos = 0;
3822   for (i = 0; i < size; i++)
3823   {
3824     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ... adding %s\n",
3825                 GNUNET_i2s (&pi[i]));
3826     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
3827     if (path->peers[i] == myid)
3828       own_pos = i;
3829   }
3830   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
3831   if (own_pos < path->length - 1)
3832     send_prebuilt_message (message, path->peers[own_pos + 1], t);
3833   else
3834     send_client_tunnel_disconnect(t, NULL);
3835
3836 //   tunnel_delete_peer (t, path->peers[path->length - 1]); FIXME
3837   path_destroy (path);
3838   return GNUNET_OK;
3839 }
3840
3841
3842 /**
3843  * Core handler for notifications of broken paths
3844  *
3845  * @param cls closure
3846  * @param message message
3847  * @param peer peer identity this notification is about
3848  *
3849  * @return GNUNET_OK to keep the connection open,
3850  *         GNUNET_SYSERR to close it (signal serious error)
3851  */
3852 static int
3853 handle_mesh_path_broken (void *cls, const struct GNUNET_PeerIdentity *peer,
3854                          const struct GNUNET_MessageHeader *message)
3855 {
3856   struct GNUNET_MESH_PathBroken *msg;
3857   struct MeshTunnel *t;
3858
3859   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3860               "Received a PATH BROKEN msg from %s\n", GNUNET_i2s (peer));
3861   msg = (struct GNUNET_MESH_PathBroken *) message;
3862   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
3863               GNUNET_i2s (&msg->peer1));
3864   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
3865               GNUNET_i2s (&msg->peer2));
3866   t = tunnel_get (&msg->oid, ntohl (msg->tid));
3867   if (NULL == t)
3868   {
3869     GNUNET_break_op (0);
3870     return GNUNET_OK;
3871   }
3872   tunnel_notify_connection_broken (t, GNUNET_PEER_search (&msg->peer1),
3873                                    GNUNET_PEER_search (&msg->peer2));
3874   return GNUNET_OK;
3875
3876 }
3877
3878
3879 /**
3880  * Core handler for tunnel destruction
3881  *
3882  * @param cls closure
3883  * @param message message
3884  * @param peer peer identity this notification is about
3885  *
3886  * @return GNUNET_OK to keep the connection open,
3887  *         GNUNET_SYSERR to close it (signal serious error)
3888  */
3889 static int
3890 handle_mesh_tunnel_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
3891                             const struct GNUNET_MessageHeader *message)
3892 {
3893   struct GNUNET_MESH_TunnelDestroy *msg;
3894   struct MeshTunnel *t;
3895   GNUNET_PEER_Id pid;
3896
3897   msg = (struct GNUNET_MESH_TunnelDestroy *) message;
3898   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3899               "Got a TUNNEL DESTROY packet from %s\n",
3900               GNUNET_i2s (peer));
3901   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3902               "  for tunnel %s [%u]\n",
3903               GNUNET_i2s (&msg->oid), ntohl (msg->tid));
3904   t = tunnel_get (&msg->oid, ntohl (msg->tid));
3905   /* Check signature */
3906   if (NULL == t)
3907   {
3908     /* Probably already got the message from another path,
3909      * destroyed the tunnel and retransmitted to children.
3910      * Safe to ignore.
3911      */
3912     GNUNET_STATISTICS_update (stats, "# control on unknown tunnel",
3913                               1, GNUNET_NO);
3914     return GNUNET_OK;
3915   }
3916   pid = GNUNET_PEER_search (peer);
3917   if (pid != t->prev_hop && 0 < t->nclients)
3918   {
3919     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3920                 "still in use by %u clients\n",
3921                 t->nclients);
3922     return GNUNET_OK;
3923   }
3924   if (t->local_tid_dest >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
3925   {
3926     /* Tunnel was incoming, notify clients */
3927     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "INCOMING TUNNEL %X %X\n",
3928                 t->local_tid, t->local_tid_dest);
3929     send_clients_tunnel_destroy (t);
3930   }
3931   tunnel_send_destroy (t);
3932   t->destroy = GNUNET_YES;
3933   // TODO: add timeout to destroy the tunnel anyway
3934   return GNUNET_OK;
3935 }
3936
3937
3938 /**
3939  * Core handler for mesh network traffic going from the origin to a peer
3940  *
3941  * @param cls closure
3942  * @param peer peer identity this notification is about
3943  * @param message message
3944  * @return GNUNET_OK to keep the connection open,
3945  *         GNUNET_SYSERR to close it (signal serious error)
3946  */
3947 static int
3948 handle_mesh_data_unicast (void *cls, const struct GNUNET_PeerIdentity *peer,
3949                           const struct GNUNET_MessageHeader *message)
3950 {
3951   struct GNUNET_MESH_Unicast *msg;
3952   struct MeshTunnel *t;
3953   uint32_t pid;
3954   uint32_t ttl;
3955   size_t size;
3956
3957   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a unicast packet from %s\n",
3958               GNUNET_i2s (peer));
3959   /* Check size */
3960   size = ntohs (message->size);
3961   if (size <
3962       sizeof (struct GNUNET_MESH_Unicast) +
3963       sizeof (struct GNUNET_MessageHeader))
3964   {
3965     GNUNET_break (0);
3966     return GNUNET_OK;
3967   }
3968   msg = (struct GNUNET_MESH_Unicast *) message;
3969   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " of type %s\n",
3970               GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
3971   /* Check tunnel */
3972   t = tunnel_get (&msg->oid, ntohl (msg->tid));
3973   if (NULL == t)
3974   {
3975     /* TODO notify back: we don't know this tunnel */
3976     GNUNET_STATISTICS_update (stats, "# data on unknown tunnel", 1, GNUNET_NO);
3977     GNUNET_break_op (0);
3978     return GNUNET_OK;
3979   }
3980   pid = ntohl (msg->pid);
3981   if (t->prev_fc.last_pid_recv == pid)
3982   {
3983     GNUNET_STATISTICS_update (stats, "# duplicate PID drops", 1, GNUNET_NO);
3984     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3985                 " Already seen pid %u, DROPPING!\n", pid);
3986     return GNUNET_OK;
3987   }
3988   else
3989   {
3990     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3991                 " pid %u not seen yet, forwarding\n", pid);
3992   }
3993
3994   t->prev_fc.last_pid_recv = pid;
3995
3996   if (GMC_is_pid_bigger (pid, t->prev_fc.last_ack_sent))
3997   {
3998     GNUNET_STATISTICS_update (stats, "# unsolicited unicast", 1, GNUNET_NO);
3999     GNUNET_break_op (0);
4000     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4001                 "Received PID %u, ACK %u\n",
4002                 pid, t->prev_fc.last_ack_sent);
4003     return GNUNET_OK;
4004   }
4005
4006   tunnel_reset_timeout (t);
4007   if (t->dest == myid)
4008   {
4009     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4010                 "  it's for us! sending to clients...\n");
4011     GNUNET_STATISTICS_update (stats, "# unicast received", 1, GNUNET_NO);
4012     send_subscribed_clients (message, &msg[1].header, t);
4013     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_UNICAST);
4014     return GNUNET_OK;
4015   }
4016   ttl = ntohl (msg->ttl);
4017   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ttl: %u\n", ttl);
4018   if (ttl == 0)
4019   {
4020     GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
4021     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
4022     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
4023     return GNUNET_OK;
4024   }
4025   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4026               "  not for us, retransmitting...\n");
4027
4028   if (GNUNET_YES == t->nobuffer &&
4029       GNUNET_YES == GMC_is_pid_bigger (pid, t->next_fc.last_ack_recv))
4030   {
4031     GNUNET_STATISTICS_update (stats, "# unsolicited unicast", 1, GNUNET_NO);
4032     GNUNET_log (GNUNET_ERROR_TYPE_INFO, "  %u > %u\n",
4033                 pid, t->next_fc.last_ack_recv);
4034     GNUNET_break_op (0);
4035     return GNUNET_OK;
4036   }
4037   send_prebuilt_message (message, t->next_hop, t);
4038   GNUNET_STATISTICS_update (stats, "# unicast forwarded", 1, GNUNET_NO);
4039   return GNUNET_OK;
4040 }
4041
4042
4043 /**
4044  * Core handler for mesh network traffic toward the owner of a tunnel
4045  *
4046  * @param cls closure
4047  * @param message message
4048  * @param peer peer identity this notification is about
4049  *
4050  * @return GNUNET_OK to keep the connection open,
4051  *         GNUNET_SYSERR to close it (signal serious error)
4052  */
4053 static int
4054 handle_mesh_data_to_orig (void *cls, const struct GNUNET_PeerIdentity *peer,
4055                           const struct GNUNET_MessageHeader *message)
4056 {
4057   struct GNUNET_MESH_ToOrigin *msg;
4058   struct MeshPeerInfo *peer_info;
4059   struct MeshTunnel *t;
4060   size_t size;
4061   uint32_t pid;
4062
4063   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a ToOrigin packet from %s\n",
4064               GNUNET_i2s (peer));
4065   size = ntohs (message->size);
4066   if (size < sizeof (struct GNUNET_MESH_ToOrigin) +     /* Payload must be */
4067       sizeof (struct GNUNET_MessageHeader))     /* at least a header */
4068   {
4069     GNUNET_break_op (0);
4070     return GNUNET_OK;
4071   }
4072   msg = (struct GNUNET_MESH_ToOrigin *) message;
4073   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " of type %s\n",
4074               GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
4075   t = tunnel_get (&msg->oid, ntohl (msg->tid));
4076   pid = ntohl (msg->pid);
4077
4078   if (NULL == t)
4079   {
4080     /* TODO notify that we dont know this tunnel (whom)? */
4081     GNUNET_STATISTICS_update (stats, "# data on unknown tunnel", 1, GNUNET_NO);
4082     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4083                 "Received to_origin with PID %u on unknown tunnel %s [%u]\n",
4084                 pid, GNUNET_i2s (&msg->oid), ntohl (msg->tid));
4085     return GNUNET_OK;
4086   }
4087
4088
4089   if (t->next_fc.last_pid_recv == pid)
4090   {
4091     /* already seen this packet, drop */
4092     GNUNET_STATISTICS_update (stats, "# duplicate PID drops BCK", 1, GNUNET_NO);
4093     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4094                 " Already seen pid %u, DROPPING!\n", pid);
4095     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
4096     return GNUNET_OK;
4097   }
4098
4099   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4100               " pid %u not seen yet, forwarding\n", pid);
4101   t->next_fc.last_pid_recv = pid;
4102
4103   if (NULL != t->owner)
4104   {
4105     char cbuf[size];
4106     struct GNUNET_MESH_ToOrigin *copy;
4107
4108     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4109                 "  it's for us! sending to clients...\n");
4110     /* TODO signature verification */
4111     memcpy (cbuf, message, size);
4112     copy = (struct GNUNET_MESH_ToOrigin *) cbuf;
4113     copy->tid = htonl (t->local_tid);
4114     GNUNET_STATISTICS_update (stats, "# to origin received", 1, GNUNET_NO);
4115     GNUNET_SERVER_notification_context_unicast (nc, t->owner->handle,
4116                                                 &copy->header, GNUNET_NO);
4117     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN);
4118     return GNUNET_OK;
4119   }
4120   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4121               "  not for us, retransmitting...\n");
4122
4123   peer_info = peer_get (&msg->oid);
4124   if (NULL == peer_info)
4125   {
4126     /* unknown origin of tunnel */
4127     GNUNET_break (0);
4128     return GNUNET_OK;
4129   }
4130   if (0 == t->prev_hop) /* No owner AND no prev hop */
4131   {
4132     if (GNUNET_YES == t->destroy)
4133     {
4134       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4135                   "to orig received on a dying tunnel %s [%X]\n",
4136                   GNUNET_i2s (&msg->oid), ntohl(msg->tid));
4137       return GNUNET_OK;
4138     }
4139     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 
4140                 "unknown to origin at %s\n",
4141                 GNUNET_i2s (&my_full_id));
4142     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 
4143                 "from peer %s\n",
4144                 GNUNET_i2s (peer));
4145     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 
4146                 "for tunnel %s [%X]\n",
4147                 GNUNET_i2s (&msg->oid), ntohl(msg->tid));
4148     return GNUNET_OK;
4149   }
4150   send_prebuilt_message (message, t->prev_hop, t);
4151   GNUNET_STATISTICS_update (stats, "# to origin forwarded", 1, GNUNET_NO);
4152
4153   return GNUNET_OK;
4154 }
4155
4156
4157 /**
4158  * Core handler for mesh network traffic point-to-point acks.
4159  *
4160  * @param cls closure
4161  * @param message message
4162  * @param peer peer identity this notification is about
4163  *
4164  * @return GNUNET_OK to keep the connection open,
4165  *         GNUNET_SYSERR to close it (signal serious error)
4166  */
4167 static int
4168 handle_mesh_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
4169                  const struct GNUNET_MessageHeader *message)
4170 {
4171   struct GNUNET_MESH_ACK *msg;
4172   struct MeshTunnel *t;
4173   uint32_t ack;
4174
4175   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got an ACK packet from %s!\n",
4176               GNUNET_i2s (peer));
4177   msg = (struct GNUNET_MESH_ACK *) message;
4178
4179   t = tunnel_get (&msg->oid, ntohl (msg->tid));
4180
4181   if (NULL == t)
4182   {
4183     /* TODO notify that we dont know this tunnel (whom)? */
4184     GNUNET_STATISTICS_update (stats, "# ack on unknown tunnel", 1, GNUNET_NO);
4185     return GNUNET_OK;
4186   }
4187   ack = ntohl (msg->pid);
4188   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ACK %u\n", ack);
4189
4190   /* Is this a forward or backward ACK? */
4191   if (t->prev_hop != GNUNET_PEER_search (peer))
4192   {
4193     debug_bck_ack++;
4194     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  FWD ACK\n");
4195     t->next_fc.last_ack_recv = ack;
4196     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
4197     peer_unlock_queue (t->next_hop);
4198 //     if (GNUNET_SCHEDULER_NO_TASK != cinfo->fc_poll) FIXME
4199 //     {
4200 //       GNUNET_SCHEDULER_cancel (cinfo->fc_poll);
4201 //       cinfo->fc_poll = GNUNET_SCHEDULER_NO_TASK;
4202 //       cinfo->fc_poll_time = GNUNET_TIME_UNIT_SECONDS;
4203 //     }
4204   }
4205   else
4206   {
4207     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  BCK ACK\n");
4208     t->prev_fc.last_ack_recv = ack;
4209     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
4210     peer_unlock_queue (t->prev_hop);
4211   }
4212   return GNUNET_OK;
4213 }
4214
4215
4216 /**
4217  * Core handler for mesh network traffic point-to-point ack polls.
4218  *
4219  * @param cls closure
4220  * @param message message
4221  * @param peer peer identity this notification is about
4222  *
4223  * @return GNUNET_OK to keep the connection open,
4224  *         GNUNET_SYSERR to close it (signal serious error)
4225  */
4226 static int
4227 handle_mesh_poll (void *cls, const struct GNUNET_PeerIdentity *peer,
4228                   const struct GNUNET_MessageHeader *message)
4229 {
4230   struct GNUNET_MESH_Poll *msg;
4231   struct MeshTunnel *t;
4232
4233   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got an POLL packet from %s!\n",
4234               GNUNET_i2s (peer));
4235
4236   msg = (struct GNUNET_MESH_Poll *) message;
4237
4238   t = tunnel_get (&msg->oid, ntohl (msg->tid));
4239
4240   if (NULL == t)
4241   {
4242     /* TODO notify that we dont know this tunnel (whom)? */
4243     GNUNET_STATISTICS_update (stats, "# poll on unknown tunnel", 1, GNUNET_NO);
4244     GNUNET_break_op (0);
4245     return GNUNET_OK;
4246   }
4247
4248   /* Is this a forward or backward ACK? */
4249   if (t->prev_hop != GNUNET_PEER_search(peer))
4250   {
4251     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  from FWD\n");
4252     /* FIXME cinfo->bck_ack = cinfo->fwd_pid; // mark as ready to send */
4253     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_POLL);
4254   }
4255   else
4256   {
4257     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  from BCK\n");
4258     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_POLL);
4259   }
4260
4261   return GNUNET_OK;
4262 }
4263
4264 /**
4265  * Core handler for path ACKs
4266  *
4267  * @param cls closure
4268  * @param message message
4269  * @param peer peer identity this notification is about
4270  *
4271  * @return GNUNET_OK to keep the connection open,
4272  *         GNUNET_SYSERR to close it (signal serious error)
4273  */
4274 static int
4275 handle_mesh_path_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
4276                       const struct GNUNET_MessageHeader *message)
4277 {
4278   struct GNUNET_MESH_PathACK *msg;
4279   struct MeshPeerInfo *peer_info;
4280   struct MeshPeerPath *p;
4281   struct MeshTunnel *t;
4282
4283   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a path ACK msg [%s]\n",
4284               GNUNET_i2s (&my_full_id));
4285   msg = (struct GNUNET_MESH_PathACK *) message;
4286   t = tunnel_get (&msg->oid, ntohl(msg->tid));
4287   if (NULL == t)
4288   {
4289     /* TODO notify that we don't know the tunnel */
4290     GNUNET_STATISTICS_update (stats, "# control on unknown tunnel", 1, GNUNET_NO);
4291     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  don't know the tunnel %s [%X]!\n",
4292                 GNUNET_i2s (&msg->oid), ntohl(msg->tid));
4293     return GNUNET_OK;
4294   }
4295   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %s [%X]\n",
4296               GNUNET_i2s (&msg->oid), ntohl(msg->tid));
4297
4298   peer_info = peer_get (&msg->peer_id);
4299   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by peer %s\n",
4300               GNUNET_i2s (&msg->peer_id));
4301   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  via peer %s\n",
4302               GNUNET_i2s (peer));
4303
4304   /* Add path to peers? */
4305   p = t->path;
4306   if (NULL != p)
4307   {
4308     path_add_to_peers (p, GNUNET_YES);
4309   }
4310   else
4311   {
4312     GNUNET_break (0);
4313   }
4314
4315   /* Message for us? */
4316   if (0 == memcmp (&msg->oid, &my_full_id, sizeof (struct GNUNET_PeerIdentity)))
4317   {
4318     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
4319     if (NULL == t->owner)
4320     {
4321       GNUNET_break_op (0);
4322       return GNUNET_OK;
4323     }
4324     if (NULL != peer_info->dhtget)
4325     {
4326       GNUNET_DHT_get_stop (peer_info->dhtget);
4327       peer_info->dhtget = NULL;
4328     }
4329     return GNUNET_OK;
4330   }
4331
4332   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4333               "  not for us, retransmitting...\n");
4334   peer_info = peer_get (&msg->oid);
4335   send_prebuilt_message (message, t->prev_hop, t);
4336   return GNUNET_OK;
4337 }
4338
4339
4340 /**
4341  * Core handler for mesh keepalives.
4342  *
4343  * @param cls closure
4344  * @param message message
4345  * @param peer peer identity this notification is about
4346  * @return GNUNET_OK to keep the connection open,
4347  *         GNUNET_SYSERR to close it (signal serious error)
4348  *
4349  * TODO: Check who we got this from, to validate route.
4350  */
4351 static int
4352 handle_mesh_keepalive (void *cls, const struct GNUNET_PeerIdentity *peer,
4353                        const struct GNUNET_MessageHeader *message)
4354 {
4355   struct GNUNET_MESH_TunnelKeepAlive *msg;
4356   struct MeshTunnel *t;
4357
4358   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a keepalive packet from %s\n",
4359               GNUNET_i2s (peer));
4360
4361   msg = (struct GNUNET_MESH_TunnelKeepAlive *) message;
4362   t = tunnel_get (&msg->oid, ntohl (msg->tid));
4363
4364   if (NULL == t)
4365   {
4366     /* TODO notify that we dont know that tunnel */
4367     GNUNET_STATISTICS_update (stats, "# keepalive on unknown tunnel", 1,
4368                               GNUNET_NO);
4369     return GNUNET_OK;
4370   }
4371
4372   tunnel_reset_timeout (t);
4373
4374   GNUNET_STATISTICS_update (stats, "# keepalives forwarded", 1, GNUNET_NO);
4375   send_prebuilt_message (message, t->next_hop, t);
4376   return GNUNET_OK;
4377   }
4378
4379
4380
4381 /**
4382  * Functions to handle messages from core
4383  */
4384 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
4385   {&handle_mesh_path_create, GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE, 0},
4386   {&handle_mesh_path_destroy, GNUNET_MESSAGE_TYPE_MESH_PATH_DESTROY, 0},
4387   {&handle_mesh_path_broken, GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN,
4388    sizeof (struct GNUNET_MESH_PathBroken)},
4389   {&handle_mesh_tunnel_destroy, GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY,
4390    sizeof (struct GNUNET_MESH_TunnelDestroy)},
4391   {&handle_mesh_data_unicast, GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
4392   {&handle_mesh_keepalive, GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE,
4393     sizeof (struct GNUNET_MESH_TunnelKeepAlive)},
4394   {&handle_mesh_data_to_orig, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
4395   {&handle_mesh_ack, GNUNET_MESSAGE_TYPE_MESH_ACK,
4396     sizeof (struct GNUNET_MESH_ACK)},
4397   {&handle_mesh_poll, GNUNET_MESSAGE_TYPE_MESH_POLL,
4398     sizeof (struct GNUNET_MESH_Poll)},
4399   {&handle_mesh_path_ack, GNUNET_MESSAGE_TYPE_MESH_PATH_ACK,
4400    sizeof (struct GNUNET_MESH_PathACK)},
4401   {NULL, 0, 0}
4402 };
4403
4404
4405
4406 /******************************************************************************/
4407 /****************       MESH LOCAL HANDLER HELPERS      ***********************/
4408 /******************************************************************************/
4409
4410
4411 #if LATER
4412 /**
4413  * notify_client_connection_failure: notify a client that the connection to the
4414  * requested remote peer is not possible (for instance, no route found)
4415  * Function called when the socket is ready to queue more data. "buf" will be
4416  * NULL and "size" zero if the socket was closed for writing in the meantime.
4417  *
4418  * @param cls closure
4419  * @param size number of bytes available in buf
4420  * @param buf where the callee should write the message
4421  * @return number of bytes written to buf
4422  */
4423 static size_t
4424 notify_client_connection_failure (void *cls, size_t size, void *buf)
4425 {
4426   int size_needed;
4427   struct MeshPeerInfo *peer_info;
4428   struct GNUNET_MESH_PeerControl *msg;
4429   struct GNUNET_PeerIdentity id;
4430
4431   if (0 == size && NULL == buf)
4432   {
4433     // TODO retry? cancel?
4434     return 0;
4435   }
4436
4437   size_needed = sizeof (struct GNUNET_MESH_PeerControl);
4438   peer_info = (struct MeshPeerInfo *) cls;
4439   msg = (struct GNUNET_MESH_PeerControl *) buf;
4440   msg->header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
4441   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DISCONNECTED);
4442 //     msg->tunnel_id = htonl(peer_info->t->tid);
4443   GNUNET_PEER_resolve (peer_info->id, &id);
4444   memcpy (&msg->peer, &id, sizeof (struct GNUNET_PeerIdentity));
4445
4446   return size_needed;
4447 }
4448 #endif
4449
4450
4451 /**
4452  * Send keepalive packets for a tunnel.
4453  *
4454  * @param cls Closure (tunnel for which to send the keepalive).
4455  * @param tc Notification context.
4456  */
4457 static void
4458 path_refresh (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4459 {
4460   struct MeshTunnel *t = cls;
4461   struct GNUNET_MESH_TunnelKeepAlive *msg;
4462   size_t size = sizeof (struct GNUNET_MESH_TunnelKeepAlive);
4463   char cbuf[size];
4464
4465   t->maintenance_task = GNUNET_SCHEDULER_NO_TASK;
4466   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
4467   {
4468     return;
4469   }
4470
4471   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4472               "sending keepalive for tunnel %d\n", t->id.tid);
4473
4474   msg = (struct GNUNET_MESH_TunnelKeepAlive *) cbuf;
4475   msg->header.size = htons (size);
4476   // FIXME change to tunnel keepalive
4477   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE);
4478   msg->oid = my_full_id;
4479   msg->tid = htonl (t->id.tid);
4480   send_prebuilt_message (&msg->header, t->next_hop, t);
4481
4482   t->maintenance_task =
4483       GNUNET_SCHEDULER_add_delayed (refresh_path_time, &path_refresh, t);
4484   tunnel_reset_timeout (t);
4485 }
4486
4487
4488 /**
4489  * Function to process paths received for a new peer addition. The recorded
4490  * paths form the initial tunnel, which can be optimized later.
4491  * Called on each result obtained for the DHT search.
4492  *
4493  * @param cls closure
4494  * @param exp when will this value expire
4495  * @param key key of the result
4496  * @param get_path path of the get request
4497  * @param get_path_length lenght of get_path
4498  * @param put_path path of the put request
4499  * @param put_path_length length of the put_path
4500  * @param type type of the result
4501  * @param size number of bytes in data
4502  * @param data pointer to the result data
4503  *
4504  * TODO: re-issue the request after certain time? cancel after X results?
4505  */
4506 static void
4507 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
4508                     const struct GNUNET_HashCode * key,
4509                     const struct GNUNET_PeerIdentity *get_path,
4510                     unsigned int get_path_length,
4511                     const struct GNUNET_PeerIdentity *put_path,
4512                     unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
4513                     size_t size, const void *data)
4514 {
4515   struct MeshPeerInfo *peer = cls;
4516   struct MeshPeerPath *p;
4517   struct GNUNET_PeerIdentity pi;
4518   int i;
4519
4520   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got results from DHT!\n");
4521   GNUNET_PEER_resolve (peer->id, &pi);
4522   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for %s\n", GNUNET_i2s (&pi));
4523
4524   p = path_build_from_dht (get_path, get_path_length,
4525                            put_path, put_path_length);
4526   path_add_to_peers (p, GNUNET_NO);
4527   path_destroy (p);
4528   for (i = 0; i < peer->ntunnels; i++)
4529   {
4530     peer_connect (peer, peer->tunnels[i]); // FIXME add if
4531   }
4532
4533   return;
4534 }
4535
4536
4537 /******************************************************************************/
4538 /*********************       MESH LOCAL HANDLES      **************************/
4539 /******************************************************************************/
4540
4541
4542 /**
4543  * Handler for client disconnection
4544  *
4545  * @param cls closure
4546  * @param client identification of the client; NULL
4547  *        for the last call when the server is destroyed
4548  */
4549 static void
4550 handle_local_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
4551 {
4552   struct MeshClient *c;
4553   struct MeshClient *next;
4554
4555   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client disconnected\n");
4556   if (client == NULL)
4557   {
4558     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   (SERVER DOWN)\n");
4559     return;
4560   }
4561
4562   c = clients_head;
4563   while (NULL != c)
4564   {
4565     if (c->handle != client)
4566     {
4567       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ... searching\n");
4568       c = c->next;
4569       continue;
4570     }
4571     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "matching client found (%u)\n",
4572                 c->id);
4573     GNUNET_SERVER_client_drop (c->handle);
4574     c->shutting_down = GNUNET_YES;
4575     GNUNET_CONTAINER_multihashmap_iterate (c->own_tunnels,
4576                                            &tunnel_destroy_iterator, c);
4577     GNUNET_CONTAINER_multihashmap_iterate (c->incoming_tunnels,
4578                                            &tunnel_destroy_iterator, c);
4579     GNUNET_CONTAINER_multihashmap_iterate (c->ignore_tunnels,
4580                                            &tunnel_destroy_iterator, c);
4581     GNUNET_CONTAINER_multihashmap_destroy (c->own_tunnels);
4582     GNUNET_CONTAINER_multihashmap_destroy (c->incoming_tunnels);
4583     GNUNET_CONTAINER_multihashmap_destroy (c->ignore_tunnels);
4584
4585     if (NULL != c->types)
4586       GNUNET_CONTAINER_multihashmap_destroy (c->types);
4587     next = c->next;
4588     GNUNET_CONTAINER_DLL_remove (clients_head, clients_tail, c);
4589     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  CLIENT FREE at %p\n", c);
4590     GNUNET_free (c);
4591     GNUNET_STATISTICS_update (stats, "# clients", -1, GNUNET_NO);
4592     c = next;
4593   }
4594   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "done!\n");
4595   return;
4596 }
4597
4598
4599 /**
4600  * Handler for new clients
4601  *
4602  * @param cls closure
4603  * @param client identification of the client
4604  * @param message the actual message, which includes messages the client wants
4605  */
4606 static void
4607 handle_local_new_client (void *cls, struct GNUNET_SERVER_Client *client,
4608                          const struct GNUNET_MessageHeader *message)
4609 {
4610   struct GNUNET_MESH_ClientConnect *cc_msg;
4611   struct MeshClient *c;
4612   unsigned int size;
4613   uint16_t ntypes;
4614   uint16_t *t;
4615   uint16_t i;
4616
4617   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client connected\n");
4618
4619   /* Check data sanity */
4620   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_ClientConnect);
4621   cc_msg = (struct GNUNET_MESH_ClientConnect *) message;
4622   ntypes = ntohs (cc_msg->types);
4623   if (size != ntypes * sizeof (uint16_t))
4624   {
4625     GNUNET_break (0);
4626     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4627     return;
4628   }
4629
4630   /* Create new client structure */
4631   c = GNUNET_malloc (sizeof (struct MeshClient));
4632   c->id = next_client_id++; // overflow not important: just for debug
4633   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  CLIENT NEW %u\n", c->id);
4634   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  client has %u types\n", ntypes);
4635   c->handle = client;
4636   GNUNET_SERVER_client_keep (client);
4637   if (ntypes > 0)
4638   {
4639     uint16_t u16;
4640     struct GNUNET_HashCode hc;
4641
4642     t = (uint16_t *) &cc_msg[1];
4643     c->types = GNUNET_CONTAINER_multihashmap_create (ntypes, GNUNET_NO);
4644     for (i = 0; i < ntypes; i++)
4645     {
4646       u16 = ntohs (t[i]);
4647       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    msg type: %u\n", u16);
4648       GNUNET_CRYPTO_hash (&u16, sizeof (u16), &hc); // FIXME pseudo hash
4649
4650       /* store in clients hashmap */
4651       GNUNET_CONTAINER_multihashmap_put (c->types, &hc, c,
4652                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
4653       /* store in global hashmap */
4654       GNUNET_CONTAINER_multihashmap_put (types, &hc, c,
4655                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
4656     }
4657   }
4658
4659   GNUNET_CONTAINER_DLL_insert (clients_head, clients_tail, c);
4660   c->own_tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
4661   c->incoming_tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
4662   c->ignore_tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
4663   GNUNET_SERVER_notification_context_add (nc, client);
4664   GNUNET_STATISTICS_update (stats, "# clients", 1, GNUNET_NO);
4665
4666   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4667   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client processed\n");
4668 }
4669
4670
4671 /**
4672  * Handler for requests of new tunnels
4673  *
4674  * @param cls Closure.
4675  * @param client Identification of the client.
4676  * @param message The actual message.
4677  */
4678 static void
4679 handle_local_tunnel_create (void *cls, struct GNUNET_SERVER_Client *client,
4680                             const struct GNUNET_MessageHeader *message)
4681 {
4682   struct GNUNET_MESH_TunnelMessage *t_msg;
4683   struct MeshPeerInfo *peer_info;
4684   struct MeshTunnel *t;
4685   struct MeshClient *c;
4686   MESH_TunnelNumber tid;
4687
4688   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new tunnel requested\n");
4689
4690   /* Sanity check for client registration */
4691   if (NULL == (c = client_get (client)))
4692   {
4693     GNUNET_break (0);
4694     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4695     return;
4696   }
4697   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
4698
4699   /* Message sanity check */
4700   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
4701   {
4702     GNUNET_break (0);
4703     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4704     return;
4705   }
4706
4707   t_msg = (struct GNUNET_MESH_TunnelMessage *) message;
4708   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  towards %s\n",
4709               GNUNET_i2s (&t_msg->peer));
4710   /* Sanity check for tunnel numbering */
4711   tid = ntohl (t_msg->tunnel_id);
4712   if (0 == (tid & GNUNET_MESH_LOCAL_TUNNEL_ID_CLI))
4713   {
4714     GNUNET_break (0);
4715     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4716     return;
4717   }
4718   /* Sanity check for duplicate tunnel IDs */
4719   if (NULL != tunnel_get_by_local_id (c, tid))
4720   {
4721     GNUNET_break (0);
4722     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4723     return;
4724   }
4725
4726   while (NULL != tunnel_get_by_pi (myid, next_tid))
4727     next_tid = (next_tid + 1) & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
4728   t = tunnel_new (myid, next_tid, c, tid);
4729   next_tid = (next_tid + 1) & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
4730   if (NULL == t)
4731   {
4732     GNUNET_break (0);
4733     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4734     return;
4735   }
4736   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CREATED TUNNEL %s [%x] (%x)\n",
4737               GNUNET_i2s (&my_full_id), t->id.tid, t->local_tid);
4738
4739   peer_info = peer_get (&t_msg->peer);
4740   GNUNET_array_append (peer_info->tunnels, peer_info->ntunnels, t);
4741   peer_connect (peer_info, t);
4742   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4743   return;
4744 }
4745
4746
4747 /**
4748  * Handler for requests of deleting tunnels
4749  *
4750  * @param cls closure
4751  * @param client identification of the client
4752  * @param message the actual message
4753  */
4754 static void
4755 handle_local_tunnel_destroy (void *cls, struct GNUNET_SERVER_Client *client,
4756                              const struct GNUNET_MessageHeader *message)
4757 {
4758   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
4759   struct MeshClient *c;
4760   struct MeshTunnel *t;
4761   MESH_TunnelNumber tid;
4762
4763   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4764               "Got a DESTROY TUNNEL from client!\n");
4765
4766   /* Sanity check for client registration */
4767   if (NULL == (c = client_get (client)))
4768   {
4769     GNUNET_break (0);
4770     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4771     return;
4772   }
4773   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
4774
4775   /* Message sanity check */
4776   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
4777   {
4778     GNUNET_break (0);
4779     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4780     return;
4781   }
4782
4783   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
4784
4785   /* Retrieve tunnel */
4786   tid = ntohl (tunnel_msg->tunnel_id);
4787   t = tunnel_get_by_local_id(c, tid);
4788   if (NULL == t)
4789   {
4790     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  tunnel %X not found\n", tid);
4791     GNUNET_break (0);
4792     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4793     return;
4794   }
4795   if (c != t->owner || tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
4796   {
4797     client_ignore_tunnel (c, t);
4798     tunnel_destroy_empty (t);
4799     GNUNET_SERVER_receive_done (client, GNUNET_OK);
4800     return;
4801   }
4802   send_client_tunnel_disconnect (t, c);
4803   client_delete_tunnel (c, t);
4804
4805   /* Don't try to ACK the client about the tunnel_destroy multicast packet */
4806   t->owner = NULL;
4807   tunnel_send_destroy (t);
4808   peer_remove_tunnel (peer_get_short(t->dest), t);
4809   t->destroy = GNUNET_YES;
4810   /* The tunnel will be destroyed when the last message is transmitted. */
4811   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4812   return;
4813 }
4814
4815
4816 /**
4817  * Handler for requests of seeting tunnel's buffering policy.
4818  *
4819  * @param cls Closure (unused).
4820  * @param client Identification of the client.
4821  * @param message The actual message.
4822  */
4823 static void
4824 handle_local_tunnel_buffer (void *cls, struct GNUNET_SERVER_Client *client,
4825                             const struct GNUNET_MessageHeader *message)
4826 {
4827   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
4828   struct MeshClient *c;
4829   struct MeshTunnel *t;
4830   MESH_TunnelNumber tid;
4831
4832   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4833               "Got a BUFFER request from client!\n");
4834
4835   /* Sanity check for client registration */
4836   if (NULL == (c = client_get (client)))
4837   {
4838     GNUNET_break (0);
4839     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4840     return;
4841   }
4842   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
4843
4844   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
4845
4846   /* Retrieve tunnel */
4847   tid = ntohl (tunnel_msg->tunnel_id);
4848   t = tunnel_get_by_local_id(c, tid);
4849   if (NULL == t)
4850   {
4851     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  tunnel %X not found\n", tid);
4852     GNUNET_break (0);
4853     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4854     return;
4855   }
4856
4857   switch (ntohs(message->type))
4858   {
4859       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_BUFFER:
4860           t->nobuffer = GNUNET_NO;
4861           break;
4862       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_NOBUFFER:
4863           t->nobuffer = GNUNET_YES;
4864           break;
4865       default:
4866           GNUNET_break (0);
4867   }
4868
4869   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4870 }
4871
4872
4873 /**
4874  * Handler for client traffic directed to one peer
4875  *
4876  * @param cls closure
4877  * @param client identification of the client
4878  * @param message the actual message
4879  */
4880 static void
4881 handle_local_unicast (void *cls, struct GNUNET_SERVER_Client *client,
4882                       const struct GNUNET_MessageHeader *message)
4883 {
4884   struct MeshClient *c;
4885   struct MeshTunnel *t;
4886   struct GNUNET_MESH_Unicast *data_msg;
4887   MESH_TunnelNumber tid;
4888   size_t size;
4889
4890   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4891               "Got a unicast request from a client!\n");
4892
4893   /* Sanity check for client registration */
4894   if (NULL == (c = client_get (client)))
4895   {
4896     GNUNET_break (0);
4897     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4898     return;
4899   }
4900   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
4901
4902   data_msg = (struct GNUNET_MESH_Unicast *) message;
4903
4904   /* Sanity check for message size */
4905   size = ntohs (message->size);
4906   if (sizeof (struct GNUNET_MESH_Unicast) +
4907       sizeof (struct GNUNET_MessageHeader) > size)
4908   {
4909     GNUNET_break (0);
4910     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4911     return;
4912   }
4913
4914   /* Tunnel exists? */
4915   tid = ntohl (data_msg->tid);
4916   t = tunnel_get_by_local_id (c, tid);
4917   if (NULL == t)
4918   {
4919     GNUNET_break (0);
4920     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4921     return;
4922   }
4923
4924   /*  Is it a local tunnel? Then, does client own the tunnel? */
4925   if (t->owner->handle != client)
4926   {
4927     GNUNET_break (0);
4928     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4929     return;
4930   }
4931
4932   /* PID should be as expected: client<->service communication */
4933   if (ntohl (data_msg->pid) != t->prev_fc.last_pid_recv + 1)
4934   {
4935     GNUNET_break (0);
4936     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4937               "Unicast PID, expected %u, got %u\n",
4938               t->prev_fc.last_pid_recv + 1, ntohl (data_msg->pid));
4939     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4940     return;
4941   }
4942
4943   /* Ok, everything is correct, send the message
4944    * (pretend we got it from a mesh peer)
4945    */
4946   {
4947     /* Work around const limitation */
4948     char buf[ntohs (message->size)] GNUNET_ALIGN;
4949     struct GNUNET_MESH_Unicast *copy;
4950
4951     copy = (struct GNUNET_MESH_Unicast *) buf;
4952     memcpy (buf, data_msg, size);
4953     copy->oid = my_full_id;
4954     copy->tid = htonl (t->id.tid);
4955     copy->ttl = htonl (default_ttl);
4956     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4957                 "  calling generic handler...\n");
4958     handle_mesh_data_unicast (NULL, &my_full_id, &copy->header);
4959   }
4960   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "receive done OK\n");
4961   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4962
4963   return;
4964 }
4965
4966
4967 /**
4968  * Handler for client traffic directed to the origin
4969  *
4970  * @param cls closure
4971  * @param client identification of the client
4972  * @param message the actual message
4973  */
4974 static void
4975 handle_local_to_origin (void *cls, struct GNUNET_SERVER_Client *client,
4976                         const struct GNUNET_MessageHeader *message)
4977 {
4978   struct GNUNET_MESH_ToOrigin *data_msg;
4979   struct MeshTunnelClientInfo *clinfo;
4980   struct MeshClient *c;
4981   struct MeshTunnel *t;
4982   MESH_TunnelNumber tid;
4983   size_t size;
4984
4985   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4986               "Got a ToOrigin request from a client!\n");
4987   /* Sanity check for client registration */
4988   if (NULL == (c = client_get (client)))
4989   {
4990     GNUNET_break (0);
4991     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4992     return;
4993   }
4994   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
4995
4996   data_msg = (struct GNUNET_MESH_ToOrigin *) message;
4997
4998   /* Sanity check for message size */
4999   size = ntohs (message->size);
5000   if (sizeof (struct GNUNET_MESH_ToOrigin) +
5001       sizeof (struct GNUNET_MessageHeader) > size)
5002   {
5003     GNUNET_break (0);
5004     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5005     return;
5006   }
5007
5008   /* Tunnel exists? */
5009   tid = ntohl (data_msg->tid);
5010   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", tid);
5011   if (tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
5012   {
5013     GNUNET_break (0);
5014     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5015     return;
5016   }
5017   t = tunnel_get_by_local_id (c, tid);
5018   if (NULL == t)
5019   {
5020     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Tunnel %X unknown.\n", tid);
5021     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  for client %u.\n", c->id);
5022     GNUNET_break (0);
5023     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5024     return;
5025   }
5026
5027   /*  It should be sent by someone who has this as incoming tunnel. */
5028   if (GNUNET_NO == client_knows_tunnel (c, t))
5029   {
5030     GNUNET_break (0);
5031     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5032     return;
5033   }
5034
5035   /* PID should be as expected */
5036   clinfo = tunnel_get_client_fc (t, c);
5037   if (ntohl (data_msg->pid) != clinfo->bck_pid + 1)
5038   {
5039     GNUNET_break (0);
5040     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5041                 "To Origin PID, expected %u, got %u\n",
5042                 clinfo->bck_pid + 1,
5043                 ntohl (data_msg->pid));
5044     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5045     return;
5046   }
5047   clinfo->bck_pid++;
5048
5049   /* Ok, everything is correct, send the message
5050    * (pretend we got it from a mesh peer)
5051    */
5052   {
5053     char buf[ntohs (message->size)] GNUNET_ALIGN;
5054     struct GNUNET_MESH_ToOrigin *copy;
5055
5056     /* Work around 'const' limitation */
5057     copy = (struct GNUNET_MESH_ToOrigin *) buf;
5058     memcpy (buf, data_msg, size);
5059     GNUNET_PEER_resolve (t->id.oid, &copy->oid);
5060     copy->tid = htonl (t->id.tid);
5061     copy->ttl = htonl (default_ttl);
5062     copy->pid = htonl (t->prev_fc.last_pid_sent + 1);
5063
5064     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5065                 "  calling generic handler...\n");
5066     handle_mesh_data_to_orig (NULL, &my_full_id, &copy->header);
5067   }
5068   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5069
5070   return;
5071 }
5072
5073
5074 /**
5075  * Handler for client's ACKs for payload traffic.
5076  *
5077  * @param cls Closure (unused).
5078  * @param client Identification of the client.
5079  * @param message The actual message.
5080  */
5081 static void
5082 handle_local_ack (void *cls, struct GNUNET_SERVER_Client *client,
5083                   const struct GNUNET_MessageHeader *message)
5084 {
5085   struct GNUNET_MESH_LocalAck *msg;
5086   struct MeshTunnel *t;
5087   struct MeshClient *c;
5088   MESH_TunnelNumber tid;
5089   uint32_t ack;
5090
5091   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a local ACK\n");
5092   /* Sanity check for client registration */
5093   if (NULL == (c = client_get (client)))
5094   {
5095     GNUNET_break (0);
5096     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5097     return;
5098   }
5099   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
5100
5101   msg = (struct GNUNET_MESH_LocalAck *) message;
5102
5103   /* Tunnel exists? */
5104   tid = ntohl (msg->tunnel_id);
5105   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", tid);
5106   t = tunnel_get_by_local_id (c, tid);
5107   if (NULL == t)
5108   {
5109     GNUNET_break (0);
5110     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Tunnel %X unknown.\n", tid);
5111     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  for client %u.\n", c->id);
5112     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5113     return;
5114   }
5115
5116   ack = ntohl (msg->max_pid);
5117   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ack %u\n", ack);
5118
5119   /* Does client own tunnel? I.E: Is this an ACK for BCK traffic? */
5120   if (NULL != t->owner && t->owner->handle == client)
5121   {
5122     /* The client owns the tunnel, ACK is for data to_origin, send BCK ACK. */
5123     t->next_fc.last_ack_sent = ack;
5124     tunnel_send_bck_ack(t, GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
5125   }
5126   else
5127   {
5128     /* The client doesn't own the tunnel, this ACK is for FWD traffic. */
5129     tunnel_set_client_fwd_ack (t, c, ack);
5130     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
5131   }
5132
5133   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5134
5135   return;
5136 }
5137
5138
5139
5140 /**
5141  * Iterator over all tunnels to send a monitoring client info about each tunnel.
5142  *
5143  * @param cls Closure (client handle).
5144  * @param key Key (hashed tunnel ID, unused).
5145  * @param value Tunnel info.
5146  *
5147  * @return GNUNET_YES, to keep iterating.
5148  */
5149 static int
5150 monitor_all_tunnels_iterator (void *cls,
5151                               const struct GNUNET_HashCode * key,
5152                               void *value)
5153 {
5154   struct GNUNET_SERVER_Client *client = cls;
5155   struct MeshTunnel *t = value;
5156   struct GNUNET_MESH_LocalMonitor *msg;
5157
5158   msg = GNUNET_malloc (sizeof(struct GNUNET_MESH_LocalMonitor));
5159   GNUNET_PEER_resolve(t->id.oid, &msg->owner);
5160   msg->tunnel_id = htonl (t->id.tid);
5161   msg->header.size = htons (sizeof (struct GNUNET_MESH_LocalMonitor));
5162   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS);
5163   GNUNET_PEER_resolve (t->dest, &msg->destination);
5164
5165   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5166               "*  sending info about tunnel %s [%u]\n",
5167               GNUNET_i2s (&msg->owner), t->id.tid);
5168
5169   GNUNET_SERVER_notification_context_unicast (nc, client,
5170                                               &msg->header, GNUNET_NO);
5171   return GNUNET_YES;
5172 }
5173
5174
5175 /**
5176  * Handler for client's MONITOR request.
5177  *
5178  * @param cls Closure (unused).
5179  * @param client Identification of the client.
5180  * @param message The actual message.
5181  */
5182 static void
5183 handle_local_get_tunnels (void *cls, struct GNUNET_SERVER_Client *client,
5184                           const struct GNUNET_MessageHeader *message)
5185 {
5186   struct MeshClient *c;
5187
5188   /* Sanity check for client registration */
5189   if (NULL == (c = client_get (client)))
5190   {
5191     GNUNET_break (0);
5192     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5193     return;
5194   }
5195
5196   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5197               "Received get tunnels request from client %u\n",
5198               c->id);
5199   GNUNET_CONTAINER_multihashmap_iterate (tunnels,
5200                                          monitor_all_tunnels_iterator,
5201                                          client);
5202   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5203               "Get tunnels request from client %u completed\n",
5204               c->id);
5205   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5206 }
5207
5208
5209 /**
5210  * Handler for client's MONITOR_TUNNEL request.
5211  *
5212  * @param cls Closure (unused).
5213  * @param client Identification of the client.
5214  * @param message The actual message.
5215  */
5216 static void
5217 handle_local_show_tunnel (void *cls, struct GNUNET_SERVER_Client *client,
5218                           const struct GNUNET_MessageHeader *message)
5219 {
5220   const struct GNUNET_MESH_LocalMonitor *msg;
5221   struct GNUNET_MESH_LocalMonitor *resp;
5222   struct MeshClient *c;
5223   struct MeshTunnel *t;
5224
5225   /* Sanity check for client registration */
5226   if (NULL == (c = client_get (client)))
5227   {
5228     GNUNET_break (0);
5229     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5230     return;
5231   }
5232
5233   msg = (struct GNUNET_MESH_LocalMonitor *) message;
5234   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5235               "Received tunnel info request from client %u for tunnel %s[%X]\n",
5236               c->id,
5237               &msg->owner,
5238               ntohl (msg->tunnel_id));
5239   t = tunnel_get (&msg->owner, ntohl (msg->tunnel_id));
5240   if (NULL == t)
5241   {
5242     /* We don't know the tunnel FIXME */
5243     struct GNUNET_MESH_LocalMonitor warn;
5244
5245     warn = *msg;
5246     GNUNET_SERVER_notification_context_unicast (nc, client,
5247                                                 &warn.header,
5248                                                 GNUNET_NO);
5249     GNUNET_SERVER_receive_done (client, GNUNET_OK);
5250     return;
5251   }
5252
5253   /* Initialize context */
5254   resp = GNUNET_malloc (sizeof (struct GNUNET_MESH_LocalMonitor));
5255   *resp = *msg;
5256   GNUNET_PEER_resolve (t->dest, &resp->destination);
5257   resp->header.size = htons (sizeof (struct GNUNET_MESH_LocalMonitor));
5258   GNUNET_SERVER_notification_context_unicast (nc, c->handle,
5259                                               &resp->header, GNUNET_NO);
5260   GNUNET_free (resp);
5261
5262   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5263               "Monitor tunnel request from client %u completed\n",
5264               c->id);
5265   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5266 }
5267
5268
5269 /**
5270  * Functions to handle messages from clients
5271  */
5272 static struct GNUNET_SERVER_MessageHandler client_handlers[] = {
5273   {&handle_local_new_client, NULL,
5274    GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT, 0},
5275   {&handle_local_tunnel_create, NULL,
5276    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE,
5277    sizeof (struct GNUNET_MESH_TunnelMessage)},
5278   {&handle_local_tunnel_destroy, NULL,
5279    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY,
5280    sizeof (struct GNUNET_MESH_TunnelMessage)},
5281   {&handle_local_tunnel_buffer, NULL,
5282    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_BUFFER,
5283    sizeof (struct GNUNET_MESH_TunnelMessage)},
5284   {&handle_local_tunnel_buffer, NULL,
5285    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_NOBUFFER,
5286    sizeof (struct GNUNET_MESH_TunnelMessage)},
5287   {&handle_local_unicast, NULL,
5288    GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
5289   {&handle_local_to_origin, NULL,
5290    GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
5291   {&handle_local_ack, NULL,
5292    GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK,
5293    sizeof (struct GNUNET_MESH_LocalAck)},
5294   {&handle_local_get_tunnels, NULL,
5295    GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS,
5296    sizeof (struct GNUNET_MessageHeader)},
5297   {&handle_local_show_tunnel, NULL,
5298    GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNEL,
5299      sizeof (struct GNUNET_MESH_LocalMonitor)},
5300   {NULL, NULL, 0, 0}
5301 };
5302
5303
5304 /**
5305  * To be called on core init/fail.
5306  *
5307  * @param cls service closure
5308  * @param server handle to the server for this service
5309  * @param identity the public identity of this peer
5310  */
5311 static void
5312 core_init (void *cls, struct GNUNET_CORE_Handle *server,
5313            const struct GNUNET_PeerIdentity *identity)
5314 {
5315   static int i = 0;
5316   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Core init\n");
5317   core_handle = server;
5318   if (0 != memcmp (identity, &my_full_id, sizeof (my_full_id)) ||
5319       NULL == server)
5320   {
5321     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Wrong CORE service\n"));
5322     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5323                 " core id %s\n",
5324                 GNUNET_i2s (identity));
5325     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5326                 " my id %s\n",
5327                 GNUNET_i2s (&my_full_id));
5328     GNUNET_SCHEDULER_shutdown (); // Try gracefully
5329     if (10 < i++)
5330       GNUNET_abort(); // Try harder
5331   }
5332   return;
5333 }
5334
5335
5336 /**
5337  * Method called whenever a given peer connects.
5338  *
5339  * @param cls closure
5340  * @param peer peer identity this notification is about
5341  */
5342 static void
5343 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer)
5344 {
5345   struct MeshPeerInfo *peer_info;
5346   struct MeshPeerPath *path;
5347
5348   DEBUG_CONN ("Peer connected\n");
5349   DEBUG_CONN ("     %s\n", GNUNET_i2s (&my_full_id));
5350   peer_info = peer_get (peer);
5351   if (myid == peer_info->id)
5352   {
5353     DEBUG_CONN ("     (self)\n");
5354     return;
5355   }
5356   else
5357   {
5358     DEBUG_CONN ("     %s\n", GNUNET_i2s (peer));
5359   }
5360   path = path_new (2);
5361   path->peers[0] = myid;
5362   path->peers[1] = peer_info->id;
5363   GNUNET_PEER_change_rc (myid, 1);
5364   GNUNET_PEER_change_rc (peer_info->id, 1);
5365   peer_info_add_path (peer_info, path, GNUNET_YES);
5366   GNUNET_STATISTICS_update (stats, "# peers", 1, GNUNET_NO);
5367   return;
5368 }
5369
5370
5371 /**
5372  * Method called whenever a peer disconnects.
5373  *
5374  * @param cls closure
5375  * @param peer peer identity this notification is about
5376  */
5377 static void
5378 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
5379 {
5380   struct MeshPeerInfo *pi;
5381   struct MeshPeerQueue *q;
5382   struct MeshPeerQueue *n;
5383
5384   DEBUG_CONN ("Peer disconnected\n");
5385   pi = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
5386   if (NULL == pi)
5387   {
5388     GNUNET_break (0);
5389     return;
5390   }
5391   q = pi->queue_head;
5392   while (NULL != q)
5393   {
5394       n = q->next;
5395       /* TODO try to reroute this traffic instead */
5396       queue_destroy(q, GNUNET_YES);
5397       q = n;
5398   }
5399   if (NULL != pi->core_transmit)
5400   {
5401     GNUNET_CORE_notify_transmit_ready_cancel(pi->core_transmit);
5402     pi->core_transmit = NULL;
5403   }
5404     peer_remove_path (pi, pi->id, myid);
5405   if (myid == pi->id)
5406   {
5407     DEBUG_CONN ("     (self)\n");
5408   }
5409   GNUNET_STATISTICS_update (stats, "# peers", -1, GNUNET_NO);
5410   return;
5411 }
5412
5413
5414 /******************************************************************************/
5415 /************************      MAIN FUNCTIONS      ****************************/
5416 /******************************************************************************/
5417
5418 /**
5419  * Iterator over tunnel hash map entries to destroy the tunnel during shutdown.
5420  *
5421  * @param cls closure
5422  * @param key current key code
5423  * @param value value in the hash map
5424  * @return GNUNET_YES if we should continue to iterate,
5425  *         GNUNET_NO if not.
5426  */
5427 static int
5428 shutdown_tunnel (void *cls, const struct GNUNET_HashCode * key, void *value)
5429 {
5430   struct MeshTunnel *t = value;
5431
5432   tunnel_destroy (t);
5433   return GNUNET_YES;
5434 }
5435
5436 /**
5437  * Iterator over peer hash map entries to destroy the tunnel during shutdown.
5438  *
5439  * @param cls closure
5440  * @param key current key code
5441  * @param value value in the hash map
5442  * @return GNUNET_YES if we should continue to iterate,
5443  *         GNUNET_NO if not.
5444  */
5445 static int
5446 shutdown_peer (void *cls, const struct GNUNET_HashCode * key, void *value)
5447 {
5448   struct MeshPeerInfo *p = value;
5449   struct MeshPeerQueue *q;
5450   struct MeshPeerQueue *n;
5451
5452   q = p->queue_head;
5453   while (NULL != q)
5454   {
5455       n = q->next;
5456       if (q->peer == p)
5457       {
5458         queue_destroy(q, GNUNET_YES);
5459       }
5460       q = n;
5461   }
5462   peer_info_destroy (p);
5463   return GNUNET_YES;
5464 }
5465
5466
5467 /**
5468  * Task run during shutdown.
5469  *
5470  * @param cls unused
5471  * @param tc unused
5472  */
5473 static void
5474 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
5475 {
5476   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shutting down\n");
5477
5478   if (core_handle != NULL)
5479   {
5480     GNUNET_CORE_disconnect (core_handle);
5481     core_handle = NULL;
5482   }
5483   if (NULL != keygen)
5484   {
5485     GNUNET_CRYPTO_ecc_key_create_stop (keygen);
5486     keygen = NULL;
5487   }
5488   GNUNET_CONTAINER_multihashmap_iterate (tunnels, &shutdown_tunnel, NULL);
5489   GNUNET_CONTAINER_multihashmap_iterate (peers, &shutdown_peer, NULL);
5490   if (dht_handle != NULL)
5491   {
5492     GNUNET_DHT_disconnect (dht_handle);
5493     dht_handle = NULL;
5494   }
5495   if (nc != NULL)
5496   {
5497     GNUNET_SERVER_notification_context_destroy (nc);
5498     nc = NULL;
5499   }
5500   if (GNUNET_SCHEDULER_NO_TASK != announce_id_task)
5501   {
5502     GNUNET_SCHEDULER_cancel (announce_id_task);
5503     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
5504   }
5505   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shut down\n");
5506 }
5507
5508
5509 /**
5510  * Callback for hostkey read/generation.
5511  *
5512  * @param cls Closure (Configuration handle).
5513  * @param pk The ECC private key.
5514  * @param emsg Error message, if any.
5515  */
5516 static void
5517 key_generation_cb (void *cls,
5518                    struct GNUNET_CRYPTO_EccPrivateKey *pk,
5519                    const char *emsg)
5520 {
5521   const struct GNUNET_CONFIGURATION_Handle *c = cls;
5522   struct MeshPeerInfo *peer;
5523   struct MeshPeerPath *p;
5524
5525   keygen = NULL;  
5526   if (NULL == pk)
5527   {
5528     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5529                 _("Mesh service could not access hostkey: %s. Exiting.\n"),
5530                 emsg);
5531     GNUNET_SCHEDULER_shutdown ();
5532     return;
5533   }
5534   my_private_key = pk;
5535   GNUNET_CRYPTO_ecc_key_get_public (my_private_key, &my_public_key);
5536   GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
5537                       &my_full_id.hashPubKey);
5538   myid = GNUNET_PEER_intern (&my_full_id);
5539   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5540               "Mesh for peer [%s] starting\n",
5541               GNUNET_i2s(&my_full_id));
5542
5543   core_handle = GNUNET_CORE_connect (c, /* Main configuration */
5544                                      NULL,      /* Closure passed to MESH functions */
5545                                      &core_init,        /* Call core_init once connected */
5546                                      &core_connect,     /* Handle connects */
5547                                      &core_disconnect,  /* remove peers on disconnects */
5548                                      NULL,      /* Don't notify about all incoming messages */
5549                                      GNUNET_NO, /* For header only in notification */
5550                                      NULL,      /* Don't notify about all outbound messages */
5551                                      GNUNET_NO, /* For header-only out notification */
5552                                      core_handlers);    /* Register these handlers */
5553   
5554   if (core_handle == NULL)
5555   {
5556     GNUNET_break (0);
5557     GNUNET_SCHEDULER_shutdown ();
5558     return;
5559   }
5560
5561   next_tid = 0;
5562   next_local_tid = GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
5563
5564
5565   GNUNET_SERVER_add_handlers (server_handle, client_handlers);
5566   nc = GNUNET_SERVER_notification_context_create (server_handle, 1);
5567   GNUNET_SERVER_disconnect_notify (server_handle,
5568                                    &handle_local_client_disconnect, NULL);
5569
5570
5571   clients_head = NULL;
5572   clients_tail = NULL;
5573   next_client_id = 0;
5574
5575   announce_id_task = GNUNET_SCHEDULER_add_now (&announce_id, cls);
5576
5577   /* Create a peer_info for the local peer */
5578   peer = peer_get (&my_full_id);
5579   p = path_new (1);
5580   p->peers[0] = myid;
5581   GNUNET_PEER_change_rc (myid, 1);
5582   peer_info_add_path (peer, p, GNUNET_YES);
5583   GNUNET_SERVER_resume (server_handle);
5584   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Mesh service running\n");
5585 }
5586
5587
5588 /**
5589  * Process mesh requests.
5590  *
5591  * @param cls closure
5592  * @param server the initialized server
5593  * @param c configuration to use
5594  */
5595 static void
5596 run (void *cls, struct GNUNET_SERVER_Handle *server,
5597      const struct GNUNET_CONFIGURATION_Handle *c)
5598 {
5599   char *keyfile;
5600
5601   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "starting to run\n");
5602   server_handle = server;
5603
5604   if (GNUNET_OK !=
5605       GNUNET_CONFIGURATION_get_value_filename (c, "PEER", "PRIVATE_KEY",
5606                                                &keyfile))
5607   {
5608     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5609                 _
5610                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
5611                 "mesh", "peer/privatekey");
5612     GNUNET_SCHEDULER_shutdown ();
5613     return;
5614   }
5615
5616   if (GNUNET_OK !=
5617       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "REFRESH_PATH_TIME",
5618                                            &refresh_path_time))
5619   {
5620     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5621                 _
5622                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
5623                 "mesh", "refresh path time");
5624     GNUNET_SCHEDULER_shutdown ();
5625     return;
5626   }
5627
5628   if (GNUNET_OK !=
5629       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "ID_ANNOUNCE_TIME",
5630                                            &id_announce_time))
5631   {
5632     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5633                 _
5634                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
5635                 "mesh", "id announce time");
5636     GNUNET_SCHEDULER_shutdown ();
5637     return;
5638   }
5639
5640   if (GNUNET_OK !=
5641       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "CONNECT_TIMEOUT",
5642                                            &connect_timeout))
5643   {
5644     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5645                 _
5646                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
5647                 "mesh", "connect timeout");
5648     GNUNET_SCHEDULER_shutdown ();
5649     return;
5650   }
5651
5652   if (GNUNET_OK !=
5653       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_MSGS_QUEUE",
5654                                              &max_msgs_queue))
5655   {
5656     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5657                 _
5658                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
5659                 "mesh", "max msgs queue");
5660     GNUNET_SCHEDULER_shutdown ();
5661     return;
5662   }
5663
5664   if (GNUNET_OK !=
5665       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_TUNNELS",
5666                                              &max_tunnels))
5667   {
5668     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5669                 _
5670                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
5671                 "mesh", "max tunnels");
5672     GNUNET_SCHEDULER_shutdown ();
5673     return;
5674   }
5675
5676   if (GNUNET_OK !=
5677       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DEFAULT_TTL",
5678                                              &default_ttl))
5679   {
5680     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5681                 _
5682                 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
5683                 "mesh", "default ttl", 64);
5684     default_ttl = 64;
5685   }
5686
5687   if (GNUNET_OK !=
5688       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_PEERS",
5689                                              &max_peers))
5690   {
5691     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5692                 _("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
5693                 "mesh", "max peers", 1000);
5694     max_peers = 1000;
5695   }
5696
5697   if (GNUNET_OK !=
5698       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DHT_REPLICATION_LEVEL",
5699                                              &dht_replication_level))
5700   {
5701     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5702                 _
5703                 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
5704                 "mesh", "dht replication level", 3);
5705     dht_replication_level = 3;
5706   }
5707
5708   tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
5709   incoming_tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
5710   peers = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
5711   types = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
5712
5713   dht_handle = GNUNET_DHT_connect (c, 64);
5714   if (NULL == dht_handle)
5715   {
5716     GNUNET_break (0);
5717   }
5718   stats = GNUNET_STATISTICS_create ("mesh", c);
5719
5720   GNUNET_SERVER_suspend (server_handle);
5721   /* Scheduled the task to clean up when shutdown is called */
5722   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
5723                                 NULL);
5724   keygen = GNUNET_CRYPTO_ecc_key_create_start (keyfile,
5725                                                &key_generation_cb,
5726                                                (void *) c);
5727   GNUNET_free (keyfile);
5728 }
5729
5730
5731 /**
5732  * The main function for the mesh service.
5733  *
5734  * @param argc number of arguments from the command line
5735  * @param argv command line arguments
5736  * @return 0 ok, 1 on error
5737  */
5738 int
5739 main (int argc, char *const *argv)
5740 {
5741   int ret;
5742   int r;
5743
5744   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main()\n");
5745   r = GNUNET_SERVICE_run (argc, argv, "mesh", GNUNET_SERVICE_OPTION_NONE, &run,
5746                           NULL);
5747   ret = (GNUNET_OK == r) ? 0 : 1;
5748   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main() END\n");
5749
5750   INTERVAL_SHOW;
5751
5752   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5753               "Mesh for peer [%s] FWD ACKs %u, BCK ACKs %u\n",
5754               GNUNET_i2s(&my_full_id), debug_fwd_ack, debug_bck_ack);
5755
5756   return ret;
5757 }