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