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