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