- run test_mesh_regex by 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
3053     /* If queue is empty, send should have been cancelled */
3054     if (NULL == queue)
3055     {
3056         GNUNET_break(0);
3057         return 0;
3058     }
3059     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   not empty\n");
3060
3061     /* Check if buffer size is enough for the message */
3062     if (queue->size > size)
3063     {
3064         struct GNUNET_PeerIdentity id;
3065
3066         GNUNET_PEER_resolve (peer->id, &id);
3067         peer->core_transmit =
3068             GNUNET_CORE_notify_transmit_ready(core_handle,
3069                                               0,
3070                                               0,
3071                                               GNUNET_TIME_UNIT_FOREVER_REL,
3072                                               &id,
3073                                               queue->size,
3074                                               &queue_send,
3075                                               peer);
3076         return 0;
3077     }
3078     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   size ok\n");
3079
3080     /* Fill buf */
3081     switch (queue->type)
3082     {
3083         case GNUNET_MESSAGE_TYPE_MESH_UNICAST:
3084             GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   unicast\n");
3085             data_size = send_core_data_raw (queue->cls, size, buf);
3086             break;
3087         case GNUNET_MESSAGE_TYPE_MESH_MULTICAST:
3088             GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   multicast\n");
3089             data_size = send_core_data_multicast(queue->cls, size, buf);
3090             break;
3091         case GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE:
3092             GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   path create\n");
3093             data_size = send_core_path_create(queue->cls, size, buf);
3094             break;
3095         case GNUNET_MESSAGE_TYPE_MESH_PATH_ACK:
3096             GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   path ack\n");
3097             data_size = send_core_path_ack(queue->cls, size, buf);
3098             break;
3099         default:
3100             GNUNET_break (0);
3101             GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   type unknown\n");
3102             data_size = 0;
3103     }
3104     queue->tunnel->queue_n--;
3105
3106     /* Free queue, but cls was freed by send_core_* */
3107     queue_destroy(queue, GNUNET_NO);
3108
3109     /* If more data in queue, send next */
3110     if (NULL != peer->queue_head)
3111     {
3112         struct GNUNET_PeerIdentity id;
3113
3114         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   more data!\n");
3115         GNUNET_PEER_resolve (peer->id, &id);
3116         peer->core_transmit =
3117             GNUNET_CORE_notify_transmit_ready(core_handle,
3118                                               0,
3119                                               0,
3120                                               GNUNET_TIME_UNIT_FOREVER_REL,
3121                                               &id,
3122                                               peer->queue_head->size,
3123                                               &queue_send,
3124                                               peer);
3125     }
3126     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "*********   return %d\n", data_size);
3127     return data_size;
3128 }
3129
3130
3131 /**
3132  * Queue and pass message to core when possible.
3133  *
3134  * @param cls Closure (type dependant).
3135  * @param type Type of the message.
3136  * @param size Size of the message.
3137  * @param dst Neighbor to send message to.
3138  * @param t Tunnel this message belongs to.
3139  */
3140 static void
3141 queue_add (void *cls, uint16_t type, size_t size,
3142            struct MeshPeerInfo *dst, struct MeshTunnel *t)
3143 {
3144     struct MeshPeerQueue *queue;
3145
3146     if (t->queue_n >= t->queue_max)
3147     {
3148       if (NULL == t->owner)
3149         GNUNET_break_op(0);       // TODO: kill connection?
3150       else
3151         GNUNET_break(0);
3152       return;                       // Drop message
3153     }
3154     t->queue_n++;
3155     queue = GNUNET_malloc (sizeof (struct MeshPeerQueue));
3156     queue->cls = cls;
3157     queue->type = type;
3158     queue->size = size;
3159     queue->peer = dst;
3160     queue->tunnel = t;
3161     GNUNET_CONTAINER_DLL_insert_tail (dst->queue_head, dst->queue_tail, queue);
3162     if (NULL == dst->core_transmit)
3163     {
3164         struct GNUNET_PeerIdentity id;
3165
3166         GNUNET_PEER_resolve (dst->id, &id);
3167         dst->core_transmit =
3168             GNUNET_CORE_notify_transmit_ready(core_handle,
3169                                               0,
3170                                               0,
3171                                               GNUNET_TIME_UNIT_FOREVER_REL,
3172                                               &id,
3173                                               size,
3174                                               &queue_send,
3175                                               dst);
3176     }
3177 }
3178
3179
3180 /******************************************************************************/
3181 /********************      MESH NETWORK HANDLERS     **************************/
3182 /******************************************************************************/
3183
3184
3185 /**
3186  * Core handler for path creation
3187  *
3188  * @param cls closure
3189  * @param message message
3190  * @param peer peer identity this notification is about
3191  * @param atsi performance data
3192  * @param atsi_count number of records in 'atsi'
3193  *
3194  * @return GNUNET_OK to keep the connection open,
3195  *         GNUNET_SYSERR to close it (signal serious error)
3196  */
3197 static int
3198 handle_mesh_path_create (void *cls, const struct GNUNET_PeerIdentity *peer,
3199                          const struct GNUNET_MessageHeader *message,
3200                          const struct GNUNET_ATS_Information *atsi,
3201                          unsigned int atsi_count)
3202 {
3203   unsigned int own_pos;
3204   uint16_t size;
3205   uint16_t i;
3206   MESH_TunnelNumber tid;
3207   struct GNUNET_MESH_ManipulatePath *msg;
3208   struct GNUNET_PeerIdentity *pi;
3209   struct GNUNET_HashCode hash;
3210   struct MeshPeerPath *path;
3211   struct MeshPeerInfo *dest_peer_info;
3212   struct MeshPeerInfo *orig_peer_info;
3213   struct MeshTunnel *t;
3214
3215   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3216               "Received a path create msg [%s]\n",
3217               GNUNET_i2s (&my_full_id));
3218   size = ntohs (message->size);
3219   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
3220   {
3221     GNUNET_break_op (0);
3222     return GNUNET_OK;
3223   }
3224
3225   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
3226   if (size % sizeof (struct GNUNET_PeerIdentity))
3227   {
3228     GNUNET_break_op (0);
3229     return GNUNET_OK;
3230   }
3231   size /= sizeof (struct GNUNET_PeerIdentity);
3232   if (size < 2)
3233   {
3234     GNUNET_break_op (0);
3235     return GNUNET_OK;
3236   }
3237   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
3238   msg = (struct GNUNET_MESH_ManipulatePath *) message;
3239
3240   tid = ntohl (msg->tid);
3241   pi = (struct GNUNET_PeerIdentity *) &msg[1];
3242   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3243               "    path is for tunnel %s [%X].\n", GNUNET_i2s (pi), tid);
3244   t = tunnel_get (pi, tid);
3245   if (NULL == t) // FIXME only for INCOMING tunnels?
3246   {
3247     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating tunnel\n");
3248     t = tunnel_new (GNUNET_PEER_intern (pi), tid, NULL, 0);
3249
3250     while (NULL != tunnel_get_incoming (next_local_tid))
3251       next_local_tid = (next_local_tid + 1) | GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
3252     t->local_tid_dest = next_local_tid++;
3253     next_local_tid = next_local_tid | GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
3254
3255     tunnel_reset_timeout (t);
3256     GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
3257     if (GNUNET_OK !=
3258         GNUNET_CONTAINER_multihashmap_put (incoming_tunnels, &hash, t,
3259                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
3260     {
3261       tunnel_destroy (t);
3262       GNUNET_break (0);
3263       return GNUNET_OK;
3264     }
3265   }
3266   dest_peer_info =
3267       GNUNET_CONTAINER_multihashmap_get (peers, &pi[size - 1].hashPubKey);
3268   if (NULL == dest_peer_info)
3269   {
3270     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3271                 "  Creating PeerInfo for destination.\n");
3272     dest_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
3273     dest_peer_info->id = GNUNET_PEER_intern (&pi[size - 1]);
3274     GNUNET_CONTAINER_multihashmap_put (peers, &pi[size - 1].hashPubKey,
3275                                        dest_peer_info,
3276                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3277   }
3278   orig_peer_info = GNUNET_CONTAINER_multihashmap_get (peers, &pi->hashPubKey);
3279   if (NULL == orig_peer_info)
3280   {
3281     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3282                 "  Creating PeerInfo for origin.\n");
3283     orig_peer_info = GNUNET_malloc (sizeof (struct MeshPeerInfo));
3284     orig_peer_info->id = GNUNET_PEER_intern (pi);
3285     GNUNET_CONTAINER_multihashmap_put (peers, &pi->hashPubKey, orig_peer_info,
3286                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3287   }
3288   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
3289   path = path_new (size);
3290   own_pos = 0;
3291   for (i = 0; i < size; i++)
3292   {
3293     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ... adding %s\n",
3294                 GNUNET_i2s (&pi[i]));
3295     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
3296     if (path->peers[i] == myid)
3297       own_pos = i;
3298   }
3299   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
3300   if (own_pos == 0)
3301   {
3302     /* cannot be self, must be 'not found' */
3303     /* create path: self not found in path through self */
3304     GNUNET_break_op (0);
3305     path_destroy (path);
3306     /* FIXME error. destroy tunnel? leave for timeout? */
3307     return 0;
3308   }
3309   path_add_to_peers (path, GNUNET_NO);
3310   tunnel_add_path (t, path, own_pos);
3311   if (own_pos == size - 1)
3312   {
3313     /* It is for us! Send ack. */
3314     struct MeshTransmissionDescriptor *info;
3315
3316     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
3317     peer_info_add_path_to_origin (orig_peer_info, path, GNUNET_NO);
3318     if (NULL == t->peers)
3319     {
3320       /* New tunnel! Notify clients on data. */
3321       t->peers = GNUNET_CONTAINER_multihashmap_create (4);
3322     }
3323     GNUNET_break (GNUNET_OK ==
3324                   GNUNET_CONTAINER_multihashmap_put (t->peers,
3325                                                      &my_full_id.hashPubKey,
3326                                                      peer_info_get
3327                                                      (&my_full_id),
3328                                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE));
3329     info = GNUNET_malloc (sizeof (struct MeshTransmissionDescriptor));
3330     info->origin = &t->id;
3331     info->peer = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
3332     GNUNET_assert (NULL != info->peer);
3333     queue_add(info,
3334               GNUNET_MESSAGE_TYPE_MESH_PATH_ACK,
3335               sizeof (struct GNUNET_MESH_PathACK),
3336               info->peer,
3337               t);
3338   }
3339   else
3340   {
3341     struct MeshPeerPath *path2;
3342
3343     /* It's for somebody else! Retransmit. */
3344     path2 = path_duplicate (path);
3345     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Retransmitting.\n");
3346     peer_info_add_path (dest_peer_info, path2, GNUNET_NO);
3347     path2 = path_duplicate (path);
3348     peer_info_add_path_to_origin (orig_peer_info, path2, GNUNET_NO);
3349     send_create_path (dest_peer_info, path, t);
3350   }
3351   return GNUNET_OK;
3352 }
3353
3354
3355 /**
3356  * Core handler for path destruction
3357  *
3358  * @param cls closure
3359  * @param message message
3360  * @param peer peer identity this notification is about
3361  * @param atsi performance data
3362  * @param atsi_count number of records in 'atsi'
3363  *
3364  * @return GNUNET_OK to keep the connection open,
3365  *         GNUNET_SYSERR to close it (signal serious error)
3366  */
3367 static int
3368 handle_mesh_path_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
3369                           const struct GNUNET_MessageHeader *message,
3370                           const struct GNUNET_ATS_Information *atsi,
3371                           unsigned int atsi_count)
3372 {
3373   struct GNUNET_MESH_ManipulatePath *msg;
3374   struct GNUNET_PeerIdentity *pi;
3375   struct MeshPeerPath *path;
3376   struct MeshTunnel *t;
3377   unsigned int own_pos;
3378   unsigned int i;
3379   size_t size;
3380
3381   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3382               "Received a PATH DESTROY msg from %s\n", GNUNET_i2s (peer));
3383   size = ntohs (message->size);
3384   if (size < sizeof (struct GNUNET_MESH_ManipulatePath))
3385   {
3386     GNUNET_break_op (0);
3387     return GNUNET_OK;
3388   }
3389
3390   size -= sizeof (struct GNUNET_MESH_ManipulatePath);
3391   if (size % sizeof (struct GNUNET_PeerIdentity))
3392   {
3393     GNUNET_break_op (0);
3394     return GNUNET_OK;
3395   }
3396   size /= sizeof (struct GNUNET_PeerIdentity);
3397   if (size < 2)
3398   {
3399     GNUNET_break_op (0);
3400     return GNUNET_OK;
3401   }
3402   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
3403
3404   msg = (struct GNUNET_MESH_ManipulatePath *) message;
3405   pi = (struct GNUNET_PeerIdentity *) &msg[1];
3406   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3407               "    path is for tunnel %s [%X].\n", GNUNET_i2s (pi),
3408               msg->tid);
3409   t = tunnel_get (pi, ntohl (msg->tid));
3410   if (NULL == t)
3411   {
3412     /* TODO notify back: we don't know this tunnel */
3413     GNUNET_break_op (0);
3414     return GNUNET_OK;
3415   }
3416   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
3417   path = path_new (size);
3418   own_pos = 0;
3419   for (i = 0; i < size; i++)
3420   {
3421     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ... adding %s\n",
3422                 GNUNET_i2s (&pi[i]));
3423     path->peers[i] = GNUNET_PEER_intern (&pi[i]);
3424     if (path->peers[i] == myid)
3425       own_pos = i;
3426   }
3427   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
3428   if (own_pos < path->length - 1)
3429     send_message (message, &pi[own_pos + 1], t);
3430   else
3431     send_client_tunnel_disconnect(t, NULL);
3432
3433   tunnel_delete_peer (t, path->peers[path->length - 1]);
3434   path_destroy (path);
3435   return GNUNET_OK;
3436 }
3437
3438
3439 /**
3440  * Core handler for notifications of broken paths
3441  *
3442  * @param cls closure
3443  * @param message message
3444  * @param peer peer identity this notification is about
3445  * @param atsi performance data
3446  * @param atsi_count number of records in 'atsi'
3447  *
3448  * @return GNUNET_OK to keep the connection open,
3449  *         GNUNET_SYSERR to close it (signal serious error)
3450  */
3451 static int
3452 handle_mesh_path_broken (void *cls, const struct GNUNET_PeerIdentity *peer,
3453                          const struct GNUNET_MessageHeader *message,
3454                          const struct GNUNET_ATS_Information *atsi,
3455                          unsigned int atsi_count)
3456 {
3457   struct GNUNET_MESH_PathBroken *msg;
3458   struct MeshTunnel *t;
3459
3460   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3461               "Received a PATH BROKEN msg from %s\n", GNUNET_i2s (peer));
3462   msg = (struct GNUNET_MESH_PathBroken *) message;
3463   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
3464               GNUNET_i2s (&msg->peer1));
3465   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
3466               GNUNET_i2s (&msg->peer2));
3467   t = tunnel_get (&msg->oid, ntohl (msg->tid));
3468   if (NULL == t)
3469   {
3470     GNUNET_break_op (0);
3471     return GNUNET_OK;
3472   }
3473   tunnel_notify_connection_broken (t, GNUNET_PEER_search (&msg->peer1),
3474                                    GNUNET_PEER_search (&msg->peer2));
3475   return GNUNET_OK;
3476
3477 }
3478
3479
3480 /**
3481  * Core handler for tunnel destruction
3482  *
3483  * @param cls closure
3484  * @param message message
3485  * @param peer peer identity this notification is about
3486  * @param atsi performance data
3487  * @param atsi_count number of records in 'atsi'
3488  *
3489  * @return GNUNET_OK to keep the connection open,
3490  *         GNUNET_SYSERR to close it (signal serious error)
3491  */
3492 static int
3493 handle_mesh_tunnel_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
3494                             const struct GNUNET_MessageHeader *message,
3495                             const struct GNUNET_ATS_Information *atsi,
3496                             unsigned int atsi_count)
3497 {
3498   struct GNUNET_MESH_TunnelDestroy *msg;
3499   struct MeshTunnel *t;
3500
3501   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3502               "Got a TUNNEL DESTROY packet from %s\n", GNUNET_i2s (peer));
3503   msg = (struct GNUNET_MESH_TunnelDestroy *) message;
3504   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for tunnel %s [%u]\n",
3505               GNUNET_i2s (&msg->oid), ntohl (msg->tid));
3506   t = tunnel_get (&msg->oid, ntohl (msg->tid));
3507   if (NULL == t)
3508   {
3509     /* Probably already got the message from another path,
3510      * destroyed the tunnel and retransmitted to children.
3511      * Safe to ignore.
3512      */
3513     return GNUNET_OK;
3514   }
3515   if (t->id.oid == myid)
3516   {
3517     GNUNET_break_op (0);
3518     return GNUNET_OK;
3519   }
3520   if (t->local_tid_dest >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
3521   {
3522     /* Tunnel was incoming, notify clients */
3523     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "INCOMING TUNNEL %X %X\n",
3524                 t->local_tid, t->local_tid_dest);
3525     send_clients_tunnel_destroy (t);
3526   }
3527   tunnel_send_destroy (t);
3528   tunnel_destroy (t);
3529   return GNUNET_OK;
3530 }
3531
3532
3533 /**
3534  * Core handler for mesh network traffic going from the origin to a peer
3535  *
3536  * @param cls closure
3537  * @param peer peer identity this notification is about
3538  * @param message message
3539  * @param atsi performance data
3540  * @param atsi_count number of records in 'atsi'
3541  * @return GNUNET_OK to keep the connection open,
3542  *         GNUNET_SYSERR to close it (signal serious error)
3543  */
3544 static int
3545 handle_mesh_data_unicast (void *cls, const struct GNUNET_PeerIdentity *peer,
3546                           const struct GNUNET_MessageHeader *message,
3547                           const struct GNUNET_ATS_Information *atsi,
3548                           unsigned int atsi_count)
3549 {
3550   struct GNUNET_MESH_Unicast *msg;
3551   struct MeshTunnel *t;
3552   GNUNET_PEER_Id pid;
3553   size_t size;
3554
3555   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a unicast packet from %s\n",
3556               GNUNET_i2s (peer));
3557   size = ntohs (message->size);
3558   if (size <
3559       sizeof (struct GNUNET_MESH_Unicast) +
3560       sizeof (struct GNUNET_MessageHeader))
3561   {
3562     GNUNET_break (0);
3563     return GNUNET_OK;
3564   }
3565   msg = (struct GNUNET_MESH_Unicast *) message;
3566   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " of type %u\n",
3567               ntohs (msg[1].header.type));
3568   t = tunnel_get (&msg->oid, ntohl (msg->tid));
3569   if (NULL == t)
3570   {
3571     /* TODO notify back: we don't know this tunnel */
3572     GNUNET_break_op (0);
3573     return GNUNET_OK;
3574   }
3575   tunnel_reset_timeout (t);
3576   pid = GNUNET_PEER_search (&msg->destination);
3577   if (pid == myid)
3578   {
3579     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3580                 "  it's for us! sending to clients...\n");
3581     send_subscribed_clients (message, (struct GNUNET_MessageHeader *) &msg[1]);
3582     return GNUNET_OK;
3583   }
3584   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3585               "  not for us, retransmitting...\n");
3586   send_message (message, tree_get_first_hop (t->tree, pid), t);
3587   return GNUNET_OK;
3588 }
3589
3590
3591 /**
3592  * Core handler for mesh network traffic going from the origin to all peers
3593  *
3594  * @param cls closure
3595  * @param message message
3596  * @param peer peer identity this notification is about
3597  * @param atsi performance data
3598  * @param atsi_count number of records in 'atsi'
3599  * @return GNUNET_OK to keep the connection open,
3600  *         GNUNET_SYSERR to close it (signal serious error)
3601  *
3602  * TODO: Check who we got this from, to validate route.
3603  */
3604 static int
3605 handle_mesh_data_multicast (void *cls, const struct GNUNET_PeerIdentity *peer,
3606                             const struct GNUNET_MessageHeader *message,
3607                             const struct GNUNET_ATS_Information *atsi,
3608                             unsigned int atsi_count)
3609 {
3610   struct GNUNET_MESH_Multicast *msg;
3611   struct MeshTunnel *t;
3612   size_t size;
3613
3614   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a multicast packet from %s\n",
3615               GNUNET_i2s (peer));
3616   size = ntohs (message->size);
3617   if (sizeof (struct GNUNET_MESH_Multicast) +
3618       sizeof (struct GNUNET_MessageHeader) > size)
3619   {
3620     GNUNET_break_op (0);
3621     return GNUNET_OK;
3622   }
3623   msg = (struct GNUNET_MESH_Multicast *) message;
3624   t = tunnel_get (&msg->oid, ntohl (msg->tid));
3625
3626   if (NULL == t)
3627   {
3628     /* TODO notify that we dont know that tunnel */
3629     GNUNET_break_op (0);
3630     return GNUNET_OK;
3631   }
3632   if (t->mid == ntohl (msg->mid))
3633   {
3634     /* FIXME: already seen this packet, log dropping */
3635     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3636                 " Already seen mid %u, DROPPING!\n", t->mid);
3637     return GNUNET_OK;
3638   }
3639   else
3640   {
3641     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3642                 " mid %u not seen yet, forwarding\n", ntohl (msg->mid));
3643   }
3644   t->mid = ntohl (msg->mid);
3645   tunnel_reset_timeout (t);
3646
3647   /* Transmit to locally interested clients */
3648   if (NULL != t->peers &&
3649       GNUNET_CONTAINER_multihashmap_contains (t->peers, &my_full_id.hashPubKey))
3650   {
3651     send_subscribed_clients (message, &msg[1].header);
3652   }
3653   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ttl: %u\n", ntohl (msg->ttl));
3654   if (ntohl (msg->ttl) == 0)
3655   {
3656     /* FIXME: ttl is 0, log dropping */
3657     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
3658     return GNUNET_OK;
3659   }
3660   tunnel_send_multicast (t, message, GNUNET_NO);
3661   return GNUNET_OK;
3662 }
3663
3664
3665 /**
3666  * Core handler for mesh network traffic toward the owner of a tunnel
3667  *
3668  * @param cls closure
3669  * @param message message
3670  * @param peer peer identity this notification is about
3671  * @param atsi performance data
3672  * @param atsi_count number of records in 'atsi'
3673  *
3674  * @return GNUNET_OK to keep the connection open,
3675  *         GNUNET_SYSERR to close it (signal serious error)
3676  */
3677 static int
3678 handle_mesh_data_to_orig (void *cls, const struct GNUNET_PeerIdentity *peer,
3679                           const struct GNUNET_MessageHeader *message,
3680                           const struct GNUNET_ATS_Information *atsi,
3681                           unsigned int atsi_count)
3682 {
3683   struct GNUNET_MESH_ToOrigin *msg;
3684   struct GNUNET_PeerIdentity id;
3685   struct MeshPeerInfo *peer_info;
3686   struct MeshTunnel *t;
3687   size_t size;
3688
3689   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got a ToOrigin packet from %s\n",
3690               GNUNET_i2s (peer));
3691   size = ntohs (message->size);
3692   if (size < sizeof (struct GNUNET_MESH_ToOrigin) +     /* Payload must be */
3693       sizeof (struct GNUNET_MessageHeader))     /* at least a header */
3694   {
3695     GNUNET_break_op (0);
3696     return GNUNET_OK;
3697   }
3698   msg = (struct GNUNET_MESH_ToOrigin *) message;
3699   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " of type %u\n",
3700               ntohs (msg[1].header.type));
3701   t = tunnel_get (&msg->oid, ntohl (msg->tid));
3702
3703   if (NULL == t)
3704   {
3705     /* TODO notify that we dont know this tunnel (whom)? */
3706     GNUNET_break_op (0);
3707     return GNUNET_OK;
3708   }
3709
3710   if (t->id.oid == myid)
3711   {
3712     char cbuf[size];
3713     struct GNUNET_MESH_ToOrigin *copy;
3714
3715     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3716                 "  it's for us! sending to clients...\n");
3717     if (NULL == t->owner)
3718     {
3719       /* got data packet for ownerless tunnel */
3720       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  no clients!\n");
3721       GNUNET_break_op (0);
3722       return GNUNET_OK;
3723     }
3724     /* TODO signature verification */
3725     memcpy (cbuf, message, size);
3726     copy = (struct GNUNET_MESH_ToOrigin *) cbuf;
3727     copy->tid = htonl (t->local_tid);
3728     GNUNET_SERVER_notification_context_unicast (nc, t->owner->handle,
3729                                                 &copy->header, GNUNET_YES);
3730     return GNUNET_OK;
3731   }
3732   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3733               "  not for us, retransmitting...\n");
3734
3735   peer_info = peer_info_get (&msg->oid);
3736   if (NULL == peer_info)
3737   {
3738     /* unknown origin of tunnel */
3739     GNUNET_break (0);
3740     return GNUNET_OK;
3741   }
3742   GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &id);
3743   send_message (message, &id, t);
3744
3745   return GNUNET_OK;
3746 }
3747
3748
3749 /**
3750  * Core handler for path ACKs
3751  *
3752  * @param cls closure
3753  * @param message message
3754  * @param peer peer identity this notification is about
3755  * @param atsi performance data
3756  * @param atsi_count number of records in 'atsi'
3757  *
3758  * @return GNUNET_OK to keep the connection open,
3759  *         GNUNET_SYSERR to close it (signal serious error)
3760  */
3761 static int
3762 handle_mesh_path_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
3763                       const struct GNUNET_MessageHeader *message,
3764                       const struct GNUNET_ATS_Information *atsi,
3765                       unsigned int atsi_count)
3766 {
3767   struct GNUNET_MESH_PathACK *msg;
3768   struct GNUNET_PeerIdentity id;
3769   struct MeshPeerInfo *peer_info;
3770   struct MeshPeerPath *p;
3771   struct MeshTunnel *t;
3772
3773   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a path ACK msg [%s]\n",
3774               GNUNET_i2s (&my_full_id));
3775   msg = (struct GNUNET_MESH_PathACK *) message;
3776   t = tunnel_get (&msg->oid, msg->tid);
3777   if (NULL == t)
3778   {
3779     /* TODO notify that we don't know the tunnel */
3780     return GNUNET_OK;
3781   }
3782
3783   peer_info = peer_info_get (&msg->peer_id);
3784
3785   /* Add paths to peers? */
3786   p = tree_get_path_to_peer (t->tree, peer_info->id);
3787   if (NULL != p)
3788   {
3789     path_add_to_peers (p, GNUNET_YES);
3790     path_destroy (p);
3791   }
3792   else
3793   {
3794     GNUNET_break (0);
3795   }
3796
3797   /* Message for us? */
3798   if (0 == memcmp (&msg->oid, &my_full_id, sizeof (struct GNUNET_PeerIdentity)))
3799   {
3800     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
3801     if (NULL == t->owner)
3802     {
3803       GNUNET_break_op (0);
3804       return GNUNET_OK;
3805     }
3806     if (NULL != t->dht_get_type)
3807     {
3808       GNUNET_DHT_get_stop (t->dht_get_type);
3809       t->dht_get_type = NULL;
3810     }
3811     if (tree_get_status (t->tree, peer_info->id) != MESH_PEER_READY)
3812     {
3813       tree_set_status (t->tree, peer_info->id, MESH_PEER_READY);
3814       send_client_peer_connected (t, peer_info->id);
3815     }
3816     return GNUNET_OK;
3817   }
3818
3819   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3820               "  not for us, retransmitting...\n");
3821   GNUNET_PEER_resolve (tree_get_predecessor (t->tree), &id);
3822   peer_info = peer_info_get (&msg->oid);
3823   if (NULL == peer_info)
3824   {
3825     /* If we know the tunnel, we should DEFINITELY know the peer */
3826     GNUNET_break (0);
3827     return GNUNET_OK;
3828   }
3829   send_message (message, &id, t);
3830   return GNUNET_OK;
3831 }
3832
3833
3834 /**
3835  * Functions to handle messages from core
3836  */
3837 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
3838   {&handle_mesh_path_create, GNUNET_MESSAGE_TYPE_MESH_PATH_CREATE, 0},
3839   {&handle_mesh_path_destroy, GNUNET_MESSAGE_TYPE_MESH_PATH_DESTROY, 0},
3840   {&handle_mesh_path_broken, GNUNET_MESSAGE_TYPE_MESH_PATH_BROKEN,
3841    sizeof (struct GNUNET_MESH_PathBroken)},
3842   {&handle_mesh_tunnel_destroy, GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY, 0},
3843   {&handle_mesh_data_unicast, GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
3844   {&handle_mesh_data_multicast, GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
3845   {&handle_mesh_data_to_orig, GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
3846   {&handle_mesh_path_ack, GNUNET_MESSAGE_TYPE_MESH_PATH_ACK,
3847    sizeof (struct GNUNET_MESH_PathACK)},
3848   {NULL, 0, 0}
3849 };
3850
3851
3852
3853 /******************************************************************************/
3854 /****************       MESH LOCAL HANDLER HELPERS      ***********************/
3855 /******************************************************************************/
3856
3857 /**
3858  * deregister_app: iterator for removing each application registered by a client
3859  *
3860  * @param cls closure
3861  * @param key the hash of the application id (used to access the hashmap)
3862  * @param value the value stored at the key (client)
3863  *
3864  * @return GNUNET_OK on success
3865  */
3866 static int
3867 deregister_app (void *cls, const struct GNUNET_HashCode * key, void *value)
3868 {
3869   struct GNUNET_CONTAINER_MultiHashMap *h = cls;
3870   GNUNET_break (GNUNET_YES ==
3871                 GNUNET_CONTAINER_multihashmap_remove (h, key, value));
3872   return GNUNET_OK;
3873 }
3874
3875 #if LATER
3876 /**
3877  * notify_client_connection_failure: notify a client that the connection to the
3878  * requested remote peer is not possible (for instance, no route found)
3879  * Function called when the socket is ready to queue more data. "buf" will be
3880  * NULL and "size" zero if the socket was closed for writing in the meantime.
3881  *
3882  * @param cls closure
3883  * @param size number of bytes available in buf
3884  * @param buf where the callee should write the message
3885  * @return number of bytes written to buf
3886  */
3887 static size_t
3888 notify_client_connection_failure (void *cls, size_t size, void *buf)
3889 {
3890   int size_needed;
3891   struct MeshPeerInfo *peer_info;
3892   struct GNUNET_MESH_PeerControl *msg;
3893   struct GNUNET_PeerIdentity id;
3894
3895   if (0 == size && NULL == buf)
3896   {
3897     // TODO retry? cancel?
3898     return 0;
3899   }
3900
3901   size_needed = sizeof (struct GNUNET_MESH_PeerControl);
3902   peer_info = (struct MeshPeerInfo *) cls;
3903   msg = (struct GNUNET_MESH_PeerControl *) buf;
3904   msg->header.size = htons (sizeof (struct GNUNET_MESH_PeerControl));
3905   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DISCONNECTED);
3906 //     msg->tunnel_id = htonl(peer_info->t->tid);
3907   GNUNET_PEER_resolve (peer_info->id, &id);
3908   memcpy (&msg->peer, &id, sizeof (struct GNUNET_PeerIdentity));
3909
3910   return size_needed;
3911 }
3912 #endif
3913
3914
3915 /**
3916  * Send keepalive packets for a peer
3917  *
3918  * @param cls Closure (tunnel for which to send the keepalive).
3919  * @param tc Notification context.
3920  *
3921  * TODO: implement explicit multicast keepalive?
3922  */
3923 static void
3924 path_refresh (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3925 {
3926   struct MeshTunnel *t = cls;
3927   struct GNUNET_MessageHeader *payload;
3928   struct GNUNET_MESH_Multicast *msg;
3929   size_t size =
3930       sizeof (struct GNUNET_MESH_Multicast) +
3931       sizeof (struct GNUNET_MessageHeader);
3932   char cbuf[size];
3933
3934   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3935   {
3936     return;
3937   }
3938   t->path_refresh_task = GNUNET_SCHEDULER_NO_TASK;
3939
3940   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3941               "sending keepalive for tunnel %d\n", t->id.tid);
3942
3943   msg = (struct GNUNET_MESH_Multicast *) cbuf;
3944   msg->header.size = htons (size);
3945   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_MULTICAST);
3946   msg->oid = my_full_id;
3947   msg->tid = htonl (t->id.tid);
3948   msg->ttl = htonl (DEFAULT_TTL);
3949   msg->mid = htonl (t->mid + 1);
3950   t->mid++;
3951   payload = (struct GNUNET_MessageHeader *) &msg[1];
3952   payload->size = htons (sizeof (struct GNUNET_MessageHeader));
3953   payload->type = htons (GNUNET_MESSAGE_TYPE_MESH_PATH_KEEPALIVE);
3954   tunnel_send_multicast (t, &msg->header, GNUNET_YES);
3955
3956   t->path_refresh_task =
3957       GNUNET_SCHEDULER_add_delayed (REFRESH_PATH_TIME, &path_refresh, t);
3958   return;
3959 }
3960
3961
3962 /**
3963  * Function to process paths received for a new peer addition. The recorded
3964  * paths form the initial tunnel, which can be optimized later.
3965  * Called on each result obtained for the DHT search.
3966  *
3967  * @param cls closure
3968  * @param exp when will this value expire
3969  * @param key key of the result
3970  * @param get_path path of the get request
3971  * @param get_path_length lenght of get_path
3972  * @param put_path path of the put request
3973  * @param put_path_length length of the put_path
3974  * @param type type of the result
3975  * @param size number of bytes in data
3976  * @param data pointer to the result data
3977  *
3978  * TODO: re-issue the request after certain time? cancel after X results?
3979  */
3980 static void
3981 dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp,
3982                     const struct GNUNET_HashCode * key,
3983                     const struct GNUNET_PeerIdentity *get_path,
3984                     unsigned int get_path_length,
3985                     const struct GNUNET_PeerIdentity *put_path,
3986                     unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
3987                     size_t size, const void *data)
3988 {
3989   struct MeshPathInfo *path_info = cls;
3990   struct MeshPeerPath *p;
3991   struct GNUNET_PeerIdentity pi;
3992   int i;
3993
3994   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got results from DHT!\n");
3995   GNUNET_PEER_resolve (path_info->peer->id, &pi);
3996   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for %s\n", GNUNET_i2s (&pi));
3997
3998   p = path_build_from_dht (get_path, get_path_length, put_path,
3999                            put_path_length);
4000   path_add_to_peers (p, GNUNET_NO);
4001   path_destroy(p);
4002   for (i = 0; i < path_info->peer->ntunnels; i++)
4003   {
4004     tunnel_add_peer (path_info->peer->tunnels[i], path_info->peer);
4005     peer_info_connect (path_info->peer, path_info->t);
4006   }
4007
4008   return;
4009 }
4010
4011
4012 /**
4013  * Function to process paths received for a new peer addition. The recorded
4014  * paths form the initial tunnel, which can be optimized later.
4015  * Called on each result obtained for the DHT search.
4016  *
4017  * @param cls closure
4018  * @param exp when will this value expire
4019  * @param key key of the result
4020  * @param get_path path of the get request
4021  * @param get_path_length lenght of get_path
4022  * @param put_path path of the put request
4023  * @param put_path_length length of the put_path
4024  * @param type type of the result
4025  * @param size number of bytes in data
4026  * @param data pointer to the result data
4027  */
4028 static void
4029 dht_get_type_handler (void *cls, struct GNUNET_TIME_Absolute exp,
4030                       const struct GNUNET_HashCode * key,
4031                       const struct GNUNET_PeerIdentity *get_path,
4032                       unsigned int get_path_length,
4033                       const struct GNUNET_PeerIdentity *put_path,
4034                       unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
4035                       size_t size, const void *data)
4036 {
4037   const struct PBlock *pb = data;
4038   const struct GNUNET_PeerIdentity *pi = &pb->id;
4039   struct MeshTunnel *t = cls;
4040   struct MeshPeerInfo *peer_info;
4041   struct MeshPeerPath *p;
4042
4043   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got type DHT result!\n");
4044   if (size != sizeof (struct PBlock))
4045   {
4046     GNUNET_break_op (0);
4047     return;
4048   }
4049   if (ntohl(pb->type) != t->type)
4050   {
4051     GNUNET_break_op (0);
4052     return;
4053   }
4054   GNUNET_assert (NULL != t->owner);
4055   peer_info = peer_info_get (pi);
4056   (void) GNUNET_CONTAINER_multihashmap_put (t->peers, &pi->hashPubKey,
4057                                             peer_info,
4058                                             GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
4059
4060   p = path_build_from_dht (get_path, get_path_length, put_path,
4061                            put_path_length);
4062   path_add_to_peers (p, GNUNET_NO);
4063   path_destroy(p);
4064   tunnel_add_peer (t, peer_info);
4065   peer_info_connect (peer_info, t);
4066 }
4067
4068 /**
4069  * Function to process DHT string to regex matching..
4070  * Called on each result obtained for the DHT search.
4071  *
4072  * @param cls closure (search context)
4073  * @param exp when will this value expire
4074  * @param key key of the result
4075  * @param get_path path of the get request (not used)
4076  * @param get_path_length lenght of get_path (not used)
4077  * @param put_path path of the put request (not used)
4078  * @param put_path_length length of the put_path (not used)
4079  * @param type type of the result
4080  * @param size number of bytes in data
4081  * @param data pointer to the result data
4082  *
4083  * TODO: re-issue the request after certain time? cancel after X results?
4084  */
4085 static void
4086 dht_get_string_handler (void *cls, struct GNUNET_TIME_Absolute exp,
4087                         const struct GNUNET_HashCode * key,
4088                         const struct GNUNET_PeerIdentity *get_path,
4089                         unsigned int get_path_length,
4090                         const struct GNUNET_PeerIdentity *put_path,
4091                         unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
4092                         size_t size, const void *data);
4093
4094 /**
4095  * Iterator over edges in a block.
4096  *
4097  * @param cls Closure.
4098  * @param token Token that follows to next state.
4099  * @param len Lenght of token.
4100  * @param key Hash of next state.
4101  *
4102  * @return GNUNET_YES if should keep iterating, GNUNET_NO otherwise.
4103  */
4104 static int
4105 regex_edge_iterator (void *cls,
4106                      const char *token,
4107                      size_t len,
4108                      const struct GNUNET_HashCode *key)
4109 {
4110   struct MeshRegexSearchContext *ctx = cls;
4111   struct GNUNET_DHT_GetHandle *get_h;
4112   char *current;
4113   size_t current_len;
4114
4115   current = &ctx->description[ctx->position];
4116   current_len = strlen (ctx->description) - ctx->position;
4117   if (len > current_len)
4118     return GNUNET_YES; // Token too long, wont match
4119   if (0 != strncmp (current, token, len))
4120     return GNUNET_YES; // Token doesn't match
4121
4122   if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(ctx->dht_get_handles,
4123                                                            key))
4124   {
4125     return GNUNET_YES; // We are already looking for it
4126   }
4127   /* Start search in DHT */
4128   get_h = 
4129       GNUNET_DHT_get_start (dht_handle,    /* handle */
4130                             GNUNET_BLOCK_TYPE_MESH_REGEX, /* type */
4131                             key,     /* key to search */
4132                             DHT_REPLICATION_LEVEL, /* replication level */
4133                             GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
4134                             NULL,       /* xquery */ // FIXME BLOOMFILTER
4135                             0,     /* xquery bits */ // FIXME BLOOMFILTER SIZE
4136                             &dht_get_string_handler, ctx);
4137   if (GNUNET_OK !=
4138       GNUNET_CONTAINER_multihashmap_put(ctx->dht_get_handles, key, get_h,
4139                                         GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
4140   {
4141     GNUNET_break (0);
4142     return GNUNET_YES;
4143   }
4144   return GNUNET_YES;
4145 }
4146
4147
4148 /**
4149  * Function to process DHT string to regex matching..
4150  * Called on each result obtained for the DHT search.
4151  *
4152  * @param cls closure (search context)
4153  * @param exp when will this value expire
4154  * @param key key of the result
4155  * @param get_path path of the get request (not used)
4156  * @param get_path_length lenght of get_path (not used)
4157  * @param put_path path of the put request (not used)
4158  * @param put_path_length length of the put_path (not used)
4159  * @param type type of the result
4160  * @param size number of bytes in data
4161  * @param data pointer to the result data
4162  */
4163 static void
4164 dht_get_string_accept_handler (void *cls, struct GNUNET_TIME_Absolute exp,
4165                                const struct GNUNET_HashCode * key,
4166                                const struct GNUNET_PeerIdentity *get_path,
4167                                unsigned int get_path_length,
4168                                const struct GNUNET_PeerIdentity *put_path,
4169                                unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
4170                                size_t size, const void *data)
4171 {
4172   const struct MeshRegexAccept *block = data;
4173   struct MeshRegexSearchContext *ctx = cls;
4174   struct MeshPeerPath *p;
4175   struct MeshPeerInfo *peer_info;
4176
4177   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got results from DHT!\n");
4178
4179   peer_info = peer_info_get(&block->id);
4180   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for %s\n", ctx->description);
4181
4182   p = path_build_from_dht (get_path, get_path_length, put_path,
4183                            put_path_length);
4184   path_add_to_peers (p, GNUNET_NO);
4185   path_destroy(p);
4186
4187   tunnel_add_peer (ctx->t, peer_info);
4188   peer_info_connect (peer_info, ctx->t);
4189
4190   // FIXME cancel only AFTER successful connection (received ACK)
4191   regex_cancel_search (ctx);
4192
4193   return;
4194 }
4195
4196
4197 /**
4198  * Function to process DHT string to regex matching..
4199  * Called on each result obtained for the DHT search.
4200  *
4201  * @param cls closure (search context)
4202  * @param exp when will this value expire
4203  * @param key key of the result
4204  * @param get_path path of the get request (not used)
4205  * @param get_path_length lenght of get_path (not used)
4206  * @param put_path path of the put request (not used)
4207  * @param put_path_length length of the put_path (not used)
4208  * @param type type of the result
4209  * @param size number of bytes in data
4210  * @param data pointer to the result data
4211  *
4212  * TODO: re-issue the request after certain time? cancel after X results?
4213  */
4214 static void
4215 dht_get_string_handler (void *cls, struct GNUNET_TIME_Absolute exp,
4216                         const struct GNUNET_HashCode * key,
4217                         const struct GNUNET_PeerIdentity *get_path,
4218                         unsigned int get_path_length,
4219                         const struct GNUNET_PeerIdentity *put_path,
4220                         unsigned int put_path_length, enum GNUNET_BLOCK_Type type,
4221                         size_t size, const void *data)
4222 {
4223   const struct MeshRegexBlock *block = data;
4224   struct MeshRegexSearchContext *ctx = cls;
4225   char *proof;
4226   size_t len;
4227
4228   // FIXME: does proof have to be NULL terminated?
4229   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4230               "*******************************\n");
4231   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4232               "DHT GET STRING RETURNED RESULTS\n");
4233   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4234               "  key: %s\n", GNUNET_h2s (key));
4235   proof = (char *) &block[1];
4236   if (GNUNET_OK != GNUNET_REGEX_check_proof (proof, key))
4237   {
4238     GNUNET_break_op (0);
4239     return;
4240   }
4241   len = strlen (ctx->description);
4242   if (len == ctx->position) // String processed
4243   {
4244     if (GNUNET_YES == ntohl (block->accepting))
4245     {
4246       struct GNUNET_DHT_GetHandle *get_h;
4247       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Found peer by service\n");
4248       get_h = GNUNET_DHT_get_start (dht_handle,    /* handle */
4249                                     GNUNET_BLOCK_TYPE_MESH_REGEX_ACCEPT, /* type */
4250                                     key,     /* key to search */
4251                                     DHT_REPLICATION_LEVEL, /* replication level */
4252                                     GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE |
4253                                     GNUNET_DHT_RO_RECORD_ROUTE,
4254                                     NULL,       /* xquery */ // FIXME BLOOMFILTER
4255                                     0,     /* xquery bits */ // FIXME BLOOMFILTER SIZE
4256                                     &dht_get_string_accept_handler, ctx);
4257       GNUNET_break (GNUNET_OK ==
4258                     GNUNET_CONTAINER_multihashmap_put(ctx->dht_get_handles, key, get_h,
4259                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
4260     }
4261     else
4262     {
4263         // FIXME this block not successful, wait for more? start timeout?
4264     }
4265     return;
4266   }
4267   GNUNET_MESH_regex_block_iterate (block, size, &regex_edge_iterator, ctx);
4268   return;
4269 }
4270
4271 /******************************************************************************/
4272 /*********************       MESH LOCAL HANDLES      **************************/
4273 /******************************************************************************/
4274
4275
4276 /**
4277  * Handler for client disconnection
4278  *
4279  * @param cls closure
4280  * @param client identification of the client; NULL
4281  *        for the last call when the server is destroyed
4282  */
4283 static void
4284 handle_local_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
4285 {
4286   struct MeshClient *c;
4287   struct MeshClient *next;
4288   unsigned int i;
4289
4290   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client disconnected\n");
4291   if (client == NULL)
4292   {
4293     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   (SERVER DOWN)\n");
4294     return;
4295   }
4296   c = clients;
4297   while (NULL != c)
4298   {
4299     if (c->handle != client)
4300     {
4301       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   ... searching\n");
4302       c = c->next;
4303       continue;
4304     }
4305     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "matching client found (%u)\n",
4306                 c->id);
4307     GNUNET_SERVER_client_drop (c->handle);
4308     c->shutting_down = GNUNET_YES;
4309     GNUNET_assert (NULL != c->own_tunnels);
4310     GNUNET_assert (NULL != c->incoming_tunnels);
4311     GNUNET_CONTAINER_multihashmap_iterate (c->own_tunnels,
4312                                            &tunnel_destroy_iterator, c);
4313     GNUNET_CONTAINER_multihashmap_iterate (c->incoming_tunnels,
4314                                            &tunnel_destroy_iterator, c);
4315     GNUNET_CONTAINER_multihashmap_iterate (c->ignore_tunnels,
4316                                            &tunnel_destroy_iterator, c);
4317     GNUNET_CONTAINER_multihashmap_destroy (c->own_tunnels);
4318     GNUNET_CONTAINER_multihashmap_destroy (c->incoming_tunnels);
4319     GNUNET_CONTAINER_multihashmap_destroy (c->ignore_tunnels);
4320
4321     /* deregister clients applications */
4322     if (NULL != c->apps)
4323     {
4324       GNUNET_CONTAINER_multihashmap_iterate (c->apps, &deregister_app, c->apps);
4325       GNUNET_CONTAINER_multihashmap_destroy (c->apps);
4326     }
4327     if (0 == GNUNET_CONTAINER_multihashmap_size (applications) &&
4328         GNUNET_SCHEDULER_NO_TASK != announce_applications_task)
4329     {
4330       GNUNET_SCHEDULER_cancel (announce_applications_task);
4331       announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
4332     }
4333     if (NULL != c->types)
4334       GNUNET_CONTAINER_multihashmap_destroy (c->types);
4335     for (i = 0; i < c->n_regex; i++)
4336     {
4337       GNUNET_free (c->regexes[i]);
4338     }
4339     if (GNUNET_SCHEDULER_NO_TASK != c->regex_announce_task)
4340       GNUNET_SCHEDULER_cancel (c->regex_announce_task);
4341     next = c->next;
4342     GNUNET_CONTAINER_DLL_remove (clients, clients_tail, c);
4343     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  CLIENT FREE at %p\n", c);
4344     GNUNET_free (c);
4345     c = next;
4346   }
4347   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   done!\n");
4348   return;
4349 }
4350
4351
4352 /**
4353  * Handler for new clients
4354  *
4355  * @param cls closure
4356  * @param client identification of the client
4357  * @param message the actual message, which includes messages the client wants
4358  */
4359 static void
4360 handle_local_new_client (void *cls, struct GNUNET_SERVER_Client *client,
4361                          const struct GNUNET_MessageHeader *message)
4362 {
4363   struct GNUNET_MESH_ClientConnect *cc_msg;
4364   struct MeshClient *c;
4365   GNUNET_MESH_ApplicationType *a;
4366   unsigned int size;
4367   uint16_t ntypes;
4368   uint16_t *t;
4369   uint16_t napps;
4370   uint16_t i;
4371
4372   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client connected\n");
4373   /* Check data sanity */
4374   size = ntohs (message->size) - sizeof (struct GNUNET_MESH_ClientConnect);
4375   cc_msg = (struct GNUNET_MESH_ClientConnect *) message;
4376   ntypes = ntohs (cc_msg->types);
4377   napps = ntohs (cc_msg->applications);
4378   if (size !=
4379       ntypes * sizeof (uint16_t) + napps * sizeof (GNUNET_MESH_ApplicationType))
4380   {
4381     GNUNET_break (0);
4382     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4383     return;
4384   }
4385
4386   /* Create new client structure */
4387   c = GNUNET_malloc (sizeof (struct MeshClient));
4388   c->id = next_client_id++;
4389   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  CLIENT NEW %u\n", c->id);
4390   c->handle = client;
4391   GNUNET_SERVER_client_keep (client);
4392   a = (GNUNET_MESH_ApplicationType *) &cc_msg[1];
4393   if (napps > 0)
4394   {
4395     GNUNET_MESH_ApplicationType at;
4396     struct GNUNET_HashCode hc;
4397
4398     c->apps = GNUNET_CONTAINER_multihashmap_create (napps);
4399     for (i = 0; i < napps; i++)
4400     {
4401       at = ntohl (a[i]);
4402       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  app type: %u\n", at);
4403       GNUNET_CRYPTO_hash (&at, sizeof (at), &hc);
4404       /* store in clients hashmap */
4405       GNUNET_CONTAINER_multihashmap_put (c->apps, &hc, (void *) (long) at,
4406                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
4407       /* store in global hashmap, for announcements */
4408       GNUNET_CONTAINER_multihashmap_put (applications, &hc, c,
4409                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
4410     }
4411     if (GNUNET_SCHEDULER_NO_TASK == announce_applications_task)
4412       announce_applications_task =
4413           GNUNET_SCHEDULER_add_now (&announce_applications, NULL);
4414
4415   }
4416   if (ntypes > 0)
4417   {
4418     uint16_t u16;
4419     struct GNUNET_HashCode hc;
4420
4421     t = (uint16_t *) & a[napps];
4422     c->types = GNUNET_CONTAINER_multihashmap_create (ntypes);
4423     for (i = 0; i < ntypes; i++)
4424     {
4425       u16 = ntohs (t[i]);
4426       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  msg type: %u\n", u16);
4427       GNUNET_CRYPTO_hash (&u16, sizeof (u16), &hc);
4428
4429       /* store in clients hashmap */
4430       GNUNET_CONTAINER_multihashmap_put (c->types, &hc, c,
4431                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
4432       /* store in global hashmap */
4433       GNUNET_CONTAINER_multihashmap_put (types, &hc, c,
4434                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
4435     }
4436   }
4437   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4438               " client has %u+%u subscriptions\n", napps, ntypes);
4439
4440   GNUNET_CONTAINER_DLL_insert (clients, clients_tail, c);
4441   c->own_tunnels = GNUNET_CONTAINER_multihashmap_create (32);
4442   c->incoming_tunnels = GNUNET_CONTAINER_multihashmap_create (32);
4443   c->ignore_tunnels = GNUNET_CONTAINER_multihashmap_create (32);
4444   GNUNET_SERVER_notification_context_add (nc, client);
4445
4446   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4447   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new client processed\n");
4448 }
4449
4450
4451 /**
4452  * Handler for clients announcing available services by a regular expression.
4453  *
4454  * @param cls closure
4455  * @param client identification of the client
4456  * @param message the actual message, which includes messages the client wants
4457  */
4458 static void
4459 handle_local_announce_regex (void *cls, struct GNUNET_SERVER_Client *client,
4460                              const struct GNUNET_MessageHeader *message)
4461 {
4462   struct MeshClient *c;
4463   char *regex;
4464   size_t len;
4465
4466   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "announce regex started\n");
4467
4468   /* Sanity check for client registration */
4469   if (NULL == (c = client_get (client)))
4470   {
4471     GNUNET_break (0);
4472     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4473     return;
4474   }
4475   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
4476
4477   len = ntohs (message->size) - sizeof(struct GNUNET_MessageHeader);
4478   regex = GNUNET_malloc (len + 1);
4479   memcpy (regex, &message[1], len);
4480   regex[len] = '\0';
4481   GNUNET_array_append (c->regexes, c->n_regex, regex);
4482   if (GNUNET_SCHEDULER_NO_TASK == c->regex_announce_task)
4483   {
4484     c->regex_announce_task = GNUNET_SCHEDULER_add_now(&announce_regex, c);
4485   }
4486   else
4487   {
4488     regex_put(regex);
4489   }
4490   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4491   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "announce regex processed\n");
4492 }
4493
4494
4495 /**
4496  * Handler for requests of new tunnels
4497  *
4498  * @param cls closure
4499  * @param client identification of the client
4500  * @param message the actual message
4501  */
4502 static void
4503 handle_local_tunnel_create (void *cls, struct GNUNET_SERVER_Client *client,
4504                             const struct GNUNET_MessageHeader *message)
4505 {
4506   struct GNUNET_MESH_TunnelMessage *t_msg;
4507   struct MeshTunnel *t;
4508   struct MeshClient *c;
4509
4510   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new tunnel requested\n");
4511
4512   /* Sanity check for client registration */
4513   if (NULL == (c = client_get (client)))
4514   {
4515     GNUNET_break (0);
4516     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4517     return;
4518   }
4519   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
4520
4521   /* Message sanity check */
4522   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
4523   {
4524     GNUNET_break (0);
4525     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4526     return;
4527   }
4528
4529   t_msg = (struct GNUNET_MESH_TunnelMessage *) message;
4530   /* Sanity check for tunnel numbering */
4531   if (0 == (ntohl (t_msg->tunnel_id) & GNUNET_MESH_LOCAL_TUNNEL_ID_CLI))
4532   {
4533     GNUNET_break (0);
4534     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4535     return;
4536   }
4537   /* Sanity check for duplicate tunnel IDs */
4538   if (NULL != tunnel_get_by_local_id (c, ntohl (t_msg->tunnel_id)))
4539   {
4540     GNUNET_break (0);
4541     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4542     return;
4543   }
4544
4545   while (NULL != tunnel_get_by_pi (myid, next_tid))
4546     next_tid = (next_tid + 1) & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
4547   t = tunnel_new (myid, next_tid++, c, ntohl (t_msg->tunnel_id));
4548   next_tid = next_tid & ~GNUNET_MESH_LOCAL_TUNNEL_ID_CLI;
4549   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CREATED TUNNEL %s [%x] (%x)\n",
4550               GNUNET_i2s (&my_full_id), t->id.tid, t->local_tid);
4551   t->peers = GNUNET_CONTAINER_multihashmap_create (32);
4552
4553   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new tunnel created\n");
4554   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4555   return;
4556 }
4557
4558
4559 /**
4560  * Handler for requests of deleting tunnels
4561  *
4562  * @param cls closure
4563  * @param client identification of the client
4564  * @param message the actual message
4565  */
4566 static void
4567 handle_local_tunnel_destroy (void *cls, struct GNUNET_SERVER_Client *client,
4568                              const struct GNUNET_MessageHeader *message)
4569 {
4570   struct GNUNET_MESH_TunnelMessage *tunnel_msg;
4571   struct MeshClient *c;
4572   struct MeshTunnel *t;
4573   MESH_TunnelNumber tid;
4574
4575   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4576               "Got a DESTROY TUNNEL from client!\n");
4577
4578   /* Sanity check for client registration */
4579   if (NULL == (c = client_get (client)))
4580   {
4581     GNUNET_break (0);
4582     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4583     return;
4584   }
4585   /* Message sanity check */
4586   if (sizeof (struct GNUNET_MESH_TunnelMessage) != ntohs (message->size))
4587   {
4588     GNUNET_break (0);
4589     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4590     return;
4591   }
4592   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  by client %u\n", c->id);
4593   tunnel_msg = (struct GNUNET_MESH_TunnelMessage *) message;
4594
4595   /* Retrieve tunnel */
4596   tid = ntohl (tunnel_msg->tunnel_id);
4597   t = tunnel_get_by_local_id(c, tid);
4598   if (NULL == t)
4599   {
4600     GNUNET_break (0);
4601     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  tunnel %X not found\n", tid);
4602     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4603     return;
4604   }
4605   if (c != t->owner || tid >= GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
4606   {
4607     client_ignore_tunnel (c, t);
4608 #if 0
4609     // TODO: when to destroy incoming tunnel?
4610     if (t->nclients == 0)
4611     {
4612       GNUNET_assert (GNUNET_YES ==
4613                      GNUNET_CONTAINER_multihashmap_remove (incoming_tunnels,
4614                                                            &hash, t));
4615       GNUNET_assert (GNUNET_YES ==
4616                      GNUNET_CONTAINER_multihashmap_remove (t->peers,
4617                                                            &my_full_id.hashPubKey,
4618                                                            t));
4619     }
4620 #endif
4621     GNUNET_SERVER_receive_done (client, GNUNET_OK);
4622     return;
4623   }
4624   send_client_tunnel_disconnect(t, c);
4625   client_delete_tunnel(c, t);
4626
4627   /* Don't try to ACK the client about the tunnel_destroy multicast packet */
4628   t->owner = NULL;
4629   tunnel_send_destroy (t);
4630   tunnel_destroy (t);
4631   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4632   return;
4633 }
4634
4635
4636 /**
4637  * Handler for connection requests to new peers
4638  *
4639  * @param cls closure
4640  * @param client identification of the client
4641  * @param message the actual message (PeerControl)
4642  */
4643 static void
4644 handle_local_connect_add (void *cls, struct GNUNET_SERVER_Client *client,
4645                           const struct GNUNET_MessageHeader *message)
4646 {
4647   struct GNUNET_MESH_PeerControl *peer_msg;
4648   struct MeshPeerInfo *peer_info;
4649   struct MeshClient *c;
4650   struct MeshTunnel *t;
4651   MESH_TunnelNumber tid;
4652
4653   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got connection request\n");
4654   /* Sanity check for client registration */
4655   if (NULL == (c = client_get (client)))
4656   {
4657     GNUNET_break (0);
4658     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4659     return;
4660   }
4661
4662   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
4663   /* Sanity check for message size */
4664   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
4665   {
4666     GNUNET_break (0);
4667     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4668     return;
4669   }
4670
4671   /* Tunnel exists? */
4672   tid = ntohl (peer_msg->tunnel_id);
4673   t = tunnel_get_by_local_id (c, tid);
4674   if (NULL == t)
4675   {
4676     GNUNET_break (0);
4677     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4678     return;
4679   }
4680
4681   /* Does client own tunnel? */
4682   if (t->owner->handle != client)
4683   {
4684     GNUNET_break (0);
4685     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4686     return;
4687   }
4688   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "     for %s\n",
4689               GNUNET_i2s (&peer_msg->peer));
4690   peer_info = peer_info_get (&peer_msg->peer);
4691
4692   tunnel_add_peer (t, peer_info);
4693   peer_info_connect (peer_info, t);
4694
4695   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4696   return;
4697 }
4698
4699
4700 /**
4701  * Handler for disconnection requests of peers in a tunnel
4702  *
4703  * @param cls closure
4704  * @param client identification of the client
4705  * @param message the actual message (PeerControl)
4706  */
4707 static void
4708 handle_local_connect_del (void *cls, struct GNUNET_SERVER_Client *client,
4709                           const struct GNUNET_MessageHeader *message)
4710 {
4711   struct GNUNET_MESH_PeerControl *peer_msg;
4712   struct MeshPeerInfo *peer_info;
4713   struct MeshClient *c;
4714   struct MeshTunnel *t;
4715   MESH_TunnelNumber tid;
4716
4717   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a PEER DEL request\n");
4718   /* Sanity check for client registration */
4719   if (NULL == (c = client_get (client)))
4720   {
4721     GNUNET_break (0);
4722     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4723     return;
4724   }
4725   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
4726   /* Sanity check for message size */
4727   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
4728   {
4729     GNUNET_break (0);
4730     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4731     return;
4732   }
4733
4734   /* Tunnel exists? */
4735   tid = ntohl (peer_msg->tunnel_id);
4736   t = tunnel_get_by_local_id (c, tid);
4737   if (NULL == t)
4738   {
4739     GNUNET_break (0);
4740     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4741     return;
4742   }
4743   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", t->id.tid);
4744
4745   /* Does client own tunnel? */
4746   if (t->owner->handle != client)
4747   {
4748     GNUNET_break (0);
4749     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4750     return;
4751   }
4752
4753   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  for peer %s\n",
4754               GNUNET_i2s (&peer_msg->peer));
4755   /* Is the peer in the tunnel? */
4756   peer_info =
4757       GNUNET_CONTAINER_multihashmap_get (t->peers, &peer_msg->peer.hashPubKey);
4758   if (NULL == peer_info)
4759   {
4760     GNUNET_break (0);
4761     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4762     return;
4763   }
4764
4765   /* Ok, delete peer from tunnel */
4766   GNUNET_CONTAINER_multihashmap_remove_all (t->peers,
4767                                             &peer_msg->peer.hashPubKey);
4768
4769   send_destroy_path (t, peer_info->id);
4770   tunnel_delete_peer (t, peer_info->id);
4771   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4772   return;
4773 }
4774
4775 /**
4776  * Handler for blacklist requests of peers in a tunnel
4777  *
4778  * @param cls closure
4779  * @param client identification of the client
4780  * @param message the actual message (PeerControl)
4781  */
4782 static void
4783 handle_local_blacklist (void *cls, struct GNUNET_SERVER_Client *client,
4784                           const struct GNUNET_MessageHeader *message)
4785 {
4786   struct GNUNET_MESH_PeerControl *peer_msg;
4787   struct MeshClient *c;
4788   struct MeshTunnel *t;
4789   MESH_TunnelNumber tid;
4790
4791   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a PEER BLACKLIST request\n");
4792   /* Sanity check for client registration */
4793   if (NULL == (c = client_get (client)))
4794   {
4795     GNUNET_break (0);
4796     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4797     return;
4798   }
4799   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
4800
4801   /* Sanity check for message size */
4802   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
4803   {
4804     GNUNET_break (0);
4805     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4806     return;
4807   }
4808
4809   /* Tunnel exists? */
4810   tid = ntohl (peer_msg->tunnel_id);
4811   t = tunnel_get_by_local_id (c, tid);
4812   if (NULL == t)
4813   {
4814     GNUNET_break (0);
4815     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4816     return;
4817   }
4818   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", t->id.tid);
4819
4820   GNUNET_array_append(t->blacklisted, t->nblacklisted,
4821                       GNUNET_PEER_intern(&peer_msg->peer));
4822 }
4823
4824
4825 /**
4826  * Handler for unblacklist requests of peers in a tunnel
4827  *
4828  * @param cls closure
4829  * @param client identification of the client
4830  * @param message the actual message (PeerControl)
4831  */
4832 static void
4833 handle_local_unblacklist (void *cls, struct GNUNET_SERVER_Client *client,
4834                           const struct GNUNET_MessageHeader *message)
4835 {
4836   struct GNUNET_MESH_PeerControl *peer_msg;
4837   struct MeshClient *c;
4838   struct MeshTunnel *t;
4839   MESH_TunnelNumber tid;
4840   GNUNET_PEER_Id pid;
4841   unsigned int i;
4842
4843   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got a PEER UNBLACKLIST request\n");
4844   /* Sanity check for client registration */
4845   if (NULL == (c = client_get (client)))
4846   {
4847     GNUNET_break (0);
4848     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4849     return;
4850   }
4851   peer_msg = (struct GNUNET_MESH_PeerControl *) message;
4852
4853   /* Sanity check for message size */
4854   if (sizeof (struct GNUNET_MESH_PeerControl) != ntohs (peer_msg->header.size))
4855   {
4856     GNUNET_break (0);
4857     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4858     return;
4859   }
4860
4861   /* Tunnel exists? */
4862   tid = ntohl (peer_msg->tunnel_id);
4863   t = tunnel_get_by_local_id (c, tid);
4864   if (NULL == t)
4865   {
4866     GNUNET_break (0);
4867     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4868     return;
4869   }
4870   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  on tunnel %X\n", t->id.tid);
4871
4872   /* if peer is not known, complain */
4873   pid = GNUNET_PEER_search (&peer_msg->peer);
4874   if (0 == pid)
4875   {
4876     GNUNET_break (0);
4877     return;
4878   }
4879
4880   /* search and remove from list */
4881   for (i = 0; i < t->nblacklisted; i++)
4882   {
4883     if (t->blacklisted[i] == pid)
4884     {
4885       t->blacklisted[i] = t->blacklisted[t->nblacklisted - 1];
4886       GNUNET_array_grow (t->blacklisted, t->nblacklisted, t->nblacklisted - 1);
4887       return;
4888     }
4889   }
4890
4891   /* if peer hasn't been blacklisted, complain */
4892   GNUNET_break (0);
4893 }
4894
4895
4896 /**
4897  * Handler for connection requests to new peers by type
4898  *
4899  * @param cls closure
4900  * @param client identification of the client
4901  * @param message the actual message (ConnectPeerByType)
4902  */
4903 static void
4904 handle_local_connect_by_type (void *cls, struct GNUNET_SERVER_Client *client,
4905                               const struct GNUNET_MessageHeader *message)
4906 {
4907   struct GNUNET_MESH_ConnectPeerByType *connect_msg;
4908   struct MeshClient *c;
4909   struct MeshTunnel *t;
4910   struct GNUNET_HashCode hash;
4911   MESH_TunnelNumber tid;
4912
4913   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got connect by type request\n");
4914   /* Sanity check for client registration */
4915   if (NULL == (c = client_get (client)))
4916   {
4917     GNUNET_break (0);
4918     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4919     return;
4920   }
4921
4922   connect_msg = (struct GNUNET_MESH_ConnectPeerByType *) message;
4923   /* Sanity check for message size */
4924   if (sizeof (struct GNUNET_MESH_ConnectPeerByType) !=
4925       ntohs (connect_msg->header.size))
4926   {
4927     GNUNET_break (0);
4928     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4929     return;
4930   }
4931
4932   /* Tunnel exists? */
4933   tid = ntohl (connect_msg->tunnel_id);
4934   t = tunnel_get_by_local_id (c, tid);
4935   if (NULL == t)
4936   {
4937     GNUNET_break (0);
4938     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4939     return;
4940   }
4941
4942   /* Does client own tunnel? */
4943   if (t->owner->handle != client)
4944   {
4945     GNUNET_break (0);
4946     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
4947     return;
4948   }
4949
4950   /* Do WE have the service? */
4951   t->type = ntohl (connect_msg->type);
4952   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " type requested: %u\n", t->type);
4953   GNUNET_CRYPTO_hash (&t->type, sizeof (GNUNET_MESH_ApplicationType), &hash);
4954   if (GNUNET_CONTAINER_multihashmap_contains (applications, &hash) ==
4955       GNUNET_YES)
4956   {
4957     /* Yes! Fast forward, add ourselves to the tunnel and send the
4958      * good news to the client, and alert the destination client of
4959      * an incoming tunnel.
4960      *
4961      * FIXME send a path create to self, avoid code duplication
4962      */
4963     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " available locally\n");
4964     GNUNET_CONTAINER_multihashmap_put (t->peers, &my_full_id.hashPubKey,
4965                                        peer_info_get (&my_full_id),
4966                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
4967
4968     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " notifying client\n");
4969     send_client_peer_connected (t, myid);
4970     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " Done\n");
4971     GNUNET_SERVER_receive_done (client, GNUNET_OK);
4972
4973     t->local_tid_dest = next_local_tid++;
4974     GNUNET_CRYPTO_hash (&t->local_tid_dest, sizeof (MESH_TunnelNumber), &hash);
4975     GNUNET_CONTAINER_multihashmap_put (incoming_tunnels, &hash, t,
4976                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
4977
4978     return;
4979   }
4980   /* Ok, lets find a peer offering the service */
4981   if (NULL != t->dht_get_type)
4982   {
4983     GNUNET_DHT_get_stop (t->dht_get_type);
4984   }
4985   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " looking in DHT for %s\n",
4986               GNUNET_h2s (&hash));
4987   t->dht_get_type =
4988       GNUNET_DHT_get_start (dht_handle, 
4989                             GNUNET_BLOCK_TYPE_MESH_PEER_BY_TYPE,
4990                             &hash,
4991                             DHT_REPLICATION_LEVEL,
4992                             GNUNET_DHT_RO_RECORD_ROUTE |
4993                             GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
4994                             NULL, 0,
4995                             &dht_get_type_handler, t);
4996
4997   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4998   return;
4999 }
5000
5001
5002 /**
5003  * Handler for connection requests to new peers by a string service description.
5004  *
5005  * @param cls closure
5006  * @param client identification of the client
5007  * @param message the actual message, which includes messages the client wants
5008  */
5009 static void
5010 handle_local_connect_by_string (void *cls, struct GNUNET_SERVER_Client *client,
5011                                 const struct GNUNET_MessageHeader *message)
5012 {
5013   struct GNUNET_MESH_ConnectPeerByString *msg;
5014   struct MeshRegexSearchContext *ctx;
5015   struct GNUNET_DHT_GetHandle *get_h;
5016   struct GNUNET_HashCode key;
5017   struct MeshTunnel *t;
5018   struct MeshClient *c;
5019   MESH_TunnelNumber tid;
5020   const char *string;
5021   size_t size;
5022   size_t len;
5023   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5024               "************************************************************\n");
5025   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5026               "Connect by string started\n");
5027   msg = (struct GNUNET_MESH_ConnectPeerByString *) message;
5028   size = htons (message->size);
5029
5030   /* Sanity check for client registration */
5031   if (NULL == (c = client_get (client)))
5032   {
5033     GNUNET_break (0);
5034     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5035     return;
5036   }
5037
5038   /* Message size sanity check */
5039   if (sizeof(struct GNUNET_MESH_ConnectPeerByString) >= size)
5040   {
5041       GNUNET_break (0);
5042       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5043       return;
5044   }
5045
5046   /* Tunnel exists? */
5047   tid = ntohl (msg->tunnel_id);
5048   t = tunnel_get_by_local_id (c, tid);
5049   if (NULL == t)
5050   {
5051     GNUNET_break (0);
5052     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5053     return;
5054   }
5055
5056   /* Does client own tunnel? */
5057   if (t->owner->handle != client)
5058   {
5059     GNUNET_break (0);
5060     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5061     return;
5062   }
5063
5064   /* Only one connect_by_string allowed at the same time! */
5065   /* FIXME: allow more, return handle at api level to cancel, document */
5066   if (NULL != t->regex_ctx)
5067   {
5068     GNUNET_break (0);
5069     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5070     return;
5071   }
5072
5073   /* Find string itself */
5074   len = size - sizeof(struct GNUNET_MESH_ConnectPeerByString);
5075   string = (const char *) &msg[1];
5076
5077   /* Initialize context */
5078   size = GNUNET_REGEX_get_first_key(string, len, &key);
5079   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5080               "************************************************************\n");
5081   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5082               "  consumed %u bits out of %u\n", size, len);
5083   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5084               "  looking for %s\n", GNUNET_h2s (&key));
5085
5086   ctx = GNUNET_malloc (sizeof (struct MeshRegexSearchContext));
5087   ctx->position = size;
5088   ctx->t = t;
5089   t->regex_ctx = ctx;
5090   ctx->description = GNUNET_malloc (len + 1);
5091   memcpy (ctx->description, string, len);
5092   ctx->description[len] = '\0';
5093   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "   string: %s\n", ctx->description);
5094
5095   ctx->dht_get_handles = GNUNET_CONTAINER_multihashmap_create(32);
5096
5097   /* Start search in DHT */
5098   get_h = GNUNET_DHT_get_start (dht_handle,    /* handle */
5099                                 GNUNET_BLOCK_TYPE_MESH_REGEX, /* type */
5100                                 &key,     /* key to search */
5101                                 DHT_REPLICATION_LEVEL, /* replication level */
5102                                 GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
5103                                 NULL,       /* xquery */ // FIXME BLOOMFILTER
5104                                 0,     /* xquery bits */ // FIXME BLOOMFILTER SIZE
5105                                 &dht_get_string_handler, ctx);
5106   
5107   GNUNET_break (GNUNET_OK ==
5108                 GNUNET_CONTAINER_multihashmap_put(ctx->dht_get_handles,
5109                                                   &key,
5110                                                   get_h,
5111                                                   GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
5112
5113   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5114   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "connect by string processed\n");
5115 }
5116
5117
5118 /**
5119  * Handler for client traffic directed to one peer
5120  *
5121  * @param cls closure
5122  * @param client identification of the client
5123  * @param message the actual message
5124  */
5125 static void
5126 handle_local_unicast (void *cls, struct GNUNET_SERVER_Client *client,
5127                       const struct GNUNET_MessageHeader *message)
5128 {
5129   struct MeshClient *c;
5130   struct MeshTunnel *t;
5131   struct MeshPeerInfo *pi;
5132   struct GNUNET_MESH_Unicast *data_msg;
5133   MESH_TunnelNumber tid;
5134   size_t size;
5135
5136   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5137               "Got a unicast request from a client!\n");
5138
5139   /* Sanity check for client registration */
5140   if (NULL == (c = client_get (client)))
5141   {
5142     GNUNET_break (0);
5143     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5144     return;
5145   }
5146   data_msg = (struct GNUNET_MESH_Unicast *) message;
5147   /* Sanity check for message size */
5148   size = ntohs (message->size);
5149   if (sizeof (struct GNUNET_MESH_Unicast) +
5150       sizeof (struct GNUNET_MessageHeader) > size)
5151   {
5152     GNUNET_break (0);
5153     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5154     return;
5155   }
5156
5157   /* Tunnel exists? */
5158   tid = ntohl (data_msg->tid);
5159   t = tunnel_get_by_local_id (c, tid);
5160   if (NULL == t)
5161   {
5162     GNUNET_break (0);
5163     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5164     return;
5165   }
5166
5167   /*  Is it a local tunnel? Then, does client own the tunnel? */
5168   if (t->owner->handle != client)
5169   {
5170     GNUNET_break (0);
5171     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5172     return;
5173   }
5174
5175   pi = GNUNET_CONTAINER_multihashmap_get (t->peers,
5176                                           &data_msg->destination.hashPubKey);
5177   /* Is the selected peer in the tunnel? */
5178   if (NULL == pi)
5179   {
5180     GNUNET_break (0);
5181     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5182     return;
5183   }
5184
5185   /* Ok, everything is correct, send the message
5186    * (pretend we got it from a mesh peer)
5187    */
5188   {
5189     char buf[ntohs (message->size)] GNUNET_ALIGN;
5190     struct GNUNET_MESH_Unicast *copy;
5191
5192     /* Work around const limitation */
5193     copy = (struct GNUNET_MESH_Unicast *) buf;
5194     memcpy (buf, data_msg, size);
5195     copy->oid = my_full_id;
5196     copy->tid = htonl (t->id.tid);
5197     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5198                 "  calling generic handler...\n");
5199     handle_mesh_data_unicast (NULL, &my_full_id, &copy->header, NULL, 0);
5200   }
5201   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5202   return;
5203 }
5204
5205
5206 /**
5207  * Handler for client traffic directed to the origin
5208  *
5209  * @param cls closure
5210  * @param client identification of the client
5211  * @param message the actual message
5212  */
5213 static void
5214 handle_local_to_origin (void *cls, struct GNUNET_SERVER_Client *client,
5215                         const struct GNUNET_MessageHeader *message)
5216 {
5217   struct GNUNET_MESH_ToOrigin *data_msg;
5218   struct GNUNET_PeerIdentity id;
5219   struct MeshClient *c;
5220   struct MeshTunnel *t;
5221   MESH_TunnelNumber tid;
5222   size_t size;
5223
5224   /* Sanity check for client registration */
5225   if (NULL == (c = client_get (client)))
5226   {
5227     GNUNET_break (0);
5228     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5229     return;
5230   }
5231   data_msg = (struct GNUNET_MESH_ToOrigin *) message;
5232   /* Sanity check for message size */
5233   size = ntohs (message->size);
5234   if (sizeof (struct GNUNET_MESH_ToOrigin) +
5235       sizeof (struct GNUNET_MessageHeader) > size)
5236   {
5237     GNUNET_break (0);
5238     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5239     return;
5240   }
5241
5242   /* Tunnel exists? */
5243   tid = ntohl (data_msg->tid);
5244   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5245               "Got a ToOrigin request from a client! Tunnel %X\n", tid);
5246   if (tid < GNUNET_MESH_LOCAL_TUNNEL_ID_SERV)
5247   {
5248     GNUNET_break (0);
5249     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5250     return;
5251   }
5252   t = tunnel_get_by_local_id (c, tid);
5253   if (NULL == t)
5254   {
5255     GNUNET_break (0);
5256     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5257     return;
5258   }
5259
5260   /*  It should be sent by someone who has this as incoming tunnel. */
5261   if (-1 == client_knows_tunnel (c, t))
5262   {
5263     GNUNET_break (0);
5264     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5265     return;
5266   }
5267   GNUNET_PEER_resolve (t->id.oid, &id);
5268
5269   /* Ok, everything is correct, send the message
5270    * (pretend we got it from a mesh peer)
5271    */
5272   {
5273     char buf[ntohs (message->size)] GNUNET_ALIGN;
5274     struct GNUNET_MESH_ToOrigin *copy;
5275
5276     /* Work around const limitation */
5277     copy = (struct GNUNET_MESH_ToOrigin *) buf;
5278     memcpy (buf, data_msg, size);
5279     copy->oid = id;
5280     copy->tid = htonl (t->id.tid);
5281     copy->sender = my_full_id;
5282     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5283                 "  calling generic handler...\n");
5284     handle_mesh_data_to_orig (NULL, &my_full_id, &copy->header, NULL, 0);
5285   }
5286   GNUNET_SERVER_receive_done (client, GNUNET_OK);
5287   return;
5288 }
5289
5290
5291 /**
5292  * Handler for client traffic directed to all peers in a tunnel
5293  *
5294  * @param cls closure
5295  * @param client identification of the client
5296  * @param message the actual message
5297  */
5298 static void
5299 handle_local_multicast (void *cls, struct GNUNET_SERVER_Client *client,
5300                         const struct GNUNET_MessageHeader *message)
5301 {
5302   struct MeshClient *c;
5303   struct MeshTunnel *t;
5304   struct GNUNET_MESH_Multicast *data_msg;
5305   MESH_TunnelNumber tid;
5306
5307   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5308               "Got a multicast request from a client!\n");
5309
5310   /* Sanity check for client registration */
5311   if (NULL == (c = client_get (client)))
5312   {
5313     GNUNET_break (0);
5314     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5315     return;
5316   }
5317   data_msg = (struct GNUNET_MESH_Multicast *) message;
5318   /* Sanity check for message size */
5319   if (sizeof (struct GNUNET_MESH_Multicast) +
5320       sizeof (struct GNUNET_MessageHeader) > ntohs (data_msg->header.size))
5321   {
5322     GNUNET_break (0);
5323     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5324     return;
5325   }
5326
5327   /* Tunnel exists? */
5328   tid = ntohl (data_msg->tid);
5329   t = tunnel_get_by_local_id (c, tid);
5330   if (NULL == t)
5331   {
5332     GNUNET_break (0);
5333     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5334     return;
5335   }
5336
5337   /* Does client own tunnel? */
5338   if (t->owner->handle != client)
5339   {
5340     GNUNET_break (0);
5341     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
5342     return;
5343   }
5344
5345   {
5346     char buf[ntohs (message->size)] GNUNET_ALIGN;
5347     struct GNUNET_MESH_Multicast *copy;
5348
5349     copy = (struct GNUNET_MESH_Multicast *) buf;
5350     memcpy (buf, message, ntohs (message->size));
5351     copy->oid = my_full_id;
5352     copy->tid = htonl (t->id.tid);
5353     copy->ttl = htonl (DEFAULT_TTL);
5354     copy->mid = htonl (t->mid + 1);
5355     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5356                 "  calling generic handler...\n");
5357     handle_mesh_data_multicast (client, &my_full_id, &copy->header, NULL, 0);
5358   }
5359
5360   /* receive done gets called when last copy is sent to a neighbor */
5361   return;
5362 }
5363
5364 /**
5365  * Functions to handle messages from clients
5366  */
5367 static struct GNUNET_SERVER_MessageHandler client_handlers[] = {
5368   {&handle_local_new_client, NULL,
5369    GNUNET_MESSAGE_TYPE_MESH_LOCAL_CONNECT, 0},
5370   {&handle_local_announce_regex, NULL,
5371    GNUNET_MESSAGE_TYPE_MESH_LOCAL_ANNOUNCE_REGEX, 0},
5372   {&handle_local_tunnel_create, NULL,
5373    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_CREATE,
5374    sizeof (struct GNUNET_MESH_TunnelMessage)},
5375   {&handle_local_tunnel_destroy, NULL,
5376    GNUNET_MESSAGE_TYPE_MESH_LOCAL_TUNNEL_DESTROY,
5377    sizeof (struct GNUNET_MESH_TunnelMessage)},
5378   {&handle_local_connect_add, NULL,
5379    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD,
5380    sizeof (struct GNUNET_MESH_PeerControl)},
5381   {&handle_local_connect_del, NULL,
5382    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_DEL,
5383    sizeof (struct GNUNET_MESH_PeerControl)},
5384   {&handle_local_blacklist, NULL,
5385    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_BLACKLIST,
5386    sizeof (struct GNUNET_MESH_PeerControl)},
5387   {&handle_local_unblacklist, NULL,
5388    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_UNBLACKLIST,
5389    sizeof (struct GNUNET_MESH_PeerControl)},
5390   {&handle_local_connect_by_type, NULL,
5391    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_TYPE,
5392    sizeof (struct GNUNET_MESH_ConnectPeerByType)},
5393   {&handle_local_connect_by_string, NULL,
5394    GNUNET_MESSAGE_TYPE_MESH_LOCAL_PEER_ADD_BY_STRING, 0},
5395   {&handle_local_unicast, NULL,
5396    GNUNET_MESSAGE_TYPE_MESH_UNICAST, 0},
5397   {&handle_local_to_origin, NULL,
5398    GNUNET_MESSAGE_TYPE_MESH_TO_ORIGIN, 0},
5399   {&handle_local_multicast, NULL,
5400    GNUNET_MESSAGE_TYPE_MESH_MULTICAST, 0},
5401   {NULL, NULL, 0, 0}
5402 };
5403
5404
5405 /**
5406  * To be called on core init/fail.
5407  *
5408  * @param cls service closure
5409  * @param server handle to the server for this service
5410  * @param identity the public identity of this peer
5411  */
5412 static void
5413 core_init (void *cls, struct GNUNET_CORE_Handle *server,
5414            const struct GNUNET_PeerIdentity *identity)
5415 {
5416   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Core init\n");
5417   core_handle = server;
5418   if (0 != memcmp (identity, &my_full_id, sizeof (my_full_id)) ||
5419       NULL == server)
5420   {
5421     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Wrong CORE service\n"));
5422     GNUNET_SCHEDULER_shutdown ();
5423   }
5424   return;
5425 }
5426
5427 /**
5428  * Method called whenever a given peer connects.
5429  *
5430  * @param cls closure
5431  * @param peer peer identity this notification is about
5432  * @param atsi performance data for the connection
5433  * @param atsi_count number of records in 'atsi'
5434  */
5435 static void
5436 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
5437               const struct GNUNET_ATS_Information *atsi,
5438               unsigned int atsi_count)
5439 {
5440   struct MeshPeerInfo *peer_info;
5441   struct MeshPeerPath *path;
5442
5443   DEBUG_CONN ("Peer connected\n");
5444   DEBUG_CONN ("     %s\n", GNUNET_i2s (&my_full_id));
5445   peer_info = peer_info_get (peer);
5446   if (myid == peer_info->id)
5447   {
5448     DEBUG_CONN ("     (self)\n");
5449     return;
5450   }
5451   else
5452   {
5453     DEBUG_CONN ("     %s\n", GNUNET_i2s (peer));
5454   }
5455   path = path_new (2);
5456   path->peers[0] = myid;
5457   path->peers[1] = peer_info->id;
5458   GNUNET_PEER_change_rc (myid, 1);
5459   GNUNET_PEER_change_rc (peer_info->id, 1);
5460   peer_info_add_path (peer_info, path, GNUNET_YES);
5461   return;
5462 }
5463
5464 /**
5465  * Method called whenever a peer disconnects.
5466  *
5467  * @param cls closure
5468  * @param peer peer identity this notification is about
5469  */
5470 static void
5471 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
5472 {
5473   struct MeshPeerInfo *pi;
5474   struct MeshPeerQueue *q;
5475   struct MeshPeerQueue *n;
5476
5477   DEBUG_CONN ("Peer disconnected\n");
5478   pi = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
5479   if (NULL == pi)
5480   {
5481     GNUNET_break (0);
5482     return;
5483   }
5484   q = pi->queue_head;
5485   while (NULL != q)
5486   {
5487       n = q->next;
5488       if (q->peer == pi)
5489       {
5490         /* try to reroute this traffic instead */
5491         queue_destroy(q, GNUNET_YES);
5492       }
5493       q = n;
5494   }
5495   peer_info_remove_path (pi, pi->id, myid);
5496   if (myid == pi->id)
5497   {
5498     DEBUG_CONN ("     (self)\n");
5499   }
5500   return;
5501 }
5502
5503
5504 /******************************************************************************/
5505 /************************      MAIN FUNCTIONS      ****************************/
5506 /******************************************************************************/
5507
5508 /**
5509  * Iterator over tunnel hash map entries to destroy the tunnel during shutdown.
5510  *
5511  * @param cls closure
5512  * @param key current key code
5513  * @param value value in the hash map
5514  * @return GNUNET_YES if we should continue to iterate,
5515  *         GNUNET_NO if not.
5516  */
5517 static int
5518 shutdown_tunnel (void *cls, const struct GNUNET_HashCode * key, void *value)
5519 {
5520   struct MeshTunnel *t = value;
5521
5522   tunnel_destroy (t);
5523   return GNUNET_YES;
5524 }
5525
5526 /**
5527  * Iterator over peer hash map entries to destroy the tunnel during shutdown.
5528  *
5529  * @param cls closure
5530  * @param key current key code
5531  * @param value value in the hash map
5532  * @return GNUNET_YES if we should continue to iterate,
5533  *         GNUNET_NO if not.
5534  */
5535 static int
5536 shutdown_peer (void *cls, const struct GNUNET_HashCode * key, void *value)
5537 {
5538   struct MeshPeerInfo *p = value;
5539   struct MeshPeerQueue *q;
5540   struct MeshPeerQueue *n;
5541
5542   q = p->queue_head;
5543   while (NULL != q)
5544   {
5545       n = q->next;
5546       if (q->peer == p)
5547       {
5548         queue_destroy(q, GNUNET_YES);
5549       }
5550       q = n;
5551   }
5552   peer_info_destroy (p);
5553   return GNUNET_YES;
5554 }
5555
5556 /**
5557  * Task run during shutdown.
5558  *
5559  * @param cls unused
5560  * @param tc unused
5561  */
5562 static void
5563 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
5564 {
5565   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shutting down\n");
5566
5567   if (core_handle != NULL)
5568   {
5569     GNUNET_CORE_disconnect (core_handle);
5570     core_handle = NULL;
5571   }
5572   GNUNET_CONTAINER_multihashmap_iterate (tunnels, &shutdown_tunnel, NULL);
5573   GNUNET_CONTAINER_multihashmap_iterate (peers, &shutdown_peer, NULL);
5574   if (dht_handle != NULL)
5575   {
5576     GNUNET_DHT_disconnect (dht_handle);
5577     dht_handle = NULL;
5578   }
5579   if (nc != NULL)
5580   {
5581     GNUNET_SERVER_notification_context_destroy (nc);
5582     nc = NULL;
5583   }
5584   if (GNUNET_SCHEDULER_NO_TASK != announce_id_task)
5585   {
5586     GNUNET_SCHEDULER_cancel (announce_id_task);
5587     announce_id_task = GNUNET_SCHEDULER_NO_TASK;
5588   }
5589   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shut down\n");
5590 }
5591
5592 /**
5593  * Process mesh requests.
5594  *
5595  * @param cls closure
5596  * @param server the initialized server
5597  * @param c configuration to use
5598  */
5599 static void
5600 run (void *cls, struct GNUNET_SERVER_Handle *server,
5601      const struct GNUNET_CONFIGURATION_Handle *c)
5602 {
5603   struct MeshPeerInfo *peer;
5604   struct MeshPeerPath *p;
5605   char *keyfile;
5606
5607   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "starting to run\n");
5608   server_handle = server;
5609   core_handle = GNUNET_CORE_connect (c, /* Main configuration */
5610                                      NULL,      /* Closure passed to MESH functions */
5611                                      &core_init,        /* Call core_init once connected */
5612                                      &core_connect,     /* Handle connects */
5613                                      &core_disconnect,  /* remove peers on disconnects */
5614                                      NULL,      /* Don't notify about all incoming messages */
5615                                      GNUNET_NO, /* For header only in notification */
5616                                      NULL,      /* Don't notify about all outbound messages */
5617                                      GNUNET_NO, /* For header-only out notification */
5618                                      core_handlers);    /* Register these handlers */
5619
5620   if (core_handle == NULL)
5621   {
5622     GNUNET_break (0);
5623     GNUNET_SCHEDULER_shutdown ();
5624     return;
5625   }
5626
5627   if (GNUNET_OK !=
5628       GNUNET_CONFIGURATION_get_value_filename (c, "GNUNETD", "HOSTKEY",
5629                                                &keyfile))
5630   {
5631     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5632                 _
5633                 ("Mesh service is lacking key configuration settings.  Exiting.\n"));
5634     GNUNET_SCHEDULER_shutdown ();
5635     return;
5636   }
5637   my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
5638   GNUNET_free (keyfile);
5639   if (my_private_key == NULL)
5640   {
5641     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
5642                 _("Mesh service could not access hostkey.  Exiting.\n"));
5643     GNUNET_SCHEDULER_shutdown ();
5644     return;
5645   }
5646   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
5647   GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
5648                       &my_full_id.hashPubKey);
5649   myid = GNUNET_PEER_intern (&my_full_id);
5650
5651 //   transport_handle = GNUNET_TRANSPORT_connect(c,
5652 //                                               &my_full_id,
5653 //                                               NULL,
5654 //                                               NULL,
5655 //                                               NULL,
5656 //                                               NULL);
5657
5658   dht_handle = GNUNET_DHT_connect (c, 64);
5659   if (dht_handle == NULL)
5660   {
5661     GNUNET_break (0);
5662   }
5663
5664   next_tid = 0;
5665   next_local_tid = GNUNET_MESH_LOCAL_TUNNEL_ID_SERV;
5666
5667   tunnels = GNUNET_CONTAINER_multihashmap_create (32);
5668   incoming_tunnels = GNUNET_CONTAINER_multihashmap_create (32);
5669   peers = GNUNET_CONTAINER_multihashmap_create (32);
5670   applications = GNUNET_CONTAINER_multihashmap_create (32);
5671   types = GNUNET_CONTAINER_multihashmap_create (32);
5672
5673   GNUNET_SERVER_add_handlers (server_handle, client_handlers);
5674   nc = GNUNET_SERVER_notification_context_create (server_handle,
5675                                                   LOCAL_QUEUE_SIZE);
5676   GNUNET_SERVER_disconnect_notify (server_handle,
5677                                    &handle_local_client_disconnect, NULL);
5678
5679
5680   clients = NULL;
5681   clients_tail = NULL;
5682   next_client_id = 0;
5683
5684   announce_applications_task = GNUNET_SCHEDULER_NO_TASK;
5685   announce_id_task = GNUNET_SCHEDULER_add_now (&announce_id, cls);
5686
5687   /* Create a peer_info for the local peer */
5688   peer = peer_info_get (&my_full_id);
5689   p = path_new (1);
5690   p->peers[0] = myid;
5691   GNUNET_PEER_change_rc (myid, 1);
5692   peer_info_add_path (peer, p, GNUNET_YES);
5693
5694   /* Scheduled the task to clean up when shutdown is called */
5695   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
5696                                 NULL);
5697
5698   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "end of run()\n");
5699 }
5700
5701 /**
5702  * The main function for the mesh service.
5703  *
5704  * @param argc number of arguments from the command line
5705  * @param argv command line arguments
5706  * @return 0 ok, 1 on error
5707  */
5708 int
5709 main (int argc, char *const *argv)
5710 {
5711   int ret;
5712
5713   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main()\n");
5714   ret =
5715       (GNUNET_OK ==
5716        GNUNET_SERVICE_run (argc, argv, "mesh", GNUNET_SERVICE_OPTION_NONE, &run,
5717                            NULL)) ? 0 : 1;
5718   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "main() END\n");
5719
5720   return ret;
5721 }