- more multipart fun
[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 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 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  * State of an operation where the peer has connected to us, but is not yet
32  * evaluating a set operation.  Once the peer has sent a concrete request, and
33  * the client has accepted or rejected it, this information will be deleted
34  * and replaced by the real set operation state.
35  */
36 struct OperationState
37 {
38   /**
39    * The identity of the requesting peer.  Needs to
40    * be stored here as the op spec might not have been created yet.
41    */
42   struct GNUNET_PeerIdentity peer;
43
44   /**
45    * Unique request id for the request from
46    * a remote peer, sent to the client, which will
47    * accept or reject the request.
48    * Set to '0' iff the request has not been
49    * suggested yet.
50    */
51   uint32_t suggest_id;
52
53   /**
54    * Timeout task, if the incoming peer has not been accepted
55    * after the timeout, it will be disconnected.
56    */
57   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
58 };
59
60
61 /**
62  * A listener is inhabited by a client, and
63  * waits for evaluation requests from remote peers.
64  */
65 struct Listener
66 {
67   /**
68    * Listeners are held in a doubly linked list.
69    */
70   struct Listener *next;
71
72   /**
73    * Listeners are held in a doubly linked list.
74    */
75   struct Listener *prev;
76
77   /**
78    * Client that owns the listener.
79    * Only one client may own a listener.
80    */
81   struct GNUNET_SERVER_Client *client;
82
83   /**
84    * Message queue for the client
85    */
86   struct GNUNET_MQ_Handle *client_mq;
87
88   /**
89    * The type of the operation.
90    */
91   enum GNUNET_SET_OperationType operation;
92
93   /**
94    * Application ID for the operation, used to distinguish
95    * multiple operations of the same type with the same peer.
96    */
97   struct GNUNET_HashCode app_id;
98 };
99
100
101 /**
102  * Configuration of our local peer.
103  */
104 static const struct GNUNET_CONFIGURATION_Handle *configuration;
105
106 /**
107  * Handle to the mesh service, used
108  * to listen for and connect to remote peers.
109  */
110 static struct GNUNET_MESH_Handle *mesh;
111
112 /**
113  * Sets are held in a doubly linked list.
114  */
115 static struct Set *sets_head;
116
117 /**
118  * Sets are held in a doubly linked list.
119  */
120 static struct Set *sets_tail;
121
122 /**
123  * Listeners are held in a doubly linked list.
124  */
125 static struct Listener *listeners_head;
126
127 /**
128  * Listeners are held in a doubly linked list.
129  */
130 static struct Listener *listeners_tail;
131
132 /**
133  * Incoming sockets from remote peers are
134  * held in a doubly linked list.
135  */
136 static struct Operation *incoming_head;
137
138 /**
139  * Incoming sockets from remote peers are
140  * held in a doubly linked list.
141  */
142 static struct Operation *incoming_tail;
143
144 /**
145  * Counter for allocating unique IDs for clients,
146  * used to identify incoming operation requests from remote peers,
147  * that the client can choose to accept or refuse.
148  */
149 static uint32_t suggest_id = 1;
150
151
152 /**
153  * Get set that is owned by the given client, if any.
154  *
155  * @param client client to look for
156  * @return set that the client owns, NULL if the client
157  *         does not own a set
158  */
159 static struct Set *
160 set_get (struct GNUNET_SERVER_Client *client)
161 {
162   struct Set *set;
163
164   for (set = sets_head; NULL != set; set = set->next)
165     if (set->client == client)
166       return set;
167   return NULL;
168 }
169
170
171 /**
172  * Get the listener associated with the given client, if any.
173  *
174  * @param client the client
175  * @return listener associated with the client, NULL
176  *         if there isn't any
177  */
178 static struct Listener *
179 listener_get (struct GNUNET_SERVER_Client *client)
180 {
181   struct Listener *listener;
182
183   for (listener = listeners_head; NULL != listener; listener = listener->next)
184     if (listener->client == client)
185       return listener;
186   return NULL;
187 }
188
189
190 /**
191  * Get the incoming socket associated with the given id.
192  *
193  * @param id id to look for
194  * @return the incoming socket associated with the id,
195  *         or NULL if there is none
196  */
197 static struct Operation *
198 get_incoming (uint32_t id)
199 {
200   struct Operation *op;
201
202   for (op = incoming_head; NULL != op; op = op->next)
203     if (op->state->suggest_id == id)
204       return op;
205   return NULL;
206 }
207
208
209 /**
210  * Destroy a listener, free all resources associated with it.
211  *
212  * @param listener listener to destroy
213  */
214 static void
215 listener_destroy (struct Listener *listener)
216 {
217   /* If the client is not dead yet, destroy it.
218    * The client's destroy callback will destroy the listener again. */
219   if (NULL != listener->client)
220   {
221     struct GNUNET_SERVER_Client *client = listener->client;
222     listener->client = NULL;
223     GNUNET_SERVER_client_disconnect (client);
224     return;
225   }
226   if (NULL != listener->client_mq)
227   {
228     GNUNET_MQ_destroy (listener->client_mq);
229     listener->client_mq = NULL;
230   }
231   GNUNET_CONTAINER_DLL_remove (listeners_head, listeners_tail, listener);
232   GNUNET_free (listener);
233 }
234
235
236 /**
237  * Collect and destroy elements that are not needed anymore, because
238  * their lifetime (as determined by their generation) does not overlap with any active
239  * set operation.
240  *
241  * We hereby replace the old element hashmap with a new one, instead of removing elements.
242  */
243 void
244 collect_generation_garbage (struct Set *set)
245 {
246   struct GNUNET_CONTAINER_MultiHashMapIterator *iter;
247   struct ElementEntry *ee;
248   struct GNUNET_CONTAINER_MultiHashMap *new_elements;
249   int res;
250   struct Operation *op;
251
252   new_elements = GNUNET_CONTAINER_multihashmap_create (1, GNUNET_NO);
253   iter = GNUNET_CONTAINER_multihashmap_iterator_create (set->elements);
254   while (GNUNET_OK ==
255          (res = GNUNET_CONTAINER_multihashmap_iterator_next (iter, NULL, (const void **) &ee)))
256   {
257     if (GNUNET_NO == ee->removed)
258       goto still_needed;
259     for (op = set->ops_head; NULL != op; op = op->next)
260       if ((op->generation_created >= ee->generation_added) &&
261           (op->generation_created < ee->generation_removed))
262         goto still_needed;
263     GNUNET_free (ee);
264     continue;
265 still_needed:
266     // we don't expect collisions, thus the replace option
267     GNUNET_CONTAINER_multihashmap_put (new_elements, &ee->element_hash, ee,
268                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
269   }
270   GNUNET_CONTAINER_multihashmap_iterator_destroy (iter);
271   GNUNET_CONTAINER_multihashmap_destroy (set->elements);
272   set->elements = new_elements;
273 }
274
275
276 /**
277  * Destroy the given operation.  Call the implementation-specific cancel function
278  * of the operation.  Disconnects from the remote peer.
279  * Does not disconnect the client, as there may be multiple operations per set.
280  *
281  * @param op operation to destroy
282  */
283 void
284 _GSS_operation_destroy (struct Operation *op)
285 {
286   struct Set *set;
287   struct GNUNET_MESH_Channel *channel;
288
289   if (NULL == op->vt)
290     return;
291
292   set = op->spec->set;
293
294   GNUNET_assert (GNUNET_NO == op->is_incoming);
295   GNUNET_assert (NULL != op->spec);
296   GNUNET_CONTAINER_DLL_remove (op->spec->set->ops_head,
297                                op->spec->set->ops_tail,
298                                op);
299
300   op->vt->cancel (op);
301   op->vt = NULL;
302
303   if (NULL != op->spec)
304   {
305     if (NULL != op->spec->context_msg)
306     {
307       GNUNET_free (op->spec->context_msg);
308       op->spec->context_msg = NULL;
309     }
310     GNUNET_free (op->spec);
311     op->spec = NULL;
312   }
313
314   if (NULL != op->mq)
315   {
316     GNUNET_MQ_destroy (op->mq);
317     op->mq = NULL;
318   }
319
320   if (NULL != (channel = op->channel))
321   {
322     op->channel = NULL;
323     GNUNET_MESH_channel_destroy (channel);
324   }
325
326   collect_generation_garbage (set);
327
328   /* We rely on the channel end handler to free 'op'. When 'op->channel' was NULL,
329    * there was a channel end handler that will free 'op' on the call stack. */
330 }
331
332
333 /**
334  * Iterator over hash map entries to free
335  * element entries.
336  *
337  * @param cls closure
338  * @param key current key code
339  * @param value a `struct ElementEntry *` to be free'd
340  * @return #GNUNET_YES if we should continue to
341  *         iterate,
342  *         #GNUNET_NO if not.
343  */
344 static int
345 destroy_elements_iterator (void *cls,
346                            const struct GNUNET_HashCode * key,
347                            void *value)
348 {
349   struct ElementEntry *ee = value;
350
351   GNUNET_free (ee);
352   return GNUNET_YES;
353 }
354
355
356 /**
357  * Destroy a set, and free all resources associated with it.
358  *
359  * @param set the set to destroy
360  */
361 static void
362 set_destroy (struct Set *set)
363 {
364   /* If the client is not dead yet, destroy it.
365    * The client's destroy callback will destroy the set again.
366    * We do this so that the channel end handler still has a valid set handle
367    * to destroy. */
368   if (NULL != set->client)
369   {
370     struct GNUNET_SERVER_Client *client = set->client;
371     set->client = NULL;
372     GNUNET_SERVER_client_disconnect (client);
373     return;
374   }
375   GNUNET_assert (NULL != set->state);
376   while (NULL != set->ops_head)
377     _GSS_operation_destroy (set->ops_head);
378   set->vt->destroy_set (set->state);
379   set->state = NULL;
380   if (NULL != set->client_mq)
381   {
382     GNUNET_MQ_destroy (set->client_mq);
383     set->client_mq = NULL;
384   }
385   if (NULL != set->iter)
386   {
387     GNUNET_CONTAINER_multihashmap_iterator_destroy (set->iter);
388     set->iter = NULL;
389   }
390   GNUNET_CONTAINER_DLL_remove (sets_head, sets_tail, set);
391   if (NULL != set->elements)
392   {
393     // free all elements in the hashtable, before destroying the table
394     GNUNET_CONTAINER_multihashmap_iterate (set->elements,
395                                            destroy_elements_iterator, NULL);
396     GNUNET_CONTAINER_multihashmap_destroy (set->elements);
397     set->elements = NULL;
398   }
399   GNUNET_free (set);
400 }
401
402
403 /**
404  * Clean up after a client has disconnected
405  *
406  * @param cls closure, unused
407  * @param client the client to clean up after
408  */
409 static void
410 handle_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
411 {
412   struct Set *set;
413   struct Listener *listener;
414
415   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
416               "client disconnected, cleaning up\n");
417   set = set_get (client);
418   if (NULL != set)
419   {
420     set->client = NULL;
421     set_destroy (set);
422     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
423                 "(client's set destroyed)\n");
424   }
425   listener = listener_get (client);
426   if (NULL != listener)
427   {
428     listener->client = NULL;
429     listener_destroy (listener);
430     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
431                 "(client's listener destroyed)\n");
432   }
433 }
434
435
436 /**
437  * Destroy an incoming request from a remote peer
438  *
439  * @param incoming remote request to destroy
440  */
441 static void
442 incoming_destroy (struct Operation *incoming)
443 {
444   GNUNET_CONTAINER_DLL_remove (incoming_head, incoming_tail, incoming);
445   if (GNUNET_SCHEDULER_NO_TASK != incoming->state->timeout_task)
446   {
447     GNUNET_SCHEDULER_cancel (incoming->state->timeout_task);
448     incoming->state->timeout_task = GNUNET_SCHEDULER_NO_TASK;
449   }
450   GNUNET_free (incoming->state);
451 }
452
453
454 /**
455  * remove & free state of the operation from the incoming list
456  *
457  * @param incoming the element to remove
458  */
459 static void
460 incoming_retire (struct Operation *incoming)
461 {
462   incoming->is_incoming = GNUNET_NO;
463   GNUNET_free (incoming->state);
464   incoming->state = NULL;
465   GNUNET_CONTAINER_DLL_remove (incoming_head, incoming_tail, incoming);
466 }
467
468
469 /**
470  * Find a listener that is interested in the given operation type
471  * and application id.
472  *
473  * @param op operation type to look for
474  * @param app_id application id to look for
475  * @return a matching listener, or NULL if no listener matches the
476  *         given operation and application id
477  */
478 static struct Listener *
479 listener_get_by_target (enum GNUNET_SET_OperationType op,
480                         const struct GNUNET_HashCode *app_id)
481 {
482   struct Listener *l;
483
484   for (l = listeners_head; NULL != l; l = l->next)
485   {
486     if (l->operation != op)
487       continue;
488     if (0 != GNUNET_CRYPTO_hash_cmp (app_id, &l->app_id))
489       continue;
490     return l;
491   }
492   return NULL;
493 }
494
495
496 /**
497  * Suggest the given request to the listener. The listening client can then
498  * accept or reject the remote request.
499  *
500  * @param incoming the incoming peer with the request to suggest
501  * @param listener the listener to suggest the request to
502  */
503 static void
504 incoming_suggest (struct Operation *incoming, struct Listener *listener)
505 {
506   struct GNUNET_MQ_Envelope *mqm;
507   struct GNUNET_SET_RequestMessage *cmsg;
508
509   GNUNET_assert (NULL != incoming->spec);
510   GNUNET_assert (0 == incoming->state->suggest_id);
511   incoming->state->suggest_id = suggest_id++;
512
513   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != incoming->state->timeout_task);
514   GNUNET_SCHEDULER_cancel (incoming->state->timeout_task);
515   incoming->state->timeout_task = GNUNET_SCHEDULER_NO_TASK;
516
517   mqm = GNUNET_MQ_msg_nested_mh (cmsg, GNUNET_MESSAGE_TYPE_SET_REQUEST,
518                                  incoming->spec->context_msg);
519   GNUNET_assert (NULL != mqm);
520   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "suggesting request with accept id %u\n",
521               incoming->state->suggest_id);
522   cmsg->accept_id = htonl (incoming->state->suggest_id);
523   cmsg->peer_id = incoming->spec->peer;
524   GNUNET_MQ_send (listener->client_mq, mqm);
525 }
526
527
528 /**
529  * Handle a request for a set operation from
530  * another peer.
531  *
532  * This msg is expected as the first and only msg handled through the
533  * non-operation bound virtual table, acceptance of this operation replaces
534  * our virtual table and subsequent msgs would be routed differently.
535  *
536  * @param op the operation state
537  * @param mh the received message
538  * @return #GNUNET_OK if the channel should be kept alive,
539  *         #GNUNET_SYSERR to destroy the channel
540  */
541 static int
542 handle_incoming_msg (struct Operation *op,
543                      const struct GNUNET_MessageHeader *mh)
544 {
545   const struct OperationRequestMessage *msg = (const struct OperationRequestMessage *) mh;
546   struct Listener *listener;
547   struct OperationSpecification *spec;
548
549   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got op request\n");
550
551   if (GNUNET_MESSAGE_TYPE_SET_P2P_OPERATION_REQUEST != ntohs (mh->type))
552   {
553     GNUNET_break_op (0);
554     return GNUNET_SYSERR;
555   }
556
557   /* double operation request */
558   if (NULL != op->spec)
559   {
560     GNUNET_break_op (0);
561     return GNUNET_SYSERR;
562   }
563
564   spec = GNUNET_new (struct OperationSpecification);
565   spec->context_msg = GNUNET_MQ_extract_nested_mh (msg);
566   // for simplicity we just backup the context msg instead of rebuilding it later on
567   if (NULL != spec->context_msg)
568     spec->context_msg = GNUNET_copy_message (spec->context_msg);
569   spec->operation = ntohl (msg->operation);
570   spec->app_id = msg->app_id;
571   spec->salt = ntohl (msg->salt);
572   spec->peer = op->state->peer;
573   spec->remote_element_count = ntohl (msg->element_count);
574
575   op->spec = spec;
576
577   if ( (NULL != spec->context_msg) &&
578        (ntohs (spec->context_msg->size) > GNUNET_SET_CONTEXT_MESSAGE_MAX_SIZE) )
579   {
580     GNUNET_break_op (0);
581     return GNUNET_SYSERR;
582   }
583
584   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "received P2P operation request (op %u, app %s)\n",
585               ntohl (msg->operation), GNUNET_h2s (&msg->app_id));
586   listener = listener_get_by_target (ntohl (msg->operation), &msg->app_id);
587   if (NULL == listener)
588   {
589     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
590                 "no listener matches incoming request, waiting with timeout\n");
591     return GNUNET_OK;
592   }
593   incoming_suggest (op, listener);
594   return GNUNET_OK;
595 }
596
597
598 /**
599  * Send the next element of a set to the set's client.  The next element is given by
600  * the set's current hashmap iterator.  The set's iterator will be set to NULL if there
601  * are no more elements in the set.  The caller must ensure that the set's iterator is
602  * valid.
603  *
604  * @param set set that should send its next element to its client
605  */
606 static void
607 send_client_element (struct Set *set)
608 {
609   int ret;
610   struct ElementEntry *ee;
611   struct GNUNET_MQ_Envelope *ev;
612
613   GNUNET_assert (NULL != set->iter);
614   ret = GNUNET_CONTAINER_multihashmap_iterator_next (set->iter, NULL, (const void **) &ee);
615   if (GNUNET_NO == ret)
616   {
617     ev = GNUNET_MQ_msg_header (GNUNET_MESSAGE_TYPE_SET_ITER_DONE);
618     GNUNET_CONTAINER_multihashmap_iterator_destroy (set->iter);
619     set->iter = NULL;
620   }
621   else
622   {
623     struct GNUNET_SET_IterResponseMessage *msg;
624
625     GNUNET_assert (NULL != ee);
626     ev = GNUNET_MQ_msg_extra (msg, ee->element.size, GNUNET_MESSAGE_TYPE_SET_ITER_ELEMENT);
627     memcpy (&msg[1], ee->element.data, ee->element.size);
628     msg->element_type = ee->element.type;
629   }
630   GNUNET_MQ_send (set->client_mq, ev);
631 }
632
633
634 /**
635  * Called when a client wants to iterate the elements of a set.
636  *
637  * @param cls unused
638  * @param client client that sent the message
639  * @param m message sent by the client
640  */
641 static void
642 handle_client_iterate (void *cls,
643                        struct GNUNET_SERVER_Client *client,
644                        const struct GNUNET_MessageHeader *m)
645 {
646   struct Set *set;
647
648   // iterate over a non existing set
649   set = set_get (client);
650   if (NULL == set)
651   {
652     GNUNET_break (0);
653     GNUNET_SERVER_client_disconnect (client);
654     return;
655   }
656
657   // only one concurrent iterate-action per set
658   if (NULL != set->iter)
659   {
660     GNUNET_break (0);
661     GNUNET_SERVER_client_disconnect (client);
662     return;
663   }
664   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "iterating union set with %u elements\n",
665               GNUNET_CONTAINER_multihashmap_size (set->elements));
666   GNUNET_SERVER_receive_done (client, GNUNET_OK);
667   set->iter = GNUNET_CONTAINER_multihashmap_iterator_create (set->elements);
668   send_client_element (set);
669 }
670
671
672 /**
673  * Called when a client wants to create a new set.
674  *
675  * @param cls unused
676  * @param client client that sent the message
677  * @param m message sent by the client
678  */
679 static void
680 handle_client_create_set (void *cls,
681                           struct GNUNET_SERVER_Client *client,
682                           const struct GNUNET_MessageHeader *m)
683 {
684   const struct GNUNET_SET_CreateMessage *msg;
685   struct Set *set;
686
687   msg = (const struct GNUNET_SET_CreateMessage *) m;
688   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
689               "client created new set (operation %u)\n",
690               ntohs (msg->operation));
691
692   // max. one set per client!
693   if (NULL != set_get (client))
694   {
695     GNUNET_break (0);
696     GNUNET_SERVER_client_disconnect (client);
697     return;
698   }
699
700   set = GNUNET_new (struct Set);
701
702   switch (ntohs (msg->operation))
703   {
704   case GNUNET_SET_OPERATION_INTERSECTION:
705     // FIXME: implement intersection vt
706     // set->vt = _GSS_intersection_vt ();
707     break;
708   case GNUNET_SET_OPERATION_UNION:
709     set->vt = _GSS_union_vt ();
710     break;
711   default:
712     GNUNET_free (set);
713     GNUNET_break (0);
714     GNUNET_SERVER_client_disconnect (client);
715     return;
716   }
717
718   set->state = set->vt->create ();
719   set->elements = GNUNET_CONTAINER_multihashmap_create (1, GNUNET_YES);
720   set->client = client;
721   set->client_mq = GNUNET_MQ_queue_for_server_client (client);
722   GNUNET_CONTAINER_DLL_insert (sets_head, sets_tail, set);
723   GNUNET_SERVER_receive_done (client, GNUNET_OK);
724 }
725
726
727 /**
728  * Called when a client wants to create a new listener.
729  *
730  * @param cls unused
731  * @param client client that sent the message
732  * @param m message sent by the client
733  */
734 static void
735 handle_client_listen (void *cls,
736                       struct GNUNET_SERVER_Client *client,
737                       const struct GNUNET_MessageHeader *m)
738 {
739   const struct GNUNET_SET_ListenMessage *msg;
740   struct Listener *listener;
741   struct Operation *op;
742
743   msg = (const struct GNUNET_SET_ListenMessage *) m;
744   /* max. one per client! */
745   if (NULL != listener_get (client))
746   {
747     GNUNET_break (0);
748     GNUNET_SERVER_client_disconnect (client);
749     return;
750   }
751
752   listener = GNUNET_new (struct Listener);
753   listener->client = client;
754   listener->client_mq = GNUNET_MQ_queue_for_server_client (client);
755   listener->app_id = msg->app_id;
756   listener->operation = ntohl (msg->operation);
757   GNUNET_CONTAINER_DLL_insert_tail (listeners_head, listeners_tail, listener);
758   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
759               "new listener created (op %u, app %s)\n",
760               listener->operation,
761               GNUNET_h2s (&listener->app_id));
762
763   /* check for incoming requests the listener is interested in */
764   for (op = incoming_head; NULL != op; op = op->next)
765   {
766     if (NULL == op->spec)
767     {
768       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
769                   "request has no spec yet\n");
770       continue;
771     }
772     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
773                 "considering (op: %u, app: %s, suggest: %u)\n",
774                 op->spec->operation,
775                 GNUNET_h2s (&op->spec->app_id),
776                 op->state->suggest_id);
777
778     /* don't consider the incoming request if it has been already suggested to a listener */
779     if (0 != op->state->suggest_id)
780       continue;
781     if (listener->operation != op->spec->operation)
782       continue;
783     if (0 != GNUNET_CRYPTO_hash_cmp (&listener->app_id, &op->spec->app_id))
784       continue;
785     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
786                 "request suggested\n");
787     incoming_suggest (op, listener);
788   }
789   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
790               "considered all incoming requests\n");
791   GNUNET_SERVER_receive_done (client, GNUNET_OK);
792 }
793
794
795 /**
796  * Called when the listening client rejects an operation
797  * request by another peer.
798  *
799  * @param cls unused
800  * @param client client that sent the message
801  * @param m message sent by the client
802  */
803 static void
804 handle_client_reject (void *cls,
805                       struct GNUNET_SERVER_Client *client,
806                       const struct GNUNET_MessageHeader *m)
807 {
808   struct Operation *incoming;
809   const struct GNUNET_SET_AcceptRejectMessage *msg;
810
811   msg = (const struct GNUNET_SET_AcceptRejectMessage *) m;
812   GNUNET_break (0 == ntohl (msg->request_id));
813
814   // no matching incoming operation for this reject
815   incoming = get_incoming (ntohl (msg->accept_reject_id));
816   if (NULL == incoming)
817   {
818     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
819     return;
820   }
821   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
822               "peer request rejected by client\n");
823
824   GNUNET_MESH_channel_destroy (incoming->channel);
825   //channel destruction handler called immediately upon destruction
826   GNUNET_SERVER_receive_done (client, GNUNET_OK);
827 }
828
829
830 /**
831  * Called when a client wants to add/remove an element to/from a
832  * set it inhabits.
833  *
834  * @param cls unused
835  * @param client client that sent the message
836  * @param m message sent by the client
837  */
838 static void
839 handle_client_add_remove (void *cls,
840                           struct GNUNET_SERVER_Client *client,
841                           const struct GNUNET_MessageHeader *m)
842 {
843   struct Set *set;
844   const struct GNUNET_SET_ElementMessage *msg;
845   struct GNUNET_SET_Element el;
846   struct ElementEntry *ee;
847
848   // client without a set requested an operation
849   set = set_get (client);
850   if (NULL == set)
851   {
852     GNUNET_break (0);
853     GNUNET_SERVER_client_disconnect (client);
854     return;
855   }
856   GNUNET_SERVER_receive_done (client, GNUNET_OK);
857   msg = (const struct GNUNET_SET_ElementMessage *) m;
858   el.size = ntohs (m->size) - sizeof *msg;
859   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
860               "client ins/rem element of size %u\n", el.size);
861   el.data = &msg[1];
862   if (GNUNET_MESSAGE_TYPE_SET_REMOVE == ntohs (m->type))
863   {
864     struct GNUNET_HashCode hash;
865
866     GNUNET_CRYPTO_hash (el.data, el.size, &hash);
867     ee = GNUNET_CONTAINER_multihashmap_get (set->elements, &hash);
868     if (NULL == ee)
869     {
870       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
871                   "client tried to remove non-existing element\n");
872       return;
873     }
874     if (GNUNET_YES == ee->removed)
875     {
876       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
877                   "client tried to remove element twice\n");
878       return;
879     }
880     ee->removed = GNUNET_YES;
881     ee->generation_removed = set->current_generation;
882     set->vt->remove (set->state, ee);
883   }
884   else
885   {
886     struct ElementEntry *ee_dup;
887
888     ee = GNUNET_malloc (el.size + sizeof *ee);
889     ee->element.size = el.size;
890     memcpy (&ee[1], el.data, el.size);
891     ee->element.data = &ee[1];
892     ee->generation_added = set->current_generation;
893     ee->remote = GNUNET_NO;
894     GNUNET_CRYPTO_hash (ee->element.data, el.size, &ee->element_hash);
895     ee_dup = GNUNET_CONTAINER_multihashmap_get (set->elements,
896                                                 &ee->element_hash);
897     if (NULL != ee_dup)
898     {
899       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
900                   "element inserted twice, ignoring\n");
901       GNUNET_free (ee);
902       return;
903     }
904     GNUNET_CONTAINER_multihashmap_put (set->elements, &ee->element_hash, ee,
905                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
906     set->vt->add (set->state, ee);
907   }
908 }
909
910
911 /**
912  * Called when a client wants to evaluate a set operation with another peer.
913  *
914  * @param cls unused
915  * @param client client that sent the message
916  * @param m message sent by the client
917  */
918 static void
919 handle_client_evaluate (void *cls,
920                         struct GNUNET_SERVER_Client *client,
921                         const struct GNUNET_MessageHeader *m)
922 {
923   struct Set *set;
924   const struct GNUNET_SET_EvaluateMessage *msg;
925   struct OperationSpecification *spec;
926   struct Operation *op;
927
928   set = set_get (client);
929   if (NULL == set)
930   {
931     GNUNET_break (0);
932     GNUNET_SERVER_client_disconnect (client);
933     return;
934   }
935
936   msg = (const struct GNUNET_SET_EvaluateMessage *) m;
937   spec = GNUNET_new (struct OperationSpecification);
938   spec->operation = set->operation;
939   spec->app_id = msg->app_id;
940   spec->salt = ntohl (msg->salt);
941   spec->peer = msg->target_peer;
942   spec->set = set;
943   spec->result_mode = ntohs (msg->result_mode);
944   spec->client_request_id = ntohl (msg->request_id);
945   spec->context_msg = GNUNET_MQ_extract_nested_mh (msg);
946
947   // for simplicity we just backup the context msg instead of rebuilding it later on
948   if (NULL != spec->context_msg)
949     spec->context_msg = GNUNET_copy_message (spec->context_msg);
950
951   op = GNUNET_new (struct Operation);
952   op->spec = spec;
953   op->generation_created = set->current_generation++;
954   op->vt = set->vt;
955   GNUNET_CONTAINER_DLL_insert (set->ops_head, set->ops_tail, op);
956
957   op->channel = GNUNET_MESH_channel_create (mesh, op, &msg->target_peer,
958                                           GNUNET_APPLICATION_TYPE_SET,
959                                           GNUNET_MESH_OPTION_RELIABLE);
960
961   op->mq = GNUNET_MESH_mq_create (op->channel);
962
963   set->vt->evaluate (op);
964   GNUNET_SERVER_receive_done (client, GNUNET_OK);
965 }
966
967
968 /**
969  * Handle an ack from a client, and send the next element.
970  *
971  * @param cls unused
972  * @param client the client
973  * @param m the message
974  */
975 static void
976 handle_client_iter_ack (void *cls,
977                    struct GNUNET_SERVER_Client *client,
978                    const struct GNUNET_MessageHeader *m)
979 {
980   struct Set *set;
981
982   // client without a set requested an operation
983   set = set_get (client);
984   if (NULL == set)
985   {
986     GNUNET_break (0);
987     GNUNET_SERVER_client_disconnect (client);
988     return;
989   }
990
991   // client sent an ack, but we were not expecting one
992   if (NULL == set->iter)
993   {
994     GNUNET_break (0);
995     GNUNET_SERVER_client_disconnect (client);
996     return;
997   }
998
999   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1000   send_client_element (set);
1001 }
1002
1003
1004 /**
1005  * Handle a request from the client to
1006  * cancel a running set operation.
1007  *
1008  * @param cls unused
1009  * @param client the client
1010  * @param mh the message
1011  */
1012 static void
1013 handle_client_cancel (void *cls,
1014                       struct GNUNET_SERVER_Client *client,
1015                       const struct GNUNET_MessageHeader *mh)
1016 {
1017   const struct GNUNET_SET_CancelMessage *msg =
1018       (const struct GNUNET_SET_CancelMessage *) mh;
1019   struct Set *set;
1020   struct Operation *op;
1021   int found;
1022
1023   // client without a set requested an operation
1024   set = set_get (client);
1025   if (NULL == set)
1026   {
1027     GNUNET_break (0);
1028     GNUNET_SERVER_client_disconnect (client);
1029     return;
1030   }
1031   found = GNUNET_NO;
1032   for (op = set->ops_head; NULL != op; op = op->next)
1033   {
1034     if (op->spec->client_request_id == msg->request_id)
1035     {
1036       found = GNUNET_YES;
1037       break;
1038     }
1039   }
1040
1041   if (GNUNET_NO == found)
1042   {
1043     GNUNET_break (0);
1044     GNUNET_SERVER_client_disconnect (client);
1045     return;
1046   }
1047
1048   _GSS_operation_destroy (op);
1049 }
1050
1051
1052 /**
1053  * Handle a request from the client to accept
1054  * a set operation that came from a remote peer.
1055  * We forward the accept to the associated operation for handling
1056  *
1057  * @param cls unused
1058  * @param client the client
1059  * @param mh the message
1060  */
1061 static void
1062 handle_client_accept (void *cls,
1063                       struct GNUNET_SERVER_Client *client,
1064                       const struct GNUNET_MessageHeader *mh)
1065 {
1066   struct Set *set;
1067   const struct GNUNET_SET_AcceptRejectMessage *msg;
1068   struct Operation *op;
1069
1070   msg = (const struct GNUNET_SET_AcceptRejectMessage *) mh;
1071   op = get_incoming (ntohl (msg->accept_reject_id));
1072
1073   // incoming operation does not exist
1074   if (NULL == op)
1075   {
1076     GNUNET_break (0);
1077     GNUNET_SERVER_client_disconnect (client);
1078     return;
1079   }
1080
1081   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1082               "client accepting %u\n",
1083               ntohl (msg->accept_reject_id));
1084
1085   GNUNET_assert (GNUNET_YES == op->is_incoming);
1086
1087   // client without a set requested an operation
1088   set = set_get (client);
1089
1090   if (NULL == set)
1091   {
1092     GNUNET_break (0);
1093     GNUNET_SERVER_client_disconnect (client);
1094     return;
1095   }
1096
1097   op->spec->set = set;
1098
1099   incoming_retire (op);
1100
1101   GNUNET_assert (NULL != op->spec->set);
1102   GNUNET_assert (NULL != op->spec->set->vt);
1103
1104   GNUNET_CONTAINER_DLL_insert (set->ops_head, set->ops_tail, op);
1105
1106   op->spec->client_request_id = ntohl (msg->request_id);
1107   op->spec->result_mode = ntohs (msg->result_mode);
1108   op->generation_created = set->current_generation++;
1109   op->vt = op->spec->set->vt;
1110   GNUNET_assert (NULL != op->vt->accept);
1111   set->vt->accept (op);
1112   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1113 }
1114
1115
1116 /**
1117  * Called to clean up, after a shutdown has been requested.
1118  *
1119  * @param cls closure
1120  * @param tc context information (why was this task triggered now)
1121  */
1122 static void
1123 shutdown_task (void *cls,
1124                const struct GNUNET_SCHEDULER_TaskContext *tc)
1125 {
1126   while (NULL != incoming_head)
1127     incoming_destroy (incoming_head);
1128
1129   while (NULL != listeners_head)
1130     listener_destroy (listeners_head);
1131
1132   while (NULL != sets_head)
1133     set_destroy (sets_head);
1134
1135   /* it's important to destroy mesh at the end, as all channels
1136    * must be destroyed before the mesh handle! */
1137   if (NULL != mesh)
1138   {
1139     GNUNET_MESH_disconnect (mesh);
1140     mesh = NULL;
1141   }
1142   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1143               "handled shutdown request\n");
1144 }
1145
1146
1147 /**
1148  * Timeout happens iff:
1149  *  - we suggested an operation to our listener,
1150  *    but did not receive a response in time
1151  *  - we got the channel from a peer but no #GNUNET_MESSAGE_TYPE_SET_P2P_OPERATION_REQUEST
1152  *  - shutdown (obviously)
1153  *
1154  * @param cls channel context
1155  * @param tc context information (why was this task triggered now)
1156  */
1157 static void
1158 incoming_timeout_cb (void *cls,
1159                      const struct GNUNET_SCHEDULER_TaskContext *tc)
1160 {
1161   struct Operation *incoming = cls;
1162
1163   incoming->state->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1164   GNUNET_assert (GNUNET_YES == incoming->is_incoming);
1165   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1166     return;
1167   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1168               "remote peer timed out\n");
1169   incoming_destroy (incoming);
1170 }
1171
1172
1173 /**
1174  * Terminates an incoming operation in case we have not yet received an
1175  * operation request. Called by the channel destruction handler.
1176  *
1177  * @param op the channel context
1178  */
1179 static void
1180 handle_incoming_disconnect (struct Operation *op)
1181 {
1182   GNUNET_assert (GNUNET_YES == op->is_incoming);
1183   if (NULL == op->channel)
1184     return;
1185   incoming_destroy (op);
1186 }
1187
1188
1189 /**
1190  * Method called whenever another peer has added us to a channel
1191  * the other peer initiated.
1192  * Only called (once) upon reception of data with a message type which was
1193  * subscribed to in GNUNET_MESH_connect().
1194  *
1195  * The channel context represents the operation itself and gets added to a DLL,
1196  * from where it gets looked up when our local listener client responds
1197  * to a proposed/suggested operation or connects and associates with this operation.
1198  *
1199  * @param cls closure
1200  * @param channel new handle to the channel
1201  * @param initiator peer that started the channel
1202  * @param port Port this channel is for.
1203  * @param options Unused.
1204  * @return initial channel context for the channel
1205  *         (can be NULL -- that's not an error)
1206  */
1207 static void *
1208 channel_new_cb (void *cls,
1209                struct GNUNET_MESH_Channel *channel,
1210                const struct GNUNET_PeerIdentity *initiator,
1211                uint32_t port, enum GNUNET_MESH_ChannelOption options)
1212 {
1213   struct Operation *incoming;
1214   static const struct SetVT incoming_vt = {
1215     .msg_handler = handle_incoming_msg,
1216     .peer_disconnect = handle_incoming_disconnect
1217   };
1218
1219   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1220               "new incoming channel\n");
1221
1222   if (GNUNET_APPLICATION_TYPE_SET != port)
1223   {
1224     GNUNET_break (0);
1225     GNUNET_MESH_channel_destroy (channel);
1226     return NULL;
1227   }
1228
1229   incoming = GNUNET_new (struct Operation);
1230   incoming->is_incoming = GNUNET_YES;
1231   incoming->state = GNUNET_new (struct OperationState);
1232   incoming->state->peer = *initiator;
1233   incoming->channel = channel;
1234   incoming->mq = GNUNET_MESH_mq_create (incoming->channel);
1235   incoming->vt = &incoming_vt;
1236   incoming->state->timeout_task =
1237       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
1238                                     &incoming_timeout_cb, incoming);
1239   GNUNET_CONTAINER_DLL_insert_tail (incoming_head, incoming_tail, incoming);
1240
1241   return incoming;
1242 }
1243
1244
1245 /**
1246  * Function called whenever a channel is destroyed.  Should clean up
1247  * any associated state.  It must NOT call
1248  * GNUNET_MESH_channel_destroy() on the channel.
1249  *
1250  * The peer_disconnect function is part of a a virtual table set initially either
1251  * when a peer creates a new channel with us (channel_new_cb), or once we create
1252  * a new channel ourselves (evaluate).
1253  *
1254  * Once we know the exact type of operation (union/intersection), the vt is
1255  * replaced with an operation specific instance (_GSS_[op]_vt).
1256  *
1257  * @param cls closure (set from GNUNET_MESH_connect())
1258  * @param channel connection to the other end (henceforth invalid)
1259  * @param channel_ctx place where local state associated
1260  *                   with the channel is stored
1261  */
1262 static void
1263 channel_end_cb (void *cls,
1264                const struct GNUNET_MESH_Channel *channel, void *channel_ctx)
1265 {
1266   struct Operation *op = channel_ctx;
1267
1268   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1269               "channel end cb called\n");
1270   op->channel = NULL;
1271   if (NULL != op->vt)
1272     op->vt->peer_disconnect (op);
1273   /* mesh will never call us with the context again! */
1274   GNUNET_free (channel_ctx);
1275 }
1276
1277
1278 /**
1279  * Functions with this signature are called whenever any message is
1280  * received via the mesh channel.
1281  *
1282  * The msg_handler is a virtual table set in initially either when a peer
1283  * creates a new channel with us (channel_new_cb), or once we create a new channel
1284  * ourselves (evaluate).
1285  *
1286  * Once we know the exact type of operation (union/intersection), the vt is
1287  * replaced with an operation specific instance (_GSS_[op]_vt).
1288  *
1289  * @param cls Closure (set from GNUNET_MESH_connect()).
1290  * @param channel Connection to the other end.
1291  * @param channel_ctx Place to store local state associated with the channel.
1292  * @param message The actual message.
1293  * @return #GNUNET_OK to keep the channel open,
1294  *         #GNUNET_SYSERR to close it (signal serious error).
1295  */
1296 static int
1297 dispatch_p2p_message (void *cls,
1298                       struct GNUNET_MESH_Channel *channel,
1299                       void **channel_ctx,
1300                       const struct GNUNET_MessageHeader *message)
1301 {
1302   struct Operation *op = *channel_ctx;
1303   int ret;
1304
1305   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1306               "dispatching mesh message (type: %u)\n",
1307               ntohs (message->type));
1308   /* do this before the handler, as the handler might kill the channel */
1309   GNUNET_MESH_receive_done (channel);
1310   ret = op->vt->msg_handler (op, message);
1311   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1312               "handled mesh message (type: %u)\n",
1313               ntohs (message->type));
1314   return ret;
1315 }
1316
1317
1318 /**
1319  * Function called by the service's run
1320  * method to run service-specific setup code.
1321  *
1322  * @param cls closure
1323  * @param server the initialized server
1324  * @param cfg configuration to use
1325  */
1326 static void
1327 run (void *cls, struct GNUNET_SERVER_Handle *server,
1328      const struct GNUNET_CONFIGURATION_Handle *cfg)
1329 {
1330   static const struct GNUNET_SERVER_MessageHandler server_handlers[] = {
1331     {handle_client_accept, NULL, GNUNET_MESSAGE_TYPE_SET_ACCEPT,
1332         sizeof (struct GNUNET_SET_AcceptRejectMessage)},
1333     {handle_client_iter_ack, NULL, GNUNET_MESSAGE_TYPE_SET_ITER_ACK, 0},
1334     {handle_client_add_remove, NULL, GNUNET_MESSAGE_TYPE_SET_ADD, 0},
1335     {handle_client_create_set, NULL, GNUNET_MESSAGE_TYPE_SET_CREATE,
1336         sizeof (struct GNUNET_SET_CreateMessage)},
1337     {handle_client_iterate, NULL, GNUNET_MESSAGE_TYPE_SET_ITER_REQUEST,
1338         sizeof (struct GNUNET_MessageHeader)},
1339     {handle_client_evaluate, NULL, GNUNET_MESSAGE_TYPE_SET_EVALUATE, 0},
1340     {handle_client_listen, NULL, GNUNET_MESSAGE_TYPE_SET_LISTEN,
1341         sizeof (struct GNUNET_SET_ListenMessage)},
1342     {handle_client_reject, NULL, GNUNET_MESSAGE_TYPE_SET_REJECT,
1343         sizeof (struct GNUNET_SET_AcceptRejectMessage)},
1344     {handle_client_add_remove, NULL, GNUNET_MESSAGE_TYPE_SET_REMOVE, 0},
1345     {handle_client_cancel, NULL, GNUNET_MESSAGE_TYPE_SET_CANCEL,
1346         sizeof (struct GNUNET_SET_CancelMessage)},
1347     {NULL, NULL, 0, 0}
1348   };
1349   static const struct GNUNET_MESH_MessageHandler mesh_handlers[] = {
1350     {dispatch_p2p_message, GNUNET_MESSAGE_TYPE_SET_P2P_OPERATION_REQUEST, 0},
1351     {dispatch_p2p_message, GNUNET_MESSAGE_TYPE_SET_UNION_P2P_IBF, 0},
1352     {dispatch_p2p_message, GNUNET_MESSAGE_TYPE_SET_P2P_ELEMENTS, 0},
1353     {dispatch_p2p_message, GNUNET_MESSAGE_TYPE_SET_P2P_DONE, 0},
1354     {dispatch_p2p_message, GNUNET_MESSAGE_TYPE_SET_P2P_ELEMENT_REQUESTS, 0},
1355     {dispatch_p2p_message, GNUNET_MESSAGE_TYPE_SET_UNION_P2P_SE, 0},
1356     {dispatch_p2p_message, GNUNET_MESSAGE_TYPE_SET_INTERSECTION_P2P_ELEMENT_INFO, 0},
1357     {dispatch_p2p_message, GNUNET_MESSAGE_TYPE_SET_INTERSECTION_P2P_BF, 0},
1358     {NULL, 0, 0}
1359   };
1360   static const uint32_t mesh_ports[] = {GNUNET_APPLICATION_TYPE_SET, 0};
1361
1362   configuration = cfg;
1363   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
1364                                 &shutdown_task, NULL);
1365   GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
1366   GNUNET_SERVER_add_handlers (server, server_handlers);
1367
1368   mesh = GNUNET_MESH_connect (cfg, NULL, channel_new_cb, channel_end_cb,
1369                               mesh_handlers, mesh_ports);
1370   if (NULL == mesh)
1371   {
1372     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1373                 _("Could not connect to mesh service\n"));
1374     return;
1375   }
1376 }
1377
1378
1379 /**
1380  * The main function for the set service.
1381  *
1382  * @param argc number of arguments from the command line
1383  * @param argv command line arguments
1384  * @return 0 ok, 1 on error
1385  */
1386 int
1387 main (int argc, char *const *argv)
1388 {
1389   int ret;
1390
1391   ret = GNUNET_SERVICE_run (argc, argv, "set",
1392                             GNUNET_SERVICE_OPTION_NONE, &run, NULL);
1393   return (GNUNET_OK == ret) ? 0 : 1;
1394 }
1395
1396 /* end of gnunet-service-set.c */
1397