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