754bc96e0c8bd0aff33fb588a77442dcef182bf0
[oweals/gnunet.git] / src / set / gnunet-service-set.c
1 /*
2       This file is part of GNUnet
3       Copyright (C) 2013, 2014 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., 51 Franklin Street, Fifth Floor,
18       Boston, MA 02110-1301, USA.
19 */
20 /**
21  * @file set/gnunet-service-set.c
22  * @brief two-peer set operations
23  * @author Florian Dold
24  * @author Christian Grothoff
25  */
26 #include "gnunet-service-set.h"
27 #include "gnunet-service-set_protocol.h"
28
29 /**
30  * How long do we hold on to an incoming channel if there is
31  * no local listener before giving up?
32  */
33 #define INCOMING_CHANNEL_TIMEOUT GNUNET_TIME_UNIT_MINUTES
34
35 /**
36  * A listener is inhabited by a client, and waits for evaluation
37  * requests from remote peers.
38  */
39 struct Listener
40 {
41   /**
42    * Listeners are held in a doubly linked list.
43    */
44   struct Listener *next;
45
46   /**
47    * Listeners are held in a doubly linked list.
48    */
49   struct Listener *prev;
50
51   /**
52    * Client that owns the listener.
53    * Only one client may own a listener.
54    */
55   struct GNUNET_SERVER_Client *client;
56
57   /**
58    * Message queue for the client
59    */
60   struct GNUNET_MQ_Handle *client_mq;
61
62   /**
63    * Application ID for the operation, used to distinguish
64    * multiple operations of the same type with the same peer.
65    */
66   struct GNUNET_HashCode app_id;
67
68   /**
69    * The type of the operation.
70    */
71   enum GNUNET_SET_OperationType operation;
72 };
73
74
75 struct LazyCopyRequest
76 {
77   struct Set *source_set;
78   uint32_t cookie;
79
80   struct LazyCopyRequest *prev;
81   struct LazyCopyRequest *next;
82 };
83
84
85 /**
86  * Configuration of our local peer.
87  */
88 static const struct GNUNET_CONFIGURATION_Handle *configuration;
89
90 /**
91  * Handle to the cadet service, used to listen for and connect to
92  * remote peers.
93  */
94 static struct GNUNET_CADET_Handle *cadet;
95
96 /**
97  * Sets are held in a doubly linked list.
98  */
99 static struct Set *sets_head;
100
101 /**
102  * Sets are held in a doubly linked list.
103  */
104 static struct Set *sets_tail;
105
106 /**
107  * Listeners are held in a doubly linked list.
108  */
109 static struct Listener *listeners_head;
110
111 /**
112  * Listeners are held in a doubly linked list.
113  */
114 static struct Listener *listeners_tail;
115
116 /**
117  * Incoming sockets from remote peers are held in a doubly linked
118  * list.
119  */
120 static struct Operation *incoming_head;
121
122 /**
123  * Incoming sockets from remote peers are held in a doubly linked
124  * list.
125  */
126 static struct Operation *incoming_tail;
127
128 static struct LazyCopyRequest *lazy_copy_head;
129 static struct LazyCopyRequest *lazy_copy_tail;
130
131 static uint32_t lazy_copy_cookie = 1;
132
133 /**
134  * Counter for allocating unique IDs for clients, used to identify
135  * incoming operation requests from remote peers, that the client can
136  * choose to accept or refuse.
137  */
138 static uint32_t suggest_id = 1;
139
140
141 /**
142  * Get set that is owned by the given client, if any.
143  *
144  * @param client client to look for
145  * @return set that the client owns, NULL if the client
146  *         does not own a set
147  */
148 static struct Set *
149 set_get (struct GNUNET_SERVER_Client *client)
150 {
151   struct Set *set;
152
153   for (set = sets_head; NULL != set; set = set->next)
154     if (set->client == client)
155       return set;
156   return NULL;
157 }
158
159
160 /**
161  * Get the listener associated with the given client, if any.
162  *
163  * @param client the client
164  * @return listener associated with the client, NULL
165  *         if there isn't any
166  */
167 static struct Listener *
168 listener_get (struct GNUNET_SERVER_Client *client)
169 {
170   struct Listener *listener;
171
172   for (listener = listeners_head; NULL != listener; listener = listener->next)
173     if (listener->client == client)
174       return listener;
175   return NULL;
176 }
177
178
179 /**
180  * Get the incoming socket associated with the given id.
181  *
182  * @param id id to look for
183  * @return the incoming socket associated with the id,
184  *         or NULL if there is none
185  */
186 static struct Operation *
187 get_incoming (uint32_t id)
188 {
189   struct Operation *op;
190
191   for (op = incoming_head; NULL != op; op = op->next)
192     if (op->suggest_id == id)
193     {
194       GNUNET_assert (GNUNET_YES == op->is_incoming);
195       return op;
196     }
197   return NULL;
198 }
199
200
201 /**
202  * Destroy a listener, free all resources associated with it.
203  *
204  * @param listener listener to destroy
205  */
206 static void
207 listener_destroy (struct Listener *listener)
208 {
209   /* If the client is not dead yet, destroy it.
210    * The client's destroy callback will destroy the listener again. */
211   if (NULL != listener->client)
212   {
213     struct GNUNET_SERVER_Client *client = listener->client;
214
215     listener->client = NULL;
216     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
217                 "Disconnecting listener client\n");
218     GNUNET_SERVER_client_disconnect (client);
219     return;
220   }
221   if (NULL != listener->client_mq)
222   {
223     GNUNET_MQ_destroy (listener->client_mq);
224     listener->client_mq = NULL;
225   }
226   GNUNET_CONTAINER_DLL_remove (listeners_head,
227                                listeners_tail,
228                                listener);
229   GNUNET_free (listener);
230 }
231
232
233 /**
234  * Context for the #garbage_collect_cb().
235  */
236 struct GarbageContext
237 {
238
239   /**
240    * Map for which we are garbage collecting removed elements.
241    */
242   struct GNUNET_CONTAINER_MultiHashMap *map;
243
244   /**
245    * Lowest generation for which an operation is still pending.
246    */
247   unsigned int min_op_generation;
248
249   /**
250    * Largest generation for which an operation is still pending.
251    */
252   unsigned int max_op_generation;
253
254 };
255
256
257 /**
258  * Function invoked to check if an element can be removed from
259  * the set's history because it is no longer needed.
260  *
261  * @param cls the `struct GarbageContext *`
262  * @param key key of the element in the map
263  * @param value the `struct ElementEntry *`
264  * @return #GNUNET_OK (continue to iterate)
265  */
266 static int
267 garbage_collect_cb (void *cls,
268                     const struct GNUNET_HashCode *key,
269                     void *value)
270 {
271   //struct GarbageContext *gc = cls;
272   //struct ElementEntry *ee = value;
273
274   //if (GNUNET_YES != ee->removed)
275   //  return GNUNET_OK;
276   //if ( (gc->max_op_generation < ee->generation_added) ||
277   //     (ee->generation_removed > gc->min_op_generation) )
278   //{
279   //  GNUNET_assert (GNUNET_YES ==
280   //                 GNUNET_CONTAINER_multihashmap_remove (gc->map,
281   //                                                       key,
282   //                                                       ee));
283   //  GNUNET_free (ee);
284   //}
285   return GNUNET_OK;
286 }
287
288
289 /**
290  * Collect and destroy elements that are not needed anymore, because
291  * their lifetime (as determined by their generation) does not overlap
292  * with any active set operation.
293  *
294  * @param set set to garbage collect
295  */
296 static void
297 collect_generation_garbage (struct Set *set)
298 {
299   struct Operation *op;
300   struct GarbageContext gc;
301
302   gc.min_op_generation = UINT_MAX;
303   gc.max_op_generation = 0;
304   for (op = set->ops_head; NULL != op; op = op->next)
305   {
306     gc.min_op_generation = GNUNET_MIN (gc.min_op_generation,
307                                        op->generation_created);
308     gc.max_op_generation = GNUNET_MAX (gc.max_op_generation,
309                                        op->generation_created);
310   }
311   gc.map = set->content->elements;
312   GNUNET_CONTAINER_multihashmap_iterate (set->content->elements,
313                                          &garbage_collect_cb,
314                                          &gc);
315 }
316
317 int
318 is_excluded_generation (unsigned int generation,
319                         struct GenerationRange *excluded,
320                         unsigned int excluded_size)
321 {
322   unsigned int i;
323
324   for (i = 0; i < excluded_size; i++)
325   {
326     if ( (generation >= excluded[i].start) && (generation < excluded[i].end) )
327       return GNUNET_YES;
328   }
329
330   return GNUNET_NO;
331 }
332
333
334 int
335 is_element_of_generation (struct ElementEntry *ee,
336                           unsigned int query_generation,
337                           struct GenerationRange *excluded,
338                           unsigned int excluded_size)
339 {
340   struct MutationEvent *mut;
341   int is_present;
342   unsigned int i;
343
344   /* If ee->mutations is NULL,
345      the element was added in generation 0,
346      and there are no removes, thus the element
347      is part of any generation we query. */
348   if (NULL == ee->mutations)
349     return GNUNET_YES;
350
351   if (GNUNET_YES == is_excluded_generation (query_generation, excluded, excluded_size))
352   {
353     GNUNET_break (0);
354     return GNUNET_NO;
355   }
356
357   is_present = GNUNET_NO;
358
359   /* Could be made faster with binary search, but lists
360      are small, so why bother. */
361   for (i = 0; i < ee->mutations_size; i++)
362   {
363     mut = &ee->mutations[i];
364
365     if (mut->generation > query_generation)
366     {
367       /* The mutation doesn't apply to our generation
368          anymore.  We can'b break here, since mutations aren't
369          sorted by generation. */
370       continue;
371     }
372
373     if (GNUNET_YES == is_excluded_generation (mut->generation, excluded, excluded_size))
374     {
375       /* The generation is excluded (because it belongs to another
376          fork via a lazy copy) and thus mutations aren't considered
377          for membership testing. */
378       continue;
379     }
380
381     /* This would be an inconsistency in how we manage mutations. */
382     if ( (GNUNET_YES == is_present) && (GNUNET_YES == mut->added) )
383       GNUNET_assert (0);
384
385     /* Likewise. */
386     if ( (GNUNET_NO == is_present) && (GNUNET_NO == mut->added) )
387       GNUNET_assert (0);
388
389     is_present = mut->added;
390   }
391
392   return GNUNET_YES;
393 }
394
395
396 int
397 _GSS_is_element_of_set (struct ElementEntry *ee,
398                         struct Set *set)
399 {
400   return is_element_of_generation (ee,
401                                    set->current_generation,
402                                    set->excluded_generations,
403                                    set->excluded_generations_size);
404 }
405
406
407 int
408 _GSS_is_element_of_operation (struct ElementEntry *ee,
409                               struct Operation *op)
410 {
411   return is_element_of_generation (ee,
412                                    op->generation_created,
413                                    op->spec->set->excluded_generations,
414                                    op->spec->set->excluded_generations_size);
415 }
416
417
418 /**
419  * Destroy the given operation.  Call the implementation-specific
420  * cancel function of the operation.  Disconnects from the remote
421  * peer.  Does not disconnect the client, as there may be multiple
422  * operations per set.
423  *
424  * @param op operation to destroy
425  * @param gc #GNUNET_YES to perform garbage collection on the set
426  */
427 void
428 _GSS_operation_destroy (struct Operation *op,
429                         int gc)
430 {
431   struct Set *set;
432   struct GNUNET_CADET_Channel *channel;
433
434   if (NULL == op->vt)
435   {
436     /* already in #_GSS_operation_destroy() */
437     return;
438   }
439   GNUNET_assert (GNUNET_NO == op->is_incoming);
440   GNUNET_assert (NULL != op->spec);
441   set = op->spec->set;
442   GNUNET_CONTAINER_DLL_remove (set->ops_head,
443                                set->ops_tail,
444                                op);
445   op->vt->cancel (op);
446   op->vt = NULL;
447   if (NULL != op->spec)
448   {
449     if (NULL != op->spec->context_msg)
450     {
451       GNUNET_free (op->spec->context_msg);
452       op->spec->context_msg = NULL;
453     }
454     GNUNET_free (op->spec);
455     op->spec = NULL;
456   }
457   if (NULL != op->mq)
458   {
459     GNUNET_MQ_destroy (op->mq);
460     op->mq = NULL;
461   }
462   if (NULL != (channel = op->channel))
463   {
464     op->channel = NULL;
465     GNUNET_CADET_channel_destroy (channel);
466   }
467   if (GNUNET_YES == gc)
468     collect_generation_garbage (set);
469   /* We rely on the channel end handler to free 'op'. When 'op->channel' was NULL,
470    * there was a channel end handler that will free 'op' on the call stack. */
471 }
472
473
474 /**
475  * Iterator over hash map entries to free element entries.
476  *
477  * @param cls closure
478  * @param key current key code
479  * @param value a `struct ElementEntry *` to be free'd
480  * @return #GNUNET_YES (continue to iterate)
481  */
482 static int
483 destroy_elements_iterator (void *cls,
484                            const struct GNUNET_HashCode *key,
485                            void *value)
486 {
487   struct ElementEntry *ee = value;
488
489   GNUNET_free_non_null (ee->mutations);
490
491   GNUNET_free (ee);
492   return GNUNET_YES;
493 }
494
495
496 /**
497  * Destroy a set, and free all resources and operations associated with it.
498  *
499  * @param set the set to destroy
500  */
501 static void
502 set_destroy (struct Set *set)
503 {
504   if (NULL != set->client)
505   {
506     /* If the client is not dead yet, destroy it.  The client's destroy
507      * callback will call `set_destroy()` again in this case.  We do
508      * this so that the channel end handler still has a valid set handle
509      * to destroy. */
510     struct GNUNET_SERVER_Client *client = set->client;
511
512     set->client = NULL;
513     GNUNET_SERVER_client_disconnect (client);
514     return;
515   }
516   GNUNET_assert (NULL != set->state);
517   while (NULL != set->ops_head)
518     _GSS_operation_destroy (set->ops_head, GNUNET_NO);
519   set->vt->destroy_set (set->state);
520   set->state = NULL;
521   if (NULL != set->client_mq)
522   {
523     GNUNET_MQ_destroy (set->client_mq);
524     set->client_mq = NULL;
525   }
526   if (NULL != set->iter)
527   {
528     GNUNET_CONTAINER_multihashmap_iterator_destroy (set->iter);
529     set->iter = NULL;
530     set->iteration_id++;
531   }
532   {
533     struct SetContent *content;
534     struct PendingMutation *pm;
535     struct PendingMutation *pm_current;
536
537     content = set->content;
538
539     // discard any pending mutations that reference this set
540     pm = content->pending_mutations_head;
541     while (NULL != pm)
542     {
543       pm_current = pm;
544       pm = pm->next;
545       if (pm_current-> set == set)
546         GNUNET_CONTAINER_DLL_remove (content->pending_mutations_head,
547                                      content->pending_mutations_tail,
548                                      pm_current);
549
550     }
551
552     set->content = NULL;
553     GNUNET_assert (0 != content->refcount);
554     content->refcount -= 1;
555     if (0 == content->refcount)
556     {
557       GNUNET_assert (NULL != content->elements);
558       GNUNET_CONTAINER_multihashmap_iterate (content->elements,
559                                              &destroy_elements_iterator,
560                                              NULL);
561       GNUNET_CONTAINER_multihashmap_destroy (content->elements);
562       content->elements = NULL;
563       GNUNET_free (content);
564     }
565   }
566   GNUNET_free_non_null (set->excluded_generations);
567   set->excluded_generations = NULL;
568   GNUNET_CONTAINER_DLL_remove (sets_head,
569                                sets_tail,
570                                set);
571
572   // remove set from pending copy requests
573   {
574     struct LazyCopyRequest *lcr;
575     lcr = lazy_copy_head;
576     while (NULL != lcr)
577     {
578       struct LazyCopyRequest *lcr_current;
579       lcr_current = lcr;
580       lcr = lcr->next;
581       if (lcr_current->source_set == set)
582         GNUNET_CONTAINER_DLL_remove (lazy_copy_head,
583                                      lazy_copy_tail,
584                                      lcr_current);
585     }
586   }
587
588   GNUNET_free (set);
589 }
590
591
592 /**
593  * Clean up after a client has disconnected
594  *
595  * @param cls closure, unused
596  * @param client the client to clean up after
597  */
598 static void
599 handle_client_disconnect (void *cls,
600                           struct GNUNET_SERVER_Client *client)
601 {
602   struct Set *set;
603   struct Listener *listener;
604
605   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
606               "client disconnected, cleaning up\n");
607   set = set_get (client);
608   if (NULL != set)
609   {
610     set->client = NULL;
611     set_destroy (set);
612     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
613                 "Client's set destroyed\n");
614   }
615   listener = listener_get (client);
616   if (NULL != listener)
617   {
618     listener->client = NULL;
619     listener_destroy (listener);
620     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
621                 "Client's listener destroyed\n");
622   }
623 }
624
625
626 /**
627  * Destroy an incoming request from a remote peer
628  *
629  * @param incoming remote request to destroy
630  */
631 static void
632 incoming_destroy (struct Operation *incoming)
633 {
634   struct GNUNET_CADET_Channel *channel;
635
636   GNUNET_assert (GNUNET_YES == incoming->is_incoming);
637   GNUNET_CONTAINER_DLL_remove (incoming_head,
638                                incoming_tail,
639                                incoming);
640   if (NULL != incoming->timeout_task)
641   {
642     GNUNET_SCHEDULER_cancel (incoming->timeout_task);
643     incoming->timeout_task = NULL;
644   }
645   /* make sure that the tunnel end handler will not destroy us again */
646   incoming->vt = NULL;
647   if (NULL != incoming->spec)
648   {
649     GNUNET_free (incoming->spec);
650     incoming->spec = NULL;
651   }
652   if (NULL != incoming->mq)
653   {
654     GNUNET_MQ_destroy (incoming->mq);
655     incoming->mq = NULL;
656   }
657   if (NULL != (channel = incoming->channel))
658   {
659     incoming->channel = NULL;
660     GNUNET_CADET_channel_destroy (channel);
661   }
662 }
663
664
665 /**
666  * Find a listener that is interested in the given operation type
667  * and application id.
668  *
669  * @param op operation type to look for
670  * @param app_id application id to look for
671  * @return a matching listener, or NULL if no listener matches the
672  *         given operation and application id
673  */
674 static struct Listener *
675 listener_get_by_target (enum GNUNET_SET_OperationType op,
676                         const struct GNUNET_HashCode *app_id)
677 {
678   struct Listener *listener;
679
680   for (listener = listeners_head; NULL != listener; listener = listener->next)
681     if ( (listener->operation == op) &&
682          (0 == GNUNET_CRYPTO_hash_cmp (app_id, &listener->app_id)) )
683       return listener;
684   return NULL;
685 }
686
687
688 /**
689  * Suggest the given request to the listener. The listening client can
690  * then accept or reject the remote request.
691  *
692  * @param incoming the incoming peer with the request to suggest
693  * @param listener the listener to suggest the request to
694  */
695 static void
696 incoming_suggest (struct Operation *incoming,
697                   struct Listener *listener)
698 {
699   struct GNUNET_MQ_Envelope *mqm;
700   struct GNUNET_SET_RequestMessage *cmsg;
701
702   GNUNET_assert (GNUNET_YES == incoming->is_incoming);
703   GNUNET_assert (NULL != incoming->spec);
704   GNUNET_assert (0 == incoming->suggest_id);
705   incoming->suggest_id = suggest_id++;
706   if (0 == suggest_id)
707     suggest_id++;
708   GNUNET_assert (NULL != incoming->timeout_task);
709   GNUNET_SCHEDULER_cancel (incoming->timeout_task);
710   incoming->timeout_task = NULL;
711   mqm = GNUNET_MQ_msg_nested_mh (cmsg,
712                                  GNUNET_MESSAGE_TYPE_SET_REQUEST,
713                                  incoming->spec->context_msg);
714   GNUNET_assert (NULL != mqm);
715   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
716               "Suggesting incoming request with accept id %u to listener\n",
717               incoming->suggest_id);
718   cmsg->accept_id = htonl (incoming->suggest_id);
719   cmsg->peer_id = incoming->spec->peer;
720   GNUNET_MQ_send (listener->client_mq, mqm);
721 }
722
723
724 /**
725  * Handle a request for a set operation from another peer.  Checks if we
726  * have a listener waiting for such a request (and in that case initiates
727  * asking the listener about accepting the connection). If no listener
728  * is waiting, we queue the operation request in hope that a listener
729  * shows up soon (before timeout).
730  *
731  * This msg is expected as the first and only msg handled through the
732  * non-operation bound virtual table, acceptance of this operation replaces
733  * our virtual table and subsequent msgs would be routed differently (as
734  * we then know what type of operation this is).
735  *
736  * @param op the operation state
737  * @param mh the received message
738  * @return #GNUNET_OK if the channel should be kept alive,
739  *         #GNUNET_SYSERR to destroy the channel
740  */
741 static int
742 handle_incoming_msg (struct Operation *op,
743                      const struct GNUNET_MessageHeader *mh)
744 {
745   const struct OperationRequestMessage *msg;
746   struct Listener *listener;
747   struct OperationSpecification *spec;
748   const struct GNUNET_MessageHeader *nested_context;
749
750   msg = (const struct OperationRequestMessage *) mh;
751   GNUNET_assert (GNUNET_YES == op->is_incoming);
752   if (GNUNET_MESSAGE_TYPE_SET_P2P_OPERATION_REQUEST != ntohs (mh->type))
753   {
754     GNUNET_break_op (0);
755     return GNUNET_SYSERR;
756   }
757   /* double operation request */
758   if (NULL != op->spec)
759   {
760     GNUNET_break_op (0);
761     return GNUNET_SYSERR;
762   }
763   spec = GNUNET_new (struct OperationSpecification);
764   nested_context = GNUNET_MQ_extract_nested_mh (msg);
765   if ( (NULL != nested_context) &&
766        (ntohs (nested_context->size) > GNUNET_SET_CONTEXT_MESSAGE_MAX_SIZE) )
767   {
768     GNUNET_break_op (0);
769     GNUNET_free (spec);
770     return GNUNET_SYSERR;
771   }
772   /* Make a copy of the nested_context (application-specific context
773      information that is opaque to set) so we can pass it to the
774      listener later on */
775   if (NULL != nested_context)
776     spec->context_msg = GNUNET_copy_message (nested_context);
777   spec->operation = ntohl (msg->operation);
778   spec->app_id = msg->app_id;
779   spec->salt = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
780                                          UINT32_MAX);
781   spec->peer = op->peer;
782   spec->remote_element_count = ntohl (msg->element_count);
783   op->spec = spec;
784
785   listener = listener_get_by_target (ntohl (msg->operation),
786                                      &msg->app_id);
787   if (NULL == listener)
788   {
789     GNUNET_break (NULL != op->timeout_task);
790     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
791                 "No matching listener for incoming request (op %u, app %s), waiting with timeout\n",
792                 ntohl (msg->operation),
793                 GNUNET_h2s (&msg->app_id));
794     return GNUNET_OK;
795   }
796   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
797               "Received P2P operation request (op %u, app %s) for active listener\n",
798               ntohl (msg->operation),
799               GNUNET_h2s (&msg->app_id));
800   incoming_suggest (op, listener);
801   return GNUNET_OK;
802 }
803
804
805 static void
806 execute_add (struct Set *set,
807              const struct GNUNET_MessageHeader *m)
808 {
809   const struct GNUNET_SET_ElementMessage *msg;
810   struct GNUNET_SET_Element el;
811   struct ElementEntry *ee;
812   struct GNUNET_HashCode hash;
813
814   GNUNET_assert (GNUNET_MESSAGE_TYPE_SET_ADD == ntohs (m->type));
815
816   msg = (const struct GNUNET_SET_ElementMessage *) m;
817   el.size = ntohs (m->size) - sizeof *msg;
818   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
819               "Client inserts element of size %u\n",
820               el.size);
821   el.data = &msg[1];
822   GNUNET_CRYPTO_hash (el.data,
823                       el.size,
824                       &hash);
825
826   ee = GNUNET_CONTAINER_multihashmap_get (set->content->elements,
827                                           &hash);
828
829   if (NULL == ee)
830   {
831     ee = GNUNET_malloc (el.size + sizeof *ee);
832     ee->element.size = el.size;
833     memcpy (&ee[1],
834             el.data,
835             el.size);
836     ee->element.data = &ee[1];
837     ee->remote = GNUNET_NO;
838     ee->mutations = NULL;
839     ee->mutations_size = 0;
840     ee->element_hash = hash;
841   }
842   else if (GNUNET_YES == _GSS_is_element_of_set (ee, set))
843   {
844     /* same element inserted twice */
845     GNUNET_break (0);
846     return;
847   }
848
849   if (0 != set->current_generation)
850   {
851     struct MutationEvent mut = {
852       .generation = set->current_generation,
853       .added = GNUNET_YES
854     };
855     GNUNET_array_append (ee->mutations, ee->mutations_size, mut);
856   }
857
858   GNUNET_break (GNUNET_YES ==
859                 GNUNET_CONTAINER_multihashmap_put (set->content->elements,
860                                                    &ee->element_hash,
861                                                    ee,
862                                                    GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
863   set->vt->add (set->state, ee);
864 }
865
866
867 static void
868 execute_remove (struct Set *set,
869                 const struct GNUNET_MessageHeader *m)
870 {
871   const struct GNUNET_SET_ElementMessage *msg;
872   struct GNUNET_SET_Element el;
873   struct ElementEntry *ee;
874   struct GNUNET_HashCode hash;
875
876   GNUNET_assert (GNUNET_MESSAGE_TYPE_SET_REMOVE == ntohs (m->type));
877
878   msg = (const struct GNUNET_SET_ElementMessage *) m;
879   el.size = ntohs (m->size) - sizeof *msg;
880   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
881               "Client removes element of size %u\n",
882               el.size);
883   el.data = &msg[1];
884   GNUNET_CRYPTO_hash (el.data,
885                       el.size,
886                       &hash);
887   ee = GNUNET_CONTAINER_multihashmap_get (set->content->elements,
888                                           &hash);
889   if (NULL == ee)
890   {
891     /* Client tried to remove non-existing element */
892     GNUNET_break (0);
893     return;
894   }
895   if (GNUNET_NO == _GSS_is_element_of_set (ee, set))
896   {
897     /* Client tried to remove element twice */
898     GNUNET_break (0);
899     return;
900   }
901   else if (0 == set->current_generation)
902   {
903     // If current_generation is 0, then there are no running set operations
904     // or lazy copies, thus we can safely remove the element.
905     (void) GNUNET_CONTAINER_multihashmap_remove_all (set->content->elements, &hash);
906   }
907   else
908   {
909     struct MutationEvent mut = {
910       .generation = set->current_generation,
911       .added = GNUNET_NO
912     };
913     GNUNET_array_append (ee->mutations, ee->mutations_size, mut);
914   }
915   set->vt->remove (set->state, ee);
916 }
917
918
919
920 static void
921 execute_mutation (struct Set *set,
922                   const struct GNUNET_MessageHeader *m)
923 {
924   switch (ntohs (m->type))
925   {
926     case GNUNET_MESSAGE_TYPE_SET_ADD:
927       execute_add (set, m);
928       break;
929     case GNUNET_MESSAGE_TYPE_SET_REMOVE:
930       execute_remove (set, m);
931       break;
932     default:
933       GNUNET_break (0);
934   }
935 }
936
937
938
939 /**
940  * Send the next element of a set to the set's client.  The next element is given by
941  * the set's current hashmap iterator.  The set's iterator will be set to NULL if there
942  * are no more elements in the set.  The caller must ensure that the set's iterator is
943  * valid.
944  *
945  * The client will acknowledge each received element with a
946  * #GNUNET_MESSAGE_TYPE_SET_ITER_ACK message.  Our
947  * #handle_client_iter_ack() will then trigger the next transmission.
948  * Note that the #GNUNET_MESSAGE_TYPE_SET_ITER_DONE is not acknowledged.
949  *
950  * @param set set that should send its next element to its client
951  */
952 static void
953 send_client_element (struct Set *set)
954 {
955   int ret;
956   struct ElementEntry *ee;
957   struct GNUNET_MQ_Envelope *ev;
958   struct GNUNET_SET_IterResponseMessage *msg;
959
960   GNUNET_assert (NULL != set->iter);
961   ret = GNUNET_CONTAINER_multihashmap_iterator_next (set->iter,
962                                                      NULL,
963                                                      (const void **) &ee);
964   if (GNUNET_NO == ret)
965   {
966     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
967                 "Iteration on %p done.\n",
968                 (void *) set);
969     ev = GNUNET_MQ_msg_header (GNUNET_MESSAGE_TYPE_SET_ITER_DONE);
970     GNUNET_CONTAINER_multihashmap_iterator_destroy (set->iter);
971     set->iter = NULL;
972     set->iteration_id++;
973     
974     GNUNET_assert (set->content->iterator_count > 0);
975     set->content->iterator_count -= 1;
976
977     if (0 == set->content->iterator_count)
978     {
979       while (NULL != set->content->pending_mutations_head)
980       {
981         struct PendingMutation *pm;
982
983         pm = set->content->pending_mutations_head;
984         GNUNET_CONTAINER_DLL_remove (set->content->pending_mutations_head,
985                                      set->content->pending_mutations_tail,
986                                      pm);
987         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
988                     "Executing pending mutation on %p.\n",
989                     (void *) pm->set);
990         execute_mutation (pm->set, pm->mutation_message);
991         GNUNET_free (pm->mutation_message);
992         GNUNET_free (pm);
993       }
994     }
995
996   }
997   else
998   {
999     GNUNET_assert (NULL != ee);
1000     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1001                 "Sending iteration element on %p.\n",
1002                 (void *) set);
1003     ev = GNUNET_MQ_msg_extra (msg,
1004                               ee->element.size,
1005                               GNUNET_MESSAGE_TYPE_SET_ITER_ELEMENT);
1006     memcpy (&msg[1],
1007             ee->element.data,
1008             ee->element.size);
1009     msg->element_type = ee->element.element_type;
1010     msg->iteration_id = htons (set->iteration_id);
1011   }
1012   GNUNET_MQ_send (set->client_mq, ev);
1013 }
1014
1015
1016 /**
1017  * Called when a client wants to iterate the elements of a set.
1018  * Checks if we have a set associated with the client and if we
1019  * can right now start an iteration. If all checks out, starts
1020  * sending the elements of the set to the client.
1021  *
1022  * @param cls unused
1023  * @param client client that sent the message
1024  * @param m message sent by the client
1025  */
1026 static void
1027 handle_client_iterate (void *cls,
1028                        struct GNUNET_SERVER_Client *client,
1029                        const struct GNUNET_MessageHeader *m)
1030 {
1031   struct Set *set;
1032
1033   set = set_get (client);
1034   if (NULL == set)
1035   {
1036     /* attempt to iterate over a non existing set */
1037     GNUNET_break (0);
1038     GNUNET_SERVER_client_disconnect (client);
1039     return;
1040   }
1041   if (NULL != set->iter)
1042   {
1043     /* Only one concurrent iterate-action allowed per set */
1044     GNUNET_break (0);
1045     GNUNET_SERVER_client_disconnect (client);
1046     return;
1047   }
1048   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1049               "Iterating set %p with %u elements\n",
1050               (void *) set,
1051               GNUNET_CONTAINER_multihashmap_size (set->content->elements));
1052   GNUNET_SERVER_receive_done (client,
1053                               GNUNET_OK);
1054   set->content->iterator_count += 1;
1055   set->iter = GNUNET_CONTAINER_multihashmap_iterator_create (set->content->elements);
1056   send_client_element (set);
1057 }
1058
1059
1060 /**
1061  * Called when a client wants to create a new set.  This is typically
1062  * the first request from a client, and includes the type of set
1063  * operation to be performed.
1064  *
1065  * @param cls unused
1066  * @param client client that sent the message
1067  * @param m message sent by the client
1068  */
1069 static void
1070 handle_client_create_set (void *cls,
1071                           struct GNUNET_SERVER_Client *client,
1072                           const struct GNUNET_MessageHeader *m)
1073 {
1074   const struct GNUNET_SET_CreateMessage *msg;
1075   struct Set *set;
1076
1077   msg = (const struct GNUNET_SET_CreateMessage *) m;
1078   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1079               "Client created new set (operation %u)\n",
1080               ntohl (msg->operation));
1081   if (NULL != set_get (client))
1082   {
1083     /* There can only be one set per client */
1084     GNUNET_break (0);
1085     GNUNET_SERVER_client_disconnect (client);
1086     return;
1087   }
1088   set = GNUNET_new (struct Set);
1089   switch (ntohl (msg->operation))
1090   {
1091   case GNUNET_SET_OPERATION_INTERSECTION:
1092     set->vt = _GSS_intersection_vt ();
1093     break;
1094   case GNUNET_SET_OPERATION_UNION:
1095     set->vt = _GSS_union_vt ();
1096     break;
1097   default:
1098     GNUNET_free (set);
1099     GNUNET_break (0);
1100     GNUNET_SERVER_client_disconnect (client);
1101     return;
1102   }
1103   set->operation = ntohl (msg->operation);
1104   set->state = set->vt->create ();
1105   set->content = GNUNET_new (struct SetContent);
1106   set->content->refcount = 1;
1107   set->content->elements = GNUNET_CONTAINER_multihashmap_create (1, GNUNET_YES);
1108   set->client = client;
1109   set->client_mq = GNUNET_MQ_queue_for_server_client (client);
1110   GNUNET_CONTAINER_DLL_insert (sets_head,
1111                                sets_tail,
1112                                set);
1113   GNUNET_SERVER_receive_done (client,
1114                               GNUNET_OK);
1115 }
1116
1117
1118 /**
1119  * Called when a client wants to create a new listener.
1120  *
1121  * @param cls unused
1122  * @param client client that sent the message
1123  * @param m message sent by the client
1124  */
1125 static void
1126 handle_client_listen (void *cls,
1127                       struct GNUNET_SERVER_Client *client,
1128                       const struct GNUNET_MessageHeader *m)
1129 {
1130   const struct GNUNET_SET_ListenMessage *msg;
1131   struct Listener *listener;
1132   struct Operation *op;
1133
1134   msg = (const struct GNUNET_SET_ListenMessage *) m;
1135   if (NULL != listener_get (client))
1136   {
1137     /* max. one active listener per client! */
1138     GNUNET_break (0);
1139     GNUNET_SERVER_client_disconnect (client);
1140     return;
1141   }
1142   listener = GNUNET_new (struct Listener);
1143   listener->client = client;
1144   listener->client_mq = GNUNET_MQ_queue_for_server_client (client);
1145   listener->app_id = msg->app_id;
1146   listener->operation = ntohl (msg->operation);
1147   GNUNET_CONTAINER_DLL_insert_tail (listeners_head,
1148                                     listeners_tail,
1149                                     listener);
1150   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1151               "New listener created (op %u, app %s)\n",
1152               listener->operation,
1153               GNUNET_h2s (&listener->app_id));
1154
1155   /* check for existing incoming requests the listener might be interested in */
1156   for (op = incoming_head; NULL != op; op = op->next)
1157   {
1158     if (NULL == op->spec)
1159       continue; /* no details available yet */
1160     if (0 != op->suggest_id)
1161       continue; /* this one has been already suggested to a listener */
1162     if (listener->operation != op->spec->operation)
1163       continue; /* incompatible operation */
1164     if (0 != GNUNET_CRYPTO_hash_cmp (&listener->app_id,
1165                                      &op->spec->app_id))
1166       continue; /* incompatible appliation */
1167     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1168                 "Found matching existing request\n");
1169     incoming_suggest (op,
1170                       listener);
1171   }
1172   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1173 }
1174
1175
1176 /**
1177  * Called when the listening client rejects an operation
1178  * request by another peer.
1179  *
1180  * @param cls unused
1181  * @param client client that sent the message
1182  * @param m message sent by the client
1183  */
1184 static void
1185 handle_client_reject (void *cls,
1186                       struct GNUNET_SERVER_Client *client,
1187                       const struct GNUNET_MessageHeader *m)
1188 {
1189   struct Operation *incoming;
1190   const struct GNUNET_SET_RejectMessage *msg;
1191
1192   msg = (const struct GNUNET_SET_RejectMessage *) m;
1193   incoming = get_incoming (ntohl (msg->accept_reject_id));
1194   if (NULL == incoming)
1195   {
1196     /* no matching incoming operation for this reject */
1197     GNUNET_break (0);
1198     GNUNET_SERVER_receive_done (client,
1199                                 GNUNET_SYSERR);
1200     return;
1201   }
1202   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1203               "Peer request (op %u, app %s) rejected by client\n",
1204               incoming->spec->operation,
1205               GNUNET_h2s (&incoming->spec->app_id));
1206   GNUNET_CADET_channel_destroy (incoming->channel);
1207   GNUNET_SERVER_receive_done (client,
1208                               GNUNET_OK);
1209 }
1210
1211
1212
1213 /**
1214  * Called when a client wants to add or remove an element to a set it inhabits.
1215  *
1216  * @param cls unused
1217  * @param client client that sent the message
1218  * @param m message sent by the client
1219  */
1220 static void
1221 handle_client_mutation (void *cls,
1222                         struct GNUNET_SERVER_Client *client,
1223                         const struct GNUNET_MessageHeader *m)
1224 {
1225   struct Set *set;
1226
1227   set = set_get (client);
1228   if (NULL == set)
1229   {
1230     /* client without a set requested an operation */
1231     GNUNET_break (0);
1232     GNUNET_SERVER_client_disconnect (client);
1233     return;
1234   }
1235
1236   GNUNET_SERVER_receive_done (client,
1237                               GNUNET_OK);
1238
1239   if (0 != set->content->iterator_count)
1240   {
1241     struct PendingMutation *pm;
1242
1243     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1244                 "Scheduling mutation on set\n");
1245
1246     pm = GNUNET_new (struct PendingMutation);
1247     pm->mutation_message = GNUNET_copy_message (m);
1248     pm->set = set;
1249     GNUNET_CONTAINER_DLL_insert (set->content->pending_mutations_head,
1250                                  set->content->pending_mutations_tail,
1251                                  pm);
1252     return;
1253   }
1254
1255   execute_mutation (set, m);
1256 }
1257
1258
1259 /**
1260  * Advance the current generation of a set,
1261  * adding exclusion ranges if necessary.
1262  *
1263  * @param set the set where we want to advance the generation
1264  */
1265 static void
1266 advance_generation (struct Set *set)
1267 {
1268   struct GenerationRange r;
1269
1270   if (set->current_generation == set->content->latest_generation)
1271   {
1272     set->content->latest_generation += 1;
1273     set->current_generation += 1;
1274     return;
1275   }
1276
1277   GNUNET_assert (set->current_generation < set->content->latest_generation);
1278
1279   r.start = set->current_generation + 1;
1280   r.end = set->content->latest_generation + 1;
1281
1282   set->content->latest_generation = r.end;
1283   set->current_generation = r.end;
1284
1285   GNUNET_array_append (set->excluded_generations,
1286                        set->excluded_generations_size,
1287                        r);
1288 }
1289
1290 /**
1291  * Called when a client wants to initiate a set operation with another
1292  * peer.  Initiates the CADET connection to the listener and sends the
1293  * request.
1294  *
1295  * @param cls unused
1296  * @param client client that sent the message
1297  * @param m message sent by the client
1298  */
1299 static void
1300 handle_client_evaluate (void *cls,
1301                         struct GNUNET_SERVER_Client *client,
1302                         const struct GNUNET_MessageHeader *m)
1303 {
1304   struct Set *set;
1305   const struct GNUNET_SET_EvaluateMessage *msg;
1306   struct OperationSpecification *spec;
1307   struct Operation *op;
1308   const struct GNUNET_MessageHeader *context;
1309
1310   set = set_get (client);
1311   if (NULL == set)
1312   {
1313     GNUNET_break (0);
1314     GNUNET_SERVER_client_disconnect (client);
1315     return;
1316   }
1317   msg = (const struct GNUNET_SET_EvaluateMessage *) m;
1318   spec = GNUNET_new (struct OperationSpecification);
1319   spec->operation = set->operation;
1320   spec->app_id = msg->app_id;
1321   spec->salt = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
1322                                          UINT32_MAX);
1323   spec->peer = msg->target_peer;
1324   spec->set = set;
1325   spec->result_mode = ntohl (msg->result_mode);
1326   spec->client_request_id = ntohl (msg->request_id);
1327   context = GNUNET_MQ_extract_nested_mh (msg);
1328   op = GNUNET_new (struct Operation);
1329   op->spec = spec;
1330
1331   // Advance generation values, so that
1332   // mutations won't interfer with the running operation.
1333   op->generation_created = set->current_generation;
1334   advance_generation (set);
1335
1336   op->vt = set->vt;
1337   GNUNET_CONTAINER_DLL_insert (set->ops_head,
1338                                set->ops_tail,
1339                                op);
1340   op->channel = GNUNET_CADET_channel_create (cadet,
1341                                              op,
1342                                              &msg->target_peer,
1343                                              GNUNET_APPLICATION_TYPE_SET,
1344                                              GNUNET_CADET_OPTION_RELIABLE);
1345   op->mq = GNUNET_CADET_mq_create (op->channel);
1346   set->vt->evaluate (op,
1347                      context);
1348   GNUNET_SERVER_receive_done (client,
1349                               GNUNET_OK);
1350 }
1351
1352
1353 /**
1354  * Handle an ack from a client, and send the next element. Note
1355  * that we only expect acks for set elements, not after the
1356  * #GNUNET_MESSAGE_TYPE_SET_ITER_DONE message.
1357  *
1358  * @param cls unused
1359  * @param client the client
1360  * @param m the message
1361  */
1362 static void
1363 handle_client_iter_ack (void *cls,
1364                         struct GNUNET_SERVER_Client *client,
1365                         const struct GNUNET_MessageHeader *m)
1366 {
1367   const struct GNUNET_SET_IterAckMessage *ack;
1368   struct Set *set;
1369
1370   set = set_get (client);
1371   if (NULL == set)
1372   {
1373     /* client without a set acknowledged receiving a value */
1374     GNUNET_break (0);
1375     GNUNET_SERVER_client_disconnect (client);
1376     return;
1377   }
1378   if (NULL == set->iter)
1379   {
1380     /* client sent an ack, but we were not expecting one (as
1381        set iteration has finished) */
1382     GNUNET_break (0);
1383     GNUNET_SERVER_client_disconnect (client);
1384     return;
1385   }
1386   ack = (const struct GNUNET_SET_IterAckMessage *) m;
1387   GNUNET_SERVER_receive_done (client,
1388                               GNUNET_OK);
1389   if (ntohl (ack->send_more))
1390   {
1391     send_client_element (set);
1392   }
1393   else
1394   {
1395     GNUNET_CONTAINER_multihashmap_iterator_destroy (set->iter);
1396     set->iter = NULL;
1397     set->iteration_id++;
1398   }
1399 }
1400
1401
1402 /**
1403  * Handle a request from the client to
1404  * copy a set.
1405  *
1406  * @param cls unused
1407  * @param client the client
1408  * @param mh the message
1409  */
1410 static void
1411 handle_client_copy_lazy_prepare (void *cls,
1412                                  struct GNUNET_SERVER_Client *client,
1413                                  const struct GNUNET_MessageHeader *mh)
1414 {
1415   struct Set *set;
1416   struct LazyCopyRequest *cr;
1417   struct GNUNET_MQ_Envelope *ev;
1418   struct GNUNET_SET_CopyLazyResponseMessage *resp_msg;
1419
1420   set = set_get (client);
1421   if (NULL == set)
1422   {
1423     /* client without a set requested an operation */
1424     GNUNET_break (0);
1425     GNUNET_SERVER_client_disconnect (client);
1426     return;
1427   }
1428
1429   cr = GNUNET_new (struct LazyCopyRequest);
1430
1431   cr->cookie = lazy_copy_cookie;
1432   lazy_copy_cookie += 1;
1433   cr->source_set = set;
1434
1435   GNUNET_CONTAINER_DLL_insert (lazy_copy_head,
1436                                lazy_copy_tail,
1437                                cr);
1438
1439
1440   ev = GNUNET_MQ_msg (resp_msg,
1441                       GNUNET_MESSAGE_TYPE_SET_COPY_LAZY_RESPONSE);
1442   resp_msg->cookie = cr->cookie;
1443   GNUNET_MQ_send (set->client_mq, ev);
1444
1445
1446   GNUNET_SERVER_receive_done (client,
1447                               GNUNET_OK);
1448
1449   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1450               "Client requested lazy copy\n");
1451 }
1452
1453
1454 /**
1455  * Handle a request from the client to
1456  * connect to a copy of a set.
1457  *
1458  * @param cls unused
1459  * @param client the client
1460  * @param mh the message
1461  */
1462 static void
1463 handle_client_copy_lazy_connect (void *cls,
1464                                  struct GNUNET_SERVER_Client *client,
1465                                  const struct GNUNET_MessageHeader *mh)
1466 {
1467   struct LazyCopyRequest *cr;
1468   const struct GNUNET_SET_CopyLazyConnectMessage *msg =
1469       (const struct GNUNET_SET_CopyLazyConnectMessage *) mh;
1470   struct Set *set;
1471   int found;
1472
1473   if (NULL != set_get (client))
1474   {
1475     /* There can only be one set per client */
1476     GNUNET_break (0);
1477     GNUNET_SERVER_client_disconnect (client);
1478     return;
1479   }
1480
1481   found = GNUNET_NO;
1482
1483   for (cr = lazy_copy_head; NULL != cr; cr = cr->next)
1484   {
1485     if (cr->cookie == msg->cookie)
1486     {
1487       found = GNUNET_YES;
1488       break;
1489     } 
1490   }
1491
1492   if (GNUNET_NO == found)
1493   {
1494     /* client asked for copy with cookie we don't know */
1495     GNUNET_break (0);
1496     GNUNET_SERVER_client_disconnect (client);
1497     return;
1498   }
1499
1500   GNUNET_CONTAINER_DLL_remove (lazy_copy_head,
1501                                lazy_copy_tail,
1502                                cr);
1503
1504   set = GNUNET_new (struct Set);
1505
1506   switch (cr->source_set->operation)
1507   {
1508   case GNUNET_SET_OPERATION_INTERSECTION:
1509     set->vt = _GSS_intersection_vt ();
1510     break;
1511   case GNUNET_SET_OPERATION_UNION:
1512     set->vt = _GSS_union_vt ();
1513     break;
1514   default:
1515     GNUNET_assert (0);
1516     return;
1517   }
1518
1519   if (NULL == set->vt->copy_state) {
1520     /* Lazy copy not supported for this set operation */
1521     GNUNET_break (0);
1522     GNUNET_free (set);
1523     GNUNET_free (cr);
1524     GNUNET_SERVER_client_disconnect (client);
1525     return;
1526   }
1527
1528   set->operation = cr->source_set->operation;
1529   set->state = set->vt->copy_state (cr->source_set);
1530   set->content = cr->source_set->content;
1531   set->content->refcount += 1;
1532   set->client = client;
1533   set->client_mq = GNUNET_MQ_queue_for_server_client (client);
1534   GNUNET_CONTAINER_DLL_insert (sets_head,
1535                                sets_tail,
1536                                set);
1537
1538   GNUNET_free (cr);
1539
1540   GNUNET_SERVER_receive_done (client,
1541                               GNUNET_OK);
1542
1543   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1544               "Client connected to lazy set\n");
1545 }
1546
1547
1548 /**
1549  * Handle a request from the client to
1550  * cancel a running set operation.
1551  *
1552  * @param cls unused
1553  * @param client the client
1554  * @param mh the message
1555  */
1556 static void
1557 handle_client_cancel (void *cls,
1558                       struct GNUNET_SERVER_Client *client,
1559                       const struct GNUNET_MessageHeader *mh)
1560 {
1561   const struct GNUNET_SET_CancelMessage *msg =
1562       (const struct GNUNET_SET_CancelMessage *) mh;
1563   struct Set *set;
1564   struct Operation *op;
1565   int found;
1566
1567   set = set_get (client);
1568   if (NULL == set)
1569   {
1570     /* client without a set requested an operation */
1571     GNUNET_break (0);
1572     GNUNET_SERVER_client_disconnect (client);
1573     return;
1574   }
1575   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1576               "Client requested cancel for op %u\n",
1577               ntohl (msg->request_id));
1578   found = GNUNET_NO;
1579   for (op = set->ops_head; NULL != op; op = op->next)
1580   {
1581     if (op->spec->client_request_id == ntohl (msg->request_id))
1582     {
1583       found = GNUNET_YES;
1584       break;
1585     }
1586   }
1587   if (GNUNET_NO == found)
1588   {
1589     /* It may happen that the operation was already destroyed due to
1590      * the other peer disconnecting.  The client may not know about this
1591      * yet and try to cancel the (just barely non-existent) operation.
1592      * So this is not a hard error.
1593      */
1594     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1595                 "Client canceled non-existent op\n");
1596   }
1597   else
1598   {
1599     _GSS_operation_destroy (op,
1600                             GNUNET_YES);
1601   }
1602   GNUNET_SERVER_receive_done (client,
1603                               GNUNET_OK);
1604 }
1605
1606
1607 /**
1608  * Handle a request from the client to accept a set operation that
1609  * came from a remote peer.  We forward the accept to the associated
1610  * operation for handling
1611  *
1612  * @param cls unused
1613  * @param client the client
1614  * @param mh the message
1615  */
1616 static void
1617 handle_client_accept (void *cls,
1618                       struct GNUNET_SERVER_Client *client,
1619                       const struct GNUNET_MessageHeader *mh)
1620 {
1621   struct Set *set;
1622   const struct GNUNET_SET_AcceptMessage *msg;
1623   struct Operation *op;
1624   struct GNUNET_SET_ResultMessage *result_message;
1625   struct GNUNET_MQ_Envelope *ev;
1626
1627   msg = (const struct GNUNET_SET_AcceptMessage *) mh;
1628   set = set_get (client);
1629   if (NULL == set)
1630   {
1631     /* client without a set requested to accept */
1632     GNUNET_break (0);
1633     GNUNET_SERVER_client_disconnect (client);
1634     return;
1635   }
1636   op = get_incoming (ntohl (msg->accept_reject_id));
1637   if (NULL == op)
1638   {
1639     /* It is not an error if the set op does not exist -- it may
1640      * have been destroyed when the partner peer disconnected. */
1641     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1642                 "Client accepted request that is no longer active\n");
1643     ev = GNUNET_MQ_msg (result_message,
1644                         GNUNET_MESSAGE_TYPE_SET_RESULT);
1645     result_message->request_id = msg->request_id;
1646     result_message->element_type = 0;
1647     result_message->result_status = htons (GNUNET_SET_STATUS_FAILURE);
1648     GNUNET_MQ_send (set->client_mq, ev);
1649     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1650     return;
1651   }
1652
1653   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1654               "Client accepting request %u\n",
1655               ntohl (msg->accept_reject_id));
1656   GNUNET_assert (GNUNET_YES == op->is_incoming);
1657   op->is_incoming = GNUNET_NO;
1658   GNUNET_CONTAINER_DLL_remove (incoming_head,
1659                                incoming_tail,
1660                                op);
1661   op->spec->set = set;
1662   GNUNET_CONTAINER_DLL_insert (set->ops_head,
1663                                set->ops_tail,
1664                                op);
1665   op->spec->client_request_id = ntohl (msg->request_id);
1666   op->spec->result_mode = ntohl (msg->result_mode);
1667
1668   // Advance generation values, so that
1669   // mutations won't interfer with the running operation.
1670   op->generation_created = set->current_generation;
1671   advance_generation (set);
1672
1673   op->vt = set->vt;
1674   op->vt->accept (op);
1675   GNUNET_SERVER_receive_done (client,
1676                               GNUNET_OK);
1677 }
1678
1679
1680 /**
1681  * Called to clean up, after a shutdown has been requested.
1682  *
1683  * @param cls closure
1684  * @param tc context information (why was this task triggered now)
1685  */
1686 static void
1687 shutdown_task (void *cls,
1688                const struct GNUNET_SCHEDULER_TaskContext *tc)
1689 {
1690   while (NULL != incoming_head)
1691     incoming_destroy (incoming_head);
1692   while (NULL != listeners_head)
1693     listener_destroy (listeners_head);
1694   while (NULL != sets_head)
1695     set_destroy (sets_head);
1696
1697   /* it's important to destroy cadet at the end, as all channels
1698    * must be destroyed before the cadet handle! */
1699   if (NULL != cadet)
1700   {
1701     GNUNET_CADET_disconnect (cadet);
1702     cadet = NULL;
1703   }
1704   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1705               "handled shutdown request\n");
1706 }
1707
1708
1709 /**
1710  * Timeout happens iff:
1711  *  - we suggested an operation to our listener,
1712  *    but did not receive a response in time
1713  *  - we got the channel from a peer but no #GNUNET_MESSAGE_TYPE_SET_P2P_OPERATION_REQUEST
1714  *  - shutdown (obviously)
1715  *
1716  * @param cls channel context
1717  * @param tc context information (why was this task triggered now)
1718  */
1719 static void
1720 incoming_timeout_cb (void *cls,
1721                      const struct GNUNET_SCHEDULER_TaskContext *tc)
1722 {
1723   struct Operation *incoming = cls;
1724
1725   incoming->timeout_task = NULL;
1726   GNUNET_assert (GNUNET_YES == incoming->is_incoming);
1727   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1728     return;
1729   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1730               "Remote peer's incoming request timed out\n");
1731   incoming_destroy (incoming);
1732 }
1733
1734
1735 /**
1736  * Terminates an incoming operation in case we have not yet received an
1737  * operation request. Called by the channel destruction handler.
1738  *
1739  * @param op the channel context
1740  */
1741 static void
1742 handle_incoming_disconnect (struct Operation *op)
1743 {
1744   GNUNET_assert (GNUNET_YES == op->is_incoming);
1745   /* channel is already dead, incoming_destroy must not
1746    * destroy it ... */
1747   op->channel = NULL;
1748   incoming_destroy (op);
1749   op->vt = NULL;
1750 }
1751
1752
1753 /**
1754  * Method called whenever another peer has added us to a channel the
1755  * other peer initiated.  Only called (once) upon reception of data
1756  * with a message type which was subscribed to in
1757  * GNUNET_CADET_connect().
1758  *
1759  * The channel context represents the operation itself and gets added to a DLL,
1760  * from where it gets looked up when our local listener client responds
1761  * to a proposed/suggested operation or connects and associates with this operation.
1762  *
1763  * @param cls closure
1764  * @param channel new handle to the channel
1765  * @param initiator peer that started the channel
1766  * @param port Port this channel is for.
1767  * @param options Unused.
1768  * @return initial channel context for the channel
1769  *         returns NULL on error
1770  */
1771 static void *
1772 channel_new_cb (void *cls,
1773                 struct GNUNET_CADET_Channel *channel,
1774                 const struct GNUNET_PeerIdentity *initiator,
1775                 uint32_t port,
1776                 enum GNUNET_CADET_ChannelOption options)
1777 {
1778   static const struct SetVT incoming_vt = {
1779     .msg_handler = &handle_incoming_msg,
1780     .peer_disconnect = &handle_incoming_disconnect
1781   };
1782   struct Operation *incoming;
1783
1784   if (GNUNET_APPLICATION_TYPE_SET != port)
1785   {
1786     GNUNET_break (0);
1787     GNUNET_CADET_channel_destroy (channel);
1788     return NULL;
1789   }
1790   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1791               "New incoming channel\n");
1792   incoming = GNUNET_new (struct Operation);
1793   incoming->is_incoming = GNUNET_YES;
1794   incoming->peer = *initiator;
1795   incoming->channel = channel;
1796   incoming->mq = GNUNET_CADET_mq_create (incoming->channel);
1797   incoming->vt = &incoming_vt;
1798   incoming->timeout_task
1799     = GNUNET_SCHEDULER_add_delayed (INCOMING_CHANNEL_TIMEOUT,
1800                                     &incoming_timeout_cb,
1801                                     incoming);
1802   GNUNET_CONTAINER_DLL_insert_tail (incoming_head,
1803                                     incoming_tail,
1804                                     incoming);
1805   return incoming;
1806 }
1807
1808
1809 /**
1810  * Function called whenever a channel is destroyed.  Should clean up
1811  * any associated state.  It must NOT call
1812  * GNUNET_CADET_channel_destroy() on the channel.
1813  *
1814  * The peer_disconnect function is part of a a virtual table set initially either
1815  * when a peer creates a new channel with us (#channel_new_cb()), or once we create
1816  * a new channel ourselves (evaluate).
1817  *
1818  * Once we know the exact type of operation (union/intersection), the vt is
1819  * replaced with an operation specific instance (_GSS_[op]_vt).
1820  *
1821  * @param cls closure (set from GNUNET_CADET_connect())
1822  * @param channel connection to the other end (henceforth invalid)
1823  * @param channel_ctx place where local state associated
1824  *                   with the channel is stored
1825  */
1826 static void
1827 channel_end_cb (void *cls,
1828                 const struct GNUNET_CADET_Channel *channel,
1829                 void *channel_ctx)
1830 {
1831   struct Operation *op = channel_ctx;
1832
1833   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1834               "channel_end_cb called\n");
1835   op->channel = NULL;
1836   op->keep++;
1837   /* the vt can be null if a client already requested canceling op. */
1838   if (NULL != op->vt)
1839   {
1840     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1841                 "calling peer disconnect due to channel end\n");
1842     op->vt->peer_disconnect (op);
1843   }
1844   op->keep--;
1845   if (0 == op->keep)
1846   {
1847     /* cadet will never call us with the context again! */
1848     GNUNET_free (op);
1849   }
1850   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1851               "channel_end_cb finished\n");
1852 }
1853
1854
1855 /**
1856  * Functions with this signature are called whenever a message is
1857  * received via a cadet channel.
1858  *
1859  * The msg_handler is a virtual table set in initially either when a peer
1860  * creates a new channel with us (channel_new_cb), or once we create a new channel
1861  * ourselves (evaluate).
1862  *
1863  * Once we know the exact type of operation (union/intersection), the vt is
1864  * replaced with an operation specific instance (_GSS_[op]_vt).
1865  *
1866  * @param cls Closure (set from GNUNET_CADET_connect()).
1867  * @param channel Connection to the other end.
1868  * @param channel_ctx Place to store local state associated with the channel.
1869  * @param message The actual message.
1870  * @return #GNUNET_OK to keep the channel open,
1871  *         #GNUNET_SYSERR to close it (signal serious error).
1872  */
1873 static int
1874 dispatch_p2p_message (void *cls,
1875                       struct GNUNET_CADET_Channel *channel,
1876                       void **channel_ctx,
1877                       const struct GNUNET_MessageHeader *message)
1878 {
1879   struct Operation *op = *channel_ctx;
1880   int ret;
1881
1882   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1883               "Dispatching cadet message (type: %u)\n",
1884               ntohs (message->type));
1885   /* do this before the handler, as the handler might kill the channel */
1886   GNUNET_CADET_receive_done (channel);
1887   if (NULL != op->vt)
1888     ret = op->vt->msg_handler (op,
1889                                message);
1890   else
1891     ret = GNUNET_SYSERR;
1892   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1893               "Handled cadet message (type: %u)\n",
1894               ntohs (message->type));
1895   return ret;
1896 }
1897
1898
1899 /**
1900  * Function called by the service's run
1901  * method to run service-specific setup code.
1902  *
1903  * @param cls closure
1904  * @param server the initialized server
1905  * @param cfg configuration to use
1906  */
1907 static void
1908 run (void *cls,
1909      struct GNUNET_SERVER_Handle *server,
1910      const struct GNUNET_CONFIGURATION_Handle *cfg)
1911 {
1912   static const struct GNUNET_SERVER_MessageHandler server_handlers[] = {
1913     { &handle_client_accept, NULL,
1914       GNUNET_MESSAGE_TYPE_SET_ACCEPT,
1915       sizeof (struct GNUNET_SET_AcceptMessage)},
1916     { &handle_client_iter_ack, NULL,
1917       GNUNET_MESSAGE_TYPE_SET_ITER_ACK,
1918       sizeof (struct GNUNET_SET_IterAckMessage) },
1919     { &handle_client_mutation, NULL,
1920       GNUNET_MESSAGE_TYPE_SET_ADD,
1921       0},
1922     { &handle_client_create_set, NULL,
1923       GNUNET_MESSAGE_TYPE_SET_CREATE,
1924       sizeof (struct GNUNET_SET_CreateMessage)},
1925     { &handle_client_iterate, NULL,
1926       GNUNET_MESSAGE_TYPE_SET_ITER_REQUEST,
1927       sizeof (struct GNUNET_MessageHeader)},
1928     { &handle_client_evaluate, NULL,
1929       GNUNET_MESSAGE_TYPE_SET_EVALUATE,
1930       0},
1931     { &handle_client_listen, NULL,
1932       GNUNET_MESSAGE_TYPE_SET_LISTEN,
1933       sizeof (struct GNUNET_SET_ListenMessage)},
1934     { &handle_client_reject, NULL,
1935       GNUNET_MESSAGE_TYPE_SET_REJECT,
1936       sizeof (struct GNUNET_SET_RejectMessage)},
1937     { &handle_client_mutation, NULL,
1938       GNUNET_MESSAGE_TYPE_SET_REMOVE,
1939       0},
1940     { &handle_client_cancel, NULL,
1941       GNUNET_MESSAGE_TYPE_SET_CANCEL,
1942       sizeof (struct GNUNET_SET_CancelMessage)},
1943     { &handle_client_copy_lazy_prepare, NULL,
1944       GNUNET_MESSAGE_TYPE_SET_COPY_LAZY_PREPARE,
1945       sizeof (struct GNUNET_MessageHeader)},
1946     { &handle_client_copy_lazy_connect, NULL,
1947       GNUNET_MESSAGE_TYPE_SET_COPY_LAZY_CONNECT,
1948       sizeof (struct GNUNET_SET_CopyLazyConnectMessage)},
1949     { NULL, NULL, 0, 0}
1950   };
1951   static const struct GNUNET_CADET_MessageHandler cadet_handlers[] = {
1952     { &dispatch_p2p_message, GNUNET_MESSAGE_TYPE_SET_P2P_OPERATION_REQUEST, 0},
1953     { &dispatch_p2p_message, GNUNET_MESSAGE_TYPE_SET_UNION_P2P_IBF, 0},
1954     { &dispatch_p2p_message, GNUNET_MESSAGE_TYPE_SET_P2P_ELEMENTS, 0},
1955     { &dispatch_p2p_message, GNUNET_MESSAGE_TYPE_SET_UNION_P2P_OFFER, 0},
1956     { &dispatch_p2p_message, GNUNET_MESSAGE_TYPE_SET_UNION_P2P_INQUIRY, 0},
1957     { &dispatch_p2p_message, GNUNET_MESSAGE_TYPE_SET_UNION_P2P_DEMAND, 0},
1958     { &dispatch_p2p_message, GNUNET_MESSAGE_TYPE_SET_P2P_ELEMENT_REQUESTS, 0},
1959     { &dispatch_p2p_message, GNUNET_MESSAGE_TYPE_SET_UNION_P2P_DONE, 0},
1960     { &dispatch_p2p_message, GNUNET_MESSAGE_TYPE_SET_UNION_P2P_SE, 0},
1961     { &dispatch_p2p_message, GNUNET_MESSAGE_TYPE_SET_INTERSECTION_P2P_ELEMENT_INFO, 0},
1962     { &dispatch_p2p_message, GNUNET_MESSAGE_TYPE_SET_INTERSECTION_P2P_BF, 0},
1963     { &dispatch_p2p_message, GNUNET_MESSAGE_TYPE_SET_INTERSECTION_P2P_DONE, 0},
1964     {NULL, 0, 0}
1965   };
1966   static const uint32_t cadet_ports[] = {GNUNET_APPLICATION_TYPE_SET, 0};
1967
1968   configuration = cfg;
1969   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
1970                                 &shutdown_task, NULL);
1971   GNUNET_SERVER_disconnect_notify (server,
1972                                    &handle_client_disconnect, NULL);
1973   GNUNET_SERVER_add_handlers (server,
1974                               server_handlers);
1975   cadet = GNUNET_CADET_connect (cfg, NULL,
1976                                 &channel_new_cb,
1977                                 &channel_end_cb,
1978                                 cadet_handlers,
1979                                 cadet_ports);
1980   if (NULL == cadet)
1981   {
1982     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1983                 _("Could not connect to cadet service\n"));
1984     return;
1985   }
1986 }
1987
1988
1989 /**
1990  * The main function for the set service.
1991  *
1992  * @param argc number of arguments from the command line
1993  * @param argv command line arguments
1994  * @return 0 ok, 1 on error
1995  */
1996 int
1997 main (int argc,
1998       char *const *argv)
1999 {
2000   int ret;
2001
2002   ret = GNUNET_SERVICE_run (argc, argv, "set",
2003                             GNUNET_SERVICE_OPTION_NONE,
2004                             &run, NULL);
2005   return (GNUNET_OK == ret) ? 0 : 1;
2006 }
2007
2008 /* end of gnunet-service-set.c */