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