- listener re-connects transparently
[oweals/gnunet.git] / src / set / gnunet-service-set.c
1 /*
2       This file is part of GNUnet
3       (C) 2013 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 2, 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 set/gnunet-service-set.c
23  * @brief two-peer set operations
24  * @author Florian Dold
25  */
26 #include "gnunet-service-set.h"
27 #include "set_protocol.h"
28
29
30 /**
31  * Peer that has connected to us, but is not yet evaluating a set operation.
32  * Once the peer has sent a request, and the client has
33  * accepted or rejected it, this information will be deleted.
34  */
35 struct Incoming
36 {
37   /**
38    * Incoming peers are held in a linked list
39    */
40   struct Incoming *next;
41
42   /**
43    * Incoming peers are held in a linked list
44    */
45   struct Incoming *prev;
46
47   /**
48    * Detail information about the operation.
49    * NULL as long as we did not receive the operation
50    * request from the remote peer.
51    */
52   struct OperationSpecification *spec;
53
54   /**
55    * The identity of the requesting peer.  Needs to
56    * be stored here as the op spec might not have been created yet.
57    */
58   struct GNUNET_PeerIdentity peer;
59
60   /**
61    * Tunnel to the peer.
62    */
63   struct GNUNET_MESH_Tunnel *tunnel;
64
65   /**
66    * Unique request id for the request from
67    * a remote peer, sent to the client, which will
68    * accept or reject the request.
69    * Set to '0' iff the request has not been
70    * suggested yet.
71    */
72   uint32_t suggest_id;
73
74   /**
75    * Timeout task, if the incoming peer has not been accepted
76    * after the timeout, it will be disconnected.
77    */
78   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
79
80   /**
81    * Tunnel context, needs to be stored here as a client's accept will change
82    * the tunnel context.
83    */
84   struct TunnelContext *tc;
85 };
86
87
88 /**
89  * A listener is inhabited by a client, and
90  * waits for evaluation requests from remote peers.
91  */
92 struct Listener
93 {
94   /**
95    * Listeners are held in a doubly linked list.
96    */
97   struct Listener *next;
98
99   /**
100    * Listeners are held in a doubly linked list.
101    */
102   struct Listener *prev;
103
104   /**
105    * Client that owns the listener.
106    * Only one client may own a listener.
107    */
108   struct GNUNET_SERVER_Client *client;
109
110   /**
111    * Message queue for the client
112    */
113   struct GNUNET_MQ_Handle *client_mq;
114
115   /**
116    * The type of the operation.
117    */
118   enum GNUNET_SET_OperationType operation;
119
120   /**
121    * Application ID for the operation, used to distinguish
122    * multiple operations of the same type with the same peer.
123    */
124   struct GNUNET_HashCode app_id;
125 };
126
127
128 /**
129  * Configuration of our local peer.
130  */
131 static const struct GNUNET_CONFIGURATION_Handle *configuration;
132
133 /**
134  * Handle to the mesh service, used
135  * to listen for and connect to remote peers.
136  */
137 static struct GNUNET_MESH_Handle *mesh;
138
139 /**
140  * Sets are held in a doubly linked list.
141  */
142 static struct Set *sets_head;
143
144 /**
145  * Sets are held in a doubly linked list.
146  */
147 static struct Set *sets_tail;
148
149 /**
150  * Listeners are held in a doubly linked list.
151  */
152 static struct Listener *listeners_head;
153
154 /**
155  * Listeners are held in a doubly linked list.
156  */
157 static struct Listener *listeners_tail;
158
159 /**
160  * Incoming sockets from remote peers are
161  * held in a doubly linked list.
162  */
163 static struct Incoming *incoming_head;
164
165 /**
166  * Incoming sockets from remote peers are
167  * held in a doubly linked list.
168  */
169 static struct Incoming *incoming_tail;
170
171 /**
172  * Counter for allocating unique IDs for clients,
173  * used to identify incoming operation requests from remote peers,
174  * that the client can choose to accept or refuse.
175  */
176 static uint32_t suggest_id = 1;
177
178
179 /**
180  * Get set that is owned by the given client, if any.
181  *
182  * @param client client to look for
183  * @return set that the client owns, NULL if the client
184  *         does not own a set
185  */
186 static struct Set *
187 set_get (struct GNUNET_SERVER_Client *client)
188 {
189   struct Set *set;
190
191   for (set = sets_head; NULL != set; set = set->next)
192     if (set->client == client)
193       return set;
194   return NULL;
195 }
196
197
198 /**
199  * Get the listener associated with the given client, if any.
200  *
201  * @param client the client
202  * @return listener associated with the client, NULL
203  *         if there isn't any
204  */
205 static struct Listener *
206 listener_get (struct GNUNET_SERVER_Client *client)
207 {
208   struct Listener *listener;
209
210   for (listener = listeners_head; NULL != listener; listener = listener->next)
211     if (listener->client == client)
212       return listener;
213   return NULL;
214 }
215
216
217 /**
218  * Get the incoming socket associated with the given id.
219  *
220  * @param id id to look for
221  * @return the incoming socket associated with the id,
222  *         or NULL if there is none
223  */
224 static struct Incoming *
225 get_incoming (uint32_t id)
226 {
227   struct Incoming *incoming;
228
229   for (incoming = incoming_head; NULL != incoming; incoming = incoming->next)
230     if (incoming->suggest_id == id)
231       return incoming;
232   return NULL;
233 }
234
235
236 /**
237  * Destroy a listener, free all resources associated with it.
238  *
239  * @param listener listener to destroy
240  */
241 static void
242 listener_destroy (struct Listener *listener)
243 {
244   /* If the client is not dead yet, destroy it.
245    * The client's destroy callback will destroy the listener again. */
246   if (NULL != listener->client)
247   {
248     struct GNUNET_SERVER_Client *client = listener->client;
249     listener->client = NULL;
250     GNUNET_SERVER_client_disconnect (client);
251     return;
252   }
253   if (NULL != listener->client_mq)
254   {
255     GNUNET_MQ_destroy (listener->client_mq);
256     listener->client_mq = NULL;
257   }
258   GNUNET_CONTAINER_DLL_remove (listeners_head, listeners_tail, listener);
259   GNUNET_free (listener);
260 }
261
262
263 /**
264  * Destroy a set, and free all resources associated with it.
265  *
266  * @param set the set to destroy
267  */
268 static void
269 set_destroy (struct Set *set)
270 {
271   /* If the client is not dead yet, destroy it.
272    * The client's destroy callback will destroy the set again. */
273   if (NULL != set->client)
274   {
275     struct GNUNET_SERVER_Client *client = set->client;
276     set->client = NULL;
277     GNUNET_SERVER_client_disconnect (client);
278     return;
279   }
280   if (NULL != set->client_mq)
281   {
282     GNUNET_MQ_destroy (set->client_mq);
283     set->client_mq = NULL;
284   }
285   GNUNET_assert (NULL != set->state);
286   set->vt->destroy_set (set->state);
287   set->state = NULL;
288   GNUNET_CONTAINER_DLL_remove (sets_head, sets_tail, set);
289   GNUNET_free (set);
290 }
291
292
293 /**
294  * Clean up after a client after it is
295  * disconnected (either by us or by itself)
296  *
297  * @param cls closure, unused
298  * @param client the client to clean up after
299  */
300 static void
301 handle_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
302 {
303   struct Set *set;
304   struct Listener *listener;
305
306   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client disconnected, cleaning up\n");
307
308   set = set_get (client);
309   if (NULL != set)
310   {
311     set->client = NULL;
312     set_destroy (set);
313     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "(client's set destroyed)\n");
314   }
315   listener = listener_get (client);
316   if (NULL != listener)
317   {
318     listener->client = NULL;
319     listener_destroy (listener);
320     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "(client's listener destroyed)\n");
321   }
322 }
323
324
325 /**
326  * Destroy an incoming request from a remote peer
327  *
328  * @param incoming remote request to destroy
329  */
330 static void
331 incoming_destroy (struct Incoming *incoming)
332 {
333   GNUNET_CONTAINER_DLL_remove (incoming_head, incoming_tail, incoming);
334   if (NULL != incoming->tunnel)
335   {
336     struct GNUNET_MESH_Tunnel *t = incoming->tunnel;
337     incoming->tunnel = NULL;
338     GNUNET_MESH_tunnel_destroy (t);
339     return;
340   }
341   GNUNET_free (incoming);
342 }
343
344
345 static struct Listener *
346 listener_get_by_target (enum GNUNET_SET_OperationType op,
347                         const struct GNUNET_HashCode *app_id)
348 {
349   struct Listener *l;
350
351   for (l = listeners_head; NULL != l; l = l->next)
352   {
353     if (l->operation != op)
354       continue;
355     if (0 != GNUNET_CRYPTO_hash_cmp (app_id, &l->app_id))
356       continue;
357     return l;
358   }
359   return NULL;
360 }
361
362
363 /**
364  * Suggest the given request to the listener,
365  * who can accept or reject the request.
366  *
367  * @param incoming the incoming peer with the request to suggest
368  * @param listener the listener to suggest the request to
369  */
370 static void
371 incoming_suggest (struct Incoming *incoming, struct Listener *listener)
372 {
373   struct GNUNET_MQ_Envelope *mqm;
374   struct GNUNET_SET_RequestMessage *cmsg;
375
376   GNUNET_assert (0 == incoming->suggest_id);
377   GNUNET_assert (NULL != incoming->spec);
378   incoming->suggest_id = suggest_id++;
379
380   GNUNET_SCHEDULER_cancel (incoming->timeout_task);
381   mqm = GNUNET_MQ_msg_nested_mh (cmsg, GNUNET_MESSAGE_TYPE_SET_REQUEST,
382                                  incoming->spec->context_msg);
383   GNUNET_assert (NULL != mqm);
384   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "suggesting request with accept id %u\n",
385               incoming->suggest_id);
386   cmsg->accept_id = htonl (incoming->suggest_id);
387   cmsg->peer_id = incoming->spec->peer;
388   GNUNET_MQ_send (listener->client_mq, mqm);
389
390 }
391
392
393 /**
394  * Handle a request for a set operation from
395  * another peer.
396  *
397  * @param op the operation state
398  * @param mh the received message
399  * @return GNUNET_OK if the tunnel should be kept alive,
400  *         GNUNET_SYSERR to destroy the tunnel
401  */
402 static int
403 handle_incoming_msg (struct OperationState *op,
404                      const struct GNUNET_MessageHeader *mh)
405 {
406   struct Incoming *incoming = (struct Incoming *) op;
407   const struct OperationRequestMessage *msg = (const struct OperationRequestMessage *) mh;
408   struct Listener *listener;
409   struct OperationSpecification *spec;
410
411   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got op request\n");
412
413   if (GNUNET_MESSAGE_TYPE_SET_P2P_OPERATION_REQUEST != ntohs (mh->type))
414   {
415     GNUNET_break_op (0);
416     return GNUNET_SYSERR;
417   }
418
419   if (NULL != incoming->spec)
420   {
421     /* double operation request */
422     GNUNET_break_op (0);
423     return GNUNET_SYSERR;
424   }
425
426   spec = GNUNET_new (struct OperationSpecification);
427   spec->context_msg = GNUNET_MQ_extract_nested_mh (msg);
428   if (NULL != spec->context_msg)
429     spec->context_msg = GNUNET_copy_message (spec->context_msg);
430   spec->operation = ntohl (msg->operation);
431   spec->app_id = msg->app_id;
432   spec->salt = ntohl (msg->salt);
433   spec->peer = incoming->peer;
434
435   incoming->spec = spec;
436
437   if ( (NULL != spec->context_msg) &&
438        (ntohs (spec->context_msg->size) > GNUNET_SET_CONTEXT_MESSAGE_MAX_SIZE) )
439   {
440     GNUNET_break_op (0);
441     return GNUNET_SYSERR;
442   }
443
444   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "received P2P operation request (op %u, app %s)\n",
445               ntohl (msg->operation), GNUNET_h2s (&msg->app_id));
446   listener = listener_get_by_target (ntohl (msg->operation), &msg->app_id);
447   if (NULL == listener)
448   {
449     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
450                 "no listener matches incoming request, waiting with timeout\n");
451     return GNUNET_OK;
452   }
453   incoming_suggest (incoming, listener);
454   return GNUNET_OK;
455 }
456
457
458 /**
459  * Called when a client wants to iterate the elements of a set.
460  *
461  * @param cls unused
462  * @param client client that sent the message
463  * @param m message sent by the client
464  */
465 static void
466 handle_client_iterate (void *cls,
467                        struct GNUNET_SERVER_Client *client,
468                        const struct GNUNET_MessageHeader *m)
469 {
470   struct Set *set;
471   
472   set = set_get (client);
473   if (NULL == set)
474   {
475     GNUNET_break (0);
476     GNUNET_SERVER_client_disconnect (client);
477     return;
478   }
479
480   GNUNET_SERVER_receive_done (client, GNUNET_OK);
481   set->vt->iterate (set);
482 }
483
484
485 /**
486  * Called when a client wants to create a new set.
487  *
488  * @param cls unused
489  * @param client client that sent the message
490  * @param m message sent by the client
491  */
492 static void
493 handle_client_create (void *cls,
494                       struct GNUNET_SERVER_Client *client,
495                       const struct GNUNET_MessageHeader *m)
496 {
497   struct GNUNET_SET_CreateMessage *msg = (struct GNUNET_SET_CreateMessage *) m;
498   struct Set *set;
499
500   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client created new set (operation %u)\n",
501               ntohs (msg->operation));
502
503   if (NULL != set_get (client))
504   {
505     GNUNET_break (0);
506     GNUNET_SERVER_client_disconnect (client);
507     return;
508   }
509
510   set = GNUNET_new (struct Set);
511
512   switch (ntohs (msg->operation))
513   {
514     case GNUNET_SET_OPERATION_INTERSECTION:
515       // FIXME
516       break;
517     case GNUNET_SET_OPERATION_UNION:
518       set->vt = _GSS_union_vt ();
519       break;
520     default:
521       GNUNET_free (set);
522       GNUNET_break (0);
523       GNUNET_SERVER_client_disconnect (client);
524       return;
525   }
526
527   set->state = set->vt->create ();
528   set->client = client;
529   set->client_mq = GNUNET_MQ_queue_for_server_client (client);
530   GNUNET_CONTAINER_DLL_insert (sets_head, sets_tail, set);
531   GNUNET_SERVER_receive_done (client, GNUNET_OK);
532 }
533
534
535 /**
536  * Called when a client wants to create a new listener.
537  *
538  * @param cls unused
539  * @param client client that sent the message
540  * @param m message sent by the client
541  */
542 static void
543 handle_client_listen (void *cls,
544                       struct GNUNET_SERVER_Client *client,
545                       const struct GNUNET_MessageHeader *m)
546 {
547   struct GNUNET_SET_ListenMessage *msg = (struct GNUNET_SET_ListenMessage *) m;
548   struct Listener *listener;
549   struct Incoming *incoming;
550
551   if (NULL != listener_get (client))
552   {
553     GNUNET_break (0);
554     GNUNET_SERVER_client_disconnect (client);
555     return;
556   }
557   listener = GNUNET_new (struct Listener);
558   listener->client = client;
559   listener->client_mq = GNUNET_MQ_queue_for_server_client (client);
560   listener->app_id = msg->app_id;
561   listener->operation = ntohl (msg->operation);
562   GNUNET_CONTAINER_DLL_insert_tail (listeners_head, listeners_tail, listener);
563   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new listener created (op %u, app %s)\n",
564               listener->operation, GNUNET_h2s (&listener->app_id));
565   for (incoming = incoming_head; NULL != incoming; incoming = incoming->next)
566   {
567     if (NULL == incoming->spec)
568     {
569       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "request has no spec yet\n");
570       continue;
571     }
572     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "considering (op: %u, app: %s, suggest: %u)\n",
573                 incoming->spec->operation, GNUNET_h2s (&incoming->spec->app_id), incoming->suggest_id);
574
575     if (0 != incoming->suggest_id)
576       continue;
577     if (listener->operation != incoming->spec->operation)
578       continue;
579     if (0 != GNUNET_CRYPTO_hash_cmp (&listener->app_id, &incoming->spec->app_id))
580       continue;
581     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "request suggested\n");
582     incoming_suggest (incoming, listener);
583   }
584   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "considered all incoming requests\n");
585   GNUNET_SERVER_receive_done (client, GNUNET_OK);
586 }
587
588
589 /**
590  * Called when the client wants to reject an operation
591  * request from another peer.
592  *
593  * @param cls unused
594  * @param client client that sent the message
595  * @param m message sent by the client
596  */
597 static void
598 handle_client_reject (void *cls,
599                       struct GNUNET_SERVER_Client *client,
600                       const struct GNUNET_MessageHeader *m)
601 {
602   struct Incoming *incoming;
603   const struct GNUNET_SET_AcceptRejectMessage *msg;
604
605   msg = (const struct GNUNET_SET_AcceptRejectMessage *) m;
606   GNUNET_break (0 == ntohl (msg->request_id));
607
608   incoming = get_incoming (ntohl (msg->accept_reject_id));
609   if (NULL == incoming)
610   {
611     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
612     return;
613   }
614   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "peer request rejected by client\n");
615   GNUNET_MESH_tunnel_destroy (incoming->tunnel);
616   GNUNET_SERVER_receive_done (client, GNUNET_OK);
617 }
618
619
620 /**
621  * Called when a client wants to add an element to a
622  * set it inhabits.
623  *
624  * @param cls unused
625  * @param client client that sent the message
626  * @param m message sent by the client
627  */
628 static void
629 handle_client_add_remove (void *cls,
630                           struct GNUNET_SERVER_Client *client,
631                           const struct GNUNET_MessageHeader *m)
632 {
633   struct Set *set;
634   const struct GNUNET_SET_ElementMessage *msg;
635   struct GNUNET_SET_Element el;
636
637   set = set_get (client);
638   if (NULL == set)
639   {
640     GNUNET_break (0);
641     GNUNET_SERVER_client_disconnect (client);
642     return;
643   }
644   msg = (const struct GNUNET_SET_ElementMessage *) m;
645   el.size = ntohs (m->size) - sizeof *msg;
646   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
647               "client ins/rem element of size %u\n", el.size);
648   el.data = &msg[1];
649   if (GNUNET_MESSAGE_TYPE_SET_REMOVE == ntohs (m->type))
650     set->vt->remove (set->state, &el);
651   else
652     set->vt->add (set->state, &el);
653   GNUNET_SERVER_receive_done (client, GNUNET_OK);
654 }
655
656
657 /**
658  * Called when a client wants to evaluate a set operation with another peer.
659  *
660  * @param cls unused
661  * @param client client that sent the message
662  * @param m message sent by the client
663  */
664 static void
665 handle_client_evaluate (void *cls,
666                         struct GNUNET_SERVER_Client *client,
667                         const struct GNUNET_MessageHeader *m)
668 {
669   struct Set *set;
670   struct TunnelContext *tc;
671   struct GNUNET_MESH_Tunnel *tunnel;
672   struct GNUNET_SET_EvaluateMessage *msg;
673   struct OperationSpecification *spec;
674
675   set = set_get (client);
676   if (NULL == set)
677   {
678     GNUNET_break (0);
679     GNUNET_SERVER_client_disconnect (client);
680     return;
681   }
682
683   msg = (struct GNUNET_SET_EvaluateMessage *) m;
684   tc = GNUNET_new (struct TunnelContext);
685   spec = GNUNET_new (struct OperationSpecification);
686   spec->operation = set->operation;
687   spec->app_id = msg->app_id;
688   spec->salt = ntohl (msg->salt);
689   spec->peer = msg->target_peer;
690   spec->set = set;
691   spec->client_request_id = ntohl (msg->request_id);
692   spec->context_msg = GNUNET_MQ_extract_nested_mh (msg);
693   if (NULL != spec->context_msg)
694     spec->context_msg = GNUNET_copy_message (spec->context_msg);
695
696   tunnel = GNUNET_MESH_tunnel_create (mesh, tc, &msg->target_peer,
697                                       GNUNET_APPLICATION_TYPE_SET,
698                                       GNUNET_YES,
699                                       GNUNET_YES);
700
701   set->vt->evaluate (spec, tunnel, tc);
702
703   GNUNET_SERVER_receive_done (client, GNUNET_OK);
704 }
705
706
707 /**
708  * Handle an ack from a client.
709  *
710  * @param cls unused
711  * @param client the client
712  * @param m the message
713  */
714 static void
715 handle_client_ack (void *cls,
716                    struct GNUNET_SERVER_Client *client,
717                    const struct GNUNET_MessageHeader *m)
718 {
719   /* FIXME: implement */
720   GNUNET_SERVER_receive_done (client, GNUNET_OK);
721 }
722
723
724 /**
725  * Handle a request from the client to accept
726  * a set operation that came from a remote peer.
727  *
728  * @param cls unused
729  * @param client the client
730  * @param mh the message
731  */
732 static void
733 handle_client_cancel (void *cls,
734                       struct GNUNET_SERVER_Client *client,
735                       const struct GNUNET_MessageHeader *mh)
736 {
737   const struct GNUNET_SET_CancelMessage *msg =
738       (const struct GNUNET_SET_CancelMessage *) mh;
739   struct Set *set;
740
741   set = set_get (client);
742   if (NULL == set)
743   {
744     GNUNET_break (0);
745     GNUNET_SERVER_client_disconnect (client);
746     return;
747   }
748   /* FIXME: maybe cancel should return success/error code? */
749   set->vt->cancel (set->state, ntohl (msg->request_id));
750 }
751
752
753 /**
754  * Handle a request from the client to accept
755  * a set operation that came from a remote peer.
756  *
757  * @param cls unused
758  * @param client the client
759  * @param mh the message
760  */
761 static void
762 handle_client_accept (void *cls,
763                       struct GNUNET_SERVER_Client *client,
764                       const struct GNUNET_MessageHeader *mh)
765 {
766   struct Set *set;
767   struct Incoming *incoming;
768   struct GNUNET_SET_AcceptRejectMessage *msg = (struct GNUNET_SET_AcceptRejectMessage *) mh;
769
770   incoming = get_incoming (ntohl (msg->accept_reject_id));
771
772   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client accepting %u\n", ntohl (msg->accept_reject_id));
773
774   if (NULL == incoming)
775   {
776
777     GNUNET_break (0);
778     GNUNET_SERVER_client_disconnect (client);
779     return;
780   }
781
782   set = set_get (client);
783
784   if (NULL == set)
785   {
786     GNUNET_break (0);
787     GNUNET_SERVER_client_disconnect (client);
788     return;
789   }
790
791   incoming->spec->set = set;
792   incoming->spec->client_request_id = ntohl (msg->request_id);
793   set->vt->accept (incoming->spec, incoming->tunnel, incoming->tc);
794   /* tunnel ownership goes to operation */
795   incoming->tunnel = NULL;
796   incoming_destroy (incoming);
797   GNUNET_SERVER_receive_done (client, GNUNET_OK);
798 }
799
800
801 /**
802  * Called to clean up, after a shutdown has been requested.
803  *
804  * @param cls closure
805  * @param tc context information (why was this task triggered now)
806  */
807 static void
808 shutdown_task (void *cls,
809                const struct GNUNET_SCHEDULER_TaskContext *tc)
810 {
811   while (NULL != incoming_head)
812     incoming_destroy (incoming_head);
813
814   while (NULL != listeners_head)
815     listener_destroy (listeners_head);
816
817   while (NULL != sets_head)
818     set_destroy (sets_head);
819
820
821   /* it's important to destroy mesh at the end, as tunnels
822    * must be destroyed first! */
823   if (NULL != mesh)
824   {
825     GNUNET_MESH_disconnect (mesh);
826     mesh = NULL;
827   }
828
829   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "handled shutdown request\n");
830 }
831
832
833 /**
834  * Signature of the main function of a task.
835  *
836  * @param cls closure
837  * @param tc context information (why was this task triggered now)
838  */
839 static void
840 incoming_timeout_cb (void *cls,
841                      const struct GNUNET_SCHEDULER_TaskContext *tc)
842 {
843   struct Incoming *incoming = cls;
844
845   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "remote peer timed out\n");
846   incoming_destroy (incoming);
847 }
848
849
850 static void
851 handle_incoming_disconnect (struct OperationState *op_state)
852 {
853   struct Incoming *incoming = (struct Incoming *) op_state;
854   if (NULL == incoming->tunnel)
855     return;
856
857   incoming_destroy (incoming);
858 }
859
860
861 /**
862  * Method called whenever another peer has added us to a tunnel
863  * the other peer initiated.
864  * Only called (once) upon reception of data with a message type which was
865  * subscribed to in GNUNET_MESH_connect. A call to GNUNET_MESH_tunnel_destroy
866  * causes te tunnel to be ignored and no further notifications are sent about
867  * the same tunnel.
868  *
869  * @param cls closure
870  * @param tunnel new handle to the tunnel
871  * @param initiator peer that started the tunnel
872  * @param port Port this tunnel is for.
873  * @return initial tunnel context for the tunnel
874  *         (can be NULL -- that's not an error)
875  */
876 static void *
877 tunnel_new_cb (void *cls,
878                struct GNUNET_MESH_Tunnel *tunnel,
879                const struct GNUNET_PeerIdentity *initiator,
880                uint32_t port)
881 {
882   struct Incoming *incoming;
883   static const struct SetVT incoming_vt = {
884     .msg_handler = handle_incoming_msg,
885     .peer_disconnect = handle_incoming_disconnect
886   };
887
888   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new incoming tunnel\n");
889
890   GNUNET_assert (port == GNUNET_APPLICATION_TYPE_SET);
891   incoming = GNUNET_new (struct Incoming);
892   incoming->peer = *initiator;
893   incoming->tunnel = tunnel;
894   incoming->tc = GNUNET_new (struct TunnelContext);;
895   incoming->tc->vt = &incoming_vt;
896   incoming->tc->op = (struct OperationState *) incoming;
897   incoming->timeout_task = 
898       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES, incoming_timeout_cb, incoming);
899   GNUNET_CONTAINER_DLL_insert_tail (incoming_head, incoming_tail, incoming);
900
901   return incoming->tc;
902 }
903
904
905 /**
906  * Function called whenever a tunnel is destroyed.  Should clean up
907  * any associated state.
908  * GNUNET_MESH_tunnel_destroy. It must NOT call GNUNET_MESH_tunnel_destroy on
909  * the tunnel.
910  *
911  * @param cls closure (set from GNUNET_MESH_connect)
912  * @param tunnel connection to the other end (henceforth invalid)
913  * @param tunnel_ctx place where local state associated
914  *                   with the tunnel is stored
915  */
916 static void
917 tunnel_end_cb (void *cls,
918                const struct GNUNET_MESH_Tunnel *tunnel, void *tunnel_ctx)
919 {
920   struct TunnelContext *ctx = tunnel_ctx;
921
922   ctx->vt->peer_disconnect (ctx->op);
923   /* mesh will never call us with the context again! */
924   GNUNET_free (tunnel_ctx);
925 }
926
927
928 /**
929  * Functions with this signature are called whenever a message is
930  * received.
931  * 
932  * Each time the function must call GNUNET_MESH_receive_done on the tunnel
933  * in order to receive the next message. This doesn't need to be immediate:
934  * can be delayed if some processing is done on the message.
935  *
936  * @param cls Closure (set from GNUNET_MESH_connect).
937  * @param tunnel Connection to the other end.
938  * @param tunnel_ctx Place to store local state associated with the tunnel.
939  * @param message The actual message.
940  * 
941  * @return GNUNET_OK to keep the tunnel open,
942  *         GNUNET_SYSERR to close it (signal serious error).
943  */
944 static int
945 dispatch_p2p_message (void *cls,
946                       struct GNUNET_MESH_Tunnel *tunnel,
947                       void **tunnel_ctx,
948                       const struct GNUNET_MessageHeader *message)
949 {
950   struct TunnelContext *tc = *tunnel_ctx;
951   int ret;
952
953   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "dispatching mesh message (type: %u)\n",
954               ntohs (message->type));
955   /* FIXME: do this before or after the handler? */
956   GNUNET_MESH_receive_done (tunnel);
957   ret = tc->vt->msg_handler (tc->op, message);
958   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "handled mesh message (type: %u)\n",
959               ntohs (message->type));
960   return ret;
961 }
962
963
964 /**
965  * Function called by the service's run
966  * method to run service-specific setup code.
967  *
968  * @param cls closure
969  * @param server the initialized server
970  * @param cfg configuration to use
971  */
972 static void
973 run (void *cls, struct GNUNET_SERVER_Handle *server,
974      const struct GNUNET_CONFIGURATION_Handle *cfg)
975 {
976   static const struct GNUNET_SERVER_MessageHandler server_handlers[] = {
977     {handle_client_accept, NULL, GNUNET_MESSAGE_TYPE_SET_ACCEPT,
978         sizeof (struct GNUNET_SET_AcceptRejectMessage)},
979     {handle_client_ack, NULL, GNUNET_MESSAGE_TYPE_SET_ACK, 0},
980     {handle_client_add_remove, NULL, GNUNET_MESSAGE_TYPE_SET_ADD, 0},
981     {handle_client_create, NULL, GNUNET_MESSAGE_TYPE_SET_CREATE,
982         sizeof (struct GNUNET_SET_CreateMessage)},
983     {handle_client_iterate, NULL, GNUNET_MESSAGE_TYPE_SET_ITER_REQUEST,
984         sizeof (struct GNUNET_MessageHeader)},
985     {handle_client_evaluate, NULL, GNUNET_MESSAGE_TYPE_SET_EVALUATE, 0},
986     {handle_client_listen, NULL, GNUNET_MESSAGE_TYPE_SET_LISTEN,
987         sizeof (struct GNUNET_SET_ListenMessage)},
988     {handle_client_reject, NULL, GNUNET_MESSAGE_TYPE_SET_REJECT,
989         sizeof (struct GNUNET_SET_AcceptRejectMessage)},
990     {handle_client_add_remove, NULL, GNUNET_MESSAGE_TYPE_SET_REMOVE, 0},
991     {handle_client_cancel, NULL, GNUNET_MESSAGE_TYPE_SET_REMOVE,
992         sizeof (struct GNUNET_SET_CancelMessage)},
993     {NULL, NULL, 0, 0}
994   };
995   static const struct GNUNET_MESH_MessageHandler mesh_handlers[] = {
996     {dispatch_p2p_message, GNUNET_MESSAGE_TYPE_SET_P2P_OPERATION_REQUEST, 0},
997     {dispatch_p2p_message, GNUNET_MESSAGE_TYPE_SET_P2P_IBF, 0},
998     {dispatch_p2p_message, GNUNET_MESSAGE_TYPE_SET_P2P_ELEMENTS, 0},
999     {dispatch_p2p_message, GNUNET_MESSAGE_TYPE_SET_P2P_DONE, 0},
1000     {dispatch_p2p_message, GNUNET_MESSAGE_TYPE_SET_P2P_ELEMENT_REQUESTS, 0},
1001     {dispatch_p2p_message, GNUNET_MESSAGE_TYPE_SET_P2P_SE, 0},
1002     {NULL, 0, 0}
1003   };
1004   static const uint32_t mesh_ports[] = {GNUNET_APPLICATION_TYPE_SET, 0};
1005
1006   configuration = cfg;
1007   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
1008                                 &shutdown_task, NULL);
1009   GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
1010   GNUNET_SERVER_add_handlers (server, server_handlers);
1011
1012   mesh = GNUNET_MESH_connect (cfg, NULL, tunnel_new_cb, tunnel_end_cb,
1013                               mesh_handlers, mesh_ports);
1014   if (NULL == mesh)
1015   {
1016     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "could not connect to mesh\n");
1017     return;
1018   }
1019
1020   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "started\n");
1021 }
1022
1023
1024 /**
1025  * The main function for the set service.
1026  *
1027  * @param argc number of arguments from the command line
1028  * @param argv command line arguments
1029  * @return 0 ok, 1 on error
1030  */
1031 int
1032 main (int argc, char *const *argv)
1033 {
1034   int ret;
1035   ret = GNUNET_SERVICE_run (argc, argv, "set",
1036                             GNUNET_SERVICE_OPTION_NONE, &run, NULL);
1037   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "exit (%d)\n", GNUNET_OK != ret);
1038   return (GNUNET_OK == ret) ? 0 : 1;
1039 }
1040