-rename file
[oweals/gnunet.git] / src / set / set_api.c
1 /*
2      This file is part of GNUnet.
3      (C) 2012-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., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20 /**
21  * @file set/set_api.c
22  * @brief api for the set service
23  * @author Florian Dold
24  * @author Christian Grothoff
25  */
26 #include "platform.h"
27 #include "gnunet_util_lib.h"
28 #include "gnunet_protocols.h"
29 #include "gnunet_client_lib.h"
30 #include "gnunet_set_service.h"
31 #include "set.h"
32
33
34 #define LOG(kind,...) GNUNET_log_from (kind, "set-api",__VA_ARGS__)
35
36 /**
37  * Opaque handle to a set.
38  */
39 struct GNUNET_SET_Handle
40 {
41   /**
42    * Client connected to the set service.
43    */
44   struct GNUNET_CLIENT_Connection *client;
45
46   /**
47    * Message queue for @e client.
48    */
49   struct GNUNET_MQ_Handle *mq;
50
51   /**
52    * Linked list of operations on the set.
53    */
54   struct GNUNET_SET_OperationHandle *ops_head;
55
56   /**
57    * Linked list of operations on the set.
58    */
59   struct GNUNET_SET_OperationHandle *ops_tail;
60
61   /**
62    * Callback for the current iteration over the set,
63    * NULL if no iterator is active.
64    */
65   GNUNET_SET_ElementIterator iterator;
66
67   /**
68    * Closure for @e iterator
69    */
70   void *iterator_cls;
71
72   /**
73    * Should the set be destroyed once all operations are gone?
74    */
75   int destroy_requested;
76
77   /**
78    * Has the set become invalid (e.g. service died)?
79    */
80   int invalid;
81
82   /**
83    * Both client and service count the number of iterators
84    * created so far to match replies with iterators.
85    */
86   uint16_t iteration_id;
87 };
88
89
90 /**
91  * Handle for a set operation request from another peer.
92  */
93 struct GNUNET_SET_Request
94 {
95   /**
96    * Id of the request, used to identify the request when
97    * accepting/rejecting it.
98    */
99   uint32_t accept_id;
100
101   /**
102    * Has the request been accepted already?
103    * #GNUNET_YES/#GNUNET_NO
104    */
105   int accepted;
106 };
107
108
109 /**
110  * Handle to an operation.  Only known to the service after committing
111  * the handle with a set.
112  */
113 struct GNUNET_SET_OperationHandle
114 {
115   /**
116    * Function to be called when we have a result,
117    * or an error.
118    */
119   GNUNET_SET_ResultIterator result_cb;
120
121   /**
122    * Closure for @e result_cb.
123    */
124   void *result_cls;
125
126   /**
127    * Local set used for the operation,
128    * NULL if no set has been provided by conclude yet.
129    */
130   struct GNUNET_SET_Handle *set;
131
132   /**
133    * Message sent to the server on calling conclude,
134    * NULL if conclude has been called.
135    */
136   struct GNUNET_MQ_Envelope *conclude_mqm;
137
138   /**
139    * Address of the request if in the conclude message,
140    * used to patch the request id into the message when the set is known.
141    */
142   uint32_t *request_id_addr;
143
144   /**
145    * Handles are kept in a linked list.
146    */
147   struct GNUNET_SET_OperationHandle *prev;
148
149   /**
150    * Handles are kept in a linked list.
151    */
152   struct GNUNET_SET_OperationHandle *next;
153
154   /**
155    * Request ID to identify the operation within the set.
156    */
157   uint32_t request_id;
158 };
159
160
161 /**
162  * Opaque handle to a listen operation.
163  */
164 struct GNUNET_SET_ListenHandle
165 {
166   /**
167    * Connection to the service.
168    */
169   struct GNUNET_CLIENT_Connection *client;
170
171   /**
172    * Message queue for the client.
173    */
174   struct GNUNET_MQ_Handle* mq;
175
176   /**
177    * Configuration handle for the listener, stored
178    * here to be able to reconnect transparently on
179    * connection failure.
180    */
181   const struct GNUNET_CONFIGURATION_Handle *cfg;
182
183   /**
184    * Function to call on a new incoming request,
185    * or on error.
186    */
187   GNUNET_SET_ListenCallback listen_cb;
188
189   /**
190    * Closure for @e listen_cb.
191    */
192   void *listen_cls;
193
194   /**
195    * Application ID we listen for.
196    */
197   struct GNUNET_HashCode app_id;
198
199   /**
200    * Time to wait until we try to reconnect on failure.
201    */
202   struct GNUNET_TIME_Relative reconnect_backoff;
203
204   /**
205    * Task for reconnecting when the listener fails.
206    */
207   GNUNET_SCHEDULER_TaskIdentifier reconnect_task;
208
209   /**
210    * Operation we listen for.
211    */
212   enum GNUNET_SET_OperationType operation;
213 };
214
215
216 /**
217  * Handle element for iteration over the set.  Notifies the
218  * iterator and sends an acknowledgement to the service.
219  *
220  * @param cls the `struct GNUNET_SET_Handle *`
221  * @param mh the message
222  */
223 static void
224 handle_iter_element (void *cls,
225                      const struct GNUNET_MessageHeader *mh)
226 {
227   struct GNUNET_SET_Handle *set = cls;
228   GNUNET_SET_ElementIterator iter = set->iterator;
229   struct GNUNET_SET_Element element;
230   const struct GNUNET_SET_IterResponseMessage *msg;
231   struct GNUNET_SET_IterAckMessage *ack_msg;
232   struct GNUNET_MQ_Envelope *ev;
233   uint16_t msize;
234
235   msize = ntohs (mh->size);
236   if (msize < sizeof (sizeof (struct GNUNET_SET_IterResponseMessage)))
237   {
238     /* message malformed */
239     GNUNET_break (0);
240     set->iterator = NULL;
241     set->iteration_id++;
242     iter (set->iterator_cls,
243           NULL);
244     iter = NULL;
245   }
246   msg = (const struct GNUNET_SET_IterResponseMessage *) mh;
247   if (set->iteration_id != ntohs (msg->iteration_id))
248   {
249     /* element from a previous iteration, skip! */
250     iter = NULL;
251   }
252   if (NULL != iter)
253   {
254     element.size = msize - sizeof (struct GNUNET_SET_IterResponseMessage);
255     element.element_type = htons (msg->element_type);
256     element.data = &msg[1];
257     iter (set->iterator_cls,
258           &element);
259   }
260   ev = GNUNET_MQ_msg (ack_msg,
261                       GNUNET_MESSAGE_TYPE_SET_ITER_ACK);
262   ack_msg->send_more = htonl ((NULL != iter));
263   GNUNET_MQ_send (set->mq, ev);
264 }
265
266
267 /**
268  * Handle message signalling conclusion of iteration over the set.
269  * Notifies the iterator that we are done.
270  *
271  * @param cls the set
272  * @param mh the message
273  */
274 static void
275 handle_iter_done (void *cls,
276                   const struct GNUNET_MessageHeader *mh)
277 {
278   struct GNUNET_SET_Handle *set = cls;
279   GNUNET_SET_ElementIterator iter = set->iterator;
280
281   if (NULL == iter)
282     return;
283   set->iterator = NULL;
284   set->iteration_id++;
285   iter (set->iterator_cls,
286         NULL);
287 }
288
289
290 /**
291  * Handle result message for a set operation.
292  *
293  * @param cls the set
294  * @param mh the message
295  */
296 static void
297 handle_result (void *cls,
298                const struct GNUNET_MessageHeader *mh)
299 {
300   struct GNUNET_SET_Handle *set = cls;
301   const struct GNUNET_SET_ResultMessage *msg;
302   struct GNUNET_SET_OperationHandle *oh;
303   struct GNUNET_SET_Element e;
304   enum GNUNET_SET_Status result_status;
305
306   msg = (const struct GNUNET_SET_ResultMessage *) mh;
307   GNUNET_assert (NULL != set->mq);
308   result_status = ntohs (msg->result_status);
309   oh = GNUNET_MQ_assoc_get (set->mq,
310                             ntohl (msg->request_id));
311   if (NULL == oh)
312   {
313     /* 'oh' can be NULL if we canceled the operation, but the service
314        did not get the cancel message yet. */
315     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
316                 "Ignoring result from canceled operation\n");
317     return;
318   }
319   if (GNUNET_SET_STATUS_OK != result_status)
320   {
321     /* status is not #GNUNET_SET_STATUS_OK => there's no attached element,
322      * and this is the last result message we get */
323     GNUNET_MQ_assoc_remove (set->mq, ntohl (msg->request_id));
324     GNUNET_CONTAINER_DLL_remove (set->ops_head,
325                                  set->ops_tail,
326                                  oh);
327     if ( (GNUNET_YES == set->destroy_requested) &&
328          (NULL == set->ops_head) )
329       GNUNET_SET_destroy (set);
330     if (NULL != oh->result_cb)
331       oh->result_cb (oh->result_cls,
332                      NULL,
333                      result_status);
334     GNUNET_free (oh);
335     return;
336   }
337   e.data = &msg[1];
338   e.size = ntohs (mh->size) - sizeof (struct GNUNET_SET_ResultMessage);
339   e.element_type = msg->element_type;
340   if (NULL != oh->result_cb)
341     oh->result_cb (oh->result_cls,
342                    &e,
343                    result_status);
344 }
345
346
347 /**
348  * Destroy the given set operation.
349  *
350  * @param oh set operation to destroy
351  */
352 static void
353 set_operation_destroy (struct GNUNET_SET_OperationHandle *oh)
354 {
355   struct GNUNET_SET_Handle *set = oh->set;
356   struct GNUNET_SET_OperationHandle *h_assoc;
357
358   if (NULL != oh->conclude_mqm)
359     GNUNET_MQ_discard (oh->conclude_mqm);
360   /* is the operation already commited? */
361   if (NULL != set)
362   {
363     GNUNET_CONTAINER_DLL_remove (set->ops_head,
364                                  set->ops_tail,
365                                  oh);
366     h_assoc = GNUNET_MQ_assoc_remove (set->mq,
367                                       oh->request_id);
368     GNUNET_assert ((NULL == h_assoc) || (h_assoc == oh));
369   }
370   GNUNET_free (oh);
371 }
372
373
374 /**
375  * Cancel the given set operation.  We need to send an explicit cancel
376  * message, as all operations one one set communicate using one
377  * handle.
378  *
379  * @param oh set operation to cancel
380  */
381 void
382 GNUNET_SET_operation_cancel (struct GNUNET_SET_OperationHandle *oh)
383 {
384   struct GNUNET_SET_Handle *set = oh->set;
385   struct GNUNET_SET_CancelMessage *m;
386   struct GNUNET_MQ_Envelope *mqm;
387
388   if (NULL != set)
389   {
390     mqm = GNUNET_MQ_msg (m, GNUNET_MESSAGE_TYPE_SET_CANCEL);
391     m->request_id = htonl (oh->request_id);
392     GNUNET_MQ_send (set->mq, mqm);
393   }
394   set_operation_destroy (oh);
395   if ( (NULL != set) &&
396        (GNUNET_YES == set->destroy_requested) &&
397        (NULL == set->ops_head) )
398   {
399     LOG (GNUNET_ERROR_TYPE_DEBUG,
400          "Destroying set after operation cancel\n");
401     GNUNET_SET_destroy (set);
402   }
403 }
404
405
406 /**
407  * We encountered an error communicating with the set service while
408  * performing a set operation. Report to the application.
409  *
410  * @param cls the `struct GNUNET_SET_Handle`
411  * @param error error code
412  */
413 static void
414 handle_client_set_error (void *cls,
415                          enum GNUNET_MQ_Error error)
416 {
417   struct GNUNET_SET_Handle *set = cls;
418
419   LOG (GNUNET_ERROR_TYPE_DEBUG,
420        "Handling client set error\n");
421   while (NULL != set->ops_head)
422   {
423     if (NULL != set->ops_head->result_cb)
424       set->ops_head->result_cb (set->ops_head->result_cls,
425                                 NULL,
426                                 GNUNET_SET_STATUS_FAILURE);
427     set_operation_destroy (set->ops_head);
428   }
429   set->invalid = GNUNET_YES;
430   if (GNUNET_YES == set->destroy_requested)
431   {
432     LOG (GNUNET_ERROR_TYPE_DEBUG,
433          "Destroying set after operation failure\n");
434     GNUNET_SET_destroy (set);
435   }
436 }
437
438
439 /**
440  * Create an empty set, supporting the specified operation.
441  *
442  * @param cfg configuration to use for connecting to the
443  *        set service
444  * @param op operation supported by the set
445  *        Note that the operation has to be specified
446  *        beforehand, as certain set operations need to maintain
447  *        data structures spefific to the operation
448  * @return a handle to the set
449  */
450 struct GNUNET_SET_Handle *
451 GNUNET_SET_create (const struct GNUNET_CONFIGURATION_Handle *cfg,
452                    enum GNUNET_SET_OperationType op)
453 {
454   static const struct GNUNET_MQ_MessageHandler mq_handlers[] = {
455     { &handle_result,
456       GNUNET_MESSAGE_TYPE_SET_RESULT,
457       0 },
458     { &handle_iter_element,
459       GNUNET_MESSAGE_TYPE_SET_ITER_ELEMENT,
460       0 },
461     { &handle_iter_done,
462       GNUNET_MESSAGE_TYPE_SET_ITER_DONE,
463       sizeof (struct GNUNET_MessageHeader) },
464     GNUNET_MQ_HANDLERS_END
465   };
466   struct GNUNET_SET_Handle *set;
467   struct GNUNET_MQ_Envelope *mqm;
468   struct GNUNET_SET_CreateMessage *msg;
469
470   set = GNUNET_new (struct GNUNET_SET_Handle);
471   set->client = GNUNET_CLIENT_connect ("set", cfg);
472   if (NULL == set->client)
473   {
474     GNUNET_free (set);
475     return NULL;
476   }
477   set->mq = GNUNET_MQ_queue_for_connection_client (set->client,
478                                                    mq_handlers,
479                                                    &handle_client_set_error, set);
480   GNUNET_assert (NULL != set->mq);
481   mqm = GNUNET_MQ_msg (msg,
482                        GNUNET_MESSAGE_TYPE_SET_CREATE);
483   msg->operation = htonl (op);
484   GNUNET_MQ_send (set->mq, mqm);
485   return set;
486 }
487
488
489 /**
490  * Add an element to the given set.  After the element has been added
491  * (in the sense of being transmitted to the set service), @a cont
492  * will be called.  Multiple calls to GNUNET_SET_add_element() can be
493  * queued.
494  *
495  * @param set set to add element to
496  * @param element element to add to the set
497  * @param cont continuation called after the element has been added
498  * @param cont_cls closure for @a cont
499  * @return #GNUNET_OK on success, #GNUNET_SYSERR if the
500  *         set is invalid (e.g. the set service crashed)
501  */
502 int
503 GNUNET_SET_add_element (struct GNUNET_SET_Handle *set,
504                         const struct GNUNET_SET_Element *element,
505                         GNUNET_SET_Continuation cont,
506                         void *cont_cls)
507 {
508   struct GNUNET_MQ_Envelope *mqm;
509   struct GNUNET_SET_ElementMessage *msg;
510
511   if (GNUNET_YES == set->invalid)
512   {
513     if (NULL != cont)
514       cont (cont_cls);
515     return GNUNET_SYSERR;
516   }
517   mqm = GNUNET_MQ_msg_extra (msg, element->size,
518                              GNUNET_MESSAGE_TYPE_SET_ADD);
519   msg->element_type = element->element_type;
520   memcpy (&msg[1],
521           element->data,
522           element->size);
523   GNUNET_MQ_notify_sent (mqm,
524                          cont, cont_cls);
525   GNUNET_MQ_send (set->mq, mqm);
526   return GNUNET_OK;
527 }
528
529
530 /**
531  * Remove an element to the given set.  After the element has been
532  * removed (in the sense of the request being transmitted to the set
533  * service), @a cont will be called.  Multiple calls to
534  * GNUNET_SET_remove_element() can be queued
535  *
536  * @param set set to remove element from
537  * @param element element to remove from the set
538  * @param cont continuation called after the element has been removed
539  * @param cont_cls closure for @a cont
540  * @return #GNUNET_OK on success, #GNUNET_SYSERR if the
541  *         set is invalid (e.g. the set service crashed)
542  */
543 int
544 GNUNET_SET_remove_element (struct GNUNET_SET_Handle *set,
545                            const struct GNUNET_SET_Element *element,
546                            GNUNET_SET_Continuation cont,
547                            void *cont_cls)
548 {
549   struct GNUNET_MQ_Envelope *mqm;
550   struct GNUNET_SET_ElementMessage *msg;
551
552   if (GNUNET_YES == set->invalid)
553   {
554     if (NULL != cont)
555       cont (cont_cls);
556     return GNUNET_SYSERR;
557   }
558   mqm = GNUNET_MQ_msg_extra (msg,
559                              element->size,
560                              GNUNET_MESSAGE_TYPE_SET_REMOVE);
561   msg->element_type = element->element_type;
562   memcpy (&msg[1],
563           element->data,
564           element->size);
565   GNUNET_MQ_notify_sent (mqm,
566                          cont, cont_cls);
567   GNUNET_MQ_send (set->mq, mqm);
568   return GNUNET_OK;
569 }
570
571
572 /**
573  * Destroy the set handle if no operations are left, mark the set
574  * for destruction otherwise.
575  *
576  * @param set set handle to destroy
577  */
578 void
579 GNUNET_SET_destroy (struct GNUNET_SET_Handle *set)
580 {
581   /* destroying set while iterator is active is currently
582      not supported; we should expand the API to allow
583      clients to explicitly cancel the iteration! */
584   GNUNET_assert (NULL == set->iterator);
585   if (NULL != set->ops_head)
586   {
587     LOG (GNUNET_ERROR_TYPE_DEBUG,
588          "Set operations are pending, delaying set destruction\n");
589     set->destroy_requested = GNUNET_YES;
590     return;
591   }
592   LOG (GNUNET_ERROR_TYPE_DEBUG,
593        "Really destroying set\n");
594   if (NULL != set->client)
595   {
596     GNUNET_CLIENT_disconnect (set->client);
597     set->client = NULL;
598   }
599   if (NULL != set->mq)
600   {
601     GNUNET_MQ_destroy (set->mq);
602     set->mq = NULL;
603   }
604   GNUNET_free (set);
605 }
606
607
608 /**
609  * Prepare a set operation to be evaluated with another peer.
610  * The evaluation will not start until the client provides
611  * a local set with #GNUNET_SET_commit().
612  *
613  * @param other_peer peer with the other set
614  * @param app_id hash for the application using the set
615  * @param context_msg additional information for the request
616  * @param result_mode specified how results will be returned,
617  *        see `enum GNUNET_SET_ResultMode`.
618  * @param result_cb called on error or success
619  * @param result_cls closure for @e result_cb
620  * @return a handle to cancel the operation
621  */
622 struct GNUNET_SET_OperationHandle *
623 GNUNET_SET_prepare (const struct GNUNET_PeerIdentity *other_peer,
624                     const struct GNUNET_HashCode *app_id,
625                     const struct GNUNET_MessageHeader *context_msg,
626                     enum GNUNET_SET_ResultMode result_mode,
627                     GNUNET_SET_ResultIterator result_cb,
628                     void *result_cls)
629 {
630   struct GNUNET_MQ_Envelope *mqm;
631   struct GNUNET_SET_OperationHandle *oh;
632   struct GNUNET_SET_EvaluateMessage *msg;
633
634   oh = GNUNET_new (struct GNUNET_SET_OperationHandle);
635   oh->result_cb = result_cb;
636   oh->result_cls = result_cls;
637   mqm = GNUNET_MQ_msg_nested_mh (msg,
638                                  GNUNET_MESSAGE_TYPE_SET_EVALUATE,
639                                  context_msg);
640   msg->app_id = *app_id;
641   msg->result_mode = htonl (result_mode);
642   msg->target_peer = *other_peer;
643   oh->conclude_mqm = mqm;
644   oh->request_id_addr = &msg->request_id;
645
646   return oh;
647 }
648
649
650 /**
651  * Connect to the set service in order to listen for requests.
652  *
653  * @param cls the `struct GNUNET_SET_ListenHandle *` to connect
654  * @param tc task context if invoked as a task, NULL otherwise
655  */
656 static void
657 listen_connect (void *cls,
658                 const struct GNUNET_SCHEDULER_TaskContext *tc);
659
660
661 /**
662  * Handle request message for a listen operation
663  *
664  * @param cls the listen handle
665  * @param mh the message
666  */
667 static void
668 handle_request (void *cls,
669                 const struct GNUNET_MessageHeader *mh)
670 {
671   struct GNUNET_SET_ListenHandle *lh = cls;
672   const struct GNUNET_SET_RequestMessage *msg;
673   struct GNUNET_SET_Request req;
674   const struct GNUNET_MessageHeader *context_msg;
675   uint16_t msize;
676   struct GNUNET_MQ_Envelope *mqm;
677   struct GNUNET_SET_RejectMessage *rmsg;
678
679   LOG (GNUNET_ERROR_TYPE_DEBUG,
680        "Processing incoming operation request\n");
681   msize = ntohs (mh->size);
682   if (msize < sizeof (struct GNUNET_SET_RequestMessage))
683   {
684     GNUNET_break (0);
685     GNUNET_CLIENT_disconnect (lh->client);
686     lh->client = NULL;
687     GNUNET_MQ_destroy (lh->mq);
688     lh->mq = NULL;
689     lh->reconnect_task = GNUNET_SCHEDULER_add_delayed (lh->reconnect_backoff,
690                                                        &listen_connect, lh);
691     lh->reconnect_backoff = GNUNET_TIME_STD_BACKOFF (lh->reconnect_backoff);
692     return;
693   }
694   /* we got another valid request => reset the backoff */
695   lh->reconnect_backoff = GNUNET_TIME_UNIT_MILLISECONDS;
696   msg = (const struct GNUNET_SET_RequestMessage *) mh;
697   req.accept_id = ntohl (msg->accept_id);
698   req.accepted = GNUNET_NO;
699   context_msg = GNUNET_MQ_extract_nested_mh (msg);
700   /* calling #GNUNET_SET_accept() in the listen cb will set req->accepted */
701   lh->listen_cb (lh->listen_cls,
702                  &msg->peer_id,
703                  context_msg,
704                  &req);
705   if (GNUNET_YES == req.accepted)
706     return; /* the accept-case is handled in #GNUNET_SET_accept() */
707   LOG (GNUNET_ERROR_TYPE_DEBUG,
708        "Rejecting request\n");
709   mqm = GNUNET_MQ_msg (rmsg,
710                        GNUNET_MESSAGE_TYPE_SET_REJECT);
711   rmsg->accept_reject_id = msg->accept_id;
712   GNUNET_MQ_send (lh->mq, mqm);
713 }
714
715
716 /**
717  * Our connection with the set service encountered an error,
718  * re-initialize with exponential back-off.
719  *
720  * @param cls the `struct GNUNET_SET_ListenHandle *`
721  * @param error reason for the disconnect
722  */
723 static void
724 handle_client_listener_error (void *cls,
725                               enum GNUNET_MQ_Error error)
726 {
727   struct GNUNET_SET_ListenHandle *lh = cls;
728
729   LOG (GNUNET_ERROR_TYPE_DEBUG,
730        "Listener broke down (%d), re-connecting\n",
731        (int) error);
732   GNUNET_CLIENT_disconnect (lh->client);
733   lh->client = NULL;
734   GNUNET_MQ_destroy (lh->mq);
735   lh->mq = NULL;
736   lh->reconnect_task = GNUNET_SCHEDULER_add_delayed (lh->reconnect_backoff,
737                                                      &listen_connect, lh);
738   lh->reconnect_backoff = GNUNET_TIME_STD_BACKOFF (lh->reconnect_backoff);
739 }
740
741
742 /**
743  * Connect to the set service in order to listen for requests.
744  *
745  * @param cls the `struct GNUNET_SET_ListenHandle *` to connect
746  * @param tc task context if invoked as a task, NULL otherwise
747  */
748 static void
749 listen_connect (void *cls,
750                 const struct GNUNET_SCHEDULER_TaskContext *tc)
751 {
752   static const struct GNUNET_MQ_MessageHandler mq_handlers[] = {
753     { &handle_request, GNUNET_MESSAGE_TYPE_SET_REQUEST },
754     GNUNET_MQ_HANDLERS_END
755   };
756   struct GNUNET_SET_ListenHandle *lh = cls;
757   struct GNUNET_MQ_Envelope *mqm;
758   struct GNUNET_SET_ListenMessage *msg;
759
760   if ( (NULL != tc) &&
761        (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN)) )
762   {
763     LOG (GNUNET_ERROR_TYPE_DEBUG,
764          "Listener not reconnecting due to shutdown\n");
765     return;
766   }
767   lh->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
768   GNUNET_assert (NULL == lh->client);
769   lh->client = GNUNET_CLIENT_connect ("set", lh->cfg);
770   if (NULL == lh->client)
771     return;
772   GNUNET_assert (NULL == lh->mq);
773   lh->mq = GNUNET_MQ_queue_for_connection_client (lh->client,
774                                                   mq_handlers,
775                                                   &handle_client_listener_error, lh);
776   mqm = GNUNET_MQ_msg (msg, GNUNET_MESSAGE_TYPE_SET_LISTEN);
777   msg->operation = htonl (lh->operation);
778   msg->app_id = lh->app_id;
779   GNUNET_MQ_send (lh->mq, mqm);
780 }
781
782
783 /**
784  * Wait for set operation requests for the given application id
785  *
786  * @param cfg configuration to use for connecting to
787  *            the set service, needs to be valid for the lifetime of the listen handle
788  * @param operation operation we want to listen for
789  * @param app_id id of the application that handles set operation requests
790  * @param listen_cb called for each incoming request matching the operation
791  *                  and application id
792  * @param listen_cls handle for @a listen_cb
793  * @return a handle that can be used to cancel the listen operation
794  */
795 struct GNUNET_SET_ListenHandle *
796 GNUNET_SET_listen (const struct GNUNET_CONFIGURATION_Handle *cfg,
797                    enum GNUNET_SET_OperationType operation,
798                    const struct GNUNET_HashCode *app_id,
799                    GNUNET_SET_ListenCallback listen_cb,
800                    void *listen_cls)
801 {
802   struct GNUNET_SET_ListenHandle *lh;
803
804   lh = GNUNET_new (struct GNUNET_SET_ListenHandle);
805   lh->listen_cb = listen_cb;
806   lh->listen_cls = listen_cls;
807   lh->cfg = cfg;
808   lh->operation = operation;
809   lh->app_id = *app_id;
810   lh->reconnect_backoff = GNUNET_TIME_UNIT_MILLISECONDS;
811   listen_connect (lh, NULL);
812   if (NULL == lh->client)
813   {
814     GNUNET_free (lh);
815     return NULL;
816   }
817   return lh;
818 }
819
820
821 /**
822  * Cancel the given listen operation.
823  *
824  * @param lh handle for the listen operation
825  */
826 void
827 GNUNET_SET_listen_cancel (struct GNUNET_SET_ListenHandle *lh)
828 {
829   LOG (GNUNET_ERROR_TYPE_DEBUG,
830        "Canceling listener\n");
831   if (NULL != lh->mq)
832   {
833     GNUNET_MQ_destroy (lh->mq);
834     lh->mq = NULL;
835   }
836   if (NULL != lh->client)
837   {
838     GNUNET_CLIENT_disconnect (lh->client);
839     lh->client = NULL;
840   }
841   if (GNUNET_SCHEDULER_NO_TASK != lh->reconnect_task)
842   {
843     GNUNET_SCHEDULER_cancel (lh->reconnect_task);
844     lh->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
845   }
846   GNUNET_free (lh);
847 }
848
849
850 /**
851  * Accept a request we got via #GNUNET_SET_listen.  Must be called during
852  * #GNUNET_SET_listen, as the 'struct GNUNET_SET_Request' becomes invalid
853  * afterwards.
854  * Call #GNUNET_SET_commit to provide the local set to use for the operation,
855  * and to begin the exchange with the remote peer.
856  *
857  * @param request request to accept
858  * @param result_mode specified how results will be returned,
859  *        see `enum GNUNET_SET_ResultMode`.
860  * @param result_cb callback for the results
861  * @param result_cls closure for @a result_cb
862  * @return a handle to cancel the operation
863  */
864 struct GNUNET_SET_OperationHandle *
865 GNUNET_SET_accept (struct GNUNET_SET_Request *request,
866                    enum GNUNET_SET_ResultMode result_mode,
867                    GNUNET_SET_ResultIterator result_cb,
868                    void *result_cls)
869 {
870   struct GNUNET_MQ_Envelope *mqm;
871   struct GNUNET_SET_OperationHandle *oh;
872   struct GNUNET_SET_AcceptMessage *msg;
873
874   GNUNET_assert (GNUNET_NO == request->accepted);
875   request->accepted = GNUNET_YES;
876   mqm = GNUNET_MQ_msg (msg, GNUNET_MESSAGE_TYPE_SET_ACCEPT);
877   msg->accept_reject_id = htonl (request->accept_id);
878   msg->result_mode = htonl (result_mode);
879   oh = GNUNET_new (struct GNUNET_SET_OperationHandle);
880   oh->result_cb = result_cb;
881   oh->result_cls = result_cls;
882   oh->conclude_mqm = mqm;
883   oh->request_id_addr = &msg->request_id;
884   return oh;
885 }
886
887
888 /**
889  * Commit a set to be used with a set operation.
890  * This function is called once we have fully constructed
891  * the set that we want to use for the operation.  At this
892  * time, the P2P protocol can then begin to exchange the
893  * set information and call the result callback with the
894  * result information.
895  *
896  * @param oh handle to the set operation
897  * @param set the set to use for the operation
898  * @return #GNUNET_OK on success, #GNUNET_SYSERR if the
899  *         set is invalid (e.g. the set service crashed)
900  */
901 int
902 GNUNET_SET_commit (struct GNUNET_SET_OperationHandle *oh,
903                    struct GNUNET_SET_Handle *set)
904 {
905   GNUNET_assert (NULL == oh->set);
906   if (GNUNET_YES == set->invalid)
907     return GNUNET_SYSERR;
908   GNUNET_assert (NULL != oh->conclude_mqm);
909   oh->set = set;
910   GNUNET_CONTAINER_DLL_insert (set->ops_head,
911                                set->ops_tail,
912                                oh);
913   oh->request_id = GNUNET_MQ_assoc_add (set->mq, oh);
914   *oh->request_id_addr = htonl (oh->request_id);
915   GNUNET_MQ_send (set->mq, oh->conclude_mqm);
916   oh->conclude_mqm = NULL;
917   oh->request_id_addr = NULL;
918   return GNUNET_OK;
919 }
920
921
922 /**
923  * Iterate over all elements in the given set.  Note that this
924  * operation involves transferring every element of the set from the
925  * service to the client, and is thus costly.
926  *
927  * @param set the set to iterate over
928  * @param iter the iterator to call for each element
929  * @param iter_cls closure for @a iter
930  * @return #GNUNET_YES if the iteration started successfuly,
931  *         #GNUNET_NO if another iteration is active
932  *         #GNUNET_SYSERR if the set is invalid (e.g. the server crashed, disconnected)
933  */
934 int
935 GNUNET_SET_iterate (struct GNUNET_SET_Handle *set,
936                     GNUNET_SET_ElementIterator iter,
937                     void *iter_cls)
938 {
939   struct GNUNET_MQ_Envelope *ev;
940
941   GNUNET_assert (NULL != iter);
942   if (GNUNET_YES == set->invalid)
943     return GNUNET_SYSERR;
944   if (NULL != set->iterator)
945     return GNUNET_NO;
946   LOG (GNUNET_ERROR_TYPE_DEBUG,
947        "Iterating over set\n");
948   set->iterator = iter;
949   set->iterator_cls = iter_cls;
950   ev = GNUNET_MQ_msg_header (GNUNET_MESSAGE_TYPE_SET_ITER_REQUEST);
951   GNUNET_MQ_send (set->mq, ev);
952   return GNUNET_YES;
953 }
954
955
956 /**
957  * Stop iteration over all elements in the given set.  Can only
958  * be called before the iteration has "naturally" completed its
959  * turn.
960  *
961  * @param set the set to stop iterating over
962  */
963 void
964 GNUNET_SET_iterate_cancel (struct GNUNET_SET_Handle *set)
965 {
966   GNUNET_assert (NULL != set->iterator);
967   set->iterator = NULL;
968   set->iteration_id++;
969 }
970
971
972 /* end of set_api.c */