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