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