- IBF alpha adjusted
[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  * Iterator over hash map entries.
265  *
266  * @param cls closure
267  * @param key current key code
268  * @param value value in the hash map
269  * @return GNUNET_YES if we should continue to
270  *         iterate,
271  *         GNUNET_NO if not.
272  */
273 static int
274 destroy_elements_iterator (void *cls,
275                            const struct GNUNET_HashCode * key,
276                            void *value)
277 {
278   struct ElementEntry *ee = value;
279
280   GNUNET_free (ee);
281   return GNUNET_YES;
282 }
283
284
285 /**
286  * Destroy a set, and free all resources associated with it.
287  *
288  * @param set the set to destroy
289  */
290 static void
291 set_destroy (struct Set *set)
292 {
293   /* If the client is not dead yet, destroy it.
294    * The client's destroy callback will destroy the set again.
295    * We do this so that the tunnel end handler still has a valid set handle
296    * to destroy. */
297   if (NULL != set->client)
298   {
299     struct GNUNET_SERVER_Client *client = set->client;
300     set->client = NULL;
301     GNUNET_SERVER_client_disconnect (client);
302     return;
303   }
304   GNUNET_assert (NULL != set->state);
305   set->vt->destroy_set (set->state);
306   set->state = NULL;
307   if (NULL != set->client_mq)
308   {
309     GNUNET_MQ_destroy (set->client_mq);
310     set->client_mq = NULL;
311   }
312   if (NULL != set->iter)
313   {
314     GNUNET_CONTAINER_multihashmap_iterator_destroy (set->iter);
315     set->iter = NULL;
316   }
317   GNUNET_CONTAINER_DLL_remove (sets_head, sets_tail, set);
318   if (NULL != set->elements)
319   {
320     GNUNET_CONTAINER_multihashmap_iterate (set->elements,
321                                            destroy_elements_iterator, NULL);
322     GNUNET_CONTAINER_multihashmap_destroy (set->elements);
323     set->elements = NULL;
324   }
325   GNUNET_free (set);
326 }
327
328
329 /**
330  * Clean up after a client after it is
331  * disconnected (either by us or by itself)
332  *
333  * @param cls closure, unused
334  * @param client the client to clean up after
335  */
336 static void
337 handle_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
338 {
339   struct Set *set;
340   struct Listener *listener;
341
342   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client disconnected, cleaning up\n");
343
344   set = set_get (client);
345   if (NULL != set)
346   {
347     set->client = NULL;
348     set_destroy (set);
349     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "(client's set destroyed)\n");
350   }
351   listener = listener_get (client);
352   if (NULL != listener)
353   {
354     listener->client = NULL;
355     listener_destroy (listener);
356     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "(client's listener destroyed)\n");
357   }
358 }
359
360
361 /**
362  * Destroy an incoming request from a remote peer
363  *
364  * @param incoming remote request to destroy
365  */
366 static void
367 incoming_destroy (struct Incoming *incoming)
368 {
369   GNUNET_CONTAINER_DLL_remove (incoming_head, incoming_tail, incoming);
370   if (NULL != incoming->tunnel)
371   {
372     struct GNUNET_MESH_Tunnel *t = incoming->tunnel;
373     incoming->tunnel = NULL;
374     GNUNET_MESH_tunnel_destroy (t);
375     return;
376   }
377   GNUNET_free (incoming);
378 }
379
380
381 static struct Listener *
382 listener_get_by_target (enum GNUNET_SET_OperationType op,
383                         const struct GNUNET_HashCode *app_id)
384 {
385   struct Listener *l;
386
387   for (l = listeners_head; NULL != l; l = l->next)
388   {
389     if (l->operation != op)
390       continue;
391     if (0 != GNUNET_CRYPTO_hash_cmp (app_id, &l->app_id))
392       continue;
393     return l;
394   }
395   return NULL;
396 }
397
398
399 /**
400  * Suggest the given request to the listener,
401  * who can accept or reject the request.
402  *
403  * @param incoming the incoming peer with the request to suggest
404  * @param listener the listener to suggest the request to
405  */
406 static void
407 incoming_suggest (struct Incoming *incoming, struct Listener *listener)
408 {
409   struct GNUNET_MQ_Envelope *mqm;
410   struct GNUNET_SET_RequestMessage *cmsg;
411
412   GNUNET_assert (0 == incoming->suggest_id);
413   GNUNET_assert (NULL != incoming->spec);
414   incoming->suggest_id = suggest_id++;
415
416   GNUNET_SCHEDULER_cancel (incoming->timeout_task);
417   mqm = GNUNET_MQ_msg_nested_mh (cmsg, GNUNET_MESSAGE_TYPE_SET_REQUEST,
418                                  incoming->spec->context_msg);
419   GNUNET_assert (NULL != mqm);
420   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "suggesting request with accept id %u\n",
421               incoming->suggest_id);
422   cmsg->accept_id = htonl (incoming->suggest_id);
423   cmsg->peer_id = incoming->spec->peer;
424   GNUNET_MQ_send (listener->client_mq, mqm);
425
426 }
427
428
429 /**
430  * Handle a request for a set operation from
431  * another peer.
432  *
433  * @param op the operation state
434  * @param mh the received message
435  * @return GNUNET_OK if the tunnel should be kept alive,
436  *         GNUNET_SYSERR to destroy the tunnel
437  */
438 static int
439 handle_incoming_msg (struct OperationState *op,
440                      const struct GNUNET_MessageHeader *mh)
441 {
442   struct Incoming *incoming = (struct Incoming *) op;
443   const struct OperationRequestMessage *msg = (const struct OperationRequestMessage *) mh;
444   struct Listener *listener;
445   struct OperationSpecification *spec;
446
447   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got op request\n");
448
449   if (GNUNET_MESSAGE_TYPE_SET_P2P_OPERATION_REQUEST != ntohs (mh->type))
450   {
451     GNUNET_break_op (0);
452     return GNUNET_SYSERR;
453   }
454
455   if (NULL != incoming->spec)
456   {
457     /* double operation request */
458     GNUNET_break_op (0);
459     return GNUNET_SYSERR;
460   }
461
462   spec = GNUNET_new (struct OperationSpecification);
463   spec->context_msg = GNUNET_MQ_extract_nested_mh (msg);
464   if (NULL != spec->context_msg)
465     spec->context_msg = GNUNET_copy_message (spec->context_msg);
466   spec->operation = ntohl (msg->operation);
467   spec->app_id = msg->app_id;
468   spec->salt = ntohl (msg->salt);
469   spec->peer = incoming->peer;
470
471   incoming->spec = spec;
472
473   if ( (NULL != spec->context_msg) &&
474        (ntohs (spec->context_msg->size) > GNUNET_SET_CONTEXT_MESSAGE_MAX_SIZE) )
475   {
476     GNUNET_break_op (0);
477     return GNUNET_SYSERR;
478   }
479
480   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "received P2P operation request (op %u, app %s)\n",
481               ntohl (msg->operation), GNUNET_h2s (&msg->app_id));
482   listener = listener_get_by_target (ntohl (msg->operation), &msg->app_id);
483   if (NULL == listener)
484   {
485     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
486                 "no listener matches incoming request, waiting with timeout\n");
487     return GNUNET_OK;
488   }
489   incoming_suggest (incoming, listener);
490   return GNUNET_OK;
491 }
492
493
494 static void
495 send_client_element (struct Set *set)
496 {
497   int ret;
498   struct ElementEntry *ee;
499   struct GNUNET_MQ_Envelope *ev;
500
501   GNUNET_assert (NULL != set->iter);
502   ret = GNUNET_CONTAINER_multihashmap_iterator_next (set->iter, NULL, (const void **) &ee);
503   if (GNUNET_NO == ret)
504   {
505     ev = GNUNET_MQ_msg_header (GNUNET_MESSAGE_TYPE_SET_ITER_DONE);
506   }
507   else
508   {
509     struct GNUNET_SET_IterResponseMessage *msg;
510
511     GNUNET_assert (NULL != ee);
512     ev = GNUNET_MQ_msg_extra (msg, ee->element.size, GNUNET_MESSAGE_TYPE_SET_ITER_ELEMENT);
513     memcpy (&msg[1], ee->element.data, ee->element.size);
514     msg->element_type = ee->element.type;
515   }
516   GNUNET_MQ_send (set->client_mq, ev);
517 }
518
519
520 /**
521  * Called when a client wants to iterate the elements of a set.
522  *
523  * @param cls unused
524  * @param client client that sent the message
525  * @param m message sent by the client
526  */
527 static void
528 handle_client_iterate (void *cls,
529                        struct GNUNET_SERVER_Client *client,
530                        const struct GNUNET_MessageHeader *m)
531 {
532   struct Set *set;
533   
534   set = set_get (client);
535   if (NULL == set)
536   {
537     GNUNET_break (0);
538     GNUNET_SERVER_client_disconnect (client);
539     return;
540   }
541
542   if (NULL != set->iter)
543   {
544     GNUNET_break (0);
545     GNUNET_SERVER_client_disconnect (client);
546     return;
547   }
548   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "iterating union set with %u elements\n",
549               GNUNET_CONTAINER_multihashmap_size (set->elements));
550   GNUNET_SERVER_receive_done (client, GNUNET_OK);
551   set->iter = GNUNET_CONTAINER_multihashmap_iterator_create (set->elements);
552   send_client_element (set);
553 }
554
555
556 /**
557  * Called when a client wants to create a new set.
558  *
559  * @param cls unused
560  * @param client client that sent the message
561  * @param m message sent by the client
562  */
563 static void
564 handle_client_create (void *cls,
565                       struct GNUNET_SERVER_Client *client,
566                       const struct GNUNET_MessageHeader *m)
567 {
568   struct GNUNET_SET_CreateMessage *msg = (struct GNUNET_SET_CreateMessage *) m;
569   struct Set *set;
570
571   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client created new set (operation %u)\n",
572               ntohs (msg->operation));
573
574   if (NULL != set_get (client))
575   {
576     GNUNET_break (0);
577     GNUNET_SERVER_client_disconnect (client);
578     return;
579   }
580
581   set = GNUNET_new (struct Set);
582
583   switch (ntohs (msg->operation))
584   {
585     case GNUNET_SET_OPERATION_INTERSECTION:
586       // FIXME
587       break;
588     case GNUNET_SET_OPERATION_UNION:
589       set->vt = _GSS_union_vt ();
590       break;
591     default:
592       GNUNET_free (set);
593       GNUNET_break (0);
594       GNUNET_SERVER_client_disconnect (client);
595       return;
596   }
597
598   set->state = set->vt->create ();
599   set->elements = GNUNET_CONTAINER_multihashmap_create (1, GNUNET_YES);
600   set->client = client;
601   set->client_mq = GNUNET_MQ_queue_for_server_client (client);
602   GNUNET_CONTAINER_DLL_insert (sets_head, sets_tail, set);
603   GNUNET_SERVER_receive_done (client, GNUNET_OK);
604 }
605
606
607 /**
608  * Called when a client wants to create a new listener.
609  *
610  * @param cls unused
611  * @param client client that sent the message
612  * @param m message sent by the client
613  */
614 static void
615 handle_client_listen (void *cls,
616                       struct GNUNET_SERVER_Client *client,
617                       const struct GNUNET_MessageHeader *m)
618 {
619   struct GNUNET_SET_ListenMessage *msg = (struct GNUNET_SET_ListenMessage *) m;
620   struct Listener *listener;
621   struct Incoming *incoming;
622
623   if (NULL != listener_get (client))
624   {
625     GNUNET_break (0);
626     GNUNET_SERVER_client_disconnect (client);
627     return;
628   }
629   listener = GNUNET_new (struct Listener);
630   listener->client = client;
631   listener->client_mq = GNUNET_MQ_queue_for_server_client (client);
632   listener->app_id = msg->app_id;
633   listener->operation = ntohl (msg->operation);
634   GNUNET_CONTAINER_DLL_insert_tail (listeners_head, listeners_tail, listener);
635   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new listener created (op %u, app %s)\n",
636               listener->operation, GNUNET_h2s (&listener->app_id));
637   for (incoming = incoming_head; NULL != incoming; incoming = incoming->next)
638   {
639     if (NULL == incoming->spec)
640     {
641       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "request has no spec yet\n");
642       continue;
643     }
644     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "considering (op: %u, app: %s, suggest: %u)\n",
645                 incoming->spec->operation, GNUNET_h2s (&incoming->spec->app_id), incoming->suggest_id);
646
647     if (0 != incoming->suggest_id)
648       continue;
649     if (listener->operation != incoming->spec->operation)
650       continue;
651     if (0 != GNUNET_CRYPTO_hash_cmp (&listener->app_id, &incoming->spec->app_id))
652       continue;
653     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "request suggested\n");
654     incoming_suggest (incoming, listener);
655   }
656   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "considered all incoming requests\n");
657   GNUNET_SERVER_receive_done (client, GNUNET_OK);
658 }
659
660
661 /**
662  * Called when the client wants to reject an operation
663  * request from another peer.
664  *
665  * @param cls unused
666  * @param client client that sent the message
667  * @param m message sent by the client
668  */
669 static void
670 handle_client_reject (void *cls,
671                       struct GNUNET_SERVER_Client *client,
672                       const struct GNUNET_MessageHeader *m)
673 {
674   struct Incoming *incoming;
675   const struct GNUNET_SET_AcceptRejectMessage *msg;
676
677   msg = (const struct GNUNET_SET_AcceptRejectMessage *) m;
678   GNUNET_break (0 == ntohl (msg->request_id));
679
680   incoming = get_incoming (ntohl (msg->accept_reject_id));
681   if (NULL == incoming)
682   {
683     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
684     return;
685   }
686   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "peer request rejected by client\n");
687   GNUNET_MESH_tunnel_destroy (incoming->tunnel);
688   GNUNET_SERVER_receive_done (client, GNUNET_OK);
689 }
690
691
692 /**
693  * Called when a client wants to add an element to a
694  * set it inhabits.
695  *
696  * @param cls unused
697  * @param client client that sent the message
698  * @param m message sent by the client
699  */
700 static void
701 handle_client_add_remove (void *cls,
702                           struct GNUNET_SERVER_Client *client,
703                           const struct GNUNET_MessageHeader *m)
704 {
705   struct Set *set;
706   const struct GNUNET_SET_ElementMessage *msg;
707   struct GNUNET_SET_Element el;
708   struct ElementEntry *ee;
709
710   set = set_get (client);
711   if (NULL == set)
712   {
713     GNUNET_break (0);
714     GNUNET_SERVER_client_disconnect (client);
715     return;
716   }
717   GNUNET_SERVER_receive_done (client, GNUNET_OK);
718   msg = (const struct GNUNET_SET_ElementMessage *) m;
719   el.size = ntohs (m->size) - sizeof *msg;
720   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
721               "client ins/rem element of size %u\n", el.size);
722   el.data = &msg[1];
723   if (GNUNET_MESSAGE_TYPE_SET_REMOVE == ntohs (m->type))
724   {
725     struct GNUNET_HashCode hash;
726
727     GNUNET_CRYPTO_hash (el.data, el.size, &hash);
728     ee = GNUNET_CONTAINER_multihashmap_get (set->elements, &hash);
729     if (NULL == ee)
730     {
731       GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "client tried to remove non-existing element\n");
732       return;
733     }
734     if (GNUNET_YES == ee->removed)
735     {
736       GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "client tried to remove element twice\n");
737       return;
738     }
739     ee->removed = GNUNET_YES;
740     ee->generation_removed = set->current_generation;
741     set->vt->remove (set->state, ee);
742   }
743   else
744   {
745     struct ElementEntry *ee_dup;
746
747     ee = GNUNET_malloc (el.size + sizeof *ee);
748     ee->element.size = el.size;
749     memcpy (&ee[1], el.data, el.size);
750     ee->element.data = &ee[1];
751     ee->generation_added = set->current_generation;
752     ee->remote = GNUNET_NO;
753     GNUNET_CRYPTO_hash (ee->element.data, el.size, &ee->element_hash);
754     ee_dup = GNUNET_CONTAINER_multihashmap_get (set->elements,
755                                                 &ee->element_hash);
756     if (NULL != ee_dup)
757     {
758       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "element inserted twice, ignoring\n");
759       GNUNET_free (ee);
760       return;
761     }
762     GNUNET_CONTAINER_multihashmap_put (set->elements, &ee->element_hash, ee,
763                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
764     set->vt->add (set->state, ee);
765   }
766 }
767
768
769 /**
770  * Called when a client wants to evaluate a set operation with another peer.
771  *
772  * @param cls unused
773  * @param client client that sent the message
774  * @param m message sent by the client
775  */
776 static void
777 handle_client_evaluate (void *cls,
778                         struct GNUNET_SERVER_Client *client,
779                         const struct GNUNET_MessageHeader *m)
780 {
781   struct Set *set;
782   struct TunnelContext *tc;
783   struct GNUNET_MESH_Tunnel *tunnel;
784   struct GNUNET_SET_EvaluateMessage *msg;
785   struct OperationSpecification *spec;
786
787   set = set_get (client);
788   if (NULL == set)
789   {
790     GNUNET_break (0);
791     GNUNET_SERVER_client_disconnect (client);
792     return;
793   }
794
795   msg = (struct GNUNET_SET_EvaluateMessage *) m;
796   tc = GNUNET_new (struct TunnelContext);
797   spec = GNUNET_new (struct OperationSpecification);
798   spec->operation = set->operation;
799   spec->app_id = msg->app_id;
800   spec->salt = ntohl (msg->salt);
801   spec->peer = msg->target_peer;
802   spec->set = set;
803   spec->client_request_id = ntohl (msg->request_id);
804   spec->context_msg = GNUNET_MQ_extract_nested_mh (msg);
805   if (NULL != spec->context_msg)
806     spec->context_msg = GNUNET_copy_message (spec->context_msg);
807
808   tunnel = GNUNET_MESH_tunnel_create (mesh, tc, &msg->target_peer,
809                                       GNUNET_APPLICATION_TYPE_SET,
810                                       GNUNET_YES,
811                                       GNUNET_YES);
812
813   set->vt->evaluate (spec, tunnel, tc);
814
815   GNUNET_SERVER_receive_done (client, GNUNET_OK);
816 }
817
818
819 /**
820  * Handle an ack from a client.
821  *
822  * @param cls unused
823  * @param client the client
824  * @param m the message
825  */
826 static void
827 handle_client_iter_ack (void *cls,
828                    struct GNUNET_SERVER_Client *client,
829                    const struct GNUNET_MessageHeader *m)
830 {
831   struct Set *set;
832   
833   set = set_get (client);
834   if (NULL == set)
835   {
836     GNUNET_break (0);
837     GNUNET_SERVER_client_disconnect (client);
838     return;
839   }
840
841   if (NULL == set->iter)
842   {
843     GNUNET_break (0);
844     GNUNET_SERVER_client_disconnect (client);
845     return;
846   }
847
848   GNUNET_SERVER_receive_done (client, GNUNET_OK);
849   send_client_element (set);
850 }
851
852
853 /**
854  * Handle a request from the client to accept
855  * a set operation that came from a remote peer.
856  *
857  * @param cls unused
858  * @param client the client
859  * @param mh the message
860  */
861 static void
862 handle_client_cancel (void *cls,
863                       struct GNUNET_SERVER_Client *client,
864                       const struct GNUNET_MessageHeader *mh)
865 {
866   const struct GNUNET_SET_CancelMessage *msg =
867       (const struct GNUNET_SET_CancelMessage *) mh;
868   struct Set *set;
869
870   set = set_get (client);
871   if (NULL == set)
872   {
873     GNUNET_break (0);
874     GNUNET_SERVER_client_disconnect (client);
875     return;
876   }
877   /* FIXME: maybe cancel should return success/error code? */
878   set->vt->cancel (set->state, ntohl (msg->request_id));
879 }
880
881
882 /**
883  * Handle a request from the client to accept
884  * a set operation that came from a remote peer.
885  *
886  * @param cls unused
887  * @param client the client
888  * @param mh the message
889  */
890 static void
891 handle_client_accept (void *cls,
892                       struct GNUNET_SERVER_Client *client,
893                       const struct GNUNET_MessageHeader *mh)
894 {
895   struct Set *set;
896   struct Incoming *incoming;
897   struct GNUNET_SET_AcceptRejectMessage *msg = (struct GNUNET_SET_AcceptRejectMessage *) mh;
898
899   incoming = get_incoming (ntohl (msg->accept_reject_id));
900
901   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client accepting %u\n", ntohl (msg->accept_reject_id));
902
903   if (NULL == incoming)
904   {
905
906     GNUNET_break (0);
907     GNUNET_SERVER_client_disconnect (client);
908     return;
909   }
910
911   set = set_get (client);
912
913   if (NULL == set)
914   {
915     GNUNET_break (0);
916     GNUNET_SERVER_client_disconnect (client);
917     return;
918   }
919
920   incoming->spec->set = set;
921   incoming->spec->client_request_id = ntohl (msg->request_id);
922   set->vt->accept (incoming->spec, incoming->tunnel, incoming->tc);
923   /* tunnel ownership goes to operation */
924   incoming->tunnel = NULL;
925   incoming_destroy (incoming);
926   GNUNET_SERVER_receive_done (client, GNUNET_OK);
927 }
928
929
930 /**
931  * Called to clean up, after a shutdown has been requested.
932  *
933  * @param cls closure
934  * @param tc context information (why was this task triggered now)
935  */
936 static void
937 shutdown_task (void *cls,
938                const struct GNUNET_SCHEDULER_TaskContext *tc)
939 {
940   while (NULL != incoming_head)
941     incoming_destroy (incoming_head);
942
943   while (NULL != listeners_head)
944     listener_destroy (listeners_head);
945
946   while (NULL != sets_head)
947     set_destroy (sets_head);
948
949
950   /* it's important to destroy mesh at the end, as tunnels
951    * must be destroyed first! */
952   if (NULL != mesh)
953   {
954     GNUNET_MESH_disconnect (mesh);
955     mesh = NULL;
956   }
957
958   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "handled shutdown request\n");
959 }
960
961
962 /**
963  * Signature of the main function of a task.
964  *
965  * @param cls closure
966  * @param tc context information (why was this task triggered now)
967  */
968 static void
969 incoming_timeout_cb (void *cls,
970                      const struct GNUNET_SCHEDULER_TaskContext *tc)
971 {
972   struct Incoming *incoming = cls;
973
974   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "remote peer timed out\n");
975   incoming_destroy (incoming);
976 }
977
978
979 static void
980 handle_incoming_disconnect (struct OperationState *op_state)
981 {
982   struct Incoming *incoming = (struct Incoming *) op_state;
983   if (NULL == incoming->tunnel)
984     return;
985
986   incoming_destroy (incoming);
987 }
988
989
990 /**
991  * Method called whenever another peer has added us to a tunnel
992  * the other peer initiated.
993  * Only called (once) upon reception of data with a message type which was
994  * subscribed to in GNUNET_MESH_connect. A call to GNUNET_MESH_tunnel_destroy
995  * causes te tunnel to be ignored and no further notifications are sent about
996  * the same tunnel.
997  *
998  * @param cls closure
999  * @param tunnel new handle to the tunnel
1000  * @param initiator peer that started the tunnel
1001  * @param port Port this tunnel is for.
1002  * @return initial tunnel context for the tunnel
1003  *         (can be NULL -- that's not an error)
1004  */
1005 static void *
1006 tunnel_new_cb (void *cls,
1007                struct GNUNET_MESH_Tunnel *tunnel,
1008                const struct GNUNET_PeerIdentity *initiator,
1009                uint32_t port)
1010 {
1011   struct Incoming *incoming;
1012   static const struct SetVT incoming_vt = {
1013     .msg_handler = handle_incoming_msg,
1014     .peer_disconnect = handle_incoming_disconnect
1015   };
1016
1017   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new incoming tunnel\n");
1018
1019   GNUNET_assert (port == GNUNET_APPLICATION_TYPE_SET);
1020   incoming = GNUNET_new (struct Incoming);
1021   incoming->peer = *initiator;
1022   incoming->tunnel = tunnel;
1023   incoming->tc = GNUNET_new (struct TunnelContext);;
1024   incoming->tc->vt = &incoming_vt;
1025   incoming->tc->op = (struct OperationState *) incoming;
1026   incoming->timeout_task = 
1027       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES, incoming_timeout_cb, incoming);
1028   GNUNET_CONTAINER_DLL_insert_tail (incoming_head, incoming_tail, incoming);
1029
1030   return incoming->tc;
1031 }
1032
1033
1034 /**
1035  * Function called whenever a tunnel is destroyed.  Should clean up
1036  * any associated state.
1037  * GNUNET_MESH_tunnel_destroy. It must NOT call GNUNET_MESH_tunnel_destroy on
1038  * the tunnel.
1039  *
1040  * @param cls closure (set from GNUNET_MESH_connect)
1041  * @param tunnel connection to the other end (henceforth invalid)
1042  * @param tunnel_ctx place where local state associated
1043  *                   with the tunnel is stored
1044  */
1045 static void
1046 tunnel_end_cb (void *cls,
1047                const struct GNUNET_MESH_Tunnel *tunnel, void *tunnel_ctx)
1048 {
1049   struct TunnelContext *ctx = tunnel_ctx;
1050
1051   ctx->vt->peer_disconnect (ctx->op);
1052   /* mesh will never call us with the context again! */
1053   GNUNET_free (tunnel_ctx);
1054 }
1055
1056
1057 /**
1058  * Functions with this signature are called whenever a message is
1059  * received.
1060  * 
1061  * Each time the function must call GNUNET_MESH_receive_done on the tunnel
1062  * in order to receive the next message. This doesn't need to be immediate:
1063  * can be delayed if some processing is done on the message.
1064  *
1065  * @param cls Closure (set from GNUNET_MESH_connect).
1066  * @param tunnel Connection to the other end.
1067  * @param tunnel_ctx Place to store local state associated with the tunnel.
1068  * @param message The actual message.
1069  * 
1070  * @return GNUNET_OK to keep the tunnel open,
1071  *         GNUNET_SYSERR to close it (signal serious error).
1072  */
1073 static int
1074 dispatch_p2p_message (void *cls,
1075                       struct GNUNET_MESH_Tunnel *tunnel,
1076                       void **tunnel_ctx,
1077                       const struct GNUNET_MessageHeader *message)
1078 {
1079   struct TunnelContext *tc = *tunnel_ctx;
1080   int ret;
1081
1082   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "dispatching mesh message (type: %u)\n",
1083               ntohs (message->type));
1084   /* do this before the handler, as the handler might kill the tunnel */
1085   GNUNET_MESH_receive_done (tunnel);
1086   ret = tc->vt->msg_handler (tc->op, message);
1087   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "handled mesh message (type: %u)\n",
1088               ntohs (message->type));
1089   return ret;
1090 }
1091
1092
1093 /**
1094  * Function called by the service's run
1095  * method to run service-specific setup code.
1096  *
1097  * @param cls closure
1098  * @param server the initialized server
1099  * @param cfg configuration to use
1100  */
1101 static void
1102 run (void *cls, struct GNUNET_SERVER_Handle *server,
1103      const struct GNUNET_CONFIGURATION_Handle *cfg)
1104 {
1105   static const struct GNUNET_SERVER_MessageHandler server_handlers[] = {
1106     {handle_client_accept, NULL, GNUNET_MESSAGE_TYPE_SET_ACCEPT,
1107         sizeof (struct GNUNET_SET_AcceptRejectMessage)},
1108     {handle_client_iter_ack, NULL, GNUNET_MESSAGE_TYPE_SET_ITER_ACK, 0},
1109     {handle_client_add_remove, NULL, GNUNET_MESSAGE_TYPE_SET_ADD, 0},
1110     {handle_client_create, NULL, GNUNET_MESSAGE_TYPE_SET_CREATE,
1111         sizeof (struct GNUNET_SET_CreateMessage)},
1112     {handle_client_iterate, NULL, GNUNET_MESSAGE_TYPE_SET_ITER_REQUEST,
1113         sizeof (struct GNUNET_MessageHeader)},
1114     {handle_client_evaluate, NULL, GNUNET_MESSAGE_TYPE_SET_EVALUATE, 0},
1115     {handle_client_listen, NULL, GNUNET_MESSAGE_TYPE_SET_LISTEN,
1116         sizeof (struct GNUNET_SET_ListenMessage)},
1117     {handle_client_reject, NULL, GNUNET_MESSAGE_TYPE_SET_REJECT,
1118         sizeof (struct GNUNET_SET_AcceptRejectMessage)},
1119     {handle_client_add_remove, NULL, GNUNET_MESSAGE_TYPE_SET_REMOVE, 0},
1120     {handle_client_cancel, NULL, GNUNET_MESSAGE_TYPE_SET_REMOVE,
1121         sizeof (struct GNUNET_SET_CancelMessage)},
1122     {NULL, NULL, 0, 0}
1123   };
1124   static const struct GNUNET_MESH_MessageHandler mesh_handlers[] = {
1125     {dispatch_p2p_message, GNUNET_MESSAGE_TYPE_SET_P2P_OPERATION_REQUEST, 0},
1126     {dispatch_p2p_message, GNUNET_MESSAGE_TYPE_SET_P2P_IBF, 0},
1127     {dispatch_p2p_message, GNUNET_MESSAGE_TYPE_SET_P2P_ELEMENTS, 0},
1128     {dispatch_p2p_message, GNUNET_MESSAGE_TYPE_SET_P2P_DONE, 0},
1129     {dispatch_p2p_message, GNUNET_MESSAGE_TYPE_SET_P2P_DIE, 0},
1130     {dispatch_p2p_message, GNUNET_MESSAGE_TYPE_SET_P2P_ELEMENT_REQUESTS, 0},
1131     {dispatch_p2p_message, GNUNET_MESSAGE_TYPE_SET_P2P_SE, 0},
1132     {NULL, 0, 0}
1133   };
1134   static const uint32_t mesh_ports[] = {GNUNET_APPLICATION_TYPE_SET, 0};
1135
1136   configuration = cfg;
1137   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
1138                                 &shutdown_task, NULL);
1139   GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
1140   GNUNET_SERVER_add_handlers (server, server_handlers);
1141
1142   mesh = GNUNET_MESH_connect (cfg, NULL, tunnel_new_cb, tunnel_end_cb,
1143                               mesh_handlers, mesh_ports);
1144   if (NULL == mesh)
1145   {
1146     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "could not connect to mesh\n");
1147     return;
1148   }
1149
1150   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "started\n");
1151 }
1152
1153
1154 /**
1155  * The main function for the set service.
1156  *
1157  * @param argc number of arguments from the command line
1158  * @param argv command line arguments
1159  * @return 0 ok, 1 on error
1160  */
1161 int
1162 main (int argc, char *const *argv)
1163 {
1164   int ret;
1165   ret = GNUNET_SERVICE_run (argc, argv, "set",
1166                             GNUNET_SERVICE_OPTION_NONE, &run, NULL);
1167   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "exit (%d)\n", GNUNET_OK != ret);
1168   return (GNUNET_OK == ret) ? 0 : 1;
1169 }
1170