- too much uncommited work
[oweals/gnunet.git] / src / mesh / gnunet-service-mesh-enc.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-enc.c
23  * @brief GNUnet MESH service with encryption
24  * @author Bartlomiej Polot
25  *
26  *  FIXME in progress:
27  * - when sending in-order buffered data, wait for client ACKs
28  * - add signatures
29  * - add encryption
30  * - set connection IDs independently from tunnel, tunnel has no ID
31  *
32  * TODO:
33  * - relay corking down to core
34  * - set ttl relative to path length
35  * TODO END
36  * 
37  * Dictionary:
38  * - peer: other mesh instance. If there is direct connection it's a neighbor.
39  * - tunnel: encrypted connection to a peer, neighbor or not.
40  * - channel: connection between two clients, on the same or different peers.
41  *            have properties like reliability.
42  * - path: series of directly connected peer from one peer to another.
43  * - connection: path which is being used in a tunnel.
44  */
45
46 #include "platform.h"
47 #include "gnunet_util_lib.h"
48 #include "mesh_enc.h"
49 #include "mesh_protocol_enc.h"
50 #include "mesh_path.h"
51 #include "block_mesh.h"
52 #include "gnunet_dht_service.h"
53 #include "gnunet_statistics_service.h"
54
55 #include "gnunet-service-mesh_local.h"
56 #include "gnunet-service-mesh_channel.h"
57 #include "gnunet-service-mesh_connection.h"
58
59 #define MESH_BLOOM_SIZE         128
60 #define MESH_MAX_POLL_TIME      GNUNET_TIME_relative_multiply (\
61                                   GNUNET_TIME_UNIT_MINUTES,\
62                                   10)
63 #define MESH_RETRANSMIT_TIME    GNUNET_TIME_UNIT_SECONDS
64 #define MESH_RETRANSMIT_MARGIN  4
65
66 #define MESH_DEBUG_DHT          GNUNET_NO
67 #define MESH_DEBUG_CONNECTION   GNUNET_NO
68 #define MESH_DEBUG_TIMING       __LINUX__ && GNUNET_NO
69
70 #if MESH_DEBUG_DHT
71 #define DEBUG_DHT(...) GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__)
72 #else
73 #define DEBUG_DHT(...)
74 #endif
75
76 #if MESH_DEBUG_CONNECTION
77 #define DEBUG_CONN(...) GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__)
78 #else
79 #define DEBUG_CONN(...)
80 #endif
81
82 #if MESH_DEBUG_TIMING
83 #include <time.h>
84 double __sum;
85 uint64_t __count;
86 struct timespec __mesh_start;
87 struct timespec __mesh_end;
88 #define INTERVAL_START clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &(__mesh_start))
89 #define INTERVAL_END \
90 do {\
91   clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &(__mesh_end));\
92   double __diff = __mesh_end.tv_nsec - __mesh_start.tv_nsec;\
93   if (__diff < 0) __diff += 1000000000;\
94   __sum += __diff;\
95   __count++;\
96 } while (0)
97 #define INTERVAL_SHOW \
98 if (0 < __count)\
99   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "AVG process time: %f ns\n", __sum/__count)
100 #else
101 #define INTERVAL_START
102 #define INTERVAL_END
103 #define INTERVAL_SHOW
104 #endif
105
106 /**
107  * All the states a tunnel can be in.
108  */
109 enum MeshTunnelState
110 {
111     /**
112      * Uninitialized status, should never appear in operation.
113      */
114   MESH_TUNNEL_NEW,
115
116     /**
117      * Path to the peer not known yet
118      */
119   MESH_TUNNEL_SEARCHING,
120
121     /**
122      * Request sent, not yet answered.
123      */
124   MESH_TUNNEL_WAITING,
125
126     /**
127      * Peer connected and ready to accept data
128      */
129   MESH_TUNNEL_READY,
130
131     /**
132      * Peer connected previosly but not responding
133      */
134   MESH_TUNNEL_RECONNECTING
135 };
136
137
138
139 /******************************************************************************/
140 /************************      DATA STRUCTURES     ****************************/
141 /******************************************************************************/
142
143 /** FWD declaration */
144 struct MeshClient;
145 struct MeshPeer;
146 struct MeshTunnel2;
147 struct MeshConnection;
148
149
150
151 /**
152  * Struct containing all information regarding a given peer
153  */
154 struct MeshPeer
155 {
156     /**
157      * ID of the peer
158      */
159   GNUNET_PEER_Id id;
160
161     /**
162      * Last time we heard from this peer
163      */
164   struct GNUNET_TIME_Absolute last_contact;
165
166     /**
167      * Paths to reach the peer, ordered by ascending hop count
168      */
169   struct MeshPeerPath *path_head;
170
171     /**
172      * Paths to reach the peer, ordered by ascending hop count
173      */
174   struct MeshPeerPath *path_tail;
175
176     /**
177      * Handle to stop the DHT search for paths to this peer
178      */
179   struct GNUNET_DHT_GetHandle *dhtget;
180
181     /**
182      * Tunnel to this peer, if any.
183      */
184   struct MeshTunnel2 *tunnel;
185
186     /**
187      * Connections that go through this peer, indexed by tid;
188      */
189   struct GNUNET_CONTAINER_MultiHashMap *connections;
190
191     /**
192      * Handle for queued transmissions
193      */
194   struct GNUNET_CORE_TransmitHandle *core_transmit;
195
196   /**
197    * Transmission queue to core DLL head
198    */
199   struct MeshPeerQueue *queue_head;
200   
201   /**
202    * Transmission queue to core DLL tail
203    */
204   struct MeshPeerQueue *queue_tail;
205
206   /**
207    * How many messages are in the queue to this peer.
208    */
209   unsigned int queue_n;
210 };
211
212
213
214
215 /**
216  * Struct used to queue messages in a tunnel.
217  */
218 struct MeshTunnelQueue
219 {
220   /**
221    * DLL
222    */
223   struct MeshTunnelQueue *next;
224   struct MeshTunnelQueue *prev;
225
226   /**
227    * Channel.
228    */
229   struct MeshChannel *ch;
230
231   /**
232    * Message to send.
233    */
234   /* struct GNUNET_MessageHeader *msg; */
235 };
236
237
238 /**
239  * Struct containing all information regarding a tunnel to a peer.
240  */
241 struct MeshTunnel2
242 {
243     /**
244      * Endpoint of the tunnel.
245      */
246   struct MeshPeer *peer;
247
248     /**
249      * State of the tunnel.
250      */
251   enum MeshTunnelState state;
252
253   /**
254    * Local peer ephemeral private key
255    */
256   struct GNUNET_CRYPTO_EccPrivateKey *my_eph_key;
257
258   /**
259    * Local peer ephemeral public key
260    */
261   struct GNUNET_CRYPTO_EccPublicSignKey *my_eph;
262
263   /**
264    * Remote peer's public key.
265    */
266   struct GNUNET_CRYPTO_EccPublicSignKey *peers_eph;
267
268   /**
269    * Encryption ("our") key.
270    */
271   struct GNUNET_CRYPTO_SymmetricSessionKey e_key;
272
273   /**
274    * Decryption ("their") key.
275    */
276   struct GNUNET_CRYPTO_SymmetricSessionKey d_key;
277
278   /**
279    * Paths that are actively used to reach the destination peer.
280    */
281   struct MeshConnection *connection_head;
282   struct MeshConnection *connection_tail;
283
284   /**
285    * Next connection number.
286    */
287   uint32_t next_cid;
288
289   /**
290    * Channels inside this tunnel.
291    */
292   struct MeshChannel *channel_head;
293   struct MeshChannel *channel_tail;
294
295   /**
296    * Channel ID for the next created channel.
297    */
298   MESH_ChannelNumber next_chid;
299
300   /**
301    * Channel ID for the next incoming channel.
302    */
303   MESH_ChannelNumber next_local_chid;
304
305   /**
306    * Pending message count.
307    */
308   int pending_messages;
309
310   /**
311    * Destroy flag: if true, destroy on last message.
312    */
313   int destroy;
314
315   /**
316    * Queued messages, to transmit once tunnel gets connected.
317    */
318   struct MeshTunnelQueue *tq_head;
319   struct MeshTunnelQueue *tq_tail;
320 };
321
322
323
324 /******************************************************************************/
325 /************************      DEBUG FUNCTIONS     ****************************/
326 /******************************************************************************/
327
328 #if MESH_DEBUG
329 /**
330  * GNUNET_SCHEDULER_Task for printing a message after some operation is done
331  * @param cls string to print
332  * @param success  GNUNET_OK if the PUT was transmitted,
333  *                GNUNET_NO on timeout,
334  *                GNUNET_SYSERR on disconnect from service
335  *                after the PUT message was transmitted
336  *                (so we don't know if it was received or not)
337  */
338
339 #if 0
340 static void
341 mesh_debug (void *cls, int success)
342 {
343   char *s = cls;
344
345   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "%s (%d)\n", s, success);
346 }
347 #endif
348
349 #endif
350
351 /******************************************************************************/
352 /***********************      GLOBAL VARIABLES     ****************************/
353 /******************************************************************************/
354
355 /************************** Configuration parameters **************************/
356
357 /**
358  * How often to PUT own ID in the DHT.
359  */
360 static struct GNUNET_TIME_Relative id_announce_time;
361
362 /**
363  * Maximum time allowed to connect to a peer found by string.
364  */
365 static struct GNUNET_TIME_Relative connect_timeout;
366
367 /**
368  * Default TTL for payload packets.
369  */
370 static unsigned long long default_ttl;
371
372 /**
373  * DHT replication level, see DHT API: GNUNET_DHT_get_start, GNUNET_DHT_put.
374  */
375 static unsigned long long dht_replication_level;
376
377 /**
378  * How many peers do we want to remember?
379  */
380 static unsigned long long max_peers;
381
382 /**
383  * Percentage of messages that will be dropped (for test purposes only).
384  */
385 static unsigned long long drop_percent;
386
387 /*************************** Static global variables **************************/
388
389 /**
390  * Peers known, indexed by PeerIdentity (MeshPeer).
391  */
392 static struct GNUNET_CONTAINER_MultiPeerMap *peers;
393
394 /**
395  * Handle to communicate with core.
396  */
397 static struct GNUNET_CORE_Handle *core_handle;
398
399 /**
400  * Handle to use DHT.
401  */
402 static struct GNUNET_DHT_Handle *dht_handle;
403
404 /**
405  * Handle to the statistics service.
406  */
407 static struct GNUNET_STATISTICS_Handle *stats;
408
409 /**
410  * Local peer own ID (memory efficient handle).
411  */
412 static GNUNET_PEER_Id myid;
413
414 /**
415  * Local peer own ID (full value).
416  */
417 static struct GNUNET_PeerIdentity my_full_id;
418
419 /**
420  * Own private key.
421  */
422 static struct GNUNET_CRYPTO_EccPrivateKey *my_private_key;
423
424 /**
425  * Task to periodically announce itself in the network.
426  */
427 GNUNET_SCHEDULER_TaskIdentifier announce_id_task;
428
429
430 /******************************************************************************/
431 /***********************         DECLARATIONS        **************************/
432 /******************************************************************************/
433
434 /**
435  * Function to process paths received for a new peer addition. The recorded
436  * paths form the initial tunnel, which can be optimized later.
437  * Called on each result obtained for the DHT search.
438  *
439  * @param cls closure
440  * @param exp when will this value expire
441  * @param key key of the result
442  * @param type type of the result
443  * @param size number of bytes in data
444  * @param data pointer to the result data
445  */
446 static void
447 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
448                     const struct GNUNET_HashCode * key,
449                     const struct GNUNET_PeerIdentity *get_path,
450                     unsigned int get_path_length,
451                     const struct GNUNET_PeerIdentity *put_path,
452                     unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
453                     size_t size, const void *data);
454
455
456 /**
457  * Retrieve the MeshPeer stucture associated with the peer, create one
458  * and insert it in the appropriate structures if the peer is not known yet.
459  *
460  * @param peer Full identity of the peer.
461  *
462  * @return Existing or newly created peer info.
463  */
464 static struct MeshPeer *
465 peer_get (const struct GNUNET_PeerIdentity *peer);
466
467
468 /**
469  * Retrieve the MeshPeer stucture associated with the peer, create one
470  * and insert it in the appropriate structures if the peer is not known yet.
471  *
472  * @param peer Short identity of the peer.
473  *
474  * @return Existing or newly created peer info.
475  */
476 static struct MeshPeer *
477 peer_get_short (const GNUNET_PEER_Id peer);
478
479
480 /**
481  * Build a PeerPath from the paths returned from the DHT, reversing the paths
482  * to obtain a local peer -> destination path and interning the peer ids.
483  *
484  * @return Newly allocated and created path
485  */
486 static struct MeshPeerPath *
487 path_build_from_dht (const struct GNUNET_PeerIdentity *get_path,
488                      unsigned int get_path_length,
489                      const struct GNUNET_PeerIdentity *put_path,
490                      unsigned int put_path_length);
491
492
493 /**
494  * Adds a path to the data structs of all the peers in the path
495  *
496  * @param p Path to process.
497  * @param confirmed Whether we know if the path works or not.
498  */
499 static void
500 path_add_to_peers (struct MeshPeerPath *p, int confirmed);
501
502
503 /**
504  * Change the tunnel state.
505  *
506  * @param t Tunnel whose state to change.
507  * @param state New state.
508  */
509 static void
510 tunnel_change_state (struct MeshTunnel2 *t, enum MeshTunnelState state);
511
512
513 /**
514  * Notify a tunnel that a connection has broken that affects at least
515  * some of its peers.
516  *
517  * @param t Tunnel affected.
518  * @param p1 Peer that got disconnected from p2.
519  * @param p2 Peer that got disconnected from p1.
520  *
521  * @return Short ID of the peer disconnected (either p1 or p2).
522  *         0 if the tunnel remained unaffected.
523  */
524 static GNUNET_PEER_Id
525 tunnel_notify_connection_broken (struct MeshTunnel2 *t,
526                                  GNUNET_PEER_Id p1, GNUNET_PEER_Id p2);
527
528 /**
529  * @brief Use the given path for the tunnel.
530  * Update the next and prev hops (and RCs).
531  * (Re)start the path refresh in case the tunnel is locally owned.
532  * 
533  * @param t Tunnel to update.
534  * @param p Path to use.
535  *
536  * @return Connection created.
537  */
538 static struct MeshConnection *
539 tunnel_use_path (struct MeshTunnel2 *t, struct MeshPeerPath *p);
540
541 /**
542  * Tunnel is empty: destroy it.
543  * 
544  * Notifies all participants (peers, cleints) about the destruction.
545  * 
546  * @param t Tunnel to destroy. 
547  */
548 static void
549 tunnel_destroy_empty (struct MeshTunnel2 *t);
550
551 /**
552  * Destroy the tunnel.
553  *
554  * This function does not generate any warning traffic to clients or peers.
555  *
556  * Tasks:
557  * Cancel messages belonging to this tunnel queued to neighbors.
558  * Free any allocated resources linked to the tunnel.
559  *
560  * @param t The tunnel to destroy.
561  */
562 static void
563 tunnel_destroy (struct MeshTunnel2 *t);
564
565
566 /**
567  * Demultiplex by message type and call appropriate handler for a message
568  * towards a channel of a local tunnel.
569  *
570  * @param t Tunnel this message came on.
571  * @param msgh Message header.
572  * @param fwd Is this message fwd?
573  */
574 static void
575 handle_decrypted (struct MeshTunnel2 *t,
576                   const struct GNUNET_MessageHeader *msgh,
577                   int fwd);
578
579
580 /**
581  * Dummy function to separate declarations from definitions in function list.
582  */
583 void
584 __mesh_divider______________________________________________________________();
585
586
587 /**
588  * Get string description for tunnel state.
589  *
590  * @param s Tunnel state.
591  *
592  * @return String representation. 
593  */
594 static const char *
595 GNUNET_MESH_DEBUG_TS2S (enum MeshTunnelState s)
596 {
597   static char buf[128];
598
599   switch (s)
600   {
601     case MESH_TUNNEL_NEW:
602       return "MESH_TUNNEL_NEW";
603     case MESH_TUNNEL_SEARCHING:
604       return "MESH_TUNNEL_SEARCHING";
605     case MESH_TUNNEL_WAITING:
606       return "MESH_TUNNEL_WAITING";
607     case MESH_TUNNEL_READY:
608       return "MESH_TUNNEL_READY";
609     case MESH_TUNNEL_RECONNECTING:
610       return "MESH_TUNNEL_RECONNECTING";
611
612     default:
613       sprintf (buf, "%u (UNKNOWN STATE)", s);
614       return buf;
615   }
616 }
617
618
619 /**
620  * Get string description for tunnel state.
621  *
622  * @param s Tunnel state.
623  *
624  * @return String representation. 
625  */
626 static const char *
627 GNUNET_MESH_DEBUG_CS2S (enum MeshTunnelState s)
628 {
629   switch (s) 
630   {
631     case MESH_CONNECTION_NEW:
632       return "MESH_CONNECTION_NEW";
633     case MESH_CONNECTION_SENT:
634       return "MESH_CONNECTION_SENT";
635     case MESH_CONNECTION_ACK:
636       return "MESH_CONNECTION_ACK";
637     case MESH_CONNECTION_READY:
638       return "MESH_CONNECTION_READY";
639     default:
640       return "MESH_CONNECTION_STATE_ERROR";
641   }
642 }
643
644
645
646 /******************************************************************************/
647 /************************    PERIODIC FUNCTIONS    ****************************/
648 /******************************************************************************/
649
650 /**
651  * Periodically announce self id in the DHT
652  *
653  * @param cls closure
654  * @param tc task context
655  */
656 static void
657 announce_id (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
658 {
659   struct PBlock block;
660   struct GNUNET_HashCode phash;
661
662   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
663   {
664     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
665     return;
666   }
667   /* TODO
668    * - Set data expiration in function of X
669    * - Adapt X to churn
670    */
671   DEBUG_DHT ("DHT_put for ID %s started.\n", GNUNET_i2s (&my_full_id));
672
673   block.id = my_full_id;
674   GNUNET_CRYPTO_hash (&my_full_id, sizeof (struct GNUNET_PeerIdentity), &phash);
675   GNUNET_DHT_put (dht_handle,   /* DHT handle */
676                   &phash,       /* Key to use */
677                   dht_replication_level,     /* Replication level */
678                   GNUNET_DHT_RO_RECORD_ROUTE | GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,    /* DHT options */
679                   GNUNET_BLOCK_TYPE_MESH_PEER,       /* Block type */
680                   sizeof (block),  /* Size of the data */
681                   (const char *) &block, /* Data itself */
682                   GNUNET_TIME_UNIT_FOREVER_ABS,  /* Data expiration */
683                   GNUNET_TIME_UNIT_FOREVER_REL, /* Retry time */
684                   NULL,         /* Continuation */
685                   NULL);        /* Continuation closure */
686   announce_id_task =
687       GNUNET_SCHEDULER_add_delayed (id_announce_time, &announce_id, cls);
688 }
689
690
691 /******************************************************************************/
692 /******************      GENERAL HELPER FUNCTIONS      ************************/
693 /******************************************************************************/
694
695
696 /**
697  * Get the static string for a peer ID.
698  *
699  * @param peer Peer.
700  *
701  * @return Static string for it's ID.
702  */
703 static const char *
704 peer2s (const struct MeshPeer *peer)
705 {
706   if (NULL == peer)
707     return "(NULL)";
708   return GNUNET_i2s (GNUNET_PEER_resolve2 (peer->id));
709 }
710
711
712
713 /**
714  * Count established (ready) connections of a tunnel.
715  *
716  * @param t Tunnel on which to send the message.
717  *
718  * @return Number of connections.
719  */
720 static unsigned int
721 tunnel_count_connections (struct MeshTunnel2 *t)
722 {
723   struct MeshConnection *c;
724   unsigned int i;
725
726   for (c = t->connection_head, i = 0; NULL != c; c = c->next, i++);
727
728   return i;
729 }
730
731
732 /**
733  * Pick a connection on which send the next data message.
734  *
735  * @param t Tunnel on which to send the message.
736  * @param fwd Is this a fwd message?
737  *
738  * @return The connection on which to send the next message.
739  */
740 static struct MeshConnection *
741 tunnel_get_connection (struct MeshTunnel2 *t, int fwd)
742 {
743   struct MeshConnection *c;
744   struct MeshConnection *best;
745   struct MeshFlowControl *fc;
746   unsigned int lowest_q;
747
748   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "tunnel_get_connection %s\n",
749               peer2s (t->peer));
750   best = NULL;
751   lowest_q = UINT_MAX;
752   for (c = t->connection_head; NULL != c; c = c->next)
753   {
754     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  connection %s: %u\n",
755                 GNUNET_h2s (&c->id), c->state);
756     if (MESH_CONNECTION_READY == c->state)
757     {
758       fc = fwd ? &c->fwd_fc : &c->bck_fc;
759       if (NULL == fc)
760       {
761         GNUNET_break (0);
762         continue;
763       }
764       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    q_n %u, \n", fc->queue_n);
765       if (fc->queue_n < lowest_q)
766       {
767         best = c;
768         lowest_q = fc->queue_n;
769       }
770     }
771   }
772   return best;
773 }
774
775
776
777
778 /**
779  * Get the total buffer space for a tunnel.
780  *
781  * @param t Tunnel.
782  * @param fwd Is this for FWD traffic?
783  *
784  * @return Buffer space offered by all connections in the tunnel.
785  */
786 static unsigned int
787 tunnel_get_buffer (struct MeshTunnel2 *t, int fwd)
788 {
789   struct MeshConnection *c;
790   struct MeshFlowControl *fc;
791   unsigned int buffer;
792
793   c = t->connection_head;
794   buffer = 0;
795
796   /* If terminal, return biggest channel buffer */
797   if (NULL == c || GMC_is_terminal (c, fwd))
798   {
799     struct MeshChannel *ch;
800     unsigned int ch_buf;
801
802     if (NULL == t->channel_head)
803       return 64;
804
805     for (ch = t->channel_head; NULL != ch; ch = ch->next)
806     {
807       ch_buf = channel_get_buffer (ch, fwd);
808       if (ch_buf > buffer)
809         buffer = ch_buf;
810     }
811     return buffer;
812   }
813
814   /* If not terminal, return sum of connection buffers */
815   while (NULL != c)
816   {
817     if (c->state != MESH_CONNECTION_READY)
818     {
819       c = c->next;
820       continue;
821     }
822
823     fc = fwd ? &c->fwd_fc : &c->bck_fc;
824     buffer += fc->queue_max - fc->queue_n;
825     c = c->next;
826   }
827
828   return buffer;
829 }
830
831
832 /**
833  * FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME 
834  * Encrypt data with the tunnel key.
835  *
836  * @param t Tunnel whose key to use.
837  * @param dst Destination for the encrypted data.
838  * @param src Source of the plaintext.
839  * @param size Size of the plaintext.
840  * @param iv Initialization Vector to use.
841  * @param fwd Is this a fwd message?
842  */
843 static void
844 tunnel_encrypt (struct MeshTunnel2 *t,
845                 void *dst, const void *src,
846                 size_t size, uint64_t iv, int fwd)
847 {
848   memcpy (dst, src, size);
849 }
850
851
852 /**
853  * FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME 
854  * Decrypt data with the tunnel key.
855  *
856  * @param t Tunnel whose key to use.
857  * @param dst Destination for the plaintext.
858  * @param src Source of the encrypted data.
859  * @param size Size of the encrypted data.
860  * @param iv Initialization Vector to use.
861  * @param fwd Is this a fwd message?
862  */
863 static void
864 tunnel_decrypt (struct MeshTunnel2 *t,
865                 void *dst, const void *src,
866                 size_t size, uint64_t iv, int fwd)
867 {
868   memcpy (dst, src, size);
869 }
870
871
872 /**
873  * Sends an already built message on a tunnel, choosing the best connection.
874  *
875  * @param message Message to send. Function modifies it.
876  * @param t Tunnel on which this message is transmitted.
877  * @param ch Channel on which this message is transmitted.
878  * @param fwd Is this a fwd message?
879  */
880 static void
881 send_prebuilt_message_tunnel (struct GNUNET_MESH_Encrypted *msg,
882                               struct MeshTunnel2 *t,
883                               struct MeshChannel *ch,
884                               int fwd)
885 {
886   struct MeshConnection *c;
887   uint16_t type;
888
889   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Send on Tunnel %s\n",
890               peer2s (t->peer));
891   c = tunnel_get_connection (t, fwd);
892   if (NULL == c)
893   {
894     GNUNET_break (GNUNET_YES == t->destroy);
895     return;
896   }
897   type = ntohs (msg->header.type);
898   switch (type)
899   {
900     case GNUNET_MESSAGE_TYPE_MESH_FWD:
901     case GNUNET_MESSAGE_TYPE_MESH_BCK:
902     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE:
903     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY:
904       msg->cid = c->id;
905       msg->ttl = htonl (default_ttl);
906       break;
907     default:
908       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "unkown type %s\n",
909                   GNUNET_MESH_DEBUG_M2S (type));
910       GNUNET_break (0);
911   }
912   msg->reserved = 0;
913
914   send_prebuilt_message_connection (&msg->header, c, ch, fwd);
915 }
916
917
918
919 /**
920  * Sends a CREATE CONNECTION message for a path to a peer.
921  * Changes the connection and tunnel states if necessary.
922  *
923  * @param connection Connection to create.
924  */
925 static void
926 send_connection_create (struct MeshConnection *connection)
927 {
928   struct MeshTunnel2 *t;
929
930   t = connection->t;
931   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Send connection create\n");
932   queue_add (NULL,
933              GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE,
934              sizeof (struct GNUNET_MESH_ConnectionCreate) +
935                 (connection->path->length *
936                  sizeof (struct GNUNET_PeerIdentity)),
937              connection,
938              NULL,
939              GNUNET_YES);
940   if (NULL != t &&
941       (MESH_TUNNEL_SEARCHING == t->state || MESH_TUNNEL_NEW == t->state))
942     tunnel_change_state (t, MESH_TUNNEL_WAITING);
943   if (MESH_CONNECTION_NEW == connection->state)
944     connection_change_state (connection, MESH_CONNECTION_SENT);
945 }
946
947
948 /**
949  * Sends a CONNECTION ACK message in reponse to a received CONNECTION_CREATE
950  * directed to us.
951  *
952  * @param connection Connection to confirm.
953  * @param fwd Is this a fwd ACK? (First is bck (SYNACK), second is fwd (ACK))
954  */
955 static void
956 send_connection_ack (struct MeshConnection *connection, int fwd) 
957 {
958   struct MeshTunnel2 *t;
959
960   t = connection->t;
961   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Send connection ack\n");
962   queue_add (NULL,
963              GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK,
964              sizeof (struct GNUNET_MESH_ConnectionACK),
965              connection,
966              NULL,
967              fwd);
968   if (MESH_TUNNEL_NEW == t->state)
969     tunnel_change_state (t, MESH_TUNNEL_WAITING);
970   if (MESH_CONNECTION_READY != connection->state)
971     connection_change_state (connection, MESH_CONNECTION_SENT);
972 }
973
974
975 /**
976   * Core callback to write a pre-constructed data packet to core buffer
977   *
978   * @param cls Closure (MeshTransmissionDescriptor with data in "data" member).
979   * @param size Number of bytes available in buf.
980   * @param buf Where the to write the message.
981   *
982   * @return number of bytes written to buf
983   */
984 static size_t
985 send_core_data_raw (void *cls, size_t size, void *buf)
986 {
987   struct GNUNET_MessageHeader *msg = cls;
988   size_t total_size;
989
990   GNUNET_assert (NULL != msg);
991   total_size = ntohs (msg->size);
992
993   if (total_size > size)
994   {
995     GNUNET_break (0);
996     return 0;
997   }
998   memcpy (buf, msg, total_size);
999   GNUNET_free (cls);
1000   return total_size;
1001 }
1002
1003
1004 /**
1005  * Function to send a create connection message to a peer.
1006  *
1007  * @param c Connection to create.
1008  * @param size number of bytes available in buf
1009  * @param buf where the callee should write the message
1010  * @return number of bytes written to buf
1011  */
1012 static size_t
1013 send_core_connection_create (struct MeshConnection *c, size_t size, void *buf)
1014 {
1015   struct GNUNET_MESH_ConnectionCreate *msg;
1016   struct GNUNET_PeerIdentity *peer_ptr;
1017   struct MeshPeerPath *p = c->path;
1018   size_t size_needed;
1019   int i;
1020
1021   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending CONNECTION CREATE...\n");
1022   size_needed =
1023       sizeof (struct GNUNET_MESH_ConnectionCreate) +
1024       p->length * sizeof (struct GNUNET_PeerIdentity);
1025
1026   if (size < size_needed || NULL == buf)
1027   {
1028     GNUNET_break (0);
1029     return 0;
1030   }
1031   msg = (struct GNUNET_MESH_ConnectionCreate *) buf;
1032   msg->header.size = htons (size_needed);
1033   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE);
1034   msg->cid = c->id;
1035
1036   peer_ptr = (struct GNUNET_PeerIdentity *) &msg[1];
1037   for (i = 0; i < p->length; i++)
1038   {
1039     GNUNET_PEER_resolve (p->peers[i], peer_ptr++);
1040   }
1041
1042   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1043               "CONNECTION CREATE (%u bytes long) sent!\n", size_needed);
1044   return size_needed;
1045 }
1046
1047
1048 /**
1049  * Creates a path ack message in buf and frees all unused resources.
1050  *
1051  * @param c Connection to send an ACK on.
1052  * @param size number of bytes available in buf
1053  * @param buf where the callee should write the message
1054  *
1055  * @return number of bytes written to buf
1056  */
1057 static size_t
1058 send_core_connection_ack (struct MeshConnection *c, size_t size, void *buf)
1059 {
1060   struct GNUNET_MESH_ConnectionACK *msg = buf;
1061   struct MeshTunnel2 *t = c->t;
1062
1063   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending CONNECTION ACK...\n");
1064   GNUNET_assert (NULL != t);
1065   if (sizeof (struct GNUNET_MESH_ConnectionACK) > size)
1066   {
1067     GNUNET_break (0);
1068     return 0;
1069   }
1070   msg->header.size = htons (sizeof (struct GNUNET_MESH_ConnectionACK));
1071   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK);
1072   msg->cid = c->id;
1073   msg->reserved = 0;
1074
1075   /* TODO add signature */
1076
1077   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CONNECTION ACK sent!\n");
1078   return sizeof (struct GNUNET_MESH_ConnectionACK);
1079 }
1080
1081
1082 /**
1083  * Destroy the peer_info and free any allocated resources linked to it
1084  *
1085  * @param peer The peer_info to destroy.
1086  *
1087  * @return GNUNET_OK on success
1088  */
1089 static int
1090 peer_destroy (struct MeshPeer *peer)
1091 {
1092   struct GNUNET_PeerIdentity id;
1093   struct MeshPeerPath *p;
1094   struct MeshPeerPath *nextp;
1095
1096   GNUNET_PEER_resolve (peer->id, &id);
1097   GNUNET_PEER_change_rc (peer->id, -1);
1098
1099   if (GNUNET_YES !=
1100       GNUNET_CONTAINER_multipeermap_remove (peers, &id, peer))
1101   {
1102     GNUNET_break (0);
1103     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1104                 "removing peer %s, not in peermap\n", GNUNET_i2s (&id));
1105   }
1106   if (NULL != peer->dhtget)
1107   {
1108     GNUNET_DHT_get_stop (peer->dhtget);
1109   }
1110   p = peer->path_head;
1111   while (NULL != p)
1112   {
1113     nextp = p->next;
1114     GNUNET_CONTAINER_DLL_remove (peer->path_head, peer->path_tail, p);
1115     path_destroy (p);
1116     p = nextp;
1117   }
1118   tunnel_destroy_empty (peer->tunnel);
1119   GNUNET_free (peer);
1120   return GNUNET_OK;
1121 }
1122
1123
1124 /**
1125  * Returns if peer is used (has a tunnel, is neighbor).
1126  *
1127  * @peer Peer to check.
1128  *
1129  * @return GNUNET_YES if peer is in use.
1130  */
1131 static int
1132 peer_is_used (struct MeshPeer *peer)
1133 {
1134   struct MeshPeerPath *p;
1135
1136   if (NULL != peer->tunnel)
1137     return GNUNET_YES;
1138
1139   for (p = peer->path_head; NULL != p; p = p->next)
1140   {
1141     if (p->length < 3)
1142       return GNUNET_YES;
1143   }
1144   return GNUNET_NO;
1145 }
1146
1147
1148 /**
1149  * Iterator over all the peers to get the oldest timestamp.
1150  *
1151  * @param cls Closure (unsued).
1152  * @param key ID of the peer.
1153  * @param value Peer_Info of the peer.
1154  */
1155 static int
1156 peer_get_oldest (void *cls,
1157                  const struct GNUNET_PeerIdentity *key,
1158                  void *value)
1159 {
1160   struct MeshPeer *p = value;
1161   struct GNUNET_TIME_Absolute *abs = cls;
1162
1163   /* Don't count active peers */
1164   if (GNUNET_YES == peer_is_used (p))
1165     return GNUNET_YES;
1166
1167   if (abs->abs_value_us < p->last_contact.abs_value_us)
1168     abs->abs_value_us = p->last_contact.abs_value_us;
1169
1170   return GNUNET_YES;
1171 }
1172
1173
1174 /**
1175  * Iterator over all the peers to remove the oldest entry.
1176  *
1177  * @param cls Closure (unsued).
1178  * @param key ID of the peer.
1179  * @param value Peer_Info of the peer.
1180  */
1181 static int
1182 peer_timeout (void *cls,
1183               const struct GNUNET_PeerIdentity *key,
1184               void *value)
1185 {
1186   struct MeshPeer *p = value;
1187   struct GNUNET_TIME_Absolute *abs = cls;
1188
1189   if (p->last_contact.abs_value_us == abs->abs_value_us &&
1190       GNUNET_NO == peer_is_used (p))
1191   {
1192     peer_destroy (p);
1193     return GNUNET_NO;
1194   }
1195   return GNUNET_YES;
1196 }
1197
1198
1199 /**
1200  * Delete oldest unused peer.
1201  */
1202 static void
1203 peer_delete_oldest (void)
1204 {
1205   struct GNUNET_TIME_Absolute abs;
1206
1207   abs = GNUNET_TIME_UNIT_FOREVER_ABS;
1208
1209   GNUNET_CONTAINER_multipeermap_iterate (peers,
1210                                          &peer_get_oldest,
1211                                          &abs);
1212   GNUNET_CONTAINER_multipeermap_iterate (peers,
1213                                          &peer_timeout,
1214                                          &abs);
1215 }
1216
1217
1218 /**
1219  * Retrieve the MeshPeer stucture associated with the peer, create one
1220  * and insert it in the appropriate structures if the peer is not known yet.
1221  *
1222  * @param peer Full identity of the peer.
1223  *
1224  * @return Existing or newly created peer info.
1225  */
1226 static struct MeshPeer *
1227 peer_get (const struct GNUNET_PeerIdentity *peer_id)
1228 {
1229   struct MeshPeer *peer;
1230
1231   peer = GNUNET_CONTAINER_multipeermap_get (peers, peer_id);
1232   if (NULL == peer)
1233   {
1234     peer = GNUNET_new (struct MeshPeer);
1235     if (GNUNET_CONTAINER_multipeermap_size (peers) > max_peers)
1236     {
1237       peer_delete_oldest ();
1238     }
1239     GNUNET_CONTAINER_multipeermap_put (peers, peer_id, peer,
1240                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
1241     peer->id = GNUNET_PEER_intern (peer_id);
1242   }
1243   peer->last_contact = GNUNET_TIME_absolute_get();
1244
1245   return peer;
1246 }
1247
1248
1249 /**
1250  * Retrieve the MeshPeer stucture associated with the peer, create one
1251  * and insert it in the appropriate structures if the peer is not known yet.
1252  *
1253  * @param peer Short identity of the peer.
1254  *
1255  * @return Existing or newly created peer info.
1256  */
1257 static struct MeshPeer *
1258 peer_get_short (const GNUNET_PEER_Id peer)
1259 {
1260   return peer_get (GNUNET_PEER_resolve2 (peer));
1261 }
1262
1263
1264 /**
1265  * Get a cost of a path for a peer considering existing tunnel connections.
1266  *
1267  * @param peer Peer towards which the path is considered.
1268  * @param path Candidate path.
1269  *
1270  * @return Cost of the path (path length + number of overlapping nodes)
1271  */
1272 static unsigned int
1273 peer_get_path_cost (const struct MeshPeer *peer,
1274                     const struct MeshPeerPath *path)
1275 {
1276   struct MeshConnection *c;
1277   unsigned int overlap;
1278   unsigned int i;
1279   unsigned int j;
1280
1281   if (NULL == path)
1282     return 0;
1283
1284   overlap = 0;
1285   GNUNET_assert (NULL != peer->tunnel);
1286
1287   for (i = 0; i < path->length; i++)
1288   {
1289     for (c = peer->tunnel->connection_head; NULL != c; c = c->next)
1290     {
1291       for (j = 0; j < c->path->length; j++)
1292       {
1293         if (path->peers[i] == c->path->peers[j])
1294         {
1295           overlap++;
1296           break;
1297         }
1298       }
1299     }
1300   }
1301   return (path->length + overlap) * (path->score * -1);
1302 }
1303
1304
1305 /**
1306  * Choose the best path towards a peer considering the tunnel properties.
1307  *
1308  * @param peer The destination peer.
1309  *
1310  * @return Best current known path towards the peer, if any.
1311  */
1312 static struct MeshPeerPath *
1313 peer_get_best_path (const struct MeshPeer *peer)
1314 {
1315   struct MeshPeerPath *best_p;
1316   struct MeshPeerPath *p;
1317   struct MeshConnection *c;
1318   unsigned int best_cost;
1319   unsigned int cost;
1320
1321   best_cost = UINT_MAX;
1322   best_p = NULL;
1323   for (p = peer->path_head; NULL != p; p = p->next)
1324   {
1325     for (c = peer->tunnel->connection_head; NULL != c; c = c->next)
1326       if (c->path == p)
1327         break;
1328     if (NULL != c)
1329       continue; /* If path is in use in a connection, skip it. */
1330
1331     if ((cost = peer_get_path_cost (peer, p)) < best_cost)
1332     {
1333       best_cost = cost;
1334       best_p = p;
1335     }
1336   }
1337   return best_p;
1338 }
1339
1340
1341
1342 /**
1343  * Try to establish a new connection to this peer in the given tunnel.
1344  * If the peer doesn't have any path to it yet, try to get one.
1345  * If the peer already has some path, send a CREATE CONNECTION towards it.
1346  *
1347  * @param peer PeerInfo of the peer.
1348  */
1349 static void
1350 peer_connect (struct MeshPeer *peer)
1351 {
1352   struct MeshTunnel2 *t;
1353   struct MeshPeerPath *p;
1354   struct MeshConnection *c;
1355   int rerun_dhtget;
1356
1357   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1358               "peer_connect towards %s\n",
1359               peer2s (peer));
1360   t = peer->tunnel;
1361   c = NULL;
1362   rerun_dhtget = GNUNET_NO;
1363
1364   if (NULL != peer->path_head)
1365   {
1366     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "path exists\n");
1367     p = peer_get_best_path (peer);
1368     if (NULL != p)
1369     {
1370       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  %u hops\n", p->length);
1371       c = tunnel_use_path (t, p);
1372       if (NULL == c)
1373       {
1374         /* This case can happen when the path includes a first hop that is
1375          * not yet known to be connected.
1376          * 
1377          * This happens quite often during testing when running mesh
1378          * under valgrind: core connect notifications come very late and the
1379          * DHT result has already come and created a valid path.
1380          * In this case, the peer->connections hashmap will be NULL and
1381          * tunnel_use_path will not be able to create a connection from that
1382          * path.
1383          *
1384          * Re-running the DHT GET should give core time to callback.
1385          */
1386         GNUNET_break(0);
1387         rerun_dhtget = GNUNET_YES;
1388       }
1389       else
1390       {
1391         send_connection_create (c);
1392         return;
1393       }
1394     }
1395   }
1396
1397   if (NULL != peer->dhtget && GNUNET_YES == rerun_dhtget)
1398   {
1399     GNUNET_DHT_get_stop (peer->dhtget);
1400     peer->dhtget = NULL;
1401     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1402                 "  Stopping DHT GET for peer %s\n", peer2s (peer));
1403   }
1404
1405   if (NULL == peer->dhtget)
1406   {
1407     const struct GNUNET_PeerIdentity *id;
1408     struct GNUNET_HashCode phash;
1409
1410     id = GNUNET_PEER_resolve2 (peer->id);
1411     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1412                 "  Starting DHT GET for peer %s\n", peer2s (peer));
1413     GNUNET_CRYPTO_hash (&id, sizeof (struct GNUNET_PeerIdentity), &phash);
1414     peer->dhtget = GNUNET_DHT_get_start (dht_handle,    /* handle */
1415                                          GNUNET_BLOCK_TYPE_MESH_PEER, /* type */
1416                                          &phash,     /* key to search */
1417                                          dht_replication_level, /* replication level */
1418                                          GNUNET_DHT_RO_RECORD_ROUTE |
1419                                          GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
1420                                          NULL,       /* xquery */
1421                                          0,     /* xquery bits */
1422                                          &dht_get_id_handler, peer);
1423     if (MESH_TUNNEL_NEW == t->state)
1424       tunnel_change_state (t, MESH_TUNNEL_SEARCHING);
1425   }
1426 }
1427
1428
1429
1430 /**
1431  * Add the path to the peer and update the path used to reach it in case this
1432  * is the shortest.
1433  *
1434  * @param peer_info Destination peer to add the path to.
1435  * @param path New path to add. Last peer must be the peer in arg 1.
1436  *             Path will be either used of freed if already known.
1437  * @param trusted Do we trust that this path is real?
1438  */
1439 void
1440 peer_add_path (struct MeshPeer *peer_info, struct MeshPeerPath *path,
1441                     int trusted)
1442 {
1443   struct MeshPeerPath *aux;
1444   unsigned int l;
1445   unsigned int l2;
1446
1447   if ((NULL == peer_info) || (NULL == path))
1448   {
1449     GNUNET_break (0);
1450     path_destroy (path);
1451     return;
1452   }
1453   if (path->peers[path->length - 1] != peer_info->id)
1454   {
1455     GNUNET_break (0);
1456     path_destroy (path);
1457     return;
1458   }
1459   if (2 >= path->length && GNUNET_NO == trusted)
1460   {
1461     /* Only allow CORE to tell us about direct paths */
1462     path_destroy (path);
1463     return;
1464   }
1465   for (l = 1; l < path->length; l++)
1466   {
1467     if (path->peers[l] == myid)
1468     {
1469       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shortening path by %u\n", l);
1470       for (l2 = 0; l2 < path->length - l; l2++)
1471       {
1472         path->peers[l2] = path->peers[l + l2];
1473       }
1474       path->length -= l;
1475       l = 1;
1476       path->peers =
1477           GNUNET_realloc (path->peers, path->length * sizeof (GNUNET_PEER_Id));
1478     }
1479   }
1480
1481   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "adding path [%u] to peer %s\n",
1482               path->length, peer2s (peer_info));
1483
1484   l = path_get_length (path);
1485   if (0 == l)
1486   {
1487     path_destroy (path);
1488     return;
1489   }
1490
1491   GNUNET_assert (peer_info->id == path->peers[path->length - 1]);
1492   for (aux = peer_info->path_head; aux != NULL; aux = aux->next)
1493   {
1494     l2 = path_get_length (aux);
1495     if (l2 > l)
1496     {
1497       GNUNET_CONTAINER_DLL_insert_before (peer_info->path_head,
1498                                           peer_info->path_tail, aux, path);
1499       return;
1500     }
1501     else
1502     {
1503       if (l2 == l && memcmp (path->peers, aux->peers, l) == 0)
1504       {
1505         path_destroy (path);
1506         return;
1507       }
1508     }
1509   }
1510   GNUNET_CONTAINER_DLL_insert_tail (peer_info->path_head, peer_info->path_tail,
1511                                     path);
1512   return;
1513 }
1514
1515
1516 /**
1517  * Add the path to the origin peer and update the path used to reach it in case
1518  * this is the shortest.
1519  * The path is given in peer_info -> destination, therefore we turn the path
1520  * upside down first.
1521  *
1522  * @param peer_info Peer to add the path to, being the origin of the path.
1523  * @param path New path to add after being inversed.
1524  *             Path will be either used or freed.
1525  * @param trusted Do we trust that this path is real?
1526  */
1527 static void
1528 peer_add_path_to_origin (struct MeshPeer *peer_info,
1529                          struct MeshPeerPath *path, int trusted)
1530 {
1531   if (NULL == path)
1532     return;
1533   path_invert (path);
1534   peer_add_path (peer_info, path, trusted);
1535 }
1536
1537 /**
1538  * Build a PeerPath from the paths returned from the DHT, reversing the paths
1539  * to obtain a local peer -> destination path and interning the peer ids.
1540  *
1541  * @return Newly allocated and created path
1542  */
1543 static struct MeshPeerPath *
1544 path_build_from_dht (const struct GNUNET_PeerIdentity *get_path,
1545                      unsigned int get_path_length,
1546                      const struct GNUNET_PeerIdentity *put_path,
1547                      unsigned int put_path_length)
1548 {
1549   struct MeshPeerPath *p;
1550   GNUNET_PEER_Id id;
1551   int i;
1552
1553   p = path_new (1);
1554   p->peers[0] = myid;
1555   GNUNET_PEER_change_rc (myid, 1);
1556   i = get_path_length;
1557   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   GET has %d hops.\n", i);
1558   for (i--; i >= 0; i--)
1559   {
1560     id = GNUNET_PEER_intern (&get_path[i]);
1561     if (p->length > 0 && id == p->peers[p->length - 1])
1562     {
1563       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   Optimizing 1 hop out.\n");
1564       GNUNET_PEER_change_rc (id, -1);
1565     }
1566     else
1567     {
1568       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   Adding from GET: %s.\n",
1569                   GNUNET_i2s (&get_path[i]));
1570       p->length++;
1571       p->peers = GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * p->length);
1572       p->peers[p->length - 1] = id;
1573     }
1574   }
1575   i = put_path_length;
1576   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   PUT has %d hops.\n", i);
1577   for (i--; i >= 0; i--)
1578   {
1579     id = GNUNET_PEER_intern (&put_path[i]);
1580     if (id == myid)
1581     {
1582       /* PUT path went through us, so discard the path up until now and start
1583        * from here to get a much shorter (and loop-free) path.
1584        */
1585       path_destroy (p);
1586       p = path_new (0);
1587     }
1588     if (p->length > 0 && id == p->peers[p->length - 1])
1589     {
1590       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   Optimizing 1 hop out.\n");
1591       GNUNET_PEER_change_rc (id, -1);
1592     }
1593     else
1594     {
1595       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   Adding from PUT: %s.\n",
1596                   GNUNET_i2s (&put_path[i]));
1597       p->length++;
1598       p->peers = GNUNET_realloc (p->peers, sizeof (GNUNET_PEER_Id) * p->length);
1599       p->peers[p->length - 1] = id;
1600     }
1601   }
1602 #if MESH_DEBUG
1603   if (get_path_length > 0)
1604     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   (first of GET: %s)\n",
1605                 GNUNET_i2s (&get_path[0]));
1606   if (put_path_length > 0)
1607     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   (first of PUT: %s)\n",
1608                 GNUNET_i2s (&put_path[0]));
1609   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   In total: %d hops\n",
1610               p->length);
1611   for (i = 0; i < p->length; i++)
1612   {
1613     struct GNUNET_PeerIdentity peer_id;
1614
1615     GNUNET_PEER_resolve (p->peers[i], &peer_id);
1616     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "       %u: %s\n", p->peers[i],
1617                 GNUNET_i2s (&peer_id));
1618   }
1619 #endif
1620   return p;
1621 }
1622
1623
1624 /**
1625  * Adds a path to the peer_infos of all the peers in the path
1626  *
1627  * @param p Path to process.
1628  * @param confirmed Whether we know if the path works or not.
1629  */
1630 static void
1631 path_add_to_peers (struct MeshPeerPath *p, int confirmed)
1632 {
1633   unsigned int i;
1634
1635   /* TODO: invert and add */
1636   for (i = 0; i < p->length && p->peers[i] != myid; i++) /* skip'em */ ;
1637   for (i++; i < p->length; i++)
1638   {
1639     struct MeshPeer *aux;
1640     struct MeshPeerPath *copy;
1641
1642     aux = peer_get_short (p->peers[i]);
1643     copy = path_duplicate (p);
1644     copy->length = i + 1;
1645     peer_add_path (aux, copy, p->length < 3 ? GNUNET_NO : confirmed);
1646   }
1647 }
1648
1649
1650 #if 0
1651 static void
1652 fc_debug (struct MeshFlowControl *fc)
1653 {
1654   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    IN: %u/%u\n",
1655               fc->last_pid_recv, fc->last_ack_sent);
1656   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    OUT: %u/%u\n",
1657               fc->last_pid_sent, fc->last_ack_recv);
1658   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    QUEUE: %u/%u\n",
1659               fc->queue_n, fc->queue_max);
1660 }
1661
1662 static void
1663 connection_debug (struct MeshConnection *c)
1664 {
1665   if (NULL == c)
1666   {
1667     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*** DEBUG NULL CONNECTION ***\n");
1668     return;
1669   }
1670   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connection %s:%X\n",
1671               peer2s (c->t->peer), GNUNET_h2s (&c->id));
1672   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  state: %u, pending msgs: %u\n", 
1673               c->state, c->pending_messages);
1674   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  FWD FC\n");
1675   fc_debug (&c->fwd_fc);
1676   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  BCK FC\n");
1677   fc_debug (&c->bck_fc);
1678 }
1679
1680 #endif
1681
1682
1683 /**
1684  * Change the tunnel state.
1685  *
1686  * @param t Tunnel whose state to change.
1687  * @param state New state.
1688  */
1689 static void
1690 tunnel_change_state (struct MeshTunnel2* t, enum MeshTunnelState state)
1691 {
1692   if (NULL == t)
1693     return;
1694   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1695               "Tunnel %s state was %s\n",
1696               peer2s (t->peer),
1697               GNUNET_MESH_DEBUG_TS2S (t->state));
1698   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1699               "Tunnel %s state is now %s\n",
1700               peer2s (t->peer),
1701               GNUNET_MESH_DEBUG_TS2S (state));
1702   t->state = state;
1703 }
1704
1705
1706 /**
1707  * Send all cached messages that we can, tunnel is online.
1708  *
1709  * @param t Tunnel that holds the messages.
1710  * @param fwd Is this fwd?
1711  */
1712 static void
1713 tunnel_send_queued_data (struct MeshTunnel2 *t, int fwd)
1714 {
1715   struct MeshTunnelQueue *tq;
1716   struct MeshTunnelQueue *next;
1717   unsigned int room;
1718
1719   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1720               "tunnel_send_queued_data on tunnel %s\n",
1721               peer2s (t->peer));
1722   room = tunnel_get_buffer (t, fwd);
1723   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  buffer space: %u\n", room);
1724   for (tq = t->tq_head; NULL != tq && room > 0; tq = next)
1725   {
1726     next = tq->next;
1727     room--;
1728     GNUNET_CONTAINER_DLL_remove (t->tq_head, t->tq_tail, tq);
1729     send_prebuilt_message_channel ((struct GNUNET_MessageHeader *) &tq[1],
1730                                    tq->ch, fwd);
1731
1732     GNUNET_free (tq);
1733   }
1734 }
1735
1736
1737 /**
1738  * Cache a message to be sent once tunnel is online.
1739  *
1740  * @param t Tunnel to hold the message.
1741  * @param ch Channel the message is about.
1742  * @param msg Message itself (copy will be made).
1743  * @param fwd Is this fwd?
1744  */
1745 static void
1746 tunnel_queue_data (struct MeshTunnel2 *t,
1747                    struct MeshChannel *ch,
1748                    struct GNUNET_MessageHeader *msg,
1749                    int fwd)
1750 {
1751   struct MeshTunnelQueue *tq;
1752   uint16_t size = ntohs (msg->size);
1753
1754   tq = GNUNET_malloc (sizeof (struct MeshTunnelQueue) + size);
1755
1756   tq->ch = ch;
1757   memcpy (&tq[1], msg, size);
1758   GNUNET_CONTAINER_DLL_insert_tail (t->tq_head, t->tq_tail, tq);
1759
1760   if (MESH_TUNNEL_READY == t->state)
1761     tunnel_send_queued_data (t, fwd);
1762 }
1763
1764
1765
1766
1767
1768 static struct MeshConnection *
1769 tunnel_use_path (struct MeshTunnel2 *t, struct MeshPeerPath *p)
1770 {
1771   struct MeshConnection *c;
1772   struct GNUNET_HashCode cid;
1773   struct MeshPeer *peer;
1774   unsigned int own_pos;
1775
1776   if (NULL == t || NULL == p)
1777   {
1778     GNUNET_break (0);
1779     return NULL;
1780   }
1781
1782   GNUNET_CRYPTO_hash_create_random (GNUNET_CRYPTO_QUALITY_NONCE, &cid);
1783
1784   c = connection_new (&cid);
1785   c->t = t;
1786   GNUNET_CONTAINER_DLL_insert (t->connection_head, t->connection_tail, c);
1787   for (own_pos = 0; own_pos < p->length; own_pos++)
1788   {
1789     if (p->peers[own_pos] == myid)
1790       break;
1791   }
1792   if (own_pos > p->length - 1)
1793   {
1794     GNUNET_break (0);
1795     connection_destroy (c);
1796     return NULL;
1797   }
1798   c->own_pos = own_pos;
1799   c->path = p;
1800
1801   if (0 == own_pos)
1802   {
1803     c->fwd_maintenance_task =
1804         GNUNET_SCHEDULER_add_delayed (refresh_connection_time,
1805                                       &connection_fwd_keepalive, c);
1806   }
1807
1808   peer = connection_get_next_hop (c);
1809   if (NULL == peer->connections)
1810   {
1811     connection_destroy (c);
1812     return NULL;
1813   }
1814   GNUNET_CONTAINER_multihashmap_put (peer->connections, &c->id, c,
1815                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
1816   peer = connection_get_prev_hop (c);
1817   if (NULL == peer->connections)
1818   {
1819     connection_destroy (c);
1820     return NULL;
1821   }
1822   GNUNET_CONTAINER_multihashmap_put (peer->connections, &c->id, c,
1823                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
1824   return c;
1825 }
1826
1827
1828 /**
1829  * Notifies a tunnel that a connection has broken that affects at least
1830  * some of its peers. Sends a notification towards the root of the tree.
1831  * In case the peer is the owner of the tree, notifies the client that owns
1832  * the tunnel and tries to reconnect.
1833  * 
1834  * FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME 
1835  *
1836  * @param t Tunnel affected.
1837  * @param p1 Peer that got disconnected from p2.
1838  * @param p2 Peer that got disconnected from p1.
1839  *
1840  * @return Short ID of the peer disconnected (either p1 or p2).
1841  *         0 if the tunnel remained unaffected.
1842  */
1843 static GNUNET_PEER_Id
1844 tunnel_notify_connection_broken (struct MeshTunnel2* t,
1845                                  GNUNET_PEER_Id p1, GNUNET_PEER_Id p2)
1846 {
1847 //   if (myid != p1 && myid != p2) FIXME
1848 //   {
1849 //     return;
1850 //   }
1851 // 
1852 //   if (tree_get_predecessor (t->tree) != 0)
1853 //   {
1854 //     /* We are the peer still connected, notify owner of the disconnection. */
1855 //     struct GNUNET_MESH_PathBroken msg;
1856 //     struct GNUNET_PeerIdentity neighbor;
1857 // 
1858 //     msg.header.size = htons (sizeof (msg));
1859 //     msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN);
1860 //     GNUNET_PEER_resolve (t->id.oid, &msg.oid);
1861 //     msg.tid = htonl (t->id.tid);
1862 //     msg.peer1 = my_full_id;
1863 //     GNUNET_PEER_resolve (pid, &msg.peer2);
1864 //     GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &neighbor);
1865 //     send_prebuilt_message (&msg.header, &neighbor, t);
1866 //   }
1867   return 0;
1868 }
1869
1870
1871
1872
1873 /**
1874  * Send an ACK on the appropriate connection/channel, depending on
1875  * the direction and the position of the peer.
1876  *
1877  * @param c Which connection to send the hop-by-hop ACK.
1878  * @param ch Channel, if any.
1879  * @param fwd Is this a fwd ACK? (will go dest->root)
1880  */
1881 static void
1882 send_ack (struct MeshConnection *c, struct MeshChannel *ch, int fwd)
1883 {
1884   unsigned int buffer;
1885
1886   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1887               "send ack %s on %p %p\n",
1888               fwd ? "FWD" : "BCK", c, ch);
1889   if (NULL == c || GMC_is_terminal (c, fwd))
1890   {
1891     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  getting from all connections\n");
1892     buffer = tunnel_get_buffer (NULL == c ? ch->t : c->t, fwd);
1893   }
1894   else
1895   {
1896     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  getting from one connection\n");
1897     buffer = connection_get_buffer (c, fwd);
1898   }
1899   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  buffer available: %u\n", buffer);
1900
1901   if ( (NULL != ch && channel_is_origin (ch, fwd)) ||
1902        (NULL != c && connection_is_origin (c, fwd)) )
1903   {
1904     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  sending on channel...\n");
1905     if (0 < buffer)
1906     {
1907       GNUNET_assert (NULL != ch);
1908       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  really sending!\n");
1909       send_local_ack (ch, fwd);
1910     }
1911   }
1912   else if (NULL == c)
1913   {
1914     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  sending on all connections\n");
1915     GNUNET_assert (NULL != ch);
1916     channel_send_connections_ack (ch, buffer, fwd);
1917   }
1918   else 
1919   {
1920     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  sending on connection\n");
1921     connection_send_ack (c, buffer, fwd);
1922   }
1923 }
1924
1925
1926
1927
1928 /**
1929  * Confirm we got a channel create.
1930  *
1931  * @param ch The channel to confirm.
1932  * @param fwd Should we send the ACK fwd?
1933  */
1934 static void
1935 channel_send_ack (struct MeshChannel *ch, int fwd)
1936 {
1937   struct GNUNET_MESH_ChannelManage msg;
1938
1939   msg.header.size = htons (sizeof (msg));
1940   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CHANNEL_ACK);
1941   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1942               "  sending channel %s ack for channel %s:%X\n",
1943               fwd ? "FWD" : "BCK", peer2s (ch->t->peer),
1944               ch->gid);
1945
1946   msg.chid = htonl (ch->gid);
1947   send_prebuilt_message_channel (&msg.header, ch, !fwd);
1948 }
1949
1950
1951 /**
1952  * Send a message to all clients (local and remote) of this channel
1953  * notifying that the channel is no longer valid.
1954  *
1955  * If some peer or client should not receive the message,
1956  * should be zero'ed out before calling this function.
1957  *
1958  * @param ch The channel whose clients to notify.
1959  */
1960 static void
1961 channel_send_destroy (struct MeshChannel *ch)
1962 {
1963   struct GNUNET_MESH_ChannelManage msg;
1964
1965   msg.header.size = htons (sizeof (msg));
1966   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY);
1967   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1968               "  sending channel destroy for channel %s:%X\n",
1969               peer2s (ch->t->peer),
1970               ch->gid);
1971
1972   if (channel_is_terminal (ch, GNUNET_NO))
1973   {
1974     if (NULL != ch->root && GNUNET_NO == ch->root->shutting_down)
1975     {
1976       msg.chid = htonl (ch->lid_root);
1977       send_local_channel_destroy (ch, GNUNET_NO);
1978     }
1979   }
1980   else
1981   {
1982     msg.chid = htonl (ch->gid);
1983     send_prebuilt_message_channel (&msg.header, ch, GNUNET_NO);
1984   }
1985
1986   if (channel_is_terminal (ch, GNUNET_YES))
1987   {
1988     if (NULL != ch->dest && GNUNET_NO == ch->dest->shutting_down)
1989     {
1990       msg.chid = htonl (ch->lid_dest);
1991       send_local_channel_destroy (ch, GNUNET_YES);
1992     }
1993   }
1994   else
1995   {
1996     msg.chid = htonl (ch->gid);
1997     send_prebuilt_message_channel (&msg.header, ch, GNUNET_YES);
1998   }
1999 }
2000
2001
2002 /**
2003  * Create a tunnel.
2004  */
2005 static struct MeshTunnel2 *
2006 tunnel_new (void)
2007 {
2008   struct MeshTunnel2 *t;
2009
2010   t = GNUNET_new (struct MeshTunnel2);
2011   t->next_chid = 0;
2012   t->next_local_chid = GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
2013 //   if (GNUNET_OK !=
2014 //       GNUNET_CONTAINER_multihashmap_put (tunnels, tid, t,
2015 //                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
2016 //   {
2017 //     GNUNET_break (0);
2018 //     tunnel_destroy (t);
2019 //     return NULL;
2020 //   }
2021
2022 //   char salt[] = "salt";
2023 //   GNUNET_CRYPTO_kdf (&t->e_key, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
2024 //                      salt, sizeof (salt),
2025 //                      &t->e_key, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
2026 //                      &my_full_id, sizeof (struct GNUNET_PeerIdentity),
2027 //                      GNUNET_PEER_resolve2 (t->peer->id), sizeof (struct GNUNET_PeerIdentity),
2028 //                      NULL);
2029 //   GNUNET_CRYPTO_kdf (&t->d_key, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
2030 //                      salt, sizeof (salt),
2031 //                      &t->d_key, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
2032 //                      GNUNET_PEER_resolve2 (t->peer->id), sizeof (struct GNUNET_PeerIdentity),
2033 //                      &my_full_id, sizeof (struct GNUNET_PeerIdentity),
2034 //                      NULL);
2035
2036   return t;
2037 }
2038
2039
2040 /**
2041  * Add a connection to a tunnel.
2042  *
2043  * @param t Tunnel.
2044  * @param c Connection.
2045  */
2046 static void
2047 tunnel_add_connection (struct MeshTunnel2 *t, struct MeshConnection *c)
2048 {
2049   struct MeshConnection *aux;
2050   c->t = t;
2051   for (aux = t->connection_head; aux != NULL; aux = aux->next)
2052     if (aux == c)
2053       return;
2054   GNUNET_CONTAINER_DLL_insert_tail (t->connection_head, t->connection_tail, c);
2055 }
2056
2057
2058
2059 static void
2060 tunnel_destroy (struct MeshTunnel2 *t)
2061 {
2062   struct MeshConnection *c;
2063   struct MeshConnection *next;
2064
2065   if (NULL == t)
2066     return;
2067
2068   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s\n",
2069               peer2s (t->peer));
2070
2071 //   if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_remove (tunnels, &t->id, t))
2072 //     GNUNET_break (0);
2073
2074   for (c = t->connection_head; NULL != c; c = next)
2075   {
2076     next = c->next;
2077     connection_destroy (c);
2078   }
2079
2080   GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
2081   t->peer->tunnel = NULL;
2082
2083   GNUNET_free (t);
2084 }
2085
2086
2087 /**
2088  * Tunnel is empty: destroy it.
2089  *
2090  * Notifies all connections about the destruction.
2091  *
2092  * @param t Tunnel to destroy. 
2093  */
2094 static void
2095 tunnel_destroy_empty (struct MeshTunnel2 *t)
2096 {
2097   struct MeshConnection *c;
2098
2099   for (c = t->connection_head; NULL != c; c = c->next)
2100   {
2101     if (GNUNET_NO == c->destroy)
2102       connection_send_destroy (c);
2103   }
2104
2105   if (0 == t->pending_messages)
2106     tunnel_destroy (t);
2107   else
2108     t->destroy = GNUNET_YES;
2109 }
2110
2111
2112 /**
2113  * Destroy tunnel if empty (no more channels).
2114  *
2115  * @param t Tunnel to destroy if empty.
2116  */
2117 static void
2118 tunnel_destroy_if_empty (struct MeshTunnel2 *t)
2119 {
2120   if (NULL != t->channel_head)
2121     return;
2122
2123   tunnel_destroy_empty (t);
2124 }
2125
2126
2127 /******************************************************************************/
2128 /****************      MESH NETWORK HANDLER HELPERS     ***********************/
2129 /******************************************************************************/
2130
2131
2132
2133
2134
2135
2136 /******************************************************************************/
2137 /********************      MESH NETWORK HANDLERS     **************************/
2138 /******************************************************************************/
2139
2140
2141 /**
2142  * Generic handler for mesh network payload traffic.
2143  *
2144  * @param t Tunnel on which we got this message.
2145  * @param message Unencryted data message.
2146  * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
2147  */
2148 static void
2149 handle_data (struct MeshTunnel2 *t, const struct GNUNET_MESH_Data *msg, int fwd)
2150 {
2151   struct MeshChannelReliability *rel;
2152   struct MeshChannel *ch;
2153   struct MeshClient *c;
2154   uint32_t mid;
2155   uint16_t type;
2156   size_t size;
2157
2158   /* Check size */
2159   size = ntohs (msg->header.size);
2160   if (size <
2161       sizeof (struct GNUNET_MESH_Data) +
2162       sizeof (struct GNUNET_MessageHeader))
2163   {
2164     GNUNET_break (0);
2165     return;
2166   }
2167   type = ntohs (msg->header.type);
2168   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a %s message\n",
2169               GNUNET_MESH_DEBUG_M2S (type));
2170   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n",
2171               GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
2172
2173   /* Check channel */
2174   ch = channel_get (t, ntohl (msg->chid));
2175   if (NULL == ch)
2176   {
2177     GNUNET_STATISTICS_update (stats, "# data on unknown channel", 1, GNUNET_NO);
2178     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
2179                 ntohl (msg->chid));
2180     return;
2181   }
2182
2183   /*  Initialize FWD/BCK data */
2184   c   = fwd ? ch->dest     : ch->root;
2185   rel = fwd ? ch->dest_rel : ch->root_rel;
2186
2187   if (NULL == c)
2188   {
2189     GNUNET_break (0);
2190     return;
2191   }
2192
2193   tunnel_change_state (t, MESH_TUNNEL_READY);
2194
2195   GNUNET_STATISTICS_update (stats, "# data received", 1, GNUNET_NO);
2196
2197   mid = ntohl (msg->mid);
2198   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " mid %u\n", mid);
2199
2200   if (GNUNET_NO == ch->reliable ||
2201       ( !GMC_is_pid_bigger (rel->mid_recv, mid) &&
2202         GMC_is_pid_bigger (rel->mid_recv + 64, mid) ) )
2203   {
2204     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! RECV %u\n", mid);
2205     if (GNUNET_YES == ch->reliable)
2206     {
2207       /* Is this the exact next expected messasge? */
2208       if (mid == rel->mid_recv)
2209       {
2210         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "as expected\n");
2211         rel->mid_recv++;
2212         channel_send_client_data (ch, msg, fwd);
2213       }
2214       else
2215       {
2216         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "save for later\n");
2217         channel_rel_add_buffered_data (msg, rel);
2218       }
2219     }
2220     else
2221     {
2222       /* Tunnel is unreliable: send to clients directly */
2223       /* FIXME: accept Out Of Order traffic */
2224       rel->mid_recv = mid + 1;
2225       channel_send_client_data (ch, msg, fwd);
2226     }
2227   }
2228   else
2229   {
2230     GNUNET_break_op (0);
2231     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2232                 " MID %u not expected (%u - %u), dropping!\n",
2233                 mid, rel->mid_recv, rel->mid_recv + 64);
2234   }
2235
2236   channel_send_data_ack (ch, fwd);
2237 }
2238
2239 /**
2240  * Handler for mesh network traffic end-to-end ACKs.
2241  *
2242  * @param t Tunnel on which we got this message.
2243  * @param message Data message.
2244  * @param fwd Is this a fwd ACK? (dest->orig)
2245  */
2246 static void
2247 handle_data_ack (struct MeshTunnel2 *t,
2248                  const struct GNUNET_MESH_DataACK *msg, int fwd)
2249 {
2250   struct MeshChannelReliability *rel;
2251   struct MeshReliableMessage *copy;
2252   struct MeshReliableMessage *next;
2253   struct MeshChannel *ch;
2254   uint32_t ack;
2255   uint16_t type;
2256   int work;
2257
2258   type = ntohs (msg->header.type);
2259   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a %s message!\n",
2260               GNUNET_MESH_DEBUG_M2S (type));
2261   ch = channel_get (t, ntohl (msg->chid));
2262   if (NULL == ch)
2263   {
2264     GNUNET_STATISTICS_update (stats, "# ack on unknown channel", 1, GNUNET_NO);
2265     return;
2266   }
2267   ack = ntohl (msg->mid);
2268   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! %s ACK %u\n",
2269               (GNUNET_YES == fwd) ? "FWD" : "BCK", ack);
2270
2271   if (GNUNET_YES == fwd)
2272   {
2273     rel = ch->root_rel;
2274   }
2275   else
2276   {
2277     rel = ch->dest_rel;
2278   }
2279   if (NULL == rel)
2280   {
2281     GNUNET_break (0);
2282     return;
2283   }
2284
2285   for (work = GNUNET_NO, copy = rel->head_sent; copy != NULL; copy = next)
2286   {
2287     if (GMC_is_pid_bigger (copy->mid, ack))
2288     {
2289       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!!  head %u, out!\n", copy->mid);
2290       channel_rel_free_sent (rel, msg);
2291       break;
2292     }
2293     work = GNUNET_YES;
2294     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!!  id %u\n", copy->mid);
2295     next = copy->next;
2296     rel_message_free (copy);
2297   }
2298   /* ACK client if needed */
2299 //   channel_send_ack (t, type, GNUNET_MESSAGE_TYPE_MESH_UNICAST_ACK == type);
2300
2301   /* If some message was free'd, update the retransmission delay*/
2302   if (GNUNET_YES == work)
2303   {
2304     if (GNUNET_SCHEDULER_NO_TASK != rel->retry_task)
2305     {
2306       GNUNET_SCHEDULER_cancel (rel->retry_task);
2307       if (NULL == rel->head_sent)
2308       {
2309         rel->retry_task = GNUNET_SCHEDULER_NO_TASK;
2310       }
2311       else
2312       {
2313         struct GNUNET_TIME_Absolute new_target;
2314         struct GNUNET_TIME_Relative delay;
2315
2316         delay = GNUNET_TIME_relative_multiply (rel->retry_timer,
2317                                                MESH_RETRANSMIT_MARGIN);
2318         new_target = GNUNET_TIME_absolute_add (rel->head_sent->timestamp,
2319                                                delay);
2320         delay = GNUNET_TIME_absolute_get_remaining (new_target);
2321         rel->retry_task =
2322             GNUNET_SCHEDULER_add_delayed (delay,
2323                                           &channel_retransmit_message,
2324                                           rel);
2325       }
2326     }
2327     else
2328       GNUNET_break (0);
2329   }
2330 }
2331
2332
2333 /**
2334  * Core handler for connection creation.
2335  *
2336  * @param cls Closure (unused).
2337  * @param peer Sender (neighbor).
2338  * @param message Message.
2339  *
2340  * @return GNUNET_OK to keep the connection open,
2341  *         GNUNET_SYSERR to close it (signal serious error)
2342  */
2343 static int
2344 handle_mesh_connection_create (void *cls,
2345                                const struct GNUNET_PeerIdentity *peer,
2346                                const struct GNUNET_MessageHeader *message)
2347 {
2348   struct GNUNET_MESH_ConnectionCreate *msg;
2349   struct GNUNET_PeerIdentity *id;
2350   struct GNUNET_HashCode *cid;
2351   struct MeshPeerPath *path;
2352   struct MeshPeer *dest_peer;
2353   struct MeshPeer *orig_peer;
2354   struct MeshConnection *c;
2355   unsigned int own_pos;
2356   uint16_t size;
2357   uint16_t i;
2358
2359   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "\n\n");
2360   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a connection create msg\n");
2361
2362   /* Check size */
2363   size = ntohs (message->size);
2364   if (size < sizeof (struct GNUNET_MESH_ConnectionCreate))
2365   {
2366     GNUNET_break_op (0);
2367     return GNUNET_OK;
2368   }
2369
2370   /* Calculate hops */
2371   size -= sizeof (struct GNUNET_MESH_ConnectionCreate);
2372   if (size % sizeof (struct GNUNET_PeerIdentity))
2373   {
2374     GNUNET_break_op (0);
2375     return GNUNET_OK;
2376   }
2377   size /= sizeof (struct GNUNET_PeerIdentity);
2378   if (1 > size)
2379   {
2380     GNUNET_break_op (0);
2381     return GNUNET_OK;
2382   }
2383   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
2384
2385   /* Get parameters */
2386   msg = (struct GNUNET_MESH_ConnectionCreate *) message;
2387   cid = &msg->cid;
2388   id = (struct GNUNET_PeerIdentity *) &msg[1];
2389   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2390               "    connection %s (%s).\n",
2391               GNUNET_h2s (cid), GNUNET_i2s (id));
2392
2393   /* Create connection */
2394   c = connection_get (cid);
2395   if (NULL == c)
2396   {
2397     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating connection\n");
2398     c = connection_new (cid);
2399     if (NULL == c)
2400       return GNUNET_OK;
2401     connection_reset_timeout (c, GNUNET_YES);
2402
2403     /* Create path */
2404     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
2405     path = path_new (size);
2406     own_pos = 0;
2407     for (i = 0; i < size; i++)
2408     {
2409       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ... adding %s\n",
2410                   GNUNET_i2s (&id[i]));
2411       path->peers[i] = GNUNET_PEER_intern (&id[i]);
2412       if (path->peers[i] == myid)
2413         own_pos = i;
2414     }
2415     if (own_pos == 0 && path->peers[own_pos] != myid)
2416     {
2417       /* create path: self not found in path through self */
2418       GNUNET_break_op (0);
2419       path_destroy (path);
2420       connection_destroy (c);
2421       return GNUNET_OK;
2422     }
2423     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
2424     path_add_to_peers (path, GNUNET_NO);
2425     c->path = path_duplicate (path);
2426     c->own_pos = own_pos;
2427   }
2428   else
2429   {
2430     path = NULL;
2431   }
2432   if (MESH_CONNECTION_NEW == c->state)
2433     connection_change_state (c, MESH_CONNECTION_SENT);
2434
2435   /* Remember peers */
2436   dest_peer = peer_get (&id[size - 1]);
2437   orig_peer = peer_get (&id[0]);
2438
2439   /* Is it a connection to us? */
2440   if (c->own_pos == size - 1)
2441   {
2442     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
2443     peer_add_path_to_origin (orig_peer, path, GNUNET_YES);
2444
2445     if (NULL == orig_peer->tunnel)
2446     {
2447       orig_peer->tunnel = tunnel_new ();
2448       orig_peer->tunnel->peer = orig_peer;
2449     }
2450     tunnel_add_connection (orig_peer->tunnel, c);
2451     if (MESH_TUNNEL_NEW == c->t->state)
2452       tunnel_change_state (c->t,  MESH_TUNNEL_WAITING);
2453
2454     send_connection_ack (c, GNUNET_NO);
2455     if (MESH_CONNECTION_SENT == c->state)
2456       connection_change_state (c, MESH_CONNECTION_ACK);
2457
2458     /* Keep tunnel alive in direction dest->owner*/
2459     connection_reset_timeout (c, GNUNET_NO);
2460   }
2461   else
2462   {
2463     /* It's for somebody else! Retransmit. */
2464     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Retransmitting.\n");
2465     peer_add_path (dest_peer, path_duplicate (path), GNUNET_NO);
2466     peer_add_path_to_origin (orig_peer, path, GNUNET_NO);
2467     send_prebuilt_message_connection (message, c, NULL, GNUNET_YES);
2468   }
2469   return GNUNET_OK;
2470 }
2471
2472
2473 /**
2474  * Core handler for path ACKs
2475  *
2476  * @param cls closure
2477  * @param message message
2478  * @param peer peer identity this notification is about
2479  *
2480  * @return GNUNET_OK to keep the connection open,
2481  *         GNUNET_SYSERR to close it (signal serious error)
2482  */
2483 static int
2484 handle_mesh_connection_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
2485                             const struct GNUNET_MessageHeader *message)
2486 {
2487   struct GNUNET_MESH_ConnectionACK *msg;
2488   struct MeshConnection *c;
2489   struct MeshPeerPath *p;
2490   struct MeshPeer *pi;
2491   int fwd;
2492
2493   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "\n\n");
2494   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a connection ACK msg\n");
2495   msg = (struct GNUNET_MESH_ConnectionACK *) message;
2496   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on connection %s\n",
2497               GNUNET_h2s (&msg->cid));
2498   c = connection_get (&msg->cid);
2499   if (NULL == c)
2500   {
2501     GNUNET_STATISTICS_update (stats, "# control on unknown connection",
2502                               1, GNUNET_NO);
2503     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  don't know the connection!\n");
2504     return GNUNET_OK;
2505   }
2506
2507
2508   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  via peer %s\n",
2509               GNUNET_i2s (peer));
2510   pi = peer_get (peer);
2511   if (connection_get_next_hop (c) == pi)
2512   {
2513     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  SYNACK\n");
2514     fwd = GNUNET_NO;
2515     if (MESH_CONNECTION_SENT == c->state)
2516       connection_change_state (c, MESH_CONNECTION_ACK);
2517   }
2518   else if (connection_get_prev_hop (c) == pi)
2519   {
2520     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ACK\n");
2521     fwd = GNUNET_YES;
2522     connection_change_state (c, MESH_CONNECTION_READY);
2523   }
2524   else
2525   {
2526     GNUNET_break_op (0);
2527     return GNUNET_OK;
2528   }
2529   connection_reset_timeout (c, fwd);
2530
2531   /* Add path to peers? */
2532   p = c->path;
2533   if (NULL != p)
2534   {
2535     path_add_to_peers (p, GNUNET_YES);
2536   }
2537   else
2538   {
2539     GNUNET_break (0);
2540   }
2541
2542   /* Message for us as creator? */
2543   if (connection_is_origin (c, GNUNET_YES))
2544   {
2545     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Connection (SYN)ACK for us!\n");
2546     connection_change_state (c, MESH_CONNECTION_READY);
2547     if (MESH_TUNNEL_READY != c->t->state)
2548       tunnel_change_state (c->t, MESH_TUNNEL_READY);
2549     send_connection_ack (c, GNUNET_YES);
2550     tunnel_send_queued_data (c->t, GNUNET_YES);
2551     if (3 <= tunnel_count_connections (c->t) && NULL != c->t->peer->dhtget)
2552     {
2553       GNUNET_DHT_get_stop (c->t->peer->dhtget);
2554       c->t->peer->dhtget = NULL;
2555     }
2556     return GNUNET_OK;
2557   }
2558
2559   /* Message for us as destination? */
2560   if (GMC_is_terminal (c, GNUNET_YES))
2561   {
2562     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Connection ACK for us!\n");
2563     if (MESH_TUNNEL_READY != c->t->state)
2564       tunnel_change_state (c->t, MESH_TUNNEL_READY);
2565     connection_change_state (c, MESH_CONNECTION_READY);
2566     tunnel_send_queued_data (c->t, GNUNET_NO);
2567     return GNUNET_OK;
2568   }
2569
2570   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  not for us, retransmitting...\n");
2571   send_prebuilt_message_connection (message, c, NULL, fwd);
2572   return GNUNET_OK;
2573 }
2574
2575
2576 /**
2577  * Core handler for notifications of broken paths
2578  *
2579  * @param cls Closure (unused).
2580  * @param peer Peer identity of sending neighbor.
2581  * @param message Message.
2582  *
2583  * @return GNUNET_OK to keep the connection open,
2584  *         GNUNET_SYSERR to close it (signal serious error)
2585  */
2586 static int
2587 handle_mesh_connection_broken (void *cls, const struct GNUNET_PeerIdentity *peer,
2588                                const struct GNUNET_MessageHeader *message)
2589 {
2590   struct GNUNET_MESH_ConnectionBroken *msg;
2591   struct MeshConnection *c;
2592
2593   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2594               "Received a CONNECTION BROKEN msg from %s\n", GNUNET_i2s (peer));
2595   msg = (struct GNUNET_MESH_ConnectionBroken *) message;
2596   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
2597               GNUNET_i2s (&msg->peer1));
2598   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
2599               GNUNET_i2s (&msg->peer2));
2600   c = connection_get (&msg->cid);
2601   if (NULL == c)
2602   {
2603     GNUNET_break_op (0);
2604     return GNUNET_OK;
2605   }
2606   tunnel_notify_connection_broken (c->t, GNUNET_PEER_search (&msg->peer1),
2607                                    GNUNET_PEER_search (&msg->peer2));
2608   return GNUNET_OK;
2609
2610 }
2611
2612
2613 /**
2614  * Core handler for tunnel destruction
2615  *
2616  * @param cls Closure (unused).
2617  * @param peer Peer identity of sending neighbor.
2618  * @param message Message.
2619  *
2620  * @return GNUNET_OK to keep the connection open,
2621  *         GNUNET_SYSERR to close it (signal serious error)
2622  */
2623 static int
2624 handle_mesh_connection_destroy (void *cls,
2625                                 const struct GNUNET_PeerIdentity *peer,
2626                                 const struct GNUNET_MessageHeader *message)
2627 {
2628   struct GNUNET_MESH_ConnectionDestroy *msg;
2629   struct MeshConnection *c;
2630   GNUNET_PEER_Id id;
2631   int fwd;
2632
2633   msg = (struct GNUNET_MESH_ConnectionDestroy *) message;
2634   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2635               "Got a CONNECTION DESTROY message from %s\n",
2636               GNUNET_i2s (peer));
2637   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2638               "  for connection %s\n",
2639               GNUNET_h2s (&msg->cid));
2640   c = connection_get (&msg->cid);
2641   if (NULL == c)
2642   {
2643     /* Probably already got the message from another path,
2644      * destroyed the tunnel and retransmitted to children.
2645      * Safe to ignore.
2646      */
2647     GNUNET_STATISTICS_update (stats, "# control on unknown tunnel",
2648                               1, GNUNET_NO);
2649     return GNUNET_OK;
2650   }
2651   id = GNUNET_PEER_search (peer);
2652   if (id == connection_get_prev_hop (c)->id)
2653     fwd = GNUNET_YES;
2654   else if (id == connection_get_next_hop (c)->id)
2655     fwd = GNUNET_NO;
2656   else
2657   {
2658     GNUNET_break_op (0);
2659     return GNUNET_OK;
2660   }
2661   send_prebuilt_message_connection (message, c, NULL, fwd);
2662   c->destroy = GNUNET_YES;
2663
2664   return GNUNET_OK;
2665 }
2666
2667
2668 /**
2669  * Handler for channel create messages.
2670  *
2671  * @param t Tunnel this channel is to be created in.
2672  * @param msg Message.
2673  * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
2674  */
2675 static void
2676 handle_channel_create (struct MeshTunnel2 *t,
2677                        struct GNUNET_MESH_ChannelCreate *msg,
2678                        int fwd)
2679 {
2680   MESH_ChannelNumber chid;
2681   struct MeshChannel *ch;
2682   struct MeshClient *c;
2683   uint32_t port;
2684
2685   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received Channel Create\n");
2686   /* Check message size */
2687   if (ntohs (msg->header.size) != sizeof (struct GNUNET_MESH_ChannelCreate))
2688   {
2689     GNUNET_break_op (0);
2690     return;
2691   }
2692
2693   /* Check if channel exists */
2694   chid = ntohl (msg->chid);
2695   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   chid %u\n", chid);
2696   ch = channel_get (t, chid);
2697   if (NULL != ch)
2698   {
2699     /* Probably a retransmission, safe to ignore */
2700     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   already exists...\n");
2701     if (NULL != ch->dest)
2702     {
2703       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   duplicate CC!!\n");
2704       channel_send_ack (ch, !fwd);
2705       return;
2706     }
2707   }
2708   else
2709   {
2710     /* Create channel */
2711     ch = channel_new (t, NULL, 0);
2712     ch->gid = chid;
2713     channel_set_options (ch, ntohl (msg->opt));
2714   }
2715
2716   /* Find a destination client */
2717   port = ntohl (msg->port);
2718   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   port %u\n", port);
2719   c = GNUNET_CONTAINER_multihashmap32_get (ports, port);
2720   if (NULL == c)
2721   {
2722     /* TODO send reject */
2723     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  no client has port registered\n");
2724     /* TODO free ch */
2725     return;
2726   }
2727
2728   channel_add_client (ch, c);
2729   if (GNUNET_YES == ch->reliable)
2730     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "!!! Reliable\n");
2731
2732   send_local_channel_create (ch);
2733   channel_send_ack (ch, fwd);
2734   send_local_ack (ch, !fwd);
2735 }
2736
2737
2738 /**
2739  * Handler for channel ack messages.
2740  *
2741  * @param t Tunnel this channel is to be created in.
2742  * @param msg Message.
2743  * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
2744  */
2745 static void
2746 handle_channel_ack (struct MeshTunnel2 *t,
2747                     struct GNUNET_MESH_ChannelManage *msg,
2748                     int fwd)
2749 {
2750   MESH_ChannelNumber chid;
2751   struct MeshChannel *ch;
2752
2753   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received Channel ACK\n");
2754   /* Check message size */
2755   if (ntohs (msg->header.size) != sizeof (struct GNUNET_MESH_ChannelManage))
2756   {
2757     GNUNET_break_op (0);
2758     return;
2759   }
2760
2761   /* Check if channel exists */
2762   chid = ntohl (msg->chid);
2763   ch = channel_get (t, chid);
2764   if (NULL == ch)
2765   {
2766     GNUNET_break_op (0);
2767     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   channel %u unknown!!\n", chid);
2768     return;
2769   }
2770
2771   channel_confirm (ch, !fwd);
2772 }
2773
2774
2775 /**
2776  * Handler for channel destroy messages.
2777  *
2778  * @param t Tunnel this channel is to be destroyed of.
2779  * @param msg Message.
2780  * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
2781  */
2782 static void
2783 handle_channel_destroy (struct MeshTunnel2 *t,
2784                         struct GNUNET_MESH_ChannelManage *msg,
2785                         int fwd)
2786 {
2787   MESH_ChannelNumber chid;
2788   struct MeshChannel *ch;
2789
2790   /* Check message size */
2791   if (ntohs (msg->header.size) != sizeof (struct GNUNET_MESH_ChannelManage))
2792   {
2793     GNUNET_break_op (0);
2794     return;
2795   }
2796
2797   /* Check if channel exists */
2798   chid = ntohl (msg->chid);
2799   ch = channel_get (t, chid);
2800   if (NULL == ch)
2801   {
2802     /* Probably a retransmission, safe to ignore */
2803     return;
2804   }
2805   if ( (fwd && NULL == ch->dest) || (!fwd && NULL == ch->root) )
2806   {
2807     /* Not for us (don't destroy twice a half-open loopback channel) */
2808     return;
2809   }
2810
2811   send_local_channel_destroy (ch, fwd);
2812   channel_destroy (ch);
2813 }
2814
2815
2816 static void
2817 handle_decrypted (struct MeshTunnel2 *t,
2818                   const struct GNUNET_MessageHeader *msgh,
2819                   int fwd)
2820 {
2821   switch (ntohs (msgh->type))
2822   {
2823     case GNUNET_MESSAGE_TYPE_MESH_DATA:
2824       /* Don't send hop ACK, wait for client to ACK */
2825       handle_data (t, (struct GNUNET_MESH_Data *) msgh, fwd);
2826       break;
2827
2828     case GNUNET_MESSAGE_TYPE_MESH_DATA_ACK:
2829       handle_data_ack (t, (struct GNUNET_MESH_DataACK *) msgh, fwd);
2830       break;
2831
2832     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE:
2833       handle_channel_create (t,
2834                              (struct GNUNET_MESH_ChannelCreate *) msgh,
2835                              fwd);
2836       break;
2837
2838     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_ACK:
2839       handle_channel_ack (t,
2840                           (struct GNUNET_MESH_ChannelManage *) msgh,
2841                           fwd);
2842       break;
2843
2844     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY:
2845       handle_channel_destroy (t,
2846                               (struct GNUNET_MESH_ChannelManage *) msgh,
2847                               fwd);
2848       break;
2849
2850     default:
2851       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2852                   "end-to-end message not known (%u)\n",
2853                   ntohs (msgh->type));
2854   }
2855 }
2856
2857
2858 /**
2859  * Generic handler for mesh network encrypted traffic.
2860  *
2861  * @param peer Peer identity this notification is about.
2862  * @param message Encrypted message.
2863  * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
2864  *
2865  * @return GNUNET_OK to keep the connection open,
2866  *         GNUNET_SYSERR to close it (signal serious error)
2867  */
2868 static int
2869 handle_mesh_encrypted (const struct GNUNET_PeerIdentity *peer,
2870                        const struct GNUNET_MESH_Encrypted *msg,
2871                        int fwd)
2872 {
2873   struct MeshConnection *c;
2874   struct MeshTunnel2 *t;
2875   struct MeshPeer *neighbor;
2876   struct MeshFlowControl *fc;
2877   uint32_t pid;
2878   uint32_t ttl;
2879   uint16_t type;
2880   size_t size;
2881
2882   /* Check size */
2883   size = ntohs (msg->header.size);
2884   if (size <
2885       sizeof (struct GNUNET_MESH_Encrypted) +
2886       sizeof (struct GNUNET_MessageHeader))
2887   {
2888     GNUNET_break_op (0);
2889     return GNUNET_OK;
2890   }
2891   type = ntohs (msg->header.type);
2892   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "\n\n");
2893   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a %s message from %s\n",
2894               GNUNET_MESH_DEBUG_M2S (type), GNUNET_i2s (peer));
2895
2896   /* Check connection */
2897   c = connection_get (&msg->cid);
2898   if (NULL == c)
2899   {
2900     GNUNET_STATISTICS_update (stats, "# unknown connection", 1, GNUNET_NO);
2901     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "WARNING connection unknown\n");
2902     return GNUNET_OK;
2903   }
2904   t = c->t;
2905   fc = fwd ? &c->bck_fc : &c->fwd_fc;
2906
2907   /* Check if origin is as expected */
2908   neighbor = connection_get_hop (c, !fwd);
2909   if (peer_get (peer)->id != neighbor->id)
2910   {
2911     GNUNET_break_op (0);
2912     return GNUNET_OK;
2913   }
2914
2915   /* Check PID */
2916   pid = ntohl (msg->pid);
2917   if (GMC_is_pid_bigger (pid, fc->last_ack_sent))
2918   {
2919     GNUNET_STATISTICS_update (stats, "# unsolicited message", 1, GNUNET_NO);
2920     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2921                 "WARNING Received PID %u, (prev %u), ACK %u\n",
2922                 pid, fc->last_pid_recv, fc->last_ack_sent);
2923     return GNUNET_OK;
2924   }
2925   if (GNUNET_NO == GMC_is_pid_bigger (pid, fc->last_pid_recv))
2926   {
2927     GNUNET_STATISTICS_update (stats, "# duplicate PID", 1, GNUNET_NO);
2928     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2929                 " Pid %u not expected (%u+), dropping!\n",
2930                 pid, fc->last_pid_recv + 1);
2931     return GNUNET_OK;
2932   }
2933   if (MESH_CONNECTION_SENT == c->state)
2934     connection_change_state (c, MESH_CONNECTION_READY);
2935   connection_reset_timeout (c, fwd);
2936   fc->last_pid_recv = pid;
2937
2938   /* Is this message for us? */
2939   if (GMC_is_terminal (c, fwd))
2940   {
2941     size_t dsize = size - sizeof (struct GNUNET_MESH_Encrypted);
2942     char cbuf[dsize];
2943     struct GNUNET_MessageHeader *msgh;
2944     unsigned int off;
2945
2946     /* TODO signature verification */
2947     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  message for us!\n");
2948     GNUNET_STATISTICS_update (stats, "# messages received", 1, GNUNET_NO);
2949
2950     fc->last_pid_recv = pid;
2951     tunnel_decrypt (t, cbuf, &msg[1], dsize, msg->iv, fwd);
2952     off = 0;
2953     while (off < dsize)
2954     {
2955       msgh = (struct GNUNET_MessageHeader *) &cbuf[off];
2956       handle_decrypted (t, msgh, fwd);
2957       off += ntohs (msgh->size);
2958     }
2959     send_ack (c, NULL, fwd);
2960     return GNUNET_OK;
2961   }
2962
2963   /* Message not for us: forward to next hop */
2964   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  not for us, retransmitting...\n");
2965   ttl = ntohl (msg->ttl);
2966   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ttl: %u\n", ttl);
2967   if (ttl == 0)
2968   {
2969     GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
2970     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
2971     send_ack (c, NULL, fwd);
2972     return GNUNET_OK;
2973   }
2974   GNUNET_STATISTICS_update (stats, "# messages forwarded", 1, GNUNET_NO);
2975
2976   send_prebuilt_message_connection (&msg->header, c, NULL, fwd);
2977
2978   return GNUNET_OK;
2979 }
2980
2981
2982 /**
2983  * Core handler for mesh network traffic going orig->dest.
2984  *
2985  * @param cls Closure (unused).
2986  * @param message Message received.
2987  * @param peer Peer who sent the message.
2988  *
2989  * @return GNUNET_OK to keep the connection open,
2990  *         GNUNET_SYSERR to close it (signal serious error)
2991  */
2992 static int
2993 handle_mesh_fwd (void *cls, const struct GNUNET_PeerIdentity *peer,
2994                      const struct GNUNET_MessageHeader *message)
2995 {
2996   return handle_mesh_encrypted (peer,
2997                                 (struct GNUNET_MESH_Encrypted *)message,
2998                                 GNUNET_YES);
2999 }
3000
3001 /**
3002  * Core handler for mesh network traffic going dest->orig.
3003  *
3004  * @param cls Closure (unused).
3005  * @param message Message received.
3006  * @param peer Peer who sent the message.
3007  *
3008  * @return GNUNET_OK to keep the connection open,
3009  *         GNUNET_SYSERR to close it (signal serious error)
3010  */
3011 static int
3012 handle_mesh_bck (void *cls, const struct GNUNET_PeerIdentity *peer,
3013                      const struct GNUNET_MessageHeader *message)
3014 {
3015   return handle_mesh_encrypted (peer,
3016                                 (struct GNUNET_MESH_Encrypted *)message,
3017                                 GNUNET_NO);
3018 }
3019
3020
3021 /**
3022  * Core handler for mesh network traffic point-to-point acks.
3023  *
3024  * @param cls closure
3025  * @param message message
3026  * @param peer peer identity this notification is about
3027  *
3028  * @return GNUNET_OK to keep the connection open,
3029  *         GNUNET_SYSERR to close it (signal serious error)
3030  */
3031 static int
3032 handle_mesh_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
3033                  const struct GNUNET_MessageHeader *message)
3034 {
3035   struct GNUNET_MESH_ACK *msg;
3036   struct MeshConnection *c;
3037   struct MeshFlowControl *fc;
3038   GNUNET_PEER_Id id;
3039   uint32_t ack;
3040   int fwd;
3041
3042   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "\n\n");
3043   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got an ACK packet from %s!\n",
3044               GNUNET_i2s (peer));
3045   msg = (struct GNUNET_MESH_ACK *) message;
3046
3047   c = connection_get (&msg->cid);
3048
3049   if (NULL == c)
3050   {
3051     GNUNET_STATISTICS_update (stats, "# ack on unknown connection", 1,
3052                               GNUNET_NO);
3053     return GNUNET_OK;
3054   }
3055
3056   /* Is this a forward or backward ACK? */
3057   id = GNUNET_PEER_search (peer);
3058   if (connection_get_next_hop (c)->id == id)
3059   {
3060     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  FWD ACK\n");
3061     fc = &c->fwd_fc;
3062     fwd = GNUNET_YES;
3063   }
3064   else if (connection_get_prev_hop (c)->id == id)
3065   {
3066     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  BCK ACK\n");
3067     fc = &c->bck_fc;
3068     fwd = GNUNET_NO;
3069   }
3070   else
3071   {
3072     GNUNET_break_op (0);
3073     return GNUNET_OK;
3074   }
3075
3076   ack = ntohl (msg->ack);
3077   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ACK %u (was %u)\n",
3078               ack, fc->last_ack_recv);
3079   if (GMC_is_pid_bigger (ack, fc->last_ack_recv))
3080     fc->last_ack_recv = ack;
3081
3082   /* Cancel polling if the ACK is big enough. */
3083   if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task &&
3084       GMC_is_pid_bigger (fc->last_ack_recv, fc->last_pid_sent))
3085   {
3086     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Cancel poll\n");
3087     GNUNET_SCHEDULER_cancel (fc->poll_task);
3088     fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
3089     fc->poll_time = GNUNET_TIME_UNIT_SECONDS;
3090   }
3091
3092   connection_unlock_queue (c, fwd);
3093
3094   return GNUNET_OK;
3095 }
3096
3097
3098 /**
3099  * Core handler for mesh network traffic point-to-point ack polls.
3100  *
3101  * @param cls closure
3102  * @param message message
3103  * @param peer peer identity this notification is about
3104  *
3105  * @return GNUNET_OK to keep the connection open,
3106  *         GNUNET_SYSERR to close it (signal serious error)
3107  */
3108 static int
3109 handle_mesh_poll (void *cls, const struct GNUNET_PeerIdentity *peer,
3110                   const struct GNUNET_MessageHeader *message)
3111 {
3112   struct GNUNET_MESH_Poll *msg;
3113   struct MeshConnection *c;
3114   struct MeshFlowControl *fc;
3115   GNUNET_PEER_Id id;
3116   uint32_t pid;
3117   int fwd;
3118
3119   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "\n\n");
3120   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a POLL packet from %s!\n",
3121               GNUNET_i2s (peer));
3122
3123   msg = (struct GNUNET_MESH_Poll *) message;
3124
3125   c = connection_get (&msg->cid);
3126
3127   if (NULL == c)
3128   {
3129     GNUNET_STATISTICS_update (stats, "# poll on unknown connection", 1,
3130                               GNUNET_NO);
3131     GNUNET_break_op (0);
3132     return GNUNET_OK;
3133   }
3134
3135   /* Is this a forward or backward ACK?
3136    * Note: a poll should never be needed in a loopback case,
3137    * since there is no possiblility of packet loss there, so
3138    * this way of discerining FWD/BCK should not be a problem.
3139    */
3140   id = GNUNET_PEER_search (peer);
3141   if (connection_get_next_hop (c)->id == id)
3142   {
3143     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  FWD ACK\n");
3144     fc = &c->fwd_fc;
3145   }
3146   else if (connection_get_prev_hop (c)->id == id)
3147   {
3148     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  BCK ACK\n");
3149     fc = &c->bck_fc;
3150   }
3151   else
3152   {
3153     GNUNET_break_op (0);
3154     return GNUNET_OK;
3155   }
3156
3157   pid = ntohl (msg->pid);
3158   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  PID %u, OLD %u\n",
3159               pid, fc->last_pid_recv);
3160   fc->last_pid_recv = pid;
3161   fwd = fc == &c->fwd_fc;
3162   send_ack (c, NULL, fwd);
3163
3164   return GNUNET_OK;
3165 }
3166
3167
3168 /**
3169  * Core handler for mesh keepalives.
3170  *
3171  * @param cls closure
3172  * @param message message
3173  * @param peer peer identity this notification is about
3174  * @return GNUNET_OK to keep the connection open,
3175  *         GNUNET_SYSERR to close it (signal serious error)
3176  *
3177  * TODO: Check who we got this from, to validate route.
3178  */
3179 static int
3180 handle_mesh_keepalive (void *cls, const struct GNUNET_PeerIdentity *peer,
3181                        const struct GNUNET_MessageHeader *message)
3182 {
3183   struct GNUNET_MESH_ConnectionKeepAlive *msg;
3184   struct MeshConnection *c;
3185   struct MeshPeer *neighbor;
3186   int fwd;
3187
3188   msg = (struct GNUNET_MESH_ConnectionKeepAlive *) message;
3189   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a keepalive packet from %s\n",
3190               GNUNET_i2s (peer));
3191
3192   c = connection_get (&msg->cid);
3193   if (NULL == c)
3194   {
3195     GNUNET_STATISTICS_update (stats, "# keepalive on unknown connection", 1,
3196                               GNUNET_NO);
3197     return GNUNET_OK;
3198   }
3199
3200   fwd = GNUNET_MESSAGE_TYPE_MESH_FWD_KEEPALIVE == ntohs (message->type) ? 
3201         GNUNET_YES : GNUNET_NO;
3202
3203   /* Check if origin is as expected */
3204   neighbor = connection_get_hop (c, fwd);
3205   if (peer_get (peer)->id != neighbor->id)
3206   {
3207     GNUNET_break_op (0);
3208     return GNUNET_OK;
3209   }
3210
3211   connection_change_state (c, MESH_CONNECTION_READY);
3212   connection_reset_timeout (c, fwd);
3213
3214   if (GMC_is_terminal (c, fwd))
3215     return GNUNET_OK;
3216
3217   GNUNET_STATISTICS_update (stats, "# keepalives forwarded", 1, GNUNET_NO);
3218   send_prebuilt_message_connection (message, c, NULL, fwd);
3219
3220   return GNUNET_OK;
3221 }
3222
3223
3224
3225 /**
3226  * Functions to handle messages from core
3227  */
3228 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
3229   {&handle_mesh_connection_create, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE,
3230     0},
3231   {&handle_mesh_connection_ack, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK,
3232     sizeof (struct GNUNET_MESH_ConnectionACK)},
3233   {&handle_mesh_connection_broken, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN,
3234     sizeof (struct GNUNET_MESH_ConnectionBroken)},
3235   {&handle_mesh_connection_destroy, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_DESTROY,
3236     sizeof (struct GNUNET_MESH_ConnectionDestroy)},
3237   {&handle_mesh_keepalive, GNUNET_MESSAGE_TYPE_MESH_FWD_KEEPALIVE,
3238     sizeof (struct GNUNET_MESH_ConnectionKeepAlive)},
3239   {&handle_mesh_keepalive, GNUNET_MESSAGE_TYPE_MESH_BCK_KEEPALIVE,
3240     sizeof (struct GNUNET_MESH_ConnectionKeepAlive)},
3241   {&handle_mesh_ack, GNUNET_MESSAGE_TYPE_MESH_ACK,
3242     sizeof (struct GNUNET_MESH_ACK)},
3243   {&handle_mesh_poll, GNUNET_MESSAGE_TYPE_MESH_POLL,
3244     sizeof (struct GNUNET_MESH_Poll)},
3245   {&handle_mesh_fwd, GNUNET_MESSAGE_TYPE_MESH_FWD, 0},
3246   {&handle_mesh_bck, GNUNET_MESSAGE_TYPE_MESH_BCK, 0},
3247   {NULL, 0, 0}
3248 };
3249
3250
3251 /**
3252  * Function to process paths received for a new peer addition. The recorded
3253  * paths form the initial tunnel, which can be optimized later.
3254  * Called on each result obtained for the DHT search.
3255  *
3256  * @param cls closure
3257  * @param exp when will this value expire
3258  * @param key key of the result
3259  * @param get_path path of the get request
3260  * @param get_path_length lenght of get_path
3261  * @param put_path path of the put request
3262  * @param put_path_length length of the put_path
3263  * @param type type of the result
3264  * @param size number of bytes in data
3265  * @param data pointer to the result data
3266  */
3267 static void
3268 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
3269                     const struct GNUNET_HashCode * key,
3270                     const struct GNUNET_PeerIdentity *get_path,
3271                     unsigned int get_path_length,
3272                     const struct GNUNET_PeerIdentity *put_path,
3273                     unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
3274                     size_t size, const void *data)
3275 {
3276   struct MeshPeer *peer = cls;
3277   struct MeshPeerPath *p;
3278   struct MeshConnection *c;
3279   struct GNUNET_PeerIdentity pi;
3280   unsigned int connection_count;
3281
3282   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got results from DHT!\n");
3283   GNUNET_PEER_resolve (peer->id, &pi);
3284   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for %s\n", GNUNET_i2s (&pi));
3285
3286   p = path_build_from_dht (get_path, get_path_length,
3287                            put_path, put_path_length);
3288   path_add_to_peers (p, GNUNET_NO);
3289   path_destroy (p);
3290
3291   /* Count connections */
3292   connection_count = GMC_count (peer->tunnel->connection_head);
3293
3294   /* If we already have 3 (or more (?!)) connections, it's enough */
3295   if (3 <= connection_count)
3296     return;
3297
3298   if (peer->tunnel->state == MESH_TUNNEL_SEARCHING)
3299   {
3300     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " ... connect!\n");
3301     peer_connect (peer);
3302   }
3303   return;
3304 }
3305
3306
3307
3308 /**
3309  * Method called whenever a given peer connects.
3310  *
3311  * @param cls closure
3312  * @param peer peer identity this notification is about
3313  */
3314 static void
3315 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer)
3316 {
3317   struct MeshPeer *pi;
3318   struct MeshPeerPath *path;
3319
3320   DEBUG_CONN ("Peer connected\n");
3321   DEBUG_CONN ("     %s\n", GNUNET_i2s (&my_full_id));
3322   pi = peer_get (peer);
3323   if (myid == pi->id)
3324   {
3325     DEBUG_CONN ("     (self)\n");
3326     path = path_new (1);
3327   }
3328   else
3329   {
3330     DEBUG_CONN ("     %s\n", GNUNET_i2s (peer));
3331     path = path_new (2);
3332     path->peers[1] = pi->id;
3333     GNUNET_PEER_change_rc (pi->id, 1);
3334     GNUNET_STATISTICS_update (stats, "# peers", 1, GNUNET_NO);
3335   }
3336   path->peers[0] = myid;
3337   GNUNET_PEER_change_rc (myid, 1);
3338   peer_add_path (pi, path, GNUNET_YES);
3339
3340   pi->connections = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_YES);
3341   return;
3342 }
3343
3344
3345 /**
3346  * Method called whenever a peer disconnects.
3347  *
3348  * @param cls closure
3349  * @param peer peer identity this notification is about
3350  */
3351 static void
3352 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
3353 {
3354   struct MeshPeer *pi;
3355
3356   DEBUG_CONN ("Peer disconnected\n");
3357   pi = GNUNET_CONTAINER_multipeermap_get (peers, peer);
3358   if (NULL == pi)
3359   {
3360     GNUNET_break (0);
3361     return;
3362   }
3363
3364   GNUNET_CONTAINER_multihashmap_iterate (pi->connections,
3365                                          GMC_notify_broken,
3366                                          pi);
3367   GNUNET_CONTAINER_multihashmap_destroy (pi->connections);
3368   pi->connections = NULL;
3369   if (NULL != pi->core_transmit)
3370     {
3371       GNUNET_CORE_notify_transmit_ready_cancel (pi->core_transmit);
3372       pi->core_transmit = NULL;
3373     }
3374   if (myid == pi->id)
3375   {
3376     DEBUG_CONN ("     (self)\n");
3377   }
3378   GNUNET_STATISTICS_update (stats, "# peers", -1, GNUNET_NO);
3379
3380   return;
3381 }
3382
3383
3384
3385 /**
3386  * To be called on core init/fail.
3387  *
3388  * @param cls Closure (config)
3389  * @param identity the public identity of this peer
3390  */
3391 static void
3392 core_init (void *cls, 
3393            const struct GNUNET_PeerIdentity *identity)
3394 {
3395   const struct GNUNET_CONFIGURATION_Handle *c = cls;
3396   static int i = 0;
3397
3398   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Core init\n");
3399   if (0 != memcmp (identity, &my_full_id, sizeof (my_full_id)))
3400   {
3401     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Wrong CORE service\n"));
3402     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3403                 " core id %s\n",
3404                 GNUNET_i2s (identity));
3405     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3406                 " my id %s\n",
3407                 GNUNET_i2s (&my_full_id));
3408     GNUNET_CORE_disconnect (core_handle);
3409     core_handle = GNUNET_CORE_connect (c, /* Main configuration */
3410                                        NULL,      /* Closure passed to MESH functions */
3411                                        &core_init,        /* Call core_init once connected */
3412                                        &core_connect,     /* Handle connects */
3413                                        &core_disconnect,  /* remove peers on disconnects */
3414                                        NULL,      /* Don't notify about all incoming messages */
3415                                        GNUNET_NO, /* For header only in notification */
3416                                        NULL,      /* Don't notify about all outbound messages */
3417                                        GNUNET_NO, /* For header-only out notification */
3418                                        core_handlers);    /* Register these handlers */
3419     if (10 < i++)
3420       GNUNET_abort();
3421   }
3422   server_init ();
3423   return;
3424 }
3425
3426
3427 /******************************************************************************/
3428 /************************      MAIN FUNCTIONS      ****************************/
3429 /******************************************************************************/
3430
3431 /**
3432  * Iterator over tunnel hash map entries to destroy the tunnel during shutdown.
3433  *
3434  * @param cls closure
3435  * @param key current key code
3436  * @param value value in the hash map
3437  * @return #GNUNET_YES if we should continue to iterate,
3438  *         #GNUNET_NO if not.
3439  */
3440 static int
3441 shutdown_tunnel (void *cls, 
3442                  const struct GNUNET_PeerIdentity *key, 
3443                  void *value)
3444 {
3445   struct MeshPeer *p = value;
3446   struct MeshTunnel2 *t = p->tunnel;
3447
3448   if (NULL != t)
3449     tunnel_destroy (t);
3450   return GNUNET_YES;
3451 }
3452
3453
3454 /**
3455  * Task run during shutdown.
3456  *
3457  * @param cls unused
3458  * @param tc unused
3459  */
3460 static void
3461 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3462 {
3463   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shutting down\n");
3464
3465   if (core_handle != NULL)
3466   {
3467     GNUNET_CORE_disconnect (core_handle);
3468     core_handle = NULL;
3469   }
3470   GNUNET_CONTAINER_multipeermap_iterate (peers, &shutdown_tunnel, NULL);
3471   if (dht_handle != NULL)
3472   {
3473     GNUNET_DHT_disconnect (dht_handle);
3474     dht_handle = NULL;
3475   }
3476   GML_shutdown ();
3477   if (GNUNET_SCHEDULER_NO_TASK != announce_id_task)
3478   {
3479     GNUNET_SCHEDULER_cancel (announce_id_task);
3480     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
3481   }
3482   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shut down\n");
3483 }
3484
3485
3486 /**
3487  * Process mesh requests.
3488  *
3489  * @param cls closure
3490  * @param server the initialized server
3491  * @param c configuration to use
3492  */
3493 static void
3494 run (void *cls, struct GNUNET_SERVER_Handle *server,
3495      const struct GNUNET_CONFIGURATION_Handle *c)
3496 {
3497   struct GNUNET_CRYPTO_EccPrivateKey *pk;
3498
3499   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "starting to run\n");
3500
3501   if (GNUNET_OK !=
3502       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "ID_ANNOUNCE_TIME",
3503                                            &id_announce_time))
3504   {
3505     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_ERROR,
3506                                "MESH", "ID_ANNOUNCE_TIME", "MISSING");
3507     GNUNET_SCHEDULER_shutdown ();
3508     return;
3509   }
3510
3511   if (GNUNET_OK !=
3512       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "CONNECT_TIMEOUT",
3513                                            &connect_timeout))
3514   {
3515     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_ERROR,
3516                                "MESH", "CONNECT_TIMEOUT", "MISSING");
3517     GNUNET_SCHEDULER_shutdown ();
3518     return;
3519   }
3520
3521   if (GNUNET_OK !=
3522       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DEFAULT_TTL",
3523                                              &default_ttl))
3524   {
3525     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
3526                                "MESH", "DEFAULT_TTL", "USING DEFAULT");
3527     default_ttl = 64;
3528   }
3529
3530   if (GNUNET_OK !=
3531       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_PEERS",
3532                                              &max_peers))
3533   {
3534     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
3535                                "MESH", "MAX_PEERS", "USING DEFAULT");
3536     max_peers = 1000;
3537   }
3538
3539   if (GNUNET_OK !=
3540       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DROP_PERCENT",
3541                                              &drop_percent))
3542   {
3543     drop_percent = 0;
3544   }
3545   else
3546   {
3547     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3548                 "\n***************************************\n"
3549                 "Mesh is running with drop mode enabled.\n"
3550                 "This is NOT a good idea!\n"
3551                 "Remove the DROP_PERCENT option from your configuration.\n"
3552                 "***************************************\n");
3553   }
3554
3555   if (GNUNET_OK !=
3556       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DHT_REPLICATION_LEVEL",
3557                                              &dht_replication_level))
3558   {
3559     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
3560                                "MESH", "DHT_REPLICATION_LEVEL", "USING DEFAULT");
3561     dht_replication_level = 3;
3562   }
3563
3564   peers = GNUNET_CONTAINER_multipeermap_create (32, GNUNET_NO);
3565
3566   dht_handle = GNUNET_DHT_connect (c, 64);
3567   if (NULL == dht_handle)
3568   {
3569     GNUNET_break (0);
3570   }
3571   stats = GNUNET_STATISTICS_create ("mesh", c);
3572
3573   /* Scheduled the task to clean up when shutdown is called */
3574   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
3575                                 NULL);
3576   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "reading key\n");
3577   pk = GNUNET_CRYPTO_ecc_key_create_from_configuration (c);
3578   GNUNET_assert (NULL != pk);
3579   my_private_key = pk;
3580   GNUNET_CRYPTO_ecc_key_get_public_for_signature (my_private_key, 
3581                                                   &my_full_id.public_key);
3582   myid = GNUNET_PEER_intern (&my_full_id);
3583   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3584               "Mesh for peer [%s] starting\n",
3585               GNUNET_i2s(&my_full_id));
3586
3587   GML_init (server);
3588   GMC_init (c);
3589
3590   core_handle = GNUNET_CORE_connect (c, /* Main configuration */
3591                                      NULL,      /* Closure passed to MESH functions */
3592                                      &core_init,        /* Call core_init once connected */
3593                                      &core_connect,     /* Handle connects */
3594                                      &core_disconnect,  /* remove peers on disconnects */
3595                                      NULL,      /* Don't notify about all incoming messages */
3596                                      GNUNET_NO, /* For header only in notification */
3597                                      NULL,      /* Don't notify about all outbound messages */
3598                                      GNUNET_NO, /* For header-only out notification */
3599                                      core_handlers);    /* Register these handlers */
3600   if (NULL == core_handle)
3601   {
3602     GNUNET_break (0);
3603     GNUNET_SCHEDULER_shutdown ();
3604     return;
3605   }
3606   announce_id_task = GNUNET_SCHEDULER_add_now (&announce_id, cls);
3607   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Mesh service running\n");
3608 }
3609
3610
3611 /**
3612  * The main function for the mesh service.
3613  *
3614  * @param argc number of arguments from the command line
3615  * @param argv command line arguments
3616  * @return 0 ok, 1 on error
3617  */
3618 int
3619 main (int argc, char *const *argv)
3620 {
3621   int ret;
3622   int r;
3623
3624   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main()\n");
3625   r = GNUNET_SERVICE_run (argc, argv, "mesh", GNUNET_SERVICE_OPTION_NONE, &run,
3626                           NULL);
3627   ret = (GNUNET_OK == r) ? 0 : 1;
3628   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main() END\n");
3629
3630   INTERVAL_SHOW;
3631
3632   return ret;
3633 }