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