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