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