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