- adapt path keepalive to unicast (retransmission)
[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                        const struct GNUNET_PeerIdentity *peer,
1434                        struct MeshTunnel *t)
1435 {
1436   struct MeshTransmissionDescriptor *info;
1437   struct MeshPeerInfo *neighbor;
1438   struct MeshPeerPath *p;
1439   size_t size;
1440   uint16_t type;
1441
1442 //   GNUNET_TRANSPORT_try_connect(); FIXME use?
1443
1444   size = ntohs (message->size);
1445   info = GNUNET_malloc (sizeof (struct MeshTransmissionDescriptor));
1446   info->data = GNUNET_malloc (size);
1447   memcpy (info->data, message, size);
1448   type = ntohs(message->type);
1449   switch (type)
1450   {
1451     struct GNUNET_MESH_Unicast *m;
1452     struct GNUNET_MESH_ToOrigin *to;
1453
1454     case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
1455       m = (struct GNUNET_MESH_Unicast *) info->data;
1456       m->ttl = htonl (ntohl (m->ttl) - 1);
1457       break;
1458     case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
1459       to = (struct GNUNET_MESH_ToOrigin *) info->data;
1460       t->bck_pid++;
1461       to->pid = htonl(t->bck_pid);
1462   }
1463   info->data_len = size;
1464   neighbor = peer_get (peer);
1465   for (p = neighbor->path_head; NULL != p; p = p->next)
1466   {
1467     if (2 >= p->length)
1468     {
1469       break;
1470     }
1471   }
1472   if (NULL == p)
1473   {
1474 #if MESH_DEBUG
1475     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1476                 "  %s IS NOT DIRECTLY CONNECTED\n",
1477                 GNUNET_i2s(peer));
1478     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1479                 "  PATHS TO %s:\n",
1480                 GNUNET_i2s(peer));
1481     for (p = neighbor->path_head; NULL != p; p = p->next)
1482     {
1483       struct GNUNET_PeerIdentity debug_id;
1484       unsigned int i;
1485
1486       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1487                   "    path with %u hops through:\n",
1488                   p->length);
1489       for (i = 0; i < p->length; i++)
1490       {
1491         GNUNET_PEER_resolve(p->peers[i], &debug_id);
1492         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1493                     "      hop %u: %s\n",
1494                     i, GNUNET_i2s(&debug_id));
1495       }
1496     }
1497 #endif
1498     GNUNET_break (0); // FIXME sometimes fails (testing disconnect?)
1499     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1500                     " no direct connection to %s\n",
1501                     GNUNET_i2s (peer));
1502     GNUNET_free (info->data);
1503     GNUNET_free (info);
1504     return;
1505   }
1506   info->peer = neighbor;
1507   if (GNUNET_MESSAGE_TYPE_MESH_PATH_ACK == type)
1508     type = 0;
1509   queue_add (info,
1510              type,
1511              size,
1512              neighbor,
1513              t);
1514 }
1515
1516
1517 /**
1518  * Sends a CREATE PATH message for a path to a peer, properly registrating
1519  * all used resources.
1520  *
1521  * @param peer PeerInfo of the final peer for whom this path is being created.
1522  * @param p Path itself.
1523  * @param t Tunnel for which the path is created.
1524  */
1525 static void
1526 send_create_path (struct MeshPeerInfo *peer, struct MeshPeerPath *p,
1527                   struct MeshTunnel *t)
1528 {
1529   struct MeshPeerInfo *neighbor;
1530
1531   if (NULL == p)
1532   {
1533     GNUNET_break (0);
1534     return;
1535   }
1536
1537   neighbor = peer_get_short (t->next_hop);
1538   queue_add (t,
1539              GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE,
1540              sizeof (struct GNUNET_MESH_ManipulatePath) +
1541                 (p->length * sizeof (struct GNUNET_PeerIdentity)),
1542              neighbor,
1543              t);
1544 }
1545
1546
1547 /**
1548  * Sends a PATH ACK message in reponse to a received PATH_CREATE directed to us.
1549  *
1550  * @param t Tunnel which to confirm.
1551  */
1552 static void
1553 send_path_ack (struct MeshTunnel *t) 
1554 {
1555   struct MeshTransmissionDescriptor *info;
1556   struct GNUNET_PeerIdentity id;
1557
1558   GNUNET_PEER_resolve (t->prev_hop, &id);
1559   info = GNUNET_malloc (sizeof (struct MeshTransmissionDescriptor));
1560   info->origin = &t->id;
1561   info->peer = GNUNET_CONTAINER_multihashmap_get (peers, &id.hashPubKey);
1562   GNUNET_assert (NULL != info->peer);
1563
1564   queue_add (info,
1565              GNUNET_MESSAGE_TYPE_MESH_PATH_ACK,
1566              sizeof (struct GNUNET_MESH_PathACK),
1567              info->peer,
1568              t);
1569 }
1570
1571
1572 /**
1573  * Try to establish a new connection to this peer in the fiven tunnel.
1574  * If the peer doesn't have any path to it yet, try to get one.
1575  * If the peer already has some path, send a CREATE PATH towards it.
1576  *
1577  * @param peer PeerInfo of the peer.
1578  * @param t Tunnel for which to create the path, if possible.
1579  */
1580 static void
1581 peer_connect (struct MeshPeerInfo *peer, struct MeshTunnel *t)
1582 {
1583   struct MeshPeerPath *p;
1584
1585   if (NULL != peer->path_head)
1586   {
1587     p = peer_get_best_path (peer, t);
1588     tunnel_use_path (t, p);
1589     send_create_path (peer, p, t);
1590   }
1591   else if (NULL == peer->dhtget)
1592   {
1593     struct GNUNET_PeerIdentity id;
1594
1595     GNUNET_PEER_resolve (peer->id, &id);
1596     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1597                 "  Starting DHT GET for peer %s\n", GNUNET_i2s (&id));
1598     peer->dhtget = GNUNET_DHT_get_start (dht_handle,    /* handle */
1599                                          GNUNET_BLOCK_TYPE_MESH_PEER, /* type */
1600                                          &id.hashPubKey,     /* key to search */
1601                                          dht_replication_level, /* replication level */
1602                                          GNUNET_DHT_RO_RECORD_ROUTE |
1603                                          GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
1604                                          NULL,       /* xquery */
1605                                          0,     /* xquery bits */
1606                                          &dht_get_id_handler, peer);
1607   }
1608   /* Otherwise, there is no path but the DHT get is already started. */
1609 }
1610
1611
1612 /**
1613  * Destroy the peer_info and free any allocated resources linked to it
1614  *
1615  * @param pi The peer_info to destroy.
1616  *
1617  * @return GNUNET_OK on success
1618  */
1619 static int
1620 peer_info_destroy (struct MeshPeerInfo *pi)
1621 {
1622   struct GNUNET_PeerIdentity id;
1623   struct MeshPeerPath *p;
1624   struct MeshPeerPath *nextp;
1625
1626   GNUNET_PEER_resolve (pi->id, &id);
1627   GNUNET_PEER_change_rc (pi->id, -1);
1628
1629   if (GNUNET_YES !=
1630       GNUNET_CONTAINER_multihashmap_remove (peers, &id.hashPubKey, pi))
1631   {
1632     GNUNET_break (0);
1633     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1634                 "removing peer %s, not in hashmap\n", GNUNET_i2s (&id));
1635   }
1636   if (NULL != pi->dhtget)
1637   {
1638     GNUNET_DHT_get_stop (pi->dhtget);
1639   }
1640   p = pi->path_head;
1641   while (NULL != p)
1642   {
1643     nextp = p->next;
1644     GNUNET_CONTAINER_DLL_remove (pi->path_head, pi->path_tail, p);
1645     path_destroy (p);
1646     p = nextp;
1647   }
1648   GNUNET_free (pi);
1649   return GNUNET_OK;
1650 }
1651
1652
1653 /**
1654  * Remove all paths that rely on a direct connection between p1 and p2
1655  * from the peer itself and notify all tunnels about it.
1656  *
1657  * @param peer PeerInfo of affected peer.
1658  * @param p1 GNUNET_PEER_Id of one peer.
1659  * @param p2 GNUNET_PEER_Id of another peer that was connected to the first and
1660  *           no longer is.
1661  *
1662  * TODO: optimize (see below)
1663  */
1664 static void
1665 peer_remove_path (struct MeshPeerInfo *peer, GNUNET_PEER_Id p1,
1666                        GNUNET_PEER_Id p2)
1667 {
1668   struct MeshPeerPath *p;
1669   struct MeshPeerPath *next;
1670   struct MeshPeerInfo *peer_d;
1671   GNUNET_PEER_Id d;
1672   unsigned int destroyed;
1673   unsigned int i;
1674
1675   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "peer_info_remove_path\n");
1676   destroyed = 0;
1677   for (p = peer->path_head; NULL != p; p = next)
1678   {
1679     next = p->next;
1680     for (i = 0; i < (p->length - 1); i++)
1681     {
1682       if ((p->peers[i] == p1 && p->peers[i + 1] == p2) ||
1683           (p->peers[i] == p2 && p->peers[i + 1] == p1))
1684       {
1685         GNUNET_CONTAINER_DLL_remove (peer->path_head, peer->path_tail, p);
1686         path_destroy (p);
1687         destroyed++;
1688         break;
1689       }
1690     }
1691   }
1692   if (0 == destroyed)
1693     return;
1694
1695   for (i = 0; i < peer->ntunnels; i++)
1696   {
1697     d = tunnel_notify_connection_broken (peer->tunnels[i], p1, p2);
1698     if (0 == d)
1699       continue;
1700
1701     peer_d = peer_get_short (d);
1702     next = peer_get_best_path (peer_d, peer->tunnels[i]);
1703     tunnel_use_path (peer->tunnels[i], next);
1704     peer_connect (peer_d, peer->tunnels[i]);
1705   }
1706   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "peer_info_remove_path END\n");
1707 }
1708
1709
1710 /**
1711  * Add the path to the peer and update the path used to reach it in case this
1712  * is the shortest.
1713  *
1714  * @param peer_info Destination peer to add the path to.
1715  * @param path New path to add. Last peer must be the peer in arg 1.
1716  *             Path will be either used of freed if already known.
1717  * @param trusted Do we trust that this path is real?
1718  */
1719 void
1720 peer_info_add_path (struct MeshPeerInfo *peer_info, struct MeshPeerPath *path,
1721                     int trusted)
1722 {
1723   struct MeshPeerPath *aux;
1724   unsigned int l;
1725   unsigned int l2;
1726
1727   if ((NULL == peer_info) || (NULL == path))
1728   {
1729     GNUNET_break (0);
1730     path_destroy (path);
1731     return;
1732   }
1733   if (path->peers[path->length - 1] != peer_info->id)
1734   {
1735     GNUNET_break (0);
1736     path_destroy (path);
1737     return;
1738   }
1739   if (path->length <= 2 && GNUNET_NO == trusted)
1740   {
1741     /* Only allow CORE to tell us about direct paths */
1742     path_destroy (path);
1743     return;
1744   }
1745   GNUNET_assert (peer_info->id == path->peers[path->length - 1]);
1746   for (l = 1; l < path->length; l++)
1747   {
1748     if (path->peers[l] == myid)
1749     {
1750       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shortening path by %u\n", l);
1751       for (l2 = 0; l2 < path->length - l; l2++)
1752       {
1753         path->peers[l2] = path->peers[l + l2];
1754       }
1755       path->length -= l;
1756       l = 1;
1757       path->peers =
1758           GNUNET_realloc (path->peers, path->length * sizeof (GNUNET_PEER_Id));
1759     }
1760   }
1761 #if MESH_DEBUG
1762   {
1763     struct GNUNET_PeerIdentity id;
1764
1765     GNUNET_PEER_resolve (peer_info->id, &id);
1766     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "adding path [%u] to peer %s\n",
1767                 path->length, GNUNET_i2s (&id));
1768   }
1769 #endif
1770   l = path_get_length (path);
1771   if (0 == l)
1772   {
1773     GNUNET_free (path);
1774     return;
1775   }
1776
1777   GNUNET_assert (peer_info->id == path->peers[path->length - 1]);
1778   for (aux = peer_info->path_head; aux != NULL; aux = aux->next)
1779   {
1780     l2 = path_get_length (aux);
1781     if (l2 > l)
1782     {
1783       GNUNET_CONTAINER_DLL_insert_before (peer_info->path_head,
1784                                           peer_info->path_tail, aux, path);
1785       return;
1786     }
1787     else
1788     {
1789       if (l2 == l && memcmp (path->peers, aux->peers, l) == 0)
1790       {
1791         path_destroy (path);
1792         return;
1793       }
1794     }
1795   }
1796   GNUNET_CONTAINER_DLL_insert_tail (peer_info->path_head, peer_info->path_tail,
1797                                     path);
1798   return;
1799 }
1800
1801
1802 /**
1803  * Add the path to the origin peer and update the path used to reach it in case
1804  * this is the shortest.
1805  * The path is given in peer_info -> destination, therefore we turn the path
1806  * upside down first.
1807  *
1808  * @param peer_info Peer to add the path to, being the origin of the path.
1809  * @param path New path to add after being inversed.
1810  * @param trusted Do we trust that this path is real?
1811  */
1812 static void
1813 peer_info_add_path_to_origin (struct MeshPeerInfo *peer_info,
1814                               struct MeshPeerPath *path, int trusted)
1815 {
1816   path_invert (path);
1817   peer_info_add_path (peer_info, path, trusted);
1818 }
1819
1820
1821 /** FIXME
1822  * Function called if the connection to the peer has been stalled for a while,
1823  * possibly due to a missed ACK. Poll the peer about its ACK status.
1824  *
1825  * @param cls Closure (cinfo).
1826  * @param tc TaskContext.
1827  */
1828 static void
1829 tunnel_poll (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1830 {
1831 //   struct GNUNET_MESH_Poll msg;
1832 //   struct GNUNET_PeerIdentity id;
1833 //   struct MeshTunnel *t;
1834
1835 //   cinfo->fc_poll = GNUNET_SCHEDULER_NO_TASK;
1836   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1837   {
1838     return;
1839   }
1840
1841 //   t = cinfo->t;
1842 //   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_POLL);
1843 //   msg.header.size = htons (sizeof (msg));
1844 //   msg.tid = htonl (t->id.tid);
1845 //   GNUNET_PEER_resolve (t->id.oid, &msg.oid);
1846 //   msg.last_ack = htonl (cinfo->fwd_ack);
1847 // 
1848 //   GNUNET_PEER_resolve (cinfo->id, &id);
1849 //   send_prebuilt_message (&msg.header, &id, cinfo->t);
1850 //   cinfo->fc_poll_time = GNUNET_TIME_relative_min (
1851 //     MESH_MAX_POLL_TIME,
1852 //     GNUNET_TIME_relative_multiply (cinfo->fc_poll_time, 2));
1853 //   cinfo->fc_poll = GNUNET_SCHEDULER_add_delayed (cinfo->fc_poll_time,
1854 //                                                  &tunnel_poll, cinfo);
1855 }
1856
1857
1858 /**
1859  * Build a PeerPath from the paths returned from the DHT, reversing the paths
1860  * to obtain a local peer -> destination path and interning the peer ids.
1861  *
1862  * @return Newly allocated and created path
1863  */
1864 static struct MeshPeerPath *
1865 path_build_from_dht (const struct GNUNET_PeerIdentity *get_path,
1866                      unsigned int get_path_length,
1867                      const struct GNUNET_PeerIdentity *put_path,
1868                      unsigned int put_path_length)
1869 {
1870   struct MeshPeerPath *p;
1871   GNUNET_PEER_Id id;
1872   int i;
1873
1874   p = path_new (1);
1875   p->peers[0] = myid;
1876   GNUNET_PEER_change_rc (myid, 1);
1877   i = get_path_length;
1878   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   GET has %d hops.\n", i);
1879   for (i--; i >= 0; i--)
1880   {
1881     id = GNUNET_PEER_intern (&get_path[i]);
1882     if (p->length > 0 && id == p->peers[p->length - 1])
1883     {
1884       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   Optimizing 1 hop out.\n");
1885       GNUNET_PEER_change_rc (id, -1);
1886     }
1887     else
1888     {
1889       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   Adding from GET: %s.\n",
1890                   GNUNET_i2s (&get_path[i]));
1891       p->length++;
1892       p->peers = GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * p->length);
1893       p->peers[p->length - 1] = id;
1894     }
1895   }
1896   i = put_path_length;
1897   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   PUT has %d hops.\n", i);
1898   for (i--; i >= 0; i--)
1899   {
1900     id = GNUNET_PEER_intern (&put_path[i]);
1901     if (id == myid)
1902     {
1903       /* PUT path went through us, so discard the path up until now and start
1904        * from here to get a much shorter (and loop-free) path.
1905        */
1906       path_destroy (p);
1907       p = path_new (0);
1908     }
1909     if (p->length > 0 && id == p->peers[p->length - 1])
1910     {
1911       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   Optimizing 1 hop out.\n");
1912       GNUNET_PEER_change_rc (id, -1);
1913     }
1914     else
1915     {
1916       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   Adding from PUT: %s.\n",
1917                   GNUNET_i2s (&put_path[i]));
1918       p->length++;
1919       p->peers = GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * p->length);
1920       p->peers[p->length - 1] = id;
1921     }
1922   }
1923 #if MESH_DEBUG
1924   if (get_path_length > 0)
1925     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   (first of GET: %s)\n",
1926                 GNUNET_i2s (&get_path[0]));
1927   if (put_path_length > 0)
1928     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   (first of PUT: %s)\n",
1929                 GNUNET_i2s (&put_path[0]));
1930   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   In total: %d hops\n",
1931               p->length);
1932   for (i = 0; i < p->length; i++)
1933   {
1934     struct GNUNET_PeerIdentity peer_id;
1935
1936     GNUNET_PEER_resolve (p->peers[i], &peer_id);
1937     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "       %u: %s\n", p->peers[i],
1938                 GNUNET_i2s (&peer_id));
1939   }
1940 #endif
1941   return p;
1942 }
1943
1944
1945 /**
1946  * Adds a path to the peer_infos of all the peers in the path
1947  *
1948  * @param p Path to process.
1949  * @param confirmed Whether we know if the path works or not.
1950  */
1951 static void
1952 path_add_to_peers (struct MeshPeerPath *p, int confirmed)
1953 {
1954   unsigned int i;
1955
1956   /* TODO: invert and add */
1957   for (i = 0; i < p->length && p->peers[i] != myid; i++) /* skip'em */ ;
1958   for (i++; i < p->length; i++)
1959   {
1960     struct MeshPeerInfo *aux;
1961     struct MeshPeerPath *copy;
1962
1963     aux = peer_get_short (p->peers[i]);
1964     copy = path_duplicate (p);
1965     copy->length = i + 1;
1966     peer_info_add_path (aux, copy, GNUNET_NO);
1967   }
1968 }
1969
1970
1971 /**
1972  * Send keepalive packets for a peer
1973  *
1974  * @param cls Closure (tunnel for which to send the keepalive).
1975  * @param tc Notification context.
1976  */
1977 static void
1978 path_refresh (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
1979
1980
1981 /**
1982  * Search for a tunnel among the incoming tunnels
1983  *
1984  * @param tid the local id of the tunnel
1985  *
1986  * @return tunnel handler, NULL if doesn't exist
1987  */
1988 static struct MeshTunnel *
1989 tunnel_get_incoming (MESH_TunnelNumber tid)
1990 {
1991   struct GNUNET_HashCode hash;
1992
1993   GNUNET_assert (tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV);
1994   GNUNET_CRYPTO_hash (&tid, sizeof (MESH_TunnelNumber), &hash);
1995   return GNUNET_CONTAINER_multihashmap_get (incoming_tunnels, &hash);
1996 }
1997
1998
1999 /**
2000  * Search for a tunnel among the tunnels for a client
2001  *
2002  * @param c the client whose tunnels to search in
2003  * @param tid the local id of the tunnel
2004  *
2005  * @return tunnel handler, NULL if doesn't exist
2006  */
2007 static struct MeshTunnel *
2008 tunnel_get_by_local_id (struct MeshClient *c, MESH_TunnelNumber tid)
2009 {
2010   if (tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
2011   {
2012     return tunnel_get_incoming (tid);
2013   }
2014   else
2015   {
2016     struct GNUNET_HashCode hash;
2017
2018     GNUNET_CRYPTO_hash (&tid, sizeof (MESH_TunnelNumber), &hash);
2019     return GNUNET_CONTAINER_multihashmap_get (c->own_tunnels, &hash);
2020   }
2021 }
2022
2023
2024 /**
2025  * Search for a tunnel by global ID using PEER_ID
2026  *
2027  * @param pi owner of the tunnel
2028  * @param tid global tunnel number
2029  *
2030  * @return tunnel handler, NULL if doesn't exist
2031  */
2032 static struct MeshTunnel *
2033 tunnel_get_by_pi (GNUNET_PEER_Id pi, MESH_TunnelNumber tid)
2034 {
2035   struct MESH_TunnelID id;
2036   struct GNUNET_HashCode hash;
2037
2038   id.oid = pi;
2039   id.tid = tid;
2040
2041   GNUNET_CRYPTO_hash (&id, sizeof (struct MESH_TunnelID), &hash);
2042   return GNUNET_CONTAINER_multihashmap_get (tunnels, &hash);
2043 }
2044
2045
2046 /**
2047  * Search for a tunnel by global ID using full PeerIdentities
2048  *
2049  * @param oid owner of the tunnel
2050  * @param tid global tunnel number
2051  *
2052  * @return tunnel handler, NULL if doesn't exist
2053  */
2054 static struct MeshTunnel *
2055 tunnel_get (const struct GNUNET_PeerIdentity *oid, MESH_TunnelNumber tid)
2056 {
2057   return tunnel_get_by_pi (GNUNET_PEER_search (oid), tid);
2058 }
2059
2060
2061 /**
2062  * Delete an active client from the tunnel.
2063  * 
2064  * @param t Tunnel.
2065  * @param c Client.
2066  */
2067 static void
2068 tunnel_delete_active_client (struct MeshTunnel *t, const struct MeshClient *c)
2069 {
2070   unsigned int i;
2071
2072   for (i = 0; i < t->nclients; i++)
2073   {
2074     if (t->clients[i] == c)
2075     {
2076       t->clients[i] = t->clients[t->nclients - 1];
2077       t->clients_fc[i] = t->clients_fc[t->nclients - 1];
2078       GNUNET_array_grow (t->clients, t->nclients, t->nclients - 1);
2079       t->nclients++;
2080       GNUNET_array_grow (t->clients_fc, t->nclients, t->nclients - 1);
2081       break;
2082     }
2083   }
2084 }
2085
2086
2087 /**
2088  * Delete an ignored client from the tunnel.
2089  * 
2090  * @param t Tunnel.
2091  * @param c Client.
2092  */
2093 static void
2094 tunnel_delete_ignored_client (struct MeshTunnel *t, const struct MeshClient *c)
2095 {
2096   unsigned int i;
2097
2098   for (i = 0; i < t->nignore; i++)
2099   {
2100     if (t->ignore[i] == c)
2101     {
2102       t->ignore[i] = t->ignore[t->nignore - 1];
2103       GNUNET_array_grow (t->ignore, t->nignore, t->nignore - 1);
2104       break;
2105     }
2106   }
2107 }
2108
2109
2110 /**
2111  * Delete a client from the tunnel. It should be only done on
2112  * client disconnection, otherwise use client_ignore_tunnel.
2113  * 
2114  * @param t Tunnel.
2115  * @param c Client.
2116  */
2117 static void
2118 tunnel_delete_client (struct MeshTunnel *t, const struct MeshClient *c)
2119 {
2120   tunnel_delete_ignored_client (t, c);
2121   tunnel_delete_active_client (t, c);
2122 }
2123
2124
2125 static void
2126 tunnel_add_client (struct MeshTunnel *t, struct MeshClient *c)
2127 {
2128   struct MeshTunnelClientInfo clinfo;
2129
2130   GNUNET_array_append (t->clients, t->nclients, c);
2131   clinfo.fwd_ack = t->fwd_pid + 1;
2132   clinfo.bck_ack = t->nobuffer ? 1 : INITIAL_WINDOW_SIZE - 1;
2133   clinfo.fwd_pid = t->fwd_pid;
2134   clinfo.bck_pid = (uint32_t) -1; // Expected next: 0
2135   t->nclients--;
2136   GNUNET_array_append (t->clients_fc, t->nclients, clinfo);
2137 }
2138
2139
2140 static void
2141 tunnel_use_path (struct MeshTunnel *t, struct MeshPeerPath *p)
2142 {
2143   unsigned int i;
2144
2145   for (i = 0; i < p->length; i++)
2146   {
2147     if (p->peers[i] == myid)
2148       break;
2149   }
2150   if (i > p->length - 1)
2151   {
2152     GNUNET_break (0);
2153     return;
2154   }
2155
2156   if (i < p->length - 1)
2157     t->next_hop = p->peers[i + 1];
2158   else
2159     t->next_hop = 0;
2160   if (0 < i)
2161     t->prev_hop = p->peers[i - 1];
2162   else
2163     t->prev_hop = 0;
2164
2165   if (NULL != t->path)
2166     path_destroy (t->path);
2167   t->path = path_duplicate (p);
2168   if (GNUNET_SCHEDULER_NO_TASK == t->path_refresh_task)
2169     t->path_refresh_task =
2170         GNUNET_SCHEDULER_add_delayed (refresh_path_time, &path_refresh, t);
2171 }
2172
2173
2174 /**
2175  * Notifies a tunnel that a connection has broken that affects at least
2176  * some of its peers. Sends a notification towards the root of the tree.
2177  * In case the peer is the owner of the tree, notifies the client that owns
2178  * the tunnel and tries to reconnect.
2179  *
2180  * @param t Tunnel affected.
2181  * @param p1 Peer that got disconnected from p2.
2182  * @param p2 Peer that got disconnected from p1.
2183  *
2184  * @return Short ID of the peer disconnected (either p1 or p2).
2185  *         0 if the tunnel remained unaffected.
2186  */
2187 static GNUNET_PEER_Id
2188 tunnel_notify_connection_broken (struct MeshTunnel *t, GNUNET_PEER_Id p1,
2189                                  GNUNET_PEER_Id p2)
2190 {
2191 //   if (myid != p1 && myid != p2) FIXME
2192 //   {
2193 //     return;
2194 //   }
2195 // 
2196 //   if (tree_get_predecessor (t->tree) != 0)
2197 //   {
2198 //     /* We are the peer still connected, notify owner of the disconnection. */
2199 //     struct GNUNET_MESH_PathBroken msg;
2200 //     struct GNUNET_PeerIdentity neighbor;
2201 // 
2202 //     msg.header.size = htons (sizeof (msg));
2203 //     msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN);
2204 //     GNUNET_PEER_resolve (t->id.oid, &msg.oid);
2205 //     msg.tid = htonl (t->id.tid);
2206 //     msg.peer1 = my_full_id;
2207 //     GNUNET_PEER_resolve (pid, &msg.peer2);
2208 //     GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &neighbor);
2209 //     send_prebuilt_message (&msg.header, &neighbor, t);
2210 //   }
2211   return 0;
2212 }
2213
2214
2215 /**
2216  * Get the Flow Control info of a client.
2217  * 
2218  * @param t Tunnel on which to look.
2219  * @param c Client whose ACK to get.
2220  * 
2221  * @return ACK value.
2222  */
2223 static struct MeshTunnelClientInfo *
2224 tunnel_get_client_fc (struct MeshTunnel *t,
2225                       struct MeshClient *c)
2226 {
2227   unsigned int i;
2228
2229   for (i = 0; i < t->nclients; i++)
2230   {
2231     if (t->clients[i] != c)
2232       continue;
2233     return &t->clients_fc[i];
2234   }
2235   GNUNET_assert (0);
2236   return NULL; // avoid compiler / coverity complaints
2237 }
2238
2239
2240 /**
2241  * Set the FWD ACK value of a client in a particular tunnel.
2242  * 
2243  * @param t Tunnel affected.
2244  * @param c Client whose ACK to set.
2245  * @param ack ACK value.
2246  */
2247 static void
2248 tunnel_set_client_fwd_ack (struct MeshTunnel *t,
2249                            struct MeshClient *c, 
2250                            uint32_t ack)
2251 {
2252   unsigned int i;
2253
2254   for (i = 0; i < t->nclients; i++)
2255   {
2256     if (t->clients[i] != c)
2257       continue;
2258     t->clients_fc[i].fwd_ack = ack;
2259     return;
2260   }
2261   GNUNET_break (0);
2262 }
2263
2264
2265 /**
2266  * Get the highest ACK value of all clients in a particular tunnel,
2267  * according to the buffering/speed settings.
2268  * 
2269  * @param t Tunnel on which to look.
2270  * 
2271  * @return Corresponding ACK value (max uint32_t).
2272  *         If no clients are suscribed, -1LL.
2273  */
2274 static int64_t
2275 tunnel_get_clients_fwd_ack (struct MeshTunnel *t)
2276 {
2277   unsigned int i;
2278   int64_t ack;
2279
2280   if (0 == t->nclients)
2281   {
2282     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2283                 "  tunnel has no clients, no FWD ACK\n");
2284     return -1LL;
2285   }
2286
2287   for (ack = -1LL, i = 0; i < t->nclients; i++)
2288   {
2289     if (-1LL == ack ||
2290         GNUNET_YES == GMC_is_pid_bigger (ack, t->clients_fc[i].fwd_ack))
2291     {
2292       ack = t->clients_fc[i].fwd_ack;
2293     }
2294   }
2295
2296   if (GNUNET_YES == t->nobuffer && GMC_is_pid_bigger(ack, t->fwd_pid))
2297     ack = (uint32_t) t->fwd_pid + 1; // Might overflow, it's ok.
2298
2299   return (uint32_t) ack;
2300 }
2301
2302
2303 /** FIXME
2304  * Get the current fwd ack value for a tunnel, taking in account the tunnel
2305  * mode and the status of all children nodes.
2306  *
2307  * @param t Tunnel.
2308  *
2309  * @return Maximum PID allowed.
2310  */
2311 static uint32_t
2312 tunnel_get_fwd_ack (struct MeshTunnel *t)
2313 {
2314   uint32_t ack;
2315   uint32_t count;
2316   uint32_t buffer_free;
2317   int64_t client_ack;
2318
2319   count = t->fwd_pid;
2320   buffer_free = t->fwd_queue_max - t->fwd_queue_n;
2321   client_ack = tunnel_get_clients_fwd_ack (t);
2322   if (GNUNET_YES == t->nobuffer)
2323   {
2324     ack = count;
2325   }
2326   else
2327   {
2328     ack = count + buffer_free; // Overflow? OK!
2329   }
2330   if (-1LL == client_ack)
2331   {
2332     client_ack = ack;
2333   }
2334   /* FIXME check */
2335   ack = GMC_max_pid ((uint32_t) client_ack, ack);
2336
2337   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2338               "c %u, bf %u, cl %lld, ACK: %u\n",
2339               count, buffer_free, client_ack, ack);
2340   return ack;
2341 }
2342
2343
2344 /**
2345  * Build a local ACK message and send it to a local client.
2346  * 
2347  * @param t Tunnel on which to send the ACK.
2348  * @param c Client to whom send the ACK.
2349  * @param ack Value of the ACK.
2350  */
2351 static void
2352 send_local_ack (struct MeshTunnel *t, struct MeshClient *c, uint32_t ack)
2353 {
2354   struct GNUNET_MESH_LocalAck msg;
2355
2356   msg.header.size = htons (sizeof (msg));
2357   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
2358   msg.tunnel_id = htonl (t->owner == c ? t->local_tid : t->local_tid_dest);
2359   msg.max_pid = htonl (ack); 
2360   GNUNET_SERVER_notification_context_unicast(nc,
2361                                               c->handle,
2362                                               &msg.header,
2363                                               GNUNET_NO);
2364 }
2365
2366 /**
2367  * Build an ACK message and queue it to send to the given peer.
2368  * 
2369  * @param t Tunnel on which to send the ACK.
2370  * @param peer Peer to whom send the ACK.
2371  * @param ack Value of the ACK.
2372  */
2373 static void
2374 send_ack (struct MeshTunnel *t, struct GNUNET_PeerIdentity *peer,  uint32_t ack)
2375 {
2376   struct GNUNET_MESH_ACK msg;
2377
2378   GNUNET_PEER_resolve (t->id.oid, &msg.oid);
2379   msg.header.size = htons (sizeof (msg));
2380   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_ACK);
2381   msg.pid = htonl (ack);
2382   msg.tid = htonl (t->id.tid);
2383
2384   send_prebuilt_message (&msg.header, peer, t);
2385 }
2386
2387
2388 /**
2389  * Notify a the owner of a tunnel about how many more
2390  * payload packages will we accept on a given tunnel.
2391  *
2392  * @param t Tunnel on which to send the ACK.
2393  */
2394 static void
2395 tunnel_send_client_fwd_ack (struct MeshTunnel *t)
2396 {
2397   uint32_t ack;
2398
2399   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2400               "Sending client FWD ACK on tunnel %X\n",
2401               t->local_tid);
2402
2403   ack = tunnel_get_fwd_ack (t);
2404
2405   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ack %u\n", ack);
2406   if (t->last_fwd_ack == ack)
2407   {
2408     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " same as last, not sending!\n");
2409     return;
2410   }
2411
2412   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " sending!\n");
2413   t->last_fwd_ack = ack;
2414   send_local_ack (t, t->owner, ack);
2415 }
2416
2417
2418 /**
2419  * Send an ACK informing the predecessor about the available buffer space.
2420  * In case there is no predecessor, inform the owning client.
2421  * If buffering is off, send only on behalf of children or self if endpoint.
2422  * If buffering is on, send when sent to children and buffer space is free.
2423  * Note that although the name is fwd_ack, the FWD mean forward *traffic*,
2424  * the ACK itself goes "back" (towards root).
2425  * 
2426  * @param t Tunnel on which to send the ACK.
2427  * @param type Type of message that triggered the ACK transmission.
2428  */
2429 static void
2430 tunnel_send_fwd_ack (struct MeshTunnel *t, uint16_t type)
2431 {
2432   struct GNUNET_PeerIdentity id;
2433   uint32_t ack;
2434
2435   if (NULL != t->owner)
2436   {
2437     tunnel_send_client_fwd_ack (t);
2438     return;
2439   }
2440   /* Is it after unicast retransmission? */
2441   switch (type)
2442   {
2443     case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
2444       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2445                   "ACK due to FWD DATA retransmission\n");
2446       if (GNUNET_YES == t->nobuffer)
2447       {
2448         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending ACK, nobuffer\n");
2449         return;
2450       }
2451       break;
2452     case GNUNET_MESSAGE_TYPE_MESH_ACK:
2453     case GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK:
2454       break;
2455     case GNUNET_MESSAGE_TYPE_MESH_POLL:
2456       t->force_ack = GNUNET_YES;
2457       break;
2458     default:
2459       GNUNET_break (0);
2460   }
2461
2462   /* Check if we need to transmit the ACK */
2463   if (t->fwd_queue_max > t->fwd_queue_n * 4 &&
2464       GMC_is_pid_bigger(t->last_fwd_ack, t->fwd_pid) &&
2465       GNUNET_NO == t->force_ack)
2466   {
2467     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending ACK, buffer free\n");
2468     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2469                 "  t->qmax: %u, t->qn: %u\n",
2470                 t->fwd_queue_max, t->fwd_queue_n);
2471     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2472                 "  t->pid: %u, t->ack: %u\n",
2473                 t->fwd_pid, t->last_fwd_ack);
2474     return;
2475   }
2476
2477   /* Ok, ACK might be necessary, what PID to ACK? */
2478   ack = tunnel_get_fwd_ack (t);
2479
2480   /* If speed_min and not all children have ack'd, dont send yet */
2481   if (ack == t->last_fwd_ack && GNUNET_NO == t->force_ack)
2482   {
2483     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Not sending FWD ACK, not ready\n");
2484     return;
2485   }
2486
2487   t->last_fwd_ack = ack;
2488   GNUNET_PEER_resolve (t->prev_hop, &id);
2489   send_ack (t, &id, ack);
2490   debug_fwd_ack++;
2491   t->force_ack = GNUNET_NO;
2492 }
2493
2494
2495 /**
2496  * Send a child node a BCK ACK to allow him to send more to_origin data.
2497  *
2498  * @param t Tunnel.
2499  * @param id Id of the child node.
2500  */
2501 static void
2502 tunnel_send_child_bck_ack (struct MeshTunnel *t,
2503                            GNUNET_PEER_Id id)
2504 {
2505   struct GNUNET_PeerIdentity peer;
2506   uint32_t ack = 0; // FIXME
2507
2508   GNUNET_PEER_resolve (id, &peer);
2509 //   ack = cinfo->bck_pid + t->bck_queue_max - t->bck_queue_n;
2510 // 
2511 //   if (cinfo->bck_ack == ack && GNUNET_NO == t->force_ack)
2512 //   {
2513 //     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2514 //                 "    Not sending ACK, not needed\n");
2515 //     return;
2516 //   }
2517 //   cinfo->bck_ack = ack;
2518 // 
2519 //   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2520 //               "    Sending BCK ACK %u (last sent: %u)\n",
2521 //               ack, cinfo->bck_ack);
2522   send_ack (t, &peer, ack);
2523 }
2524
2525
2526 /**
2527  * @brief Send BCK ACKs to clients to allow them more to_origin traffic
2528  * 
2529  * Iterates over all clients and sends BCK ACKs to the ones that need it.
2530  *
2531  * FIXME fc: what happens if we have 2 clients but q_size is 1?
2532  *           - implement a size 1 buffer in each client_fc AND children_fc
2533  *           to hold at least 1 message per "child".
2534  *             problem: violates no buffer policy
2535  *           - ack 0 and make "children" poll for transmission slots
2536  *             problem: big overhead, extra latency even in low traffic
2537  *                      settings
2538  * 
2539  * @param t Tunnel on which to send the BCK ACKs.
2540  */
2541 static void
2542 tunnel_send_clients_bck_ack (struct MeshTunnel *t)
2543 {
2544   unsigned int i;
2545   unsigned int tunnel_delta;
2546
2547   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Sending BCK ACK to clients\n");
2548
2549   tunnel_delta = t->bck_queue_max - t->bck_queue_n;
2550   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   tunnel delta: %u\n", tunnel_delta);
2551
2552   /* Find client whom to allow to send to origin (with lowest buffer space) */
2553   for (i = 0; i < t->nclients; i++)
2554   {
2555     struct MeshTunnelClientInfo *clinfo;
2556     unsigned int delta;
2557
2558     clinfo = &t->clients_fc[i];
2559     delta = clinfo->bck_ack - clinfo->bck_pid;
2560     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    client %u delta: %u\n",
2561          t->clients[i]->id, delta);
2562
2563     if ((GNUNET_NO == t->nobuffer && tunnel_delta > delta) ||
2564         (GNUNET_YES == t->nobuffer && 0 == delta))
2565     {
2566       uint32_t ack;
2567
2568       ack = clinfo->bck_pid;
2569       ack += t->nobuffer ? 1 : tunnel_delta;
2570       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2571                   "    sending ack to client %u: %u\n",
2572                   t->clients[i]->id, ack);
2573       send_local_ack (t, t->clients[i], ack);
2574       clinfo->bck_ack = ack;
2575     }
2576     else
2577     {
2578       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2579                   "    not sending ack to client %u (td %u, d %u)\n",
2580                   t->clients[i]->id, tunnel_delta, delta);
2581     }
2582   }
2583 }
2584
2585
2586 /**
2587  * Send an ACK informing the children nodes and destination clients about
2588  * the available buffer space.
2589  * If buffering is off, send only on behalf of root (can be self).
2590  * If buffering is on, send when sent to predecessor and buffer space is free.
2591  * Note that although the name is bck_ack, the BCK mean backwards *traffic*,
2592  * the ACK itself goes "forward" (towards children/clients).
2593  * 
2594  * @param t Tunnel on which to send the ACK.
2595  * @param type Type of message that triggered the ACK transmission.
2596  */
2597 static void
2598 tunnel_send_bck_ack (struct MeshTunnel *t, uint16_t type)
2599 {
2600   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2601               "Sending BCK ACK on tunnel %u [%u] due to %s\n",
2602               t->id.oid, t->id.tid, GNUNET_MESH_DEBUG_M2S(type));
2603   /* Is it after data to_origin retransmission? */
2604   switch (type)
2605   {
2606     case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
2607       if (GNUNET_YES == t->nobuffer)
2608       {
2609         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2610                     "    Not sending ACK, nobuffer\n");
2611         return;
2612       }
2613       break;
2614     case GNUNET_MESSAGE_TYPE_MESH_ACK:
2615     case GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK:
2616       break;
2617     case GNUNET_MESSAGE_TYPE_MESH_POLL:
2618       t->force_ack = GNUNET_YES;
2619       break;
2620     default:
2621       GNUNET_break (0);
2622   }
2623
2624   tunnel_send_clients_bck_ack (t);
2625   tunnel_send_child_bck_ack (t, t->next_hop);
2626   t->force_ack = GNUNET_NO;
2627 }
2628
2629
2630 /**
2631  * @brief Re-initiate traffic to this peer if necessary.
2632  *
2633  * Check if there is traffic queued towards this peer
2634  * and the core transmit handle is NULL (traffic was stalled).
2635  * If so, call core tmt rdy.
2636  *
2637  * @param peer_id Short ID of peer to which initiate traffic.
2638  */
2639 static void
2640 peer_unlock_queue(GNUNET_PEER_Id peer_id)
2641 {
2642   struct MeshPeerInfo *peer;
2643   struct GNUNET_PeerIdentity id;
2644   struct MeshPeerQueue *q;
2645   size_t size;
2646
2647   peer = peer_get_short (peer_id);
2648   if (NULL != peer->core_transmit)
2649     return;
2650
2651   q = queue_get_next (peer);
2652   if (NULL == q)
2653   {
2654     /* Might br multicast traffic already sent to this particular peer but
2655      * not to other children in this tunnel.
2656      * This way t->queue_n would be > 0 but the queue of this particular peer
2657      * would be empty.
2658      */
2659     return;
2660   }
2661   size = q->size;
2662   GNUNET_PEER_resolve (peer->id, &id);
2663   peer->core_transmit =
2664         GNUNET_CORE_notify_transmit_ready(core_handle,
2665                                           0,
2666                                           0,
2667                                           GNUNET_TIME_UNIT_FOREVER_REL,
2668                                           &id,
2669                                           size,
2670                                           &queue_send,
2671                                           peer);
2672         return;
2673 }
2674
2675
2676 /**
2677  * Send a message to all peers in this tunnel that the tunnel is no longer
2678  * valid.
2679  *
2680  * @param t The tunnel whose peers to notify.
2681  */
2682 static void
2683 tunnel_send_destroy (struct MeshTunnel *t)
2684 {
2685   struct GNUNET_MESH_TunnelDestroy msg;
2686   struct GNUNET_PeerIdentity id;
2687
2688   msg.header.size = htons (sizeof (msg));
2689   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY);
2690   GNUNET_PEER_resolve (t->id.oid, &msg.oid);
2691   msg.tid = htonl (t->id.tid);
2692   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2693               "  sending tunnel destroy for tunnel: %s [%X]\n",
2694               GNUNET_i2s (&msg.oid), t->id.tid);
2695
2696   if (0 != t->next_hop)
2697   {
2698     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  child: %u\n", t->next_hop);
2699     GNUNET_PEER_resolve (t->next_hop, &id);
2700     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2701                 "  sending back to %s\n",
2702                 GNUNET_i2s (&id));
2703     send_prebuilt_message (&msg.header, &id, t);
2704   }
2705   if (0 != t->prev_hop)
2706   {
2707     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  parent: %u\n", t->prev_hop);
2708     GNUNET_PEER_resolve (t->prev_hop, &id);
2709     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2710                 "  sending back to %s\n",
2711                 GNUNET_i2s (&id));
2712     send_prebuilt_message (&msg.header, &id, t);
2713   }
2714 }
2715
2716
2717 /**
2718  * Cancel all transmissions towards a neighbor that belongs to a certain tunnel.
2719  *
2720  * @param t Tunnel which to cancel.
2721  * @param neighbor Short ID of the neighbor to whom cancel the transmissions.
2722  */
2723 static void
2724 peer_cancel_queues (GNUNET_PEER_Id neighbor, struct MeshTunnel *t)
2725 {
2726   struct MeshPeerInfo *peer_info;
2727   struct MeshPeerQueue *pq;
2728   struct MeshPeerQueue *next;
2729
2730   peer_info = peer_get_short (neighbor);
2731   for (pq = peer_info->queue_head; NULL != pq; pq = next)
2732   {
2733     next = pq->next;
2734     if (pq->tunnel == t)
2735     {
2736       if (GNUNET_MESSAGE_TYPE_MESH_UNICAST == pq->type ||
2737           GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN == pq->type)
2738       {
2739         // Should have been removed on destroy children
2740         GNUNET_break (0);
2741       }
2742       queue_destroy (pq, GNUNET_YES);
2743     }
2744   }
2745   if (NULL == peer_info->queue_head && NULL != peer_info->core_transmit)
2746   {
2747     GNUNET_CORE_notify_transmit_ready_cancel(peer_info->core_transmit);
2748     peer_info->core_transmit = NULL;
2749   }
2750 }
2751
2752
2753 /**
2754  * Destroy the tunnel and free any allocated resources linked to it.
2755  *
2756  * @param t the tunnel to destroy
2757  *
2758  * @return GNUNET_OK on success
2759  */
2760 static int
2761 tunnel_destroy (struct MeshTunnel *t)
2762 {
2763   struct MeshClient *c;
2764   struct GNUNET_HashCode hash;
2765   unsigned int i;
2766   int r;
2767
2768   if (NULL == t)
2769     return GNUNET_OK;
2770
2771   r = GNUNET_OK;
2772   c = t->owner;
2773 #if MESH_DEBUG
2774   {
2775     struct GNUNET_PeerIdentity id;
2776
2777     GNUNET_PEER_resolve (t->id.oid, &id);
2778     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s [%x]\n",
2779                 GNUNET_i2s (&id), t->id.tid);
2780     if (NULL != c)
2781       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
2782   }
2783 #endif
2784
2785   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
2786   if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_remove (tunnels, &hash, t))
2787   {
2788     GNUNET_break (0);
2789     r = GNUNET_SYSERR;
2790   }
2791
2792   if (NULL != c)
2793   {
2794     GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
2795     if (GNUNET_YES !=
2796         GNUNET_CONTAINER_multihashmap_remove (c->own_tunnels, &hash, t))
2797     {
2798       GNUNET_break (0);
2799       r = GNUNET_SYSERR;
2800     }
2801   }
2802
2803   GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
2804   for (i = 0; i < t->nclients; i++)
2805   {
2806     c = t->clients[i];
2807     if (GNUNET_YES !=
2808           GNUNET_CONTAINER_multihashmap_remove (c->incoming_tunnels, &hash, t))
2809     {
2810       GNUNET_break (0);
2811       r = GNUNET_SYSERR;
2812     }
2813   }
2814   for (i = 0; i < t->nignore; i++)
2815   {
2816     c = t->ignore[i];
2817     if (GNUNET_YES !=
2818           GNUNET_CONTAINER_multihashmap_remove (c->ignore_tunnels, &hash, t))
2819     {
2820       GNUNET_break (0);
2821       r = GNUNET_SYSERR;
2822     }
2823   }
2824
2825   (void) GNUNET_CONTAINER_multihashmap_remove (incoming_tunnels, &hash, t);
2826   GNUNET_free_non_null (t->clients);
2827   GNUNET_free_non_null (t->ignore);
2828   GNUNET_free_non_null (t->clients_fc);
2829
2830   peer_cancel_queues (t->next_hop, t);
2831   peer_cancel_queues (t->prev_hop, t);
2832
2833   if (GNUNET_SCHEDULER_NO_TASK != t->timeout_task)
2834     GNUNET_SCHEDULER_cancel (t->timeout_task);
2835   if (GNUNET_SCHEDULER_NO_TASK != t->path_refresh_task)
2836     GNUNET_SCHEDULER_cancel (t->path_refresh_task);
2837
2838   n_tunnels--;
2839   GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
2840   GNUNET_free (t);
2841   return r;
2842 }
2843
2844 #define TUNNEL_DESTROY_EMPTY_TIME GNUNET_TIME_UNIT_MILLISECONDS
2845
2846 /**
2847  * Tunnel is empty: destroy it.
2848  * 
2849  * @param cls Closure (Tunnel).
2850  * @param tc TaskContext. 
2851  */
2852 static void
2853 tunnel_destroy_empty_delayed (void *cls,
2854                               const struct GNUNET_SCHEDULER_TaskContext *tc)
2855 {
2856   struct MeshTunnel *t = cls;
2857
2858   t->delayed_destroy = GNUNET_SCHEDULER_NO_TASK;
2859   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2860     return;
2861
2862   if (0 != t->nclients)
2863     return;
2864
2865   #if MESH_DEBUG
2866   {
2867     struct GNUNET_PeerIdentity id;
2868
2869     GNUNET_PEER_resolve (t->id.oid, &id);
2870     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2871                 "executing destruction of empty tunnel %s [%X]\n",
2872                 GNUNET_i2s (&id), t->id.tid);
2873   }
2874   #endif
2875
2876   tunnel_send_destroy (t);
2877   if (0 == t->pending_messages)
2878     tunnel_destroy (t);
2879   else
2880     t->destroy = GNUNET_YES;
2881 }
2882
2883
2884 /**
2885  * Schedule tunnel destruction if is empty and no new traffic comes in a time.
2886  * 
2887  * @param t Tunnel to destroy if empty.
2888  */
2889 static void
2890 tunnel_destroy_empty (struct MeshTunnel *t)
2891 {
2892   if (GNUNET_SCHEDULER_NO_TASK != t->delayed_destroy || 
2893       0 != t->nclients)
2894   {
2895     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "%u %u\n",
2896                 t->delayed_destroy, t->nclients);
2897     return;
2898   }
2899
2900   #if MESH_DEBUG
2901   {
2902     struct GNUNET_PeerIdentity id;
2903
2904     GNUNET_PEER_resolve (t->id.oid, &id);
2905     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2906                 "scheduling destruction of empty tunnel %s [%X]\n",
2907                 GNUNET_i2s (&id), t->id.tid);
2908   }
2909   #endif
2910
2911   t->delayed_destroy =
2912       GNUNET_SCHEDULER_add_delayed (TUNNEL_DESTROY_EMPTY_TIME,
2913                                     &tunnel_destroy_empty_delayed,
2914                                     t);
2915 }
2916
2917
2918 /**
2919  * Create a new tunnel
2920  * 
2921  * @param owner Who is the owner of the tunnel (short ID).
2922  * @param tid Tunnel Number of the tunnel.
2923  * @param client Clients that owns the tunnel, NULL for foreign tunnels.
2924  * @param local Tunnel Number for the tunnel, for the client point of view.
2925  * 
2926  * @return A new initialized tunnel. NULL on error.
2927  */
2928 static struct MeshTunnel *
2929 tunnel_new (GNUNET_PEER_Id owner,
2930             MESH_TunnelNumber tid,
2931             struct MeshClient *client,
2932             MESH_TunnelNumber local)
2933 {
2934   struct MeshTunnel *t;
2935   struct GNUNET_HashCode hash;
2936
2937   if (n_tunnels >= max_tunnels && NULL == client)
2938     return NULL;
2939
2940   t = GNUNET_malloc (sizeof (struct MeshTunnel));
2941   t->id.oid = owner;
2942   t->id.tid = tid;
2943   t->fwd_queue_max = (max_msgs_queue / max_tunnels) + 1;
2944   t->bck_queue_max = t->fwd_queue_max;
2945   t->owner = client;
2946   t->fwd_pid = (uint32_t) -1; // Next (expected) = 0
2947   t->bck_pid = (uint32_t) -1; // Next (expected) = 0
2948   t->bck_ack = INITIAL_WINDOW_SIZE - 1;
2949   t->last_fwd_ack = INITIAL_WINDOW_SIZE - 1;
2950   t->local_tid = local;
2951   n_tunnels++;
2952   GNUNET_STATISTICS_update (stats, "# tunnels", 1, GNUNET_NO);
2953
2954   GNUNET_CRYPTO_hash (&t->id, sizeof (struct MESH_TunnelID), &hash);
2955   if (GNUNET_OK !=
2956       GNUNET_CONTAINER_multihashmap_put (tunnels, &hash, t,
2957                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
2958   {
2959     GNUNET_break (0);
2960     tunnel_destroy (t);
2961     if (NULL != client)
2962     {
2963       GNUNET_break (0);
2964       GNUNET_SERVER_receive_done (client->handle, GNUNET_SYSERR);
2965     }
2966     return NULL;
2967   }
2968
2969   if (NULL != client)
2970   {
2971     GNUNET_CRYPTO_hash (&t->local_tid, sizeof (MESH_TunnelNumber), &hash);
2972     if (GNUNET_OK !=
2973         GNUNET_CONTAINER_multihashmap_put (client->own_tunnels, &hash, t,
2974                                           GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
2975     {
2976       tunnel_destroy (t);
2977       GNUNET_break (0);
2978       GNUNET_SERVER_receive_done (client->handle, GNUNET_SYSERR);
2979       return NULL;
2980     }
2981   }
2982
2983   return t;
2984 }
2985
2986
2987
2988 /**
2989  * tunnel_destroy_iterator: iterator for deleting each tunnel that belongs to a
2990  * client when the client disconnects. If the client is not the owner, the
2991  * owner will get notified if no more clients are in the tunnel and the client
2992  * get removed from the tunnel's list.
2993  *
2994  * @param cls closure (client that is disconnecting)
2995  * @param key the hash of the local tunnel id (used to access the hashmap)
2996  * @param value the value stored at the key (tunnel to destroy)
2997  *
2998  * @return GNUNET_OK, keep iterating.
2999  */
3000 static int
3001 tunnel_destroy_iterator (void *cls,
3002                          const struct GNUNET_HashCode * key,
3003                          void *value)
3004 {
3005   struct MeshTunnel *t = value;
3006   struct MeshClient *c = cls;
3007
3008   send_client_tunnel_disconnect (t, c);
3009   if (c != t->owner)
3010   {
3011     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Client %u is destination.\n", c->id);
3012     tunnel_delete_client (t, c);
3013     client_delete_tunnel (c, t);
3014     tunnel_destroy_empty (t);
3015     return GNUNET_OK;
3016   }
3017   tunnel_send_destroy (t);
3018   t->owner = NULL;
3019   t->destroy = GNUNET_YES;
3020
3021   return GNUNET_OK;
3022 }
3023
3024
3025 /**
3026  * Timeout function, destroys tunnel if called
3027  *
3028  * @param cls Closure (tunnel to destroy).
3029  * @param tc TaskContext
3030  */
3031 static void
3032 tunnel_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3033 {
3034   struct MeshTunnel *t = cls;
3035   struct GNUNET_PeerIdentity id;
3036
3037   t->timeout_task = GNUNET_SCHEDULER_NO_TASK;
3038   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
3039     return;
3040   GNUNET_PEER_resolve(t->id.oid, &id);
3041   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3042               "Tunnel %s [%X] timed out. Destroying.\n",
3043               GNUNET_i2s(&id), t->id.tid);
3044   send_clients_tunnel_destroy (t);
3045   tunnel_destroy (t);
3046 }
3047
3048 /**
3049  * Resets the tunnel timeout. Starts it if no timeout was running.
3050  *
3051  * @param t Tunnel whose timeout to reset.
3052  *
3053  * TODO use heap to improve efficiency of scheduler.
3054  */
3055 static void
3056 tunnel_reset_timeout (struct MeshTunnel *t)
3057 {
3058   if (GNUNET_SCHEDULER_NO_TASK != t->timeout_task)
3059     GNUNET_SCHEDULER_cancel (t->timeout_task);
3060   t->timeout_task =
3061       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
3062                                     (refresh_path_time, 4), &tunnel_timeout, t);
3063 }
3064
3065
3066 /******************************************************************************/
3067 /****************      MESH NETWORK HANDLER HELPERS     ***********************/
3068 /******************************************************************************/
3069
3070 /**
3071  * Function to send a create path packet to a peer.
3072  *
3073  * @param cls closure
3074  * @param size number of bytes available in buf
3075  * @param buf where the callee should write the message
3076  * @return number of bytes written to buf
3077  */
3078 static size_t
3079 send_core_path_create (void *cls, size_t size, void *buf)
3080 {
3081   struct MeshTunnel *t = cls;
3082   struct GNUNET_MESH_ManipulatePath *msg;
3083   struct GNUNET_PeerIdentity *peer_ptr;
3084   struct MeshPeerPath *p = t->path;
3085   size_t size_needed;
3086   uint32_t opt;
3087   int i;
3088
3089   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CREATE PATH sending...\n");
3090   size_needed =
3091       sizeof (struct GNUNET_MESH_ManipulatePath) +
3092       p->length * sizeof (struct GNUNET_PeerIdentity);
3093
3094   if (size < size_needed || NULL == buf)
3095   {
3096     GNUNET_break (0);
3097     return 0;
3098   }
3099   msg = (struct GNUNET_MESH_ManipulatePath *) buf;
3100   msg->header.size = htons (size_needed);
3101   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE);
3102   msg->tid = ntohl (t->id.tid);
3103
3104   opt = 0;
3105   if (GNUNET_YES == t->nobuffer)
3106     opt |= MESH_TUNNEL_OPT_NOBUFFER;
3107   msg->opt = htonl(opt);
3108   msg->reserved = 0;
3109
3110   peer_ptr = (struct GNUNET_PeerIdentity *) &msg[1];
3111   for (i = 0; i < p->length; i++)
3112   {
3113     GNUNET_PEER_resolve (p->peers[i], peer_ptr++);
3114   }
3115
3116   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3117               "CREATE PATH (%u bytes long) sent!\n", size_needed);
3118   return size_needed;
3119 }
3120
3121
3122 /**
3123  * Creates a path ack message in buf and frees all unused resources.
3124  *
3125  * @param cls closure (MeshTransmissionDescriptor)
3126  * @param size number of bytes available in buf
3127  * @param buf where the callee should write the message
3128  * @return number of bytes written to buf
3129  */
3130 static size_t
3131 send_core_path_ack (void *cls, size_t size, void *buf)
3132 {
3133   struct MeshTransmissionDescriptor *info = cls;
3134   struct GNUNET_MESH_PathACK *msg = buf;
3135
3136   GNUNET_assert (NULL != info);
3137   if (sizeof (struct GNUNET_MESH_PathACK) > size)
3138   {
3139     GNUNET_break (0);
3140     return 0;
3141   }
3142   msg->header.size = htons (sizeof (struct GNUNET_MESH_PathACK));
3143   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_ACK);
3144   GNUNET_PEER_resolve (info->origin->oid, &msg->oid);
3145   msg->tid = htonl (info->origin->tid);
3146   msg->peer_id = my_full_id;
3147
3148   GNUNET_free (info);
3149   /* TODO add signature */
3150
3151   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "PATH ACK sent!\n");
3152   return sizeof (struct GNUNET_MESH_PathACK);
3153 }
3154
3155
3156 /**
3157  * Free a transmission that was already queued with all resources
3158  * associated to the request.
3159  *
3160  * @param queue Queue handler to cancel.
3161  * @param clear_cls Is it necessary to free associated cls?
3162  */
3163 static void
3164 queue_destroy (struct MeshPeerQueue *queue, int clear_cls)
3165 {
3166   struct MeshTransmissionDescriptor *dd;
3167 //   unsigned int max;
3168
3169   if (GNUNET_YES == clear_cls)
3170   {
3171     switch (queue->type)
3172     {
3173       case GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY:
3174         GNUNET_log (GNUNET_ERROR_TYPE_INFO, "   cancelling TUNNEL_DESTROY\n");
3175         GNUNET_break (GNUNET_YES == queue->tunnel->destroy);
3176         /* fall through */
3177       case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
3178       case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
3179       case GNUNET_MESSAGE_TYPE_MESH_ACK:
3180       case GNUNET_MESSAGE_TYPE_MESH_POLL:
3181       case GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE:
3182         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3183                     "   prebuilt message\n");
3184         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3185                     "   type %s\n",
3186                     GNUNET_MESH_DEBUG_M2S(queue->type));
3187         dd = queue->cls;
3188         GNUNET_free (dd->data);
3189         break;
3190       case GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE:
3191         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   type create path\n");
3192         break;
3193       default:
3194         GNUNET_break (0);
3195         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3196                     "   type %s unknown!\n",
3197                     GNUNET_MESH_DEBUG_M2S(queue->type));
3198     }
3199     GNUNET_free_non_null (queue->cls);
3200   }
3201   GNUNET_CONTAINER_DLL_remove (queue->peer->queue_head,
3202                                queue->peer->queue_tail,
3203                                queue);
3204
3205   /* Delete from child_fc in the appropiate tunnel */
3206 //   max = queue->tunnel->fwd_queue_max;
3207 //   GNUNET_PEER_resolve (queue->peer->id, &id);
3208 //   if (NULL != cinfo)
3209 //   { FIXME
3210 //     for (i = 0; i < cinfo->send_buffer_n; i++)
3211 //     {
3212 //       i2 = (cinfo->send_buffer_start + i) % max;
3213 //       if (cinfo->send_buffer[i2] == queue)
3214 //       {
3215 //         /* Found corresponding entry in the send_buffer. Move all others back. */
3216 //         unsigned int j;
3217 // 
3218 // 
3219 //         for (j = i, j2 = 0, j3 = 0; j < cinfo->send_buffer_n - 1; j++)
3220 //         {
3221 //           j2 = (cinfo->send_buffer_start + j) % max;
3222 //           j3 = (cinfo->send_buffer_start + j + 1) % max;
3223 //           cinfo->send_buffer[j2] = cinfo->send_buffer[j3];
3224 //         }
3225 // 
3226 //         cinfo->send_buffer[j3] = NULL;
3227 //         cinfo->send_buffer_n--;
3228 //       }
3229 //     }
3230 //   }
3231
3232   GNUNET_free (queue);
3233 }
3234
3235
3236 /**
3237  * @brief Get the next transmittable message from the queue.
3238  *
3239  * This will be the head, except in the case of being a data packet
3240  * not allowed by the destination peer.
3241  *
3242  * @param peer Destination peer.
3243  *
3244  * @return The next viable MeshPeerQueue element to send to that peer.
3245  *         NULL when there are no transmittable messages.
3246  */
3247 struct MeshPeerQueue *
3248 queue_get_next (const struct MeshPeerInfo *peer)
3249 {
3250   struct MeshPeerQueue *q;
3251  
3252   struct MeshTransmissionDescriptor *info;
3253 //   struct GNUNET_MESH_Unicast *ucast;
3254 //   struct GNUNET_MESH_ToOrigin *to_orig;
3255   struct GNUNET_PeerIdentity id;
3256 //   uint32_t pid;
3257 //   uint32_t ack; FIXME
3258
3259   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   selecting message\n");
3260   for (q = peer->queue_head; NULL != q; q = q->next)
3261   {
3262 //     t = q->tunnel;
3263     info = q->cls;
3264     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3265                 "*********     %s\n",
3266                 GNUNET_MESH_DEBUG_M2S(q->type));
3267     switch (q->type)
3268     {
3269       case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
3270 //         ucast = (struct GNUNET_MESH_Unicast *) info->mesh_data->data;
3271 //         pid = ntohl (ucast->pid);
3272         GNUNET_PEER_resolve (info->peer->id, &id);
3273 //         ack = cinfo->fwd_ack;
3274         break;
3275       case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
3276 //         to_orig = (struct GNUNET_MESH_ToOrigin *) info->mesh_data->data;
3277 //         pid = ntohl (to_orig->pid);
3278 //         ack = t->bck_ack;
3279         break;
3280       default:
3281         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3282                     "*********   OK!\n");
3283         return q;
3284     }
3285 //     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3286 //                 "*********     ACK: %u, PID: %u\n",
3287 //                 ack, pid);
3288 //     if (GNUNET_NO == GMC_is_pid_bigger(pid, ack))
3289 //     {
3290 //       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3291 //                   "*********   OK!\n");
3292 //       return q;
3293 //     }
3294 //     else
3295 //     {
3296 //       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3297 //                   "*********     NEXT!\n");
3298 //     }
3299   }
3300   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3301                 "*********   nothing found\n");
3302   return NULL;
3303 }
3304
3305
3306 static size_t
3307 queue_send (void *cls, size_t size, void *buf)
3308 {
3309     struct MeshPeerInfo *peer = cls;
3310     struct GNUNET_MessageHeader *msg;
3311     struct MeshPeerQueue *queue;
3312     struct MeshTunnel *t;
3313     struct GNUNET_PeerIdentity dst_id;
3314     size_t data_size;
3315
3316     peer->core_transmit = NULL;
3317
3318     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "********* Queue send\n");
3319     queue = queue_get_next (peer);
3320
3321     /* Queue has no internal mesh traffic nor sendable payload */
3322     if (NULL == queue)
3323     {
3324       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   not ready, return\n");
3325       if (NULL == peer->queue_head)
3326         GNUNET_break (0); // Should've been canceled
3327       return 0;
3328     }
3329     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   not empty\n");
3330
3331     GNUNET_PEER_resolve (peer->id, &dst_id);
3332     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3333                 "*********   towards %s\n",
3334                 GNUNET_i2s(&dst_id));
3335     /* Check if buffer size is enough for the message */
3336     if (queue->size > size)
3337     {
3338         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3339                     "*********   not enough room, reissue\n");
3340         peer->core_transmit =
3341             GNUNET_CORE_notify_transmit_ready (core_handle,
3342                                                0,
3343                                                0,
3344                                                GNUNET_TIME_UNIT_FOREVER_REL,
3345                                                &dst_id,
3346                                                queue->size,
3347                                                &queue_send,
3348                                                peer);
3349         return 0;
3350     }
3351     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   size ok\n");
3352
3353     t = queue->tunnel;
3354     GNUNET_assert (0 < t->pending_messages);
3355     t->pending_messages--;
3356     if (GNUNET_MESSAGE_TYPE_MESH_UNICAST == queue->type)
3357     {
3358       t->fwd_queue_n--;
3359       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3360                   "*********   unicast: t->q (%u/%u)\n",
3361                   t->fwd_queue_n, t->fwd_queue_max);
3362     }
3363     else if (GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN == queue->type)
3364     {
3365       t->bck_queue_n--;
3366       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   to origin\n");
3367     }
3368
3369     /* Fill buf */
3370     switch (queue->type)
3371     {
3372       case 0:
3373       case GNUNET_MESSAGE_TYPE_MESH_ACK:
3374       case GNUNET_MESSAGE_TYPE_MESH_POLL:
3375       case GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN:
3376       case GNUNET_MESSAGE_TYPE_MESH_PATH_DESTROY:
3377       case GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY:
3378       case GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE:
3379         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3380                     "*********   raw: %s\n",
3381                     GNUNET_MESH_DEBUG_M2S (queue->type));
3382         /* Fall through */
3383       case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
3384       case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
3385         data_size = send_core_data_raw (queue->cls, size, buf);
3386         msg = (struct GNUNET_MessageHeader *) buf;
3387         switch (ntohs (msg->type)) // Type of preconstructed message
3388         {
3389           case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
3390             tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_UNICAST);
3391             break;
3392           case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
3393             tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN);
3394             break;
3395           default:
3396               break;
3397         }
3398         break;
3399       case GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE:
3400         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   path create\n");
3401         data_size = send_core_path_create (queue->cls, size, buf);
3402         break;
3403       case GNUNET_MESSAGE_TYPE_MESH_PATH_ACK:
3404         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   path ack\n");
3405         data_size = send_core_path_ack (queue->cls, size, buf);
3406         break;
3407       default:
3408         GNUNET_break (0);
3409         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3410                     "*********   type unknown: %u\n",
3411                     queue->type);
3412         data_size = 0;
3413     }
3414     switch (queue->type)
3415     {
3416       case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
3417       case GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN:
3418 //         if (cinfo->send_buffer[cinfo->send_buffer_start] != queue)
3419 //         { FIXME
3420 //           GNUNET_break (0);
3421 //           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3422 //                       "at pos %u (%p) != %p\n",
3423 //                       cinfo->send_buffer_start,
3424 //                       cinfo->send_buffer[cinfo->send_buffer_start],
3425 //                       queue);
3426 //         }
3427 //         if (cinfo->send_buffer_n > 0)
3428 //         {
3429 //           cinfo->send_buffer[cinfo->send_buffer_start] = NULL;
3430 //           cinfo->send_buffer_n--;
3431 //           cinfo->send_buffer_start++;
3432 //           cinfo->send_buffer_start %= t->fwd_queue_max;
3433 //         }
3434 //         else
3435 //         {
3436 //           GNUNET_break (0);
3437 //         }
3438         break;
3439       default:
3440         break;
3441     }
3442
3443     /* Free queue, but cls was freed by send_core_* */
3444     queue_destroy (queue, GNUNET_NO);
3445
3446     if (GNUNET_YES == t->destroy && 0 == t->pending_messages)
3447     {
3448       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********  destroying tunnel!\n");
3449       tunnel_destroy (t);
3450     }
3451
3452     /* If more data in queue, send next */
3453     queue = queue_get_next(peer);
3454     if (NULL != queue)
3455     {
3456         struct GNUNET_PeerIdentity id;
3457
3458         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   more data!\n");
3459         GNUNET_PEER_resolve (peer->id, &id);
3460         peer->core_transmit =
3461             GNUNET_CORE_notify_transmit_ready(core_handle,
3462                                               0,
3463                                               0,
3464                                               GNUNET_TIME_UNIT_FOREVER_REL,
3465                                               &id,
3466                                               queue->size,
3467                                               &queue_send,
3468                                               peer);
3469     }
3470     else
3471     {
3472       if (NULL != peer->queue_head)
3473       {
3474         GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3475                     "*********   %s stalled\n",
3476                     GNUNET_i2s(&my_full_id));
3477 //         if (NULL == cinfo) FIXME
3478 //           cinfo = tunnel_get_neighbor_fc (t, &dst_id);
3479 //         // FIXME unify bck/fwd structures, bck does not have cinfo right now
3480 //         if (NULL != cinfo && GNUNET_SCHEDULER_NO_TASK == cinfo->fc_poll)
3481 //         {
3482 //           cinfo->fc_poll = GNUNET_SCHEDULER_add_delayed (cinfo->fc_poll_time,
3483 //                                                          &tunnel_poll, cinfo);
3484 //         }
3485       }
3486     }
3487     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   return %d\n", data_size);
3488     return data_size;
3489 }
3490
3491
3492 /**
3493  * @brief Queue and pass message to core when possible.
3494  * 
3495  * If type is payload (UNICAST, TO_ORIGIN) checks for queue status and
3496  * accounts for it. In case the queue is full, the message is dropped and
3497  * a break issued.
3498  * 
3499  * Otherwise, message is treated as internal and allowed to go regardless of 
3500  * queue status.
3501  *
3502  * @param cls Closure (@c type dependant). It will be used by queue_send to
3503  *            build the message to be sent if not already prebuilt.
3504  * @param type Type of the message, 0 for a raw message.
3505  * @param size Size of the message.
3506  * @param dst Neighbor to send message to.
3507  * @param t Tunnel this message belongs to.
3508  */
3509 static void
3510 queue_add (void *cls, uint16_t type, size_t size,
3511            struct MeshPeerInfo *dst, struct MeshTunnel *t)
3512 {
3513   struct MeshPeerQueue *queue;
3514   struct GNUNET_PeerIdentity id;
3515   unsigned int *max;
3516   unsigned int *n;
3517
3518   n = NULL;
3519   if (GNUNET_MESSAGE_TYPE_MESH_UNICAST == type)
3520   {
3521     n = &t->fwd_queue_n;
3522     max = &t->fwd_queue_max;
3523   }
3524   else if (GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN == type)
3525   {
3526     n = &t->bck_queue_n;
3527     max = &t->bck_queue_max;
3528   }
3529   if (NULL != n)
3530   {
3531     if (*n >= *max)
3532     {
3533       GNUNET_break(0);
3534       GNUNET_STATISTICS_update(stats,
3535                                "# messages dropped (buffer full)",
3536                                1, GNUNET_NO);
3537       return; // Drop message
3538     }
3539     (*n)++;
3540   }
3541   queue = GNUNET_malloc (sizeof (struct MeshPeerQueue));
3542   queue->cls = cls;
3543   queue->type = type;
3544   queue->size = size;
3545   queue->peer = dst;
3546   queue->tunnel = t;
3547   GNUNET_CONTAINER_DLL_insert_tail (dst->queue_head, dst->queue_tail, queue);
3548   if (NULL == dst->core_transmit)
3549   {
3550     GNUNET_PEER_resolve (dst->id, &id);
3551     dst->core_transmit =
3552         GNUNET_CORE_notify_transmit_ready (core_handle,
3553                                            0,
3554                                            0,
3555                                            GNUNET_TIME_UNIT_FOREVER_REL,
3556                                            &id,
3557                                            size,
3558                                            &queue_send,
3559                                            dst);
3560   }
3561   t->pending_messages++;
3562 }
3563
3564
3565 /******************************************************************************/
3566 /********************      MESH NETWORK HANDLERS     **************************/
3567 /******************************************************************************/
3568
3569
3570 /**
3571  * Core handler for path creation
3572  *
3573  * @param cls closure
3574  * @param message message
3575  * @param peer peer identity this notification is about
3576  *
3577  * @return GNUNET_OK to keep the connection open,
3578  *         GNUNET_SYSERR to close it (signal serious error)
3579  */
3580 static int
3581 handle_mesh_path_create (void *cls, const struct GNUNET_PeerIdentity *peer,
3582                          const struct GNUNET_MessageHeader *message)
3583 {
3584   unsigned int own_pos;
3585   uint16_t size;
3586   uint16_t i;
3587   MESH_TunnelNumber tid;
3588   struct GNUNET_MESH_ManipulatePath *msg;
3589   struct GNUNET_PeerIdentity *pi;
3590   struct GNUNET_HashCode hash;
3591   struct MeshPeerPath *path;
3592   struct MeshPeerInfo *dest_peer_info;
3593   struct MeshPeerInfo *orig_peer_info;
3594   struct MeshTunnel *t;
3595
3596   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3597               "Received a path create msg [%s]\n",
3598               GNUNET_i2s (&my_full_id));
3599   size = ntohs (message->size);
3600   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
3601   {
3602     GNUNET_break_op (0);
3603     return GNUNET_OK;
3604   }
3605
3606   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
3607   if (size % sizeof (struct GNUNET_PeerIdentity))
3608   {
3609     GNUNET_break_op (0);
3610     return GNUNET_OK;
3611   }
3612   size /= sizeof (struct GNUNET_PeerIdentity);
3613   if (size < 2)
3614   {
3615     GNUNET_break_op (0);
3616     return GNUNET_OK;
3617   }
3618   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
3619   msg = (struct GNUNET_MESH_ManipulatePath *) message;
3620
3621   tid = ntohl (msg->tid);
3622   pi = (struct GNUNET_PeerIdentity *) &msg[1];
3623   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3624               "    path is for tunnel %s [%X].\n", GNUNET_i2s (pi), tid);
3625   t = tunnel_get (pi, tid);
3626   if (NULL == t) // FIXME only for INCOMING tunnels?
3627   {
3628     uint32_t opt;
3629
3630     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating tunnel\n");
3631     t = tunnel_new (GNUNET_PEER_intern (pi), tid, NULL, 0);
3632     if (NULL == t)
3633     {
3634       // FIXME notify failure
3635       return GNUNET_OK;
3636     }
3637     opt = ntohl (msg->opt);
3638     if (0 != (opt & MESH_TUNNEL_OPT_NOBUFFER))
3639     {
3640       t->nobuffer = GNUNET_YES;
3641       t->last_fwd_ack = t->fwd_pid + 1;
3642     }
3643     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  nobuffer:%d\n", t->nobuffer);
3644
3645     if (GNUNET_YES == t->nobuffer)
3646     {
3647       t->bck_queue_max = 1;
3648       t->fwd_queue_max = 1;
3649     }
3650
3651     // FIXME only assign a local tid if a local client is interested (on demand)
3652     while (NULL != tunnel_get_incoming (next_local_tid))
3653       next_local_tid = (next_local_tid + 1) | GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
3654     t->local_tid_dest = next_local_tid++;
3655     next_local_tid = next_local_tid | GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
3656     // FIXME end
3657
3658     tunnel_reset_timeout (t);
3659     GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
3660     if (GNUNET_OK !=
3661         GNUNET_CONTAINER_multihashmap_put (incoming_tunnels, &hash, t,
3662                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
3663     {
3664       tunnel_destroy (t);
3665       GNUNET_break (0);
3666       return GNUNET_OK;
3667     }
3668   }
3669   dest_peer_info =
3670       GNUNET_CONTAINER_multihashmap_get (peers, &pi[size - 1].hashPubKey);
3671   if (NULL == dest_peer_info)
3672   {
3673     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3674                 "  Creating PeerInfo for destination.\n");
3675     dest_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
3676     dest_peer_info->id = GNUNET_PEER_intern (&pi[size - 1]);
3677     GNUNET_CONTAINER_multihashmap_put (peers, &pi[size - 1].hashPubKey,
3678                                        dest_peer_info,
3679                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3680   }
3681   orig_peer_info = GNUNET_CONTAINER_multihashmap_get (peers, &pi->hashPubKey);
3682   if (NULL == orig_peer_info)
3683   {
3684     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3685                 "  Creating PeerInfo for origin.\n");
3686     orig_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
3687     orig_peer_info->id = GNUNET_PEER_intern (pi);
3688     GNUNET_CONTAINER_multihashmap_put (peers, &pi->hashPubKey, orig_peer_info,
3689                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3690   }
3691   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
3692   path = path_new (size);
3693   own_pos = 0;
3694   for (i = 0; i < size; i++)
3695   {
3696     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ... adding %s\n",
3697                 GNUNET_i2s (&pi[i]));
3698     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
3699     if (path->peers[i] == myid)
3700       own_pos = i;
3701   }
3702   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
3703   if (own_pos == 0)
3704   {
3705     /* cannot be self, must be 'not found' */
3706     /* create path: self not found in path through self */
3707     GNUNET_break_op (0);
3708     path_destroy (path);
3709     tunnel_destroy (t);
3710     return GNUNET_OK;
3711   }
3712   path_add_to_peers (path, GNUNET_NO);
3713   t->prev_hop = path->peers[own_pos - 1];
3714   GNUNET_PEER_change_rc (t->prev_hop, 1);
3715   if (own_pos == size - 1)
3716   {
3717     /* It is for us! Send ack. */
3718     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
3719     peer_info_add_path_to_origin (orig_peer_info, path, GNUNET_NO);
3720     t->peer = path->peers[0];
3721     send_path_ack (t);
3722   }
3723   else
3724   {
3725     struct MeshPeerPath *path2;
3726
3727     t->next_hop = path->peers[own_pos + 1];
3728     GNUNET_PEER_change_rc(t->next_hop, 1);
3729
3730     /* It's for somebody else! Retransmit. */
3731     path2 = path_duplicate (path);
3732     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Retransmitting.\n");
3733     peer_info_add_path (dest_peer_info, path2, GNUNET_NO);
3734     path2 = path_duplicate (path);
3735     peer_info_add_path_to_origin (orig_peer_info, path2, GNUNET_NO);
3736     send_create_path (dest_peer_info, path, t);
3737   }
3738   return GNUNET_OK;
3739 }
3740
3741
3742 /**
3743  * Core handler for path destruction
3744  *
3745  * @param cls closure
3746  * @param message message
3747  * @param peer peer identity this notification is about
3748  *
3749  * @return GNUNET_OK to keep the connection open,
3750  *         GNUNET_SYSERR to close it (signal serious error)
3751  */
3752 static int
3753 handle_mesh_path_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
3754                           const struct GNUNET_MessageHeader *message)
3755 {
3756   struct GNUNET_MESH_ManipulatePath *msg;
3757   struct GNUNET_PeerIdentity *pi;
3758   struct MeshPeerPath *path;
3759   struct MeshTunnel *t;
3760   unsigned int own_pos;
3761   unsigned int i;
3762   size_t size;
3763
3764   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3765               "Received a PATH DESTROY msg from %s\n", GNUNET_i2s (peer));
3766   size = ntohs (message->size);
3767   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
3768   {
3769     GNUNET_break_op (0);
3770     return GNUNET_OK;
3771   }
3772
3773   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
3774   if (size % sizeof (struct GNUNET_PeerIdentity))
3775   {
3776     GNUNET_break_op (0);
3777     return GNUNET_OK;
3778   }
3779   size /= sizeof (struct GNUNET_PeerIdentity);
3780   if (size < 2)
3781   {
3782     GNUNET_break_op (0);
3783     return GNUNET_OK;
3784   }
3785   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
3786
3787   msg = (struct GNUNET_MESH_ManipulatePath *) message;
3788   pi = (struct GNUNET_PeerIdentity *) &msg[1];
3789   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3790               "    path is for tunnel %s [%X].\n", GNUNET_i2s (pi),
3791               msg->tid);
3792   t = tunnel_get (pi, ntohl (msg->tid));
3793   if (NULL == t)
3794   {
3795     /* TODO notify back: we don't know this tunnel */
3796     GNUNET_break_op (0);
3797     return GNUNET_OK;
3798   }
3799   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
3800   path = path_new (size);
3801   own_pos = 0;
3802   for (i = 0; i < size; i++)
3803   {
3804     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ... adding %s\n",
3805                 GNUNET_i2s (&pi[i]));
3806     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
3807     if (path->peers[i] == myid)
3808       own_pos = i;
3809   }
3810   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
3811   if (own_pos < path->length - 1)
3812     send_prebuilt_message (message, &pi[own_pos + 1], t);
3813   else
3814     send_client_tunnel_disconnect(t, NULL);
3815
3816 //   tunnel_delete_peer (t, path->peers[path->length - 1]); FIXME
3817   path_destroy (path);
3818   return GNUNET_OK;
3819 }
3820
3821
3822 /**
3823  * Core handler for notifications of broken paths
3824  *
3825  * @param cls closure
3826  * @param message message
3827  * @param peer peer identity this notification is about
3828  *
3829  * @return GNUNET_OK to keep the connection open,
3830  *         GNUNET_SYSERR to close it (signal serious error)
3831  */
3832 static int
3833 handle_mesh_path_broken (void *cls, const struct GNUNET_PeerIdentity *peer,
3834                          const struct GNUNET_MessageHeader *message)
3835 {
3836   struct GNUNET_MESH_PathBroken *msg;
3837   struct MeshTunnel *t;
3838
3839   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3840               "Received a PATH BROKEN msg from %s\n", GNUNET_i2s (peer));
3841   msg = (struct GNUNET_MESH_PathBroken *) message;
3842   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
3843               GNUNET_i2s (&msg->peer1));
3844   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
3845               GNUNET_i2s (&msg->peer2));
3846   t = tunnel_get (&msg->oid, ntohl (msg->tid));
3847   if (NULL == t)
3848   {
3849     GNUNET_break_op (0);
3850     return GNUNET_OK;
3851   }
3852   tunnel_notify_connection_broken (t, GNUNET_PEER_search (&msg->peer1),
3853                                    GNUNET_PEER_search (&msg->peer2));
3854   return GNUNET_OK;
3855
3856 }
3857
3858
3859 /**
3860  * Core handler for tunnel destruction
3861  *
3862  * @param cls closure
3863  * @param message message
3864  * @param peer peer identity this notification is about
3865  *
3866  * @return GNUNET_OK to keep the connection open,
3867  *         GNUNET_SYSERR to close it (signal serious error)
3868  */
3869 static int
3870 handle_mesh_tunnel_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
3871                             const struct GNUNET_MessageHeader *message)
3872 {
3873   struct GNUNET_MESH_TunnelDestroy *msg;
3874   struct MeshTunnel *t;
3875   GNUNET_PEER_Id pid;
3876
3877   msg = (struct GNUNET_MESH_TunnelDestroy *) message;
3878   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3879               "Got a TUNNEL DESTROY packet from %s\n",
3880               GNUNET_i2s (peer));
3881   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3882               "  for tunnel %s [%u]\n",
3883               GNUNET_i2s (&msg->oid), ntohl (msg->tid));
3884   t = tunnel_get (&msg->oid, ntohl (msg->tid));
3885   /* Check signature */
3886   if (NULL == t)
3887   {
3888     /* Probably already got the message from another path,
3889      * destroyed the tunnel and retransmitted to children.
3890      * Safe to ignore.
3891      */
3892     GNUNET_STATISTICS_update (stats, "# control on unknown tunnel",
3893                               1, GNUNET_NO);
3894     return GNUNET_OK;
3895   }
3896   pid = GNUNET_PEER_search (peer);
3897   if (pid != t->prev_hop && 0 < t->nclients)
3898   {
3899     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3900                 "still in use by %u clients\n",
3901                 t->nclients);
3902     return GNUNET_OK;
3903   }
3904   if (t->local_tid_dest >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
3905   {
3906     /* Tunnel was incoming, notify clients */
3907     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "INCOMING TUNNEL %X %X\n",
3908                 t->local_tid, t->local_tid_dest);
3909     send_clients_tunnel_destroy (t);
3910   }
3911   tunnel_send_destroy (t);
3912   t->destroy = GNUNET_YES;
3913   // TODO: add timeout to destroy the tunnel anyway
3914   return GNUNET_OK;
3915 }
3916
3917
3918 /**
3919  * Core handler for mesh network traffic going from the origin to a peer
3920  *
3921  * @param cls closure
3922  * @param peer peer identity this notification is about
3923  * @param message message
3924  * @return GNUNET_OK to keep the connection open,
3925  *         GNUNET_SYSERR to close it (signal serious error)
3926  */
3927 static int
3928 handle_mesh_data_unicast (void *cls, const struct GNUNET_PeerIdentity *peer,
3929                           const struct GNUNET_MessageHeader *message)
3930 {
3931   struct GNUNET_MESH_Unicast *msg;
3932   struct GNUNET_PeerIdentity neighbor;
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   GNUNET_PEER_resolve (t->next_hop, &neighbor);
4012
4013 /*   cinfo->fwd_pid = pid; FIXME
4014
4015   if (GNUNET_YES == t->nobuffer &&
4016       GNUNET_YES == GMC_is_pid_bigger (pid, cinfo->fwd_ack))
4017   {
4018     GNUNET_STATISTICS_update (stats, "# unsolicited unicast", 1, GNUNET_NO);
4019     GNUNET_log (GNUNET_ERROR_TYPE_INFO, "  %u > %u\n", pid, cinfo->fwd_ack);
4020     GNUNET_break_op (0);
4021     return GNUNET_OK;
4022   }*/
4023   send_prebuilt_message (message, &neighbor, t);
4024   GNUNET_STATISTICS_update (stats, "# unicast forwarded", 1, GNUNET_NO);
4025   return GNUNET_OK;
4026 }
4027
4028
4029 /**
4030  * Core handler for mesh network traffic toward the owner of a tunnel
4031  *
4032  * @param cls closure
4033  * @param message message
4034  * @param peer peer identity this notification is about
4035  *
4036  * @return GNUNET_OK to keep the connection open,
4037  *         GNUNET_SYSERR to close it (signal serious error)
4038  */
4039 static int
4040 handle_mesh_data_to_orig (void *cls, const struct GNUNET_PeerIdentity *peer,
4041                           const struct GNUNET_MessageHeader *message)
4042 {
4043   struct GNUNET_MESH_ToOrigin *msg;
4044   struct GNUNET_PeerIdentity id;
4045   struct MeshPeerInfo *peer_info;
4046   struct MeshTunnel *t;
4047   size_t size;
4048   uint32_t pid;
4049
4050   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a ToOrigin packet from %s\n",
4051               GNUNET_i2s (peer));
4052   size = ntohs (message->size);
4053   if (size < sizeof (struct GNUNET_MESH_ToOrigin) +     /* Payload must be */
4054       sizeof (struct GNUNET_MessageHeader))     /* at least a header */
4055   {
4056     GNUNET_break_op (0);
4057     return GNUNET_OK;
4058   }
4059   msg = (struct GNUNET_MESH_ToOrigin *) message;
4060   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " of type %s\n",
4061               GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
4062   t = tunnel_get (&msg->oid, ntohl (msg->tid));
4063   pid = ntohl (msg->pid);
4064
4065   if (NULL == t)
4066   {
4067     /* TODO notify that we dont know this tunnel (whom)? */
4068     GNUNET_STATISTICS_update (stats, "# data on unknown tunnel", 1, GNUNET_NO);
4069     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4070                 "Received to_origin with PID %u on unknown tunnel %s [%u]\n",
4071                 pid, GNUNET_i2s (&msg->oid), ntohl (msg->tid));
4072     return GNUNET_OK;
4073   }
4074
4075
4076 //   if (cinfo->bck_pid == pid) FIXME
4077 //   {
4078 //     /* already seen this packet, drop */
4079 //     GNUNET_STATISTICS_update (stats, "# duplicate PID drops BCK", 1, GNUNET_NO);
4080 //     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4081 //                 " Already seen pid %u, DROPPING!\n", pid);
4082 //     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
4083 //     return GNUNET_OK;
4084 //   }
4085
4086   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4087               " pid %u not seen yet, forwarding\n", pid);
4088 //   cinfo->bck_pid = pid; FIXME
4089
4090   if (NULL != t->owner)
4091   {
4092     char cbuf[size];
4093     struct GNUNET_MESH_ToOrigin *copy;
4094
4095     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4096                 "  it's for us! sending to clients...\n");
4097     /* TODO signature verification */
4098     memcpy (cbuf, message, size);
4099     copy = (struct GNUNET_MESH_ToOrigin *) cbuf;
4100     copy->tid = htonl (t->local_tid);
4101     t->bck_pid++;
4102     copy->pid = htonl (t->bck_pid);
4103     GNUNET_STATISTICS_update (stats, "# to origin received", 1, GNUNET_NO);
4104     GNUNET_SERVER_notification_context_unicast (nc, t->owner->handle,
4105                                                 &copy->header, GNUNET_NO);
4106     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN);
4107     return GNUNET_OK;
4108   }
4109   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4110               "  not for us, retransmitting...\n");
4111
4112   peer_info = peer_get (&msg->oid);
4113   if (NULL == peer_info)
4114   {
4115     /* unknown origin of tunnel */
4116     GNUNET_break (0);
4117     return GNUNET_OK;
4118   }
4119   if (0 == t->prev_hop)
4120   {
4121     if (GNUNET_YES == t->destroy)
4122     {
4123       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4124                   "to orig received on a dying tunnel %s [%X]\n",
4125                   GNUNET_i2s (&msg->oid), ntohl(msg->tid));
4126       return GNUNET_OK;
4127     }
4128     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 
4129                 "unknown to origin at %s\n",
4130                 GNUNET_i2s (&my_full_id));
4131     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 
4132                 "from peer %s\n",
4133                 GNUNET_i2s (peer));
4134     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 
4135                 "for tunnel %s [%X]\n",
4136                 GNUNET_i2s (&msg->oid), ntohl(msg->tid));
4137     return GNUNET_OK;
4138   }
4139   GNUNET_PEER_resolve (t->prev_hop, &id);
4140   send_prebuilt_message (message, &id, t);
4141   GNUNET_STATISTICS_update (stats, "# to origin forwarded", 1, GNUNET_NO);
4142
4143   return GNUNET_OK;
4144 }
4145
4146
4147 /**
4148  * Core handler for mesh network traffic point-to-point acks.
4149  *
4150  * @param cls closure
4151  * @param message message
4152  * @param peer peer identity this notification is about
4153  *
4154  * @return GNUNET_OK to keep the connection open,
4155  *         GNUNET_SYSERR to close it (signal serious error)
4156  */
4157 static int
4158 handle_mesh_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
4159                  const struct GNUNET_MessageHeader *message)
4160 {
4161   struct GNUNET_MESH_ACK *msg;
4162   struct MeshTunnel *t;
4163   uint32_t ack;
4164
4165   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got an ACK packet from %s!\n",
4166               GNUNET_i2s (peer));
4167   msg = (struct GNUNET_MESH_ACK *) message;
4168
4169   t = tunnel_get (&msg->oid, ntohl (msg->tid));
4170
4171   if (NULL == t)
4172   {
4173     /* TODO notify that we dont know this tunnel (whom)? */
4174     GNUNET_STATISTICS_update (stats, "# ack on unknown tunnel", 1, GNUNET_NO);
4175     return GNUNET_OK;
4176   }
4177   ack = ntohl (msg->pid);
4178   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ACK %u\n", ack);
4179
4180   /* Is this a forward or backward ACK? */
4181   if (t->prev_hop != GNUNET_PEER_search(peer))
4182   {
4183
4184     debug_bck_ack++;
4185     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  FWD ACK\n");
4186 //     cinfo->fwd_ack = ack; FIXME
4187     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
4188     peer_unlock_queue (t->next_hop);
4189 //     if (GNUNET_SCHEDULER_NO_TASK != cinfo->fc_poll) FIXME
4190 //     {
4191 //       GNUNET_SCHEDULER_cancel (cinfo->fc_poll);
4192 //       cinfo->fc_poll = GNUNET_SCHEDULER_NO_TASK;
4193 //       cinfo->fc_poll_time = GNUNET_TIME_UNIT_SECONDS;
4194 //     }
4195   }
4196   else
4197   {
4198     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  BCK ACK\n");
4199     t->bck_ack = ack;
4200     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_ACK);
4201     peer_unlock_queue (t->prev_hop);
4202   }
4203   return GNUNET_OK;
4204 }
4205
4206
4207 /**
4208  * Core handler for mesh network traffic point-to-point ack polls.
4209  *
4210  * @param cls closure
4211  * @param message message
4212  * @param peer peer identity this notification is about
4213  *
4214  * @return GNUNET_OK to keep the connection open,
4215  *         GNUNET_SYSERR to close it (signal serious error)
4216  */
4217 static int
4218 handle_mesh_poll (void *cls, const struct GNUNET_PeerIdentity *peer,
4219                   const struct GNUNET_MessageHeader *message)
4220 {
4221   struct GNUNET_MESH_Poll *msg;
4222   struct MeshTunnel *t;
4223
4224   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got an POLL packet from %s!\n",
4225               GNUNET_i2s (peer));
4226
4227   msg = (struct GNUNET_MESH_Poll *) message;
4228
4229   t = tunnel_get (&msg->oid, ntohl (msg->tid));
4230
4231   if (NULL == t)
4232   {
4233     /* TODO notify that we dont know this tunnel (whom)? */
4234     GNUNET_STATISTICS_update (stats, "# poll on unknown tunnel", 1, GNUNET_NO);
4235     GNUNET_break_op (0);
4236     return GNUNET_OK;
4237   }
4238
4239   /* Is this a forward or backward ACK? */
4240   if (t->prev_hop != GNUNET_PEER_search(peer))
4241   {
4242     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  from FWD\n");
4243     /* FIXME cinfo->bck_ack = cinfo->fwd_pid; // mark as ready to send */
4244     tunnel_send_bck_ack (t, GNUNET_MESSAGE_TYPE_MESH_POLL);
4245   }
4246   else
4247   {
4248     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  from BCK\n");
4249     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_POLL);
4250   }
4251
4252   return GNUNET_OK;
4253 }
4254
4255 /**
4256  * Core handler for path ACKs
4257  *
4258  * @param cls closure
4259  * @param message message
4260  * @param peer peer identity this notification is about
4261  *
4262  * @return GNUNET_OK to keep the connection open,
4263  *         GNUNET_SYSERR to close it (signal serious error)
4264  */
4265 static int
4266 handle_mesh_path_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
4267                       const struct GNUNET_MessageHeader *message)
4268 {
4269   struct GNUNET_MESH_PathACK *msg;
4270   struct GNUNET_PeerIdentity id;
4271   struct MeshPeerInfo *peer_info;
4272   struct MeshPeerPath *p;
4273   struct MeshTunnel *t;
4274
4275   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a path ACK msg [%s]\n",
4276               GNUNET_i2s (&my_full_id));
4277   msg = (struct GNUNET_MESH_PathACK *) message;
4278   t = tunnel_get (&msg->oid, ntohl(msg->tid));
4279   if (NULL == t)
4280   {
4281     /* TODO notify that we don't know the tunnel */
4282     GNUNET_STATISTICS_update (stats, "# control on unknown tunnel", 1, GNUNET_NO);
4283     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  don't know the tunnel %s [%X]!\n",
4284                 GNUNET_i2s (&msg->oid), ntohl(msg->tid));
4285     return GNUNET_OK;
4286   }
4287   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %s [%X]\n",
4288               GNUNET_i2s (&msg->oid), ntohl(msg->tid));
4289
4290   peer_info = peer_get (&msg->peer_id);
4291   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by peer %s\n",
4292               GNUNET_i2s (&msg->peer_id));
4293   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  via peer %s\n",
4294               GNUNET_i2s (peer));
4295
4296   /* Add path to peers? */
4297   p = t->path;
4298   if (NULL != p)
4299   {
4300     path_add_to_peers (p, GNUNET_YES);
4301   }
4302   else
4303   {
4304     GNUNET_break (0);
4305   }
4306
4307   /* Message for us? */
4308   if (0 == memcmp (&msg->oid, &my_full_id, sizeof (struct GNUNET_PeerIdentity)))
4309   {
4310     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
4311     if (NULL == t->owner)
4312     {
4313       GNUNET_break_op (0);
4314       return GNUNET_OK;
4315     }
4316     if (NULL != peer_info->dhtget)
4317     {
4318       GNUNET_DHT_get_stop (peer_info->dhtget);
4319       peer_info->dhtget = NULL;
4320     }
4321     return GNUNET_OK;
4322   }
4323
4324   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4325               "  not for us, retransmitting...\n");
4326   GNUNET_PEER_resolve (t->prev_hop, &id);
4327   peer_info = peer_get (&msg->oid);
4328   send_prebuilt_message (message, &id, t);
4329   return GNUNET_OK;
4330 }
4331
4332
4333 /**
4334  * Core handler for mesh keepalives.
4335  *
4336  * @param cls closure
4337  * @param message message
4338  * @param peer peer identity this notification is about
4339  * @return GNUNET_OK to keep the connection open,
4340  *         GNUNET_SYSERR to close it (signal serious error)
4341  *
4342  * TODO: Check who we got this from, to validate route.
4343  */
4344 static int
4345 handle_mesh_keepalive (void *cls, const struct GNUNET_PeerIdentity *peer,
4346                        const struct GNUNET_MessageHeader *message)
4347 {
4348   struct GNUNET_MESH_TunnelKeepAlive *msg;
4349   struct GNUNET_PeerIdentity id;
4350   struct MeshTunnel *t;
4351
4352   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a keepalive packet from %s\n",
4353               GNUNET_i2s (peer));
4354
4355   msg = (struct GNUNET_MESH_TunnelKeepAlive *) message;
4356   t = tunnel_get (&msg->oid, ntohl (msg->tid));
4357
4358   if (NULL == t)
4359   {
4360     /* TODO notify that we dont know that tunnel */
4361     GNUNET_STATISTICS_update (stats, "# keepalive on unknown tunnel", 1,
4362                               GNUNET_NO);
4363     return GNUNET_OK;
4364   }
4365
4366   tunnel_reset_timeout (t);
4367
4368   GNUNET_STATISTICS_update (stats, "# keepalives forwarded", 1, GNUNET_NO);
4369   send_prebuilt_message (message, NULL, t);
4370   return GNUNET_OK;
4371   }
4372
4373
4374
4375 /**
4376  * Functions to handle messages from core
4377  */
4378 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
4379   {&handle_mesh_path_create, GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE, 0},
4380   {&handle_mesh_path_destroy, GNUNET_MESSAGE_TYPE_MESH_PATH_DESTROY, 0},
4381   {&handle_mesh_path_broken, GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN,
4382    sizeof (struct GNUNET_MESH_PathBroken)},
4383   {&handle_mesh_tunnel_destroy, GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY,
4384    sizeof (struct GNUNET_MESH_TunnelDestroy)},
4385   {&handle_mesh_data_unicast, GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
4386   {&handle_mesh_keepalive, GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE,
4387     sizeof (struct GNUNET_MESH_TunnelKeepAlive)},
4388   {&handle_mesh_data_to_orig, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
4389   {&handle_mesh_ack, GNUNET_MESSAGE_TYPE_MESH_ACK,
4390     sizeof (struct GNUNET_MESH_ACK)},
4391   {&handle_mesh_poll, GNUNET_MESSAGE_TYPE_MESH_POLL,
4392     sizeof (struct GNUNET_MESH_Poll)},
4393   {&handle_mesh_path_ack, GNUNET_MESSAGE_TYPE_MESH_PATH_ACK,
4394    sizeof (struct GNUNET_MESH_PathACK)},
4395   {NULL, 0, 0}
4396 };
4397
4398
4399
4400 /******************************************************************************/
4401 /****************       MESH LOCAL HANDLER HELPERS      ***********************/
4402 /******************************************************************************/
4403
4404
4405 #if LATER
4406 /**
4407  * notify_client_connection_failure: notify a client that the connection to the
4408  * requested remote peer is not possible (for instance, no route found)
4409  * Function called when the socket is ready to queue more data. "buf" will be
4410  * NULL and "size" zero if the socket was closed for writing in the meantime.
4411  *
4412  * @param cls closure
4413  * @param size number of bytes available in buf
4414  * @param buf where the callee should write the message
4415  * @return number of bytes written to buf
4416  */
4417 static size_t
4418 notify_client_connection_failure (void *cls, size_t size, void *buf)
4419 {
4420   int size_needed;
4421   struct MeshPeerInfo *peer_info;
4422   struct GNUNET_MESH_PeerControl *msg;
4423   struct GNUNET_PeerIdentity id;
4424
4425   if (0 == size && NULL == buf)
4426   {
4427     // TODO retry? cancel?
4428     return 0;
4429   }
4430
4431   size_needed = sizeof (struct GNUNET_MESH_PeerControl);
4432   peer_info = (struct MeshPeerInfo *) cls;
4433   msg = (struct GNUNET_MESH_PeerControl *) buf;
4434   msg->header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
4435   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DISCONNECTED);
4436 //     msg->tunnel_id = htonl(peer_info->t->tid);
4437   GNUNET_PEER_resolve (peer_info->id, &id);
4438   memcpy (&msg->peer, &id, sizeof (struct GNUNET_PeerIdentity));
4439
4440   return size_needed;
4441 }
4442 #endif
4443
4444
4445 /**
4446  * Send keepalive packets for a tunnel.
4447  *
4448  * @param cls Closure (tunnel for which to send the keepalive).
4449  * @param tc Notification context.
4450  */
4451 static void
4452 path_refresh (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4453 {
4454   struct MeshTunnel *t = cls;
4455   struct GNUNET_PeerIdentity id;
4456   struct GNUNET_MESH_TunnelKeepAlive *msg;
4457   size_t size = sizeof (struct GNUNET_MESH_TunnelKeepAlive);
4458   char cbuf[size];
4459
4460   t->path_refresh_task = GNUNET_SCHEDULER_NO_TASK;
4461   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
4462   {
4463     return;
4464   }
4465
4466   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4467               "sending keepalive for tunnel %d\n", t->id.tid);
4468
4469   msg = (struct GNUNET_MESH_TunnelKeepAlive *) cbuf;
4470   msg->header.size = htons (size);
4471   // FIXME change to tunnel keepalive
4472   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE);
4473   msg->oid = my_full_id;
4474   msg->tid = htonl (t->id.tid);
4475   GNUNET_PEER_resolve (t->next_hop, &id);
4476   send_prebuilt_message (&msg->header, &id, t);
4477
4478   t->path_refresh_task =
4479       GNUNET_SCHEDULER_add_delayed (refresh_path_time, &path_refresh, t);
4480   tunnel_reset_timeout (t);
4481 }
4482
4483
4484 /**
4485  * Function to process paths received for a new peer addition. The recorded
4486  * paths form the initial tunnel, which can be optimized later.
4487  * Called on each result obtained for the DHT search.
4488  *
4489  * @param cls closure
4490  * @param exp when will this value expire
4491  * @param key key of the result
4492  * @param get_path path of the get request
4493  * @param get_path_length lenght of get_path
4494  * @param put_path path of the put request
4495  * @param put_path_length length of the put_path
4496  * @param type type of the result
4497  * @param size number of bytes in data
4498  * @param data pointer to the result data
4499  *
4500  * TODO: re-issue the request after certain time? cancel after X results?
4501  */
4502 static void
4503 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
4504                     const struct GNUNET_HashCode * key,
4505                     const struct GNUNET_PeerIdentity *get_path,
4506                     unsigned int get_path_length,
4507                     const struct GNUNET_PeerIdentity *put_path,
4508                     unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
4509                     size_t size, const void *data)
4510 {
4511   struct MeshPeerInfo *peer = cls;
4512   struct MeshPeerPath *p;
4513   struct GNUNET_PeerIdentity pi;
4514   int i;
4515
4516   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got results from DHT!\n");
4517   GNUNET_PEER_resolve (peer->id, &pi);
4518   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for %s\n", GNUNET_i2s (&pi));
4519
4520   p = path_build_from_dht (get_path, get_path_length,
4521                            put_path, put_path_length);
4522   path_add_to_peers (p, GNUNET_NO);
4523   path_destroy (p);
4524   for (i = 0; i < peer->ntunnels; i++)
4525   {
4526     peer_connect (peer, peer->tunnels[i]); // FIXME add if
4527   }
4528
4529   return;
4530 }
4531
4532
4533 /******************************************************************************/
4534 /*********************       MESH LOCAL HANDLES      **************************/
4535 /******************************************************************************/
4536
4537
4538 /**
4539  * Handler for client disconnection
4540  *
4541  * @param cls closure
4542  * @param client identification of the client; NULL
4543  *        for the last call when the server is destroyed
4544  */
4545 static void
4546 handle_local_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
4547 {
4548   struct MeshClient *c;
4549   struct MeshClient *next;
4550
4551   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client disconnected\n");
4552   if (client == NULL)
4553   {
4554     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   (SERVER DOWN)\n");
4555     return;
4556   }
4557
4558   c = clients_head;
4559   while (NULL != c)
4560   {
4561     if (c->handle != client)
4562     {
4563       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ... searching\n");
4564       c = c->next;
4565       continue;
4566     }
4567     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "matching client found (%u)\n",
4568                 c->id);
4569     GNUNET_SERVER_client_drop (c->handle);
4570     c->shutting_down = GNUNET_YES;
4571     GNUNET_CONTAINER_multihashmap_iterate (c->own_tunnels,
4572                                            &tunnel_destroy_iterator, c);
4573     GNUNET_CONTAINER_multihashmap_iterate (c->incoming_tunnels,
4574                                            &tunnel_destroy_iterator, c);
4575     GNUNET_CONTAINER_multihashmap_iterate (c->ignore_tunnels,
4576                                            &tunnel_destroy_iterator, c);
4577     GNUNET_CONTAINER_multihashmap_destroy (c->own_tunnels);
4578     GNUNET_CONTAINER_multihashmap_destroy (c->incoming_tunnels);
4579     GNUNET_CONTAINER_multihashmap_destroy (c->ignore_tunnels);
4580
4581     if (NULL != c->types)
4582       GNUNET_CONTAINER_multihashmap_destroy (c->types);
4583     next = c->next;
4584     GNUNET_CONTAINER_DLL_remove (clients_head, clients_tail, c);
4585     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  CLIENT FREE at %p\n", c);
4586     GNUNET_free (c);
4587     GNUNET_STATISTICS_update (stats, "# clients", -1, GNUNET_NO);
4588     c = next;
4589   }
4590   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "done!\n");
4591   return;
4592 }
4593
4594
4595 /**
4596  * Handler for new clients
4597  *
4598  * @param cls closure
4599  * @param client identification of the client
4600  * @param message the actual message, which includes messages the client wants
4601  */
4602 static void
4603 handle_local_new_client (void *cls, struct GNUNET_SERVER_Client *client,
4604                          const struct GNUNET_MessageHeader *message)
4605 {
4606   struct GNUNET_MESH_ClientConnect *cc_msg;
4607   struct MeshClient *c;
4608   unsigned int size;
4609   uint16_t ntypes;
4610   uint16_t *t;
4611   uint16_t i;
4612
4613   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client connected\n");
4614
4615   /* Check data sanity */
4616   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_ClientConnect);
4617   cc_msg = (struct GNUNET_MESH_ClientConnect *) message;
4618   ntypes = ntohs (cc_msg->types);
4619   if (size != ntypes * sizeof (uint16_t))
4620   {
4621     GNUNET_break (0);
4622     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4623     return;
4624   }
4625
4626   /* Create new client structure */
4627   c = GNUNET_malloc (sizeof (struct MeshClient));
4628   c->id = next_client_id++; // overflow not important: just for debug
4629   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  CLIENT NEW %u\n", c->id);
4630   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  client has %u types\n", ntypes);
4631   c->handle = client;
4632   GNUNET_SERVER_client_keep (client);
4633   if (ntypes > 0)
4634   {
4635     uint16_t u16;
4636     struct GNUNET_HashCode hc;
4637
4638     t = (uint16_t *) &cc_msg[1];
4639     c->types = GNUNET_CONTAINER_multihashmap_create (ntypes, GNUNET_NO);
4640     for (i = 0; i < ntypes; i++)
4641     {
4642       u16 = ntohs (t[i]);
4643       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    msg type: %u\n", u16);
4644       GNUNET_CRYPTO_hash (&u16, sizeof (u16), &hc); // FIXME pseudo hash
4645
4646       /* store in clients hashmap */
4647       GNUNET_CONTAINER_multihashmap_put (c->types, &hc, c,
4648                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
4649       /* store in global hashmap */
4650       GNUNET_CONTAINER_multihashmap_put (types, &hc, c,
4651                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
4652     }
4653   }
4654
4655   GNUNET_CONTAINER_DLL_insert (clients_head, clients_tail, c);
4656   c->own_tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
4657   c->incoming_tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
4658   c->ignore_tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
4659   GNUNET_SERVER_notification_context_add (nc, client);
4660   GNUNET_STATISTICS_update (stats, "# clients", 1, GNUNET_NO);
4661
4662   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4663   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client processed\n");
4664 }
4665
4666
4667 /**
4668  * Handler for requests of new tunnels
4669  *
4670  * @param cls Closure.
4671  * @param client Identification of the client.
4672  * @param message The actual message.
4673  */
4674 static void
4675 handle_local_tunnel_create (void *cls, struct GNUNET_SERVER_Client *client,
4676                             const struct GNUNET_MessageHeader *message)
4677 {
4678   struct GNUNET_MESH_TunnelMessage *t_msg;
4679   struct MeshPeerInfo *peer_info;
4680   struct MeshTunnel *t;
4681   struct MeshClient *c;
4682   MESH_TunnelNumber tid;
4683
4684   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new tunnel requested\n");
4685
4686   /* Sanity check for client registration */
4687   if (NULL == (c = client_get (client)))
4688   {
4689     GNUNET_break (0);
4690     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4691     return;
4692   }
4693   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
4694
4695   /* Message sanity check */
4696   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
4697   {
4698     GNUNET_break (0);
4699     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4700     return;
4701   }
4702
4703   t_msg = (struct GNUNET_MESH_TunnelMessage *) message;
4704   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  towards %s\n",
4705               GNUNET_i2s (&t_msg->peer));
4706   /* Sanity check for tunnel numbering */
4707   tid = ntohl (t_msg->tunnel_id);
4708   if (0 == (tid & GNUNET_MESH_LOCAL_TUNNEL_ID_CLI))
4709   {
4710     GNUNET_break (0);
4711     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4712     return;
4713   }
4714   /* Sanity check for duplicate tunnel IDs */
4715   if (NULL != tunnel_get_by_local_id (c, tid))
4716   {
4717     GNUNET_break (0);
4718     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4719     return;
4720   }
4721
4722   while (NULL != tunnel_get_by_pi (myid, next_tid))
4723     next_tid = (next_tid + 1) & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
4724   t = tunnel_new (myid, next_tid, c, tid);
4725   next_tid = (next_tid + 1) & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
4726   if (NULL == t)
4727   {
4728     GNUNET_break (0);
4729     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4730     return;
4731   }
4732   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CREATED TUNNEL %s [%x] (%x)\n",
4733               GNUNET_i2s (&my_full_id), t->id.tid, t->local_tid);
4734
4735   peer_info = peer_get (&t_msg->peer);
4736   GNUNET_array_append (peer_info->tunnels, peer_info->ntunnels, t);
4737   peer_connect (peer_info, t);
4738   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4739   return;
4740 }
4741
4742
4743 /**
4744  * Handler for requests of deleting tunnels
4745  *
4746  * @param cls closure
4747  * @param client identification of the client
4748  * @param message the actual message
4749  */
4750 static void
4751 handle_local_tunnel_destroy (void *cls, struct GNUNET_SERVER_Client *client,
4752                              const struct GNUNET_MessageHeader *message)
4753 {
4754   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
4755   struct MeshClient *c;
4756   struct MeshTunnel *t;
4757   MESH_TunnelNumber tid;
4758
4759   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4760               "Got a DESTROY TUNNEL from client!\n");
4761
4762   /* Sanity check for client registration */
4763   if (NULL == (c = client_get (client)))
4764   {
4765     GNUNET_break (0);
4766     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4767     return;
4768   }
4769   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
4770
4771   /* Message sanity check */
4772   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
4773   {
4774     GNUNET_break (0);
4775     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4776     return;
4777   }
4778
4779   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
4780
4781   /* Retrieve tunnel */
4782   tid = ntohl (tunnel_msg->tunnel_id);
4783   t = tunnel_get_by_local_id(c, tid);
4784   if (NULL == t)
4785   {
4786     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  tunnel %X not found\n", tid);
4787     GNUNET_break (0);
4788     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4789     return;
4790   }
4791   if (c != t->owner || tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
4792   {
4793     client_ignore_tunnel (c, t);
4794     tunnel_destroy_empty (t);
4795     GNUNET_SERVER_receive_done (client, GNUNET_OK);
4796     return;
4797   }
4798   send_client_tunnel_disconnect (t, c);
4799   client_delete_tunnel (c, t);
4800
4801   /* Don't try to ACK the client about the tunnel_destroy multicast packet */
4802   t->owner = NULL;
4803   tunnel_send_destroy (t);
4804   peer_remove_tunnel (peer_get_short(t->peer), t);
4805   t->destroy = GNUNET_YES;
4806   /* The tunnel will be destroyed when the last message is transmitted. */
4807   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4808   return;
4809 }
4810
4811
4812 /**
4813  * Handler for requests of seeting tunnel's buffering policy.
4814  *
4815  * @param cls Closure (unused).
4816  * @param client Identification of the client.
4817  * @param message The actual message.
4818  */
4819 static void
4820 handle_local_tunnel_buffer (void *cls, struct GNUNET_SERVER_Client *client,
4821                             const struct GNUNET_MessageHeader *message)
4822 {
4823   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
4824   struct MeshClient *c;
4825   struct MeshTunnel *t;
4826   MESH_TunnelNumber tid;
4827
4828   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4829               "Got a BUFFER request from client!\n");
4830
4831   /* Sanity check for client registration */
4832   if (NULL == (c = client_get (client)))
4833   {
4834     GNUNET_break (0);
4835     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4836     return;
4837   }
4838   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
4839
4840   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
4841
4842   /* Retrieve tunnel */
4843   tid = ntohl (tunnel_msg->tunnel_id);
4844   t = tunnel_get_by_local_id(c, tid);
4845   if (NULL == t)
4846   {
4847     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  tunnel %X not found\n", tid);
4848     GNUNET_break (0);
4849     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4850     return;
4851   }
4852
4853   switch (ntohs(message->type))
4854   {
4855       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_BUFFER:
4856           t->nobuffer = GNUNET_NO;
4857           break;
4858       case GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_NOBUFFER:
4859           t->nobuffer = GNUNET_YES;
4860           break;
4861       default:
4862           GNUNET_break (0);
4863   }
4864
4865   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4866 }
4867
4868
4869 /**
4870  * Handler for client traffic directed to one peer
4871  *
4872  * @param cls closure
4873  * @param client identification of the client
4874  * @param message the actual message
4875  */
4876 static void
4877 handle_local_unicast (void *cls, struct GNUNET_SERVER_Client *client,
4878                       const struct GNUNET_MessageHeader *message)
4879 {
4880   struct MeshClient *c;
4881   struct MeshTunnel *t;
4882   struct GNUNET_MESH_Unicast *data_msg;
4883   MESH_TunnelNumber tid;
4884   size_t size;
4885
4886   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4887               "Got a unicast request from a client!\n");
4888
4889   /* Sanity check for client registration */
4890   if (NULL == (c = client_get (client)))
4891   {
4892     GNUNET_break (0);
4893     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4894     return;
4895   }
4896   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
4897
4898   data_msg = (struct GNUNET_MESH_Unicast *) message;
4899
4900   /* Sanity check for message size */
4901   size = ntohs (message->size);
4902   if (sizeof (struct GNUNET_MESH_Unicast) +
4903       sizeof (struct GNUNET_MessageHeader) > size)
4904   {
4905     GNUNET_break (0);
4906     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4907     return;
4908   }
4909
4910   /* Tunnel exists? */
4911   tid = ntohl (data_msg->tid);
4912   t = tunnel_get_by_local_id (c, tid);
4913   if (NULL == t)
4914   {
4915     GNUNET_break (0);
4916     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4917     return;
4918   }
4919
4920   /*  Is it a local tunnel? Then, does client own the tunnel? */
4921   if (t->owner->handle != client)
4922   {
4923     GNUNET_break (0);
4924     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4925     return;
4926   }
4927
4928   /* PID should be as expected */
4929   if (ntohl (data_msg->pid) != t->fwd_pid + 1)
4930   {
4931     GNUNET_break (0);
4932     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4933               "Unicast PID, expected %u, got %u\n",
4934               t->fwd_pid + 1, ntohl (data_msg->pid));
4935     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4936     return;
4937   }
4938
4939   /* Ok, everything is correct, send the message
4940    * (pretend we got it from a mesh peer)
4941    */
4942   {
4943     /* Work around const limitation */
4944     char buf[ntohs (message->size)] GNUNET_ALIGN;
4945     struct GNUNET_MESH_Unicast *copy;
4946
4947     copy = (struct GNUNET_MESH_Unicast *) buf;
4948     memcpy (buf, data_msg, size);
4949     copy->oid = my_full_id;
4950     copy->tid = htonl (t->id.tid);
4951     copy->ttl = htonl (default_ttl);
4952     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4953                 "  calling generic handler...\n");
4954     handle_mesh_data_unicast (NULL, &my_full_id, &copy->header);
4955   }
4956   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "receive done OK\n");
4957   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4958
4959   return;
4960 }
4961
4962
4963 /**
4964  * Handler for client traffic directed to the origin
4965  *
4966  * @param cls closure
4967  * @param client identification of the client
4968  * @param message the actual message
4969  */
4970 static void
4971 handle_local_to_origin (void *cls, struct GNUNET_SERVER_Client *client,
4972                         const struct GNUNET_MessageHeader *message)
4973 {
4974   struct GNUNET_MESH_ToOrigin *data_msg;
4975   struct MeshTunnelClientInfo *clinfo;
4976   struct MeshClient *c;
4977   struct MeshTunnel *t;
4978   MESH_TunnelNumber tid;
4979   size_t size;
4980
4981   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4982               "Got a ToOrigin request from a client!\n");
4983   /* Sanity check for client registration */
4984   if (NULL == (c = client_get (client)))
4985   {
4986     GNUNET_break (0);
4987     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4988     return;
4989   }
4990   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
4991
4992   data_msg = (struct GNUNET_MESH_ToOrigin *) message;
4993
4994   /* Sanity check for message size */
4995   size = ntohs (message->size);
4996   if (sizeof (struct GNUNET_MESH_ToOrigin) +
4997       sizeof (struct GNUNET_MessageHeader) > size)
4998   {
4999     GNUNET_break (0);
5000     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5001     return;
5002   }
5003
5004   /* Tunnel exists? */
5005   tid = ntohl (data_msg->tid);
5006   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", tid);
5007   if (tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
5008   {
5009     GNUNET_break (0);
5010     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5011     return;
5012   }
5013   t = tunnel_get_by_local_id (c, tid);
5014   if (NULL == t)
5015   {
5016     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Tunnel %X unknown.\n", tid);
5017     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  for client %u.\n", c->id);
5018     GNUNET_break (0);
5019     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5020     return;
5021   }
5022
5023   /*  It should be sent by someone who has this as incoming tunnel. */
5024   if (GNUNET_NO == client_knows_tunnel (c, t))
5025   {
5026     GNUNET_break (0);
5027     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5028     return;
5029   }
5030
5031   /* PID should be as expected */
5032   clinfo = tunnel_get_client_fc (t, c);
5033   if (ntohl (data_msg->pid) != clinfo->bck_pid + 1)
5034   {
5035     GNUNET_break (0);
5036     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5037                 "To Origin PID, expected %u, got %u\n",
5038                 clinfo->bck_pid + 1,
5039                 ntohl (data_msg->pid));
5040     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5041     return;
5042   }
5043   clinfo->bck_pid++;
5044
5045   /* Ok, everything is correct, send the message
5046    * (pretend we got it from a mesh peer)
5047    */
5048   {
5049     char buf[ntohs (message->size)] GNUNET_ALIGN;
5050     struct GNUNET_MESH_ToOrigin *copy;
5051
5052     /* Work around const limitation */
5053     copy = (struct GNUNET_MESH_ToOrigin *) buf;
5054     memcpy (buf, data_msg, size);
5055     GNUNET_PEER_resolve (t->id.oid, &copy->oid);
5056     copy->tid = htonl (t->id.tid);
5057     copy->ttl = htonl (default_ttl);
5058     copy->pid = htonl (t->bck_pid + 1);
5059
5060     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5061                 "  calling generic handler...\n");
5062     handle_mesh_data_to_orig (NULL, &my_full_id, &copy->header);
5063   }
5064   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5065
5066   return;
5067 }
5068
5069
5070 /**
5071  * Handler for client's ACKs for payload traffic.
5072  *
5073  * @param cls Closure (unused).
5074  * @param client Identification of the client.
5075  * @param message The actual message.
5076  */
5077 static void
5078 handle_local_ack (void *cls, struct GNUNET_SERVER_Client *client,
5079                   const struct GNUNET_MessageHeader *message)
5080 {
5081   struct GNUNET_MESH_LocalAck *msg;
5082   struct MeshTunnel *t;
5083   struct MeshClient *c;
5084   MESH_TunnelNumber tid;
5085   uint32_t ack;
5086
5087   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a local ACK\n");
5088   /* Sanity check for client registration */
5089   if (NULL == (c = client_get (client)))
5090   {
5091     GNUNET_break (0);
5092     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5093     return;
5094   }
5095   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
5096
5097   msg = (struct GNUNET_MESH_LocalAck *) message;
5098
5099   /* Tunnel exists? */
5100   tid = ntohl (msg->tunnel_id);
5101   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", tid);
5102   t = tunnel_get_by_local_id (c, tid);
5103   if (NULL == t)
5104   {
5105     GNUNET_break (0);
5106     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Tunnel %X unknown.\n", tid);
5107     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "  for client %u.\n", c->id);
5108     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5109     return;
5110   }
5111
5112   ack = ntohl (msg->max_pid);
5113   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ack %u\n", ack);
5114
5115   /* Does client own tunnel? I.E: Is this an ACK for BCK traffic? */
5116   if (NULL != t->owner && t->owner->handle == client)
5117   {
5118     /* The client owns the tunnel, ACK is for data to_origin, send BCK ACK. */
5119     t->bck_ack = ack;
5120     tunnel_send_bck_ack(t, GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
5121   }
5122   else
5123   {
5124     /* The client doesn't own the tunnel, this ACK is for FWD traffic. */
5125     tunnel_set_client_fwd_ack (t, c, ack);
5126     tunnel_send_fwd_ack (t, GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK);
5127   }
5128
5129   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5130
5131   return;
5132 }
5133
5134
5135
5136 /**
5137  * Iterator over all tunnels to send a monitoring client info about each tunnel.
5138  *
5139  * @param cls Closure (client handle).
5140  * @param key Key (hashed tunnel ID, unused).
5141  * @param value Tunnel info.
5142  *
5143  * @return GNUNET_YES, to keep iterating.
5144  */
5145 static int
5146 monitor_all_tunnels_iterator (void *cls,
5147                               const struct GNUNET_HashCode * key,
5148                               void *value)
5149 {
5150   struct GNUNET_SERVER_Client *client = cls;
5151   struct MeshTunnel *t = value;
5152   struct GNUNET_MESH_LocalMonitor *msg;
5153
5154   msg = GNUNET_malloc (sizeof(struct GNUNET_MESH_LocalMonitor));
5155   GNUNET_PEER_resolve(t->id.oid, &msg->owner);
5156   msg->tunnel_id = htonl (t->id.tid);
5157   msg->header.size = htons (sizeof (struct GNUNET_MESH_LocalMonitor));
5158   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS);
5159   GNUNET_PEER_resolve (t->peer, &msg->destination);
5160
5161   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5162               "*  sending info about tunnel %s [%u]\n",
5163               GNUNET_i2s (&msg->owner), t->id.tid);
5164
5165   GNUNET_SERVER_notification_context_unicast (nc, client,
5166                                               &msg->header, GNUNET_NO);
5167   return GNUNET_YES;
5168 }
5169
5170
5171 /**
5172  * Handler for client's MONITOR request.
5173  *
5174  * @param cls Closure (unused).
5175  * @param client Identification of the client.
5176  * @param message The actual message.
5177  */
5178 static void
5179 handle_local_get_tunnels (void *cls, struct GNUNET_SERVER_Client *client,
5180                           const struct GNUNET_MessageHeader *message)
5181 {
5182   struct MeshClient *c;
5183
5184   /* Sanity check for client registration */
5185   if (NULL == (c = client_get (client)))
5186   {
5187     GNUNET_break (0);
5188     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5189     return;
5190   }
5191
5192   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5193               "Received get tunnels request from client %u\n",
5194               c->id);
5195   GNUNET_CONTAINER_multihashmap_iterate (tunnels,
5196                                          monitor_all_tunnels_iterator,
5197                                          client);
5198   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5199               "Get tunnels request from client %u completed\n",
5200               c->id);
5201   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5202 }
5203
5204
5205 /**
5206  * Handler for client's MONITOR_TUNNEL request.
5207  *
5208  * @param cls Closure (unused).
5209  * @param client Identification of the client.
5210  * @param message The actual message.
5211  */
5212 static void
5213 handle_local_show_tunnel (void *cls, struct GNUNET_SERVER_Client *client,
5214                           const struct GNUNET_MessageHeader *message)
5215 {
5216   const struct GNUNET_MESH_LocalMonitor *msg;
5217   struct GNUNET_MESH_LocalMonitor *resp;
5218   struct MeshClient *c;
5219   struct MeshTunnel *t;
5220
5221   /* Sanity check for client registration */
5222   if (NULL == (c = client_get (client)))
5223   {
5224     GNUNET_break (0);
5225     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5226     return;
5227   }
5228
5229   msg = (struct GNUNET_MESH_LocalMonitor *) message;
5230   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5231               "Received tunnel info request from client %u for tunnel %s[%X]\n",
5232               c->id,
5233               &msg->owner,
5234               ntohl (msg->tunnel_id));
5235   t = tunnel_get (&msg->owner, ntohl (msg->tunnel_id));
5236   if (NULL == t)
5237   {
5238     /* We don't know the tunnel FIXME */
5239     struct GNUNET_MESH_LocalMonitor warn;
5240
5241     warn = *msg;
5242     GNUNET_SERVER_notification_context_unicast (nc, client,
5243                                                 &warn.header,
5244                                                 GNUNET_NO);
5245     GNUNET_SERVER_receive_done (client, GNUNET_OK);
5246     return;
5247   }
5248
5249   /* Initialize context */
5250   resp = GNUNET_malloc (sizeof (struct GNUNET_MESH_LocalMonitor));
5251   *resp = *msg;
5252   GNUNET_PEER_resolve (t->peer, &resp->destination);
5253   resp->header.size = htons (sizeof (struct GNUNET_MESH_LocalMonitor));
5254   GNUNET_SERVER_notification_context_unicast (nc, c->handle,
5255                                               &resp->header, GNUNET_NO);
5256   GNUNET_free (resp);
5257
5258   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5259               "Monitor tunnel request from client %u completed\n",
5260               c->id);
5261   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5262 }
5263
5264
5265 /**
5266  * Functions to handle messages from clients
5267  */
5268 static struct GNUNET_SERVER_MessageHandler client_handlers[] = {
5269   {&handle_local_new_client, NULL,
5270    GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT, 0},
5271   {&handle_local_tunnel_create, NULL,
5272    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE,
5273    sizeof (struct GNUNET_MESH_TunnelMessage)},
5274   {&handle_local_tunnel_destroy, NULL,
5275    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY,
5276    sizeof (struct GNUNET_MESH_TunnelMessage)},
5277   {&handle_local_tunnel_buffer, NULL,
5278    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_BUFFER,
5279    sizeof (struct GNUNET_MESH_TunnelMessage)},
5280   {&handle_local_tunnel_buffer, NULL,
5281    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_NOBUFFER,
5282    sizeof (struct GNUNET_MESH_TunnelMessage)},
5283   {&handle_local_unicast, NULL,
5284    GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
5285   {&handle_local_to_origin, NULL,
5286    GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
5287   {&handle_local_ack, NULL,
5288    GNUNET_MESSAGE_TYPE_MESH_LOCAL_ACK,
5289    sizeof (struct GNUNET_MESH_LocalAck)},
5290   {&handle_local_get_tunnels, NULL,
5291    GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNELS,
5292    sizeof (struct GNUNET_MessageHeader)},
5293   {&handle_local_show_tunnel, NULL,
5294    GNUNET_MESSAGE_TYPE_MESH_LOCAL_INFO_TUNNEL,
5295      sizeof (struct GNUNET_MESH_LocalMonitor)},
5296   {NULL, NULL, 0, 0}
5297 };
5298
5299
5300 /**
5301  * To be called on core init/fail.
5302  *
5303  * @param cls service closure
5304  * @param server handle to the server for this service
5305  * @param identity the public identity of this peer
5306  */
5307 static void
5308 core_init (void *cls, struct GNUNET_CORE_Handle *server,
5309            const struct GNUNET_PeerIdentity *identity)
5310 {
5311   static int i = 0;
5312   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Core init\n");
5313   core_handle = server;
5314   if (0 != memcmp (identity, &my_full_id, sizeof (my_full_id)) ||
5315       NULL == server)
5316   {
5317     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Wrong CORE service\n"));
5318     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5319                 " core id %s\n",
5320                 GNUNET_i2s (identity));
5321     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5322                 " my id %s\n",
5323                 GNUNET_i2s (&my_full_id));
5324     GNUNET_SCHEDULER_shutdown (); // Try gracefully
5325     if (10 < i++)
5326       GNUNET_abort(); // Try harder
5327   }
5328   return;
5329 }
5330
5331
5332 /**
5333  * Method called whenever a given peer connects.
5334  *
5335  * @param cls closure
5336  * @param peer peer identity this notification is about
5337  */
5338 static void
5339 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer)
5340 {
5341   struct MeshPeerInfo *peer_info;
5342   struct MeshPeerPath *path;
5343
5344   DEBUG_CONN ("Peer connected\n");
5345   DEBUG_CONN ("     %s\n", GNUNET_i2s (&my_full_id));
5346   peer_info = peer_get (peer);
5347   if (myid == peer_info->id)
5348   {
5349     DEBUG_CONN ("     (self)\n");
5350     return;
5351   }
5352   else
5353   {
5354     DEBUG_CONN ("     %s\n", GNUNET_i2s (peer));
5355   }
5356   path = path_new (2);
5357   path->peers[0] = myid;
5358   path->peers[1] = peer_info->id;
5359   GNUNET_PEER_change_rc (myid, 1);
5360   GNUNET_PEER_change_rc (peer_info->id, 1);
5361   peer_info_add_path (peer_info, path, GNUNET_YES);
5362   GNUNET_STATISTICS_update (stats, "# peers", 1, GNUNET_NO);
5363   return;
5364 }
5365
5366
5367 /**
5368  * Method called whenever a peer disconnects.
5369  *
5370  * @param cls closure
5371  * @param peer peer identity this notification is about
5372  */
5373 static void
5374 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
5375 {
5376   struct MeshPeerInfo *pi;
5377   struct MeshPeerQueue *q;
5378   struct MeshPeerQueue *n;
5379
5380   DEBUG_CONN ("Peer disconnected\n");
5381   pi = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
5382   if (NULL == pi)
5383   {
5384     GNUNET_break (0);
5385     return;
5386   }
5387   q = pi->queue_head;
5388   while (NULL != q)
5389   {
5390       n = q->next;
5391       /* TODO try to reroute this traffic instead */
5392       queue_destroy(q, GNUNET_YES);
5393       q = n;
5394   }
5395   if (NULL != pi->core_transmit)
5396   {
5397     GNUNET_CORE_notify_transmit_ready_cancel(pi->core_transmit);
5398     pi->core_transmit = NULL;
5399   }
5400     peer_remove_path (pi, pi->id, myid);
5401   if (myid == pi->id)
5402   {
5403     DEBUG_CONN ("     (self)\n");
5404   }
5405   GNUNET_STATISTICS_update (stats, "# peers", -1, GNUNET_NO);
5406   return;
5407 }
5408
5409
5410 /******************************************************************************/
5411 /************************      MAIN FUNCTIONS      ****************************/
5412 /******************************************************************************/
5413
5414 /**
5415  * Iterator over tunnel hash map entries to destroy the tunnel during shutdown.
5416  *
5417  * @param cls closure
5418  * @param key current key code
5419  * @param value value in the hash map
5420  * @return GNUNET_YES if we should continue to iterate,
5421  *         GNUNET_NO if not.
5422  */
5423 static int
5424 shutdown_tunnel (void *cls, const struct GNUNET_HashCode * key, void *value)
5425 {
5426   struct MeshTunnel *t = value;
5427
5428   tunnel_destroy (t);
5429   return GNUNET_YES;
5430 }
5431
5432 /**
5433  * Iterator over peer hash map entries to destroy the tunnel during shutdown.
5434  *
5435  * @param cls closure
5436  * @param key current key code
5437  * @param value value in the hash map
5438  * @return GNUNET_YES if we should continue to iterate,
5439  *         GNUNET_NO if not.
5440  */
5441 static int
5442 shutdown_peer (void *cls, const struct GNUNET_HashCode * key, void *value)
5443 {
5444   struct MeshPeerInfo *p = value;
5445   struct MeshPeerQueue *q;
5446   struct MeshPeerQueue *n;
5447
5448   q = p->queue_head;
5449   while (NULL != q)
5450   {
5451       n = q->next;
5452       if (q->peer == p)
5453       {
5454         queue_destroy(q, GNUNET_YES);
5455       }
5456       q = n;
5457   }
5458   peer_info_destroy (p);
5459   return GNUNET_YES;
5460 }
5461
5462
5463 /**
5464  * Task run during shutdown.
5465  *
5466  * @param cls unused
5467  * @param tc unused
5468  */
5469 static void
5470 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
5471 {
5472   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shutting down\n");
5473
5474   if (core_handle != NULL)
5475   {
5476     GNUNET_CORE_disconnect (core_handle);
5477     core_handle = NULL;
5478   }
5479   if (NULL != keygen)
5480   {
5481     GNUNET_CRYPTO_ecc_key_create_stop (keygen);
5482     keygen = NULL;
5483   }
5484   GNUNET_CONTAINER_multihashmap_iterate (tunnels, &shutdown_tunnel, NULL);
5485   GNUNET_CONTAINER_multihashmap_iterate (peers, &shutdown_peer, NULL);
5486   if (dht_handle != NULL)
5487   {
5488     GNUNET_DHT_disconnect (dht_handle);
5489     dht_handle = NULL;
5490   }
5491   if (nc != NULL)
5492   {
5493     GNUNET_SERVER_notification_context_destroy (nc);
5494     nc = NULL;
5495   }
5496   if (GNUNET_SCHEDULER_NO_TASK != announce_id_task)
5497   {
5498     GNUNET_SCHEDULER_cancel (announce_id_task);
5499     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
5500   }
5501   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shut down\n");
5502 }
5503
5504
5505 /**
5506  * Callback for hostkey read/generation.
5507  *
5508  * @param cls Closure (Configuration handle).
5509  * @param pk The ECC private key.
5510  * @param emsg Error message, if any.
5511  */
5512 static void
5513 key_generation_cb (void *cls,
5514                    struct GNUNET_CRYPTO_EccPrivateKey *pk,
5515                    const char *emsg)
5516 {
5517   const struct GNUNET_CONFIGURATION_Handle *c = cls;
5518   struct MeshPeerInfo *peer;
5519   struct MeshPeerPath *p;
5520
5521   keygen = NULL;  
5522   if (NULL == pk)
5523   {
5524     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5525                 _("Mesh service could not access hostkey: %s. Exiting.\n"),
5526                 emsg);
5527     GNUNET_SCHEDULER_shutdown ();
5528     return;
5529   }
5530   my_private_key = pk;
5531   GNUNET_CRYPTO_ecc_key_get_public (my_private_key, &my_public_key);
5532   GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
5533                       &my_full_id.hashPubKey);
5534   myid = GNUNET_PEER_intern (&my_full_id);
5535   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5536               "Mesh for peer [%s] starting\n",
5537               GNUNET_i2s(&my_full_id));
5538
5539   core_handle = GNUNET_CORE_connect (c, /* Main configuration */
5540                                      NULL,      /* Closure passed to MESH functions */
5541                                      &core_init,        /* Call core_init once connected */
5542                                      &core_connect,     /* Handle connects */
5543                                      &core_disconnect,  /* remove peers on disconnects */
5544                                      NULL,      /* Don't notify about all incoming messages */
5545                                      GNUNET_NO, /* For header only in notification */
5546                                      NULL,      /* Don't notify about all outbound messages */
5547                                      GNUNET_NO, /* For header-only out notification */
5548                                      core_handlers);    /* Register these handlers */
5549   
5550   if (core_handle == NULL)
5551   {
5552     GNUNET_break (0);
5553     GNUNET_SCHEDULER_shutdown ();
5554     return;
5555   }
5556
5557   next_tid = 0;
5558   next_local_tid = GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
5559
5560
5561   GNUNET_SERVER_add_handlers (server_handle, client_handlers);
5562   nc = GNUNET_SERVER_notification_context_create (server_handle, 1);
5563   GNUNET_SERVER_disconnect_notify (server_handle,
5564                                    &handle_local_client_disconnect, NULL);
5565
5566
5567   clients_head = NULL;
5568   clients_tail = NULL;
5569   next_client_id = 0;
5570
5571   announce_id_task = GNUNET_SCHEDULER_add_now (&announce_id, cls);
5572
5573   /* Create a peer_info for the local peer */
5574   peer = peer_get (&my_full_id);
5575   p = path_new (1);
5576   p->peers[0] = myid;
5577   GNUNET_PEER_change_rc (myid, 1);
5578   peer_info_add_path (peer, p, GNUNET_YES);
5579   GNUNET_SERVER_resume (server_handle);
5580   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Mesh service running\n");
5581 }
5582
5583
5584 /**
5585  * Process mesh requests.
5586  *
5587  * @param cls closure
5588  * @param server the initialized server
5589  * @param c configuration to use
5590  */
5591 static void
5592 run (void *cls, struct GNUNET_SERVER_Handle *server,
5593      const struct GNUNET_CONFIGURATION_Handle *c)
5594 {
5595   char *keyfile;
5596
5597   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "starting to run\n");
5598   server_handle = server;
5599
5600   if (GNUNET_OK !=
5601       GNUNET_CONFIGURATION_get_value_filename (c, "PEER", "PRIVATE_KEY",
5602                                                &keyfile))
5603   {
5604     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5605                 _
5606                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
5607                 "mesh", "peer/privatekey");
5608     GNUNET_SCHEDULER_shutdown ();
5609     return;
5610   }
5611
5612   if (GNUNET_OK !=
5613       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "REFRESH_PATH_TIME",
5614                                            &refresh_path_time))
5615   {
5616     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5617                 _
5618                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
5619                 "mesh", "refresh path time");
5620     GNUNET_SCHEDULER_shutdown ();
5621     return;
5622   }
5623
5624   if (GNUNET_OK !=
5625       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "ID_ANNOUNCE_TIME",
5626                                            &id_announce_time))
5627   {
5628     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5629                 _
5630                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
5631                 "mesh", "id announce time");
5632     GNUNET_SCHEDULER_shutdown ();
5633     return;
5634   }
5635
5636   if (GNUNET_OK !=
5637       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "CONNECT_TIMEOUT",
5638                                            &connect_timeout))
5639   {
5640     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5641                 _
5642                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
5643                 "mesh", "connect timeout");
5644     GNUNET_SCHEDULER_shutdown ();
5645     return;
5646   }
5647
5648   if (GNUNET_OK !=
5649       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_MSGS_QUEUE",
5650                                              &max_msgs_queue))
5651   {
5652     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5653                 _
5654                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
5655                 "mesh", "max msgs queue");
5656     GNUNET_SCHEDULER_shutdown ();
5657     return;
5658   }
5659
5660   if (GNUNET_OK !=
5661       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_TUNNELS",
5662                                              &max_tunnels))
5663   {
5664     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5665                 _
5666                 ("%s service is lacking key configuration settings (%s).  Exiting.\n"),
5667                 "mesh", "max tunnels");
5668     GNUNET_SCHEDULER_shutdown ();
5669     return;
5670   }
5671
5672   if (GNUNET_OK !=
5673       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DEFAULT_TTL",
5674                                              &default_ttl))
5675   {
5676     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5677                 _
5678                 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
5679                 "mesh", "default ttl", 64);
5680     default_ttl = 64;
5681   }
5682
5683   if (GNUNET_OK !=
5684       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_PEERS",
5685                                              &max_peers))
5686   {
5687     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5688                 _("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
5689                 "mesh", "max peers", 1000);
5690     max_peers = 1000;
5691   }
5692
5693   if (GNUNET_OK !=
5694       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DHT_REPLICATION_LEVEL",
5695                                              &dht_replication_level))
5696   {
5697     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5698                 _
5699                 ("%s service is lacking key configuration settings (%s). Using default (%u).\n"),
5700                 "mesh", "dht replication level", 3);
5701     dht_replication_level = 3;
5702   }
5703
5704   tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
5705   incoming_tunnels = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
5706   peers = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
5707   types = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO);
5708
5709   dht_handle = GNUNET_DHT_connect (c, 64);
5710   if (NULL == dht_handle)
5711   {
5712     GNUNET_break (0);
5713   }
5714   stats = GNUNET_STATISTICS_create ("mesh", c);
5715
5716   GNUNET_SERVER_suspend (server_handle);
5717   /* Scheduled the task to clean up when shutdown is called */
5718   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
5719                                 NULL);
5720   keygen = GNUNET_CRYPTO_ecc_key_create_start (keyfile,
5721                                                &key_generation_cb,
5722                                                (void *) c);
5723   GNUNET_free (keyfile);
5724 }
5725
5726
5727 /**
5728  * The main function for the mesh service.
5729  *
5730  * @param argc number of arguments from the command line
5731  * @param argv command line arguments
5732  * @return 0 ok, 1 on error
5733  */
5734 int
5735 main (int argc, char *const *argv)
5736 {
5737   int ret;
5738   int r;
5739
5740   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main()\n");
5741   r = GNUNET_SERVICE_run (argc, argv, "mesh", GNUNET_SERVICE_OPTION_NONE, &run,
5742                           NULL);
5743   ret = (GNUNET_OK == r) ? 0 : 1;
5744   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main() END\n");
5745
5746   INTERVAL_SHOW;
5747
5748   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
5749               "Mesh for peer [%s] FWD ACKs %u, BCK ACKs %u\n",
5750               GNUNET_i2s(&my_full_id), debug_fwd_ack, debug_bck_ack);
5751
5752   return ret;
5753 }