src: for every AGPL3.0 file, add SPDX identifier.
[oweals/gnunet.git] / src / set / gnunet-service-set_intersection.c
1 /*
2       This file is part of GNUnet
3       Copyright (C) 2013-2017 GNUnet e.V.
4
5       GNUnet is free software: you can redistribute it and/or modify it
6       under the terms of the GNU Affero General Public License as published
7       by the Free Software Foundation, either version 3 of the License,
8       or (at your 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       Affero General Public License for more details.
14
15       You should have received a copy of the GNU Affero General Public License
16       along with this program.  If not, see <http://www.gnu.org/licenses/>.
17
18      SPDX-License-Identifier: AGPL3.0-or-later
19 */
20 /**
21  * @file set/gnunet-service-set_intersection.c
22  * @brief two-peer set intersection
23  * @author Christian Fuchs
24  * @author Christian Grothoff
25  */
26 #include "platform.h"
27 #include "gnunet_util_lib.h"
28 #include "gnunet_statistics_service.h"
29 #include "gnunet-service-set.h"
30 #include "gnunet_block_lib.h"
31 #include "gnunet-service-set_protocol.h"
32 #include "gnunet-service-set_intersection.h"
33 #include <gcrypt.h>
34
35
36 /**
37  * Current phase we are in for a intersection operation.
38  */
39 enum IntersectionOperationPhase
40 {
41   /**
42    * We are just starting.
43    */
44   PHASE_INITIAL,
45
46   /**
47    * We have send the number of our elements to the other
48    * peer, but did not setup our element set yet.
49    */
50   PHASE_COUNT_SENT,
51
52   /**
53    * We have initialized our set and are now reducing it by exchanging
54    * Bloom filters until one party notices the their element hashes
55    * are equal.
56    */
57   PHASE_BF_EXCHANGE,
58
59   /**
60    * We must next send the P2P DONE message (after finishing mostly
61    * with the local client).  Then we will wait for the channel to close.
62    */
63   PHASE_MUST_SEND_DONE,
64
65   /**
66    * We have received the P2P DONE message, and must finish with the
67    * local client before terminating the channel.
68    */
69   PHASE_DONE_RECEIVED,
70
71   /**
72    * The protocol is over.  Results may still have to be sent to the
73    * client.
74    */
75   PHASE_FINISHED
76
77 };
78
79
80 /**
81  * State of an evaluate operation with another peer.
82  */
83 struct OperationState
84 {
85   /**
86    * The bf we currently receive
87    */
88   struct GNUNET_CONTAINER_BloomFilter *remote_bf;
89
90   /**
91    * BF of the set's element.
92    */
93   struct GNUNET_CONTAINER_BloomFilter *local_bf;
94
95   /**
96    * Remaining elements in the intersection operation.
97    * Maps element-id-hashes to 'elements in our set'.
98    */
99   struct GNUNET_CONTAINER_MultiHashMap *my_elements;
100
101   /**
102    * Iterator for sending the final set of @e my_elements to the client.
103    */
104   struct GNUNET_CONTAINER_MultiHashMapIterator *full_result_iter;
105
106   /**
107    * Evaluate operations are held in a linked list.
108    */
109   struct OperationState *next;
110
111   /**
112    * Evaluate operations are held in a linked list.
113    */
114   struct OperationState *prev;
115
116   /**
117    * For multipart BF transmissions, we have to store the
118    * bloomfilter-data until we fully received it.
119    */
120   char *bf_data;
121
122   /**
123    * XOR of the keys of all of the elements (remaining) in my set.
124    * Always updated when elements are added or removed to
125    * @e my_elements.
126    */
127   struct GNUNET_HashCode my_xor;
128
129   /**
130    * XOR of the keys of all of the elements (remaining) in
131    * the other peer's set.  Updated when we receive the
132    * other peer's Bloom filter.
133    */
134   struct GNUNET_HashCode other_xor;
135
136   /**
137    * How many bytes of @e bf_data are valid?
138    */
139   uint32_t bf_data_offset;
140
141   /**
142    * Current element count contained within @e my_elements.
143    * (May differ briefly during initialization.)
144    */
145   uint32_t my_element_count;
146
147   /**
148    * size of the bloomfilter in @e bf_data.
149    */
150   uint32_t bf_data_size;
151
152   /**
153    * size of the bloomfilter
154    */
155   uint32_t bf_bits_per_element;
156
157   /**
158    * Salt currently used for BF construction (by us or the other peer,
159    * depending on where we are in the code).
160    */
161   uint32_t salt;
162
163   /**
164    * Current state of the operation.
165    */
166   enum IntersectionOperationPhase phase;
167
168   /**
169    * Generation in which the operation handle
170    * was created.
171    */
172   unsigned int generation_created;
173
174   /**
175    * Did we send the client that we are done?
176    */
177   int client_done_sent;
178
179   /**
180    * Set whenever we reach the state where the death of the
181    * channel is perfectly find and should NOT result in the
182    * operation being cancelled.
183    */
184   int channel_death_expected;
185 };
186
187
188 /**
189  * Extra state required for efficient set intersection.
190  * Merely tracks the total number of elements.
191  */
192 struct SetState
193 {
194   /**
195    * Number of currently valid elements in the set which have not been
196    * removed.
197    */
198   uint32_t current_set_element_count;
199 };
200
201
202 /**
203  * If applicable in the current operation mode, send a result message
204  * to the client indicating we removed an element.
205  *
206  * @param op intersection operation
207  * @param element element to send
208  */
209 static void
210 send_client_removed_element (struct Operation *op,
211                              struct GNUNET_SET_Element *element)
212 {
213   struct GNUNET_MQ_Envelope *ev;
214   struct GNUNET_SET_ResultMessage *rm;
215
216   if (GNUNET_SET_RESULT_REMOVED != op->result_mode)
217     return; /* Wrong mode for transmitting removed elements */
218   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
219               "Sending removed element (size %u) to client\n",
220               element->size);
221   GNUNET_STATISTICS_update (_GSS_statistics,
222                             "# Element removed messages sent",
223                             1,
224                             GNUNET_NO);
225   GNUNET_assert (0 != op->client_request_id);
226   ev = GNUNET_MQ_msg_extra (rm,
227                             element->size,
228                             GNUNET_MESSAGE_TYPE_SET_RESULT);
229   if (NULL == ev)
230   {
231     GNUNET_break (0);
232     return;
233   }
234   rm->result_status = htons (GNUNET_SET_STATUS_OK);
235   rm->request_id = htonl (op->client_request_id);
236   rm->element_type = element->element_type;
237   GNUNET_memcpy (&rm[1],
238                  element->data,
239                  element->size);
240   GNUNET_MQ_send (op->set->cs->mq,
241                   ev);
242 }
243
244
245 /**
246  * Fills the "my_elements" hashmap with all relevant elements.
247  *
248  * @param cls the `struct Operation *` we are performing
249  * @param key current key code
250  * @param value the `struct ElementEntry *` from the hash map
251  * @return #GNUNET_YES (we should continue to iterate)
252  */
253 static int
254 filtered_map_initialization (void *cls,
255                              const struct GNUNET_HashCode *key,
256                              void *value)
257 {
258   struct Operation *op = cls;
259   struct ElementEntry *ee = value;
260   struct GNUNET_HashCode mutated_hash;
261
262
263   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
264               "FIMA called for %s:%u\n",
265               GNUNET_h2s (&ee->element_hash),
266               ee->element.size);
267
268   if (GNUNET_NO == _GSS_is_element_of_operation (ee, op))
269   {
270     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
271                 "Reduced initialization, not starting with %s:%u (wrong generation)\n",
272                 GNUNET_h2s (&ee->element_hash),
273                 ee->element.size);
274     return GNUNET_YES; /* element not valid in our operation's generation */
275   }
276
277   /* Test if element is in other peer's bloomfilter */
278   GNUNET_BLOCK_mingle_hash (&ee->element_hash,
279                             op->state->salt,
280                             &mutated_hash);
281   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
282               "Testing mingled hash %s with salt %u\n",
283               GNUNET_h2s (&mutated_hash),
284               op->state->salt);
285   if (GNUNET_NO ==
286       GNUNET_CONTAINER_bloomfilter_test (op->state->remote_bf,
287                                          &mutated_hash))
288   {
289     /* remove this element */
290     send_client_removed_element (op,
291                                  &ee->element);
292     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
293                 "Reduced initialization, not starting with %s:%u\n",
294                 GNUNET_h2s (&ee->element_hash),
295                 ee->element.size);
296     return GNUNET_YES;
297   }
298   op->state->my_element_count++;
299   GNUNET_CRYPTO_hash_xor (&op->state->my_xor,
300                           &ee->element_hash,
301                           &op->state->my_xor);
302   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
303               "Filtered initialization of my_elements, adding %s:%u\n",
304               GNUNET_h2s (&ee->element_hash),
305               ee->element.size);
306   GNUNET_break (GNUNET_YES ==
307                 GNUNET_CONTAINER_multihashmap_put (op->state->my_elements,
308                                                    &ee->element_hash,
309                                                    ee,
310                                                    GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
311
312   return GNUNET_YES;
313 }
314
315
316 /**
317  * Removes elements from our hashmap if they are not contained within the
318  * provided remote bloomfilter.
319  *
320  * @param cls closure with the `struct Operation *`
321  * @param key current key code
322  * @param value value in the hash map
323  * @return #GNUNET_YES (we should continue to iterate)
324  */
325 static int
326 iterator_bf_reduce (void *cls,
327                    const struct GNUNET_HashCode *key,
328                    void *value)
329 {
330   struct Operation *op = cls;
331   struct ElementEntry *ee = value;
332   struct GNUNET_HashCode mutated_hash;
333
334   GNUNET_BLOCK_mingle_hash (&ee->element_hash,
335                             op->state->salt,
336                             &mutated_hash);
337   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
338               "Testing mingled hash %s with salt %u\n",
339               GNUNET_h2s (&mutated_hash),
340               op->state->salt);
341   if (GNUNET_NO ==
342       GNUNET_CONTAINER_bloomfilter_test (op->state->remote_bf,
343                                          &mutated_hash))
344   {
345     GNUNET_break (0 < op->state->my_element_count);
346     op->state->my_element_count--;
347     GNUNET_CRYPTO_hash_xor (&op->state->my_xor,
348                             &ee->element_hash,
349                             &op->state->my_xor);
350     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
351                 "Bloom filter reduction of my_elements, removing %s:%u\n",
352                 GNUNET_h2s (&ee->element_hash),
353                 ee->element.size);
354     GNUNET_assert (GNUNET_YES ==
355                    GNUNET_CONTAINER_multihashmap_remove (op->state->my_elements,
356                                                          &ee->element_hash,
357                                                          ee));
358     send_client_removed_element (op,
359                                  &ee->element);
360   }
361   else
362   {
363     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
364                 "Bloom filter reduction of my_elements, keeping %s:%u\n",
365                 GNUNET_h2s (&ee->element_hash),
366                 ee->element.size);
367   }
368   return GNUNET_YES;
369 }
370
371
372 /**
373  * Create initial bloomfilter based on all the elements given.
374  *
375  * @param cls the `struct Operation *`
376  * @param key current key code
377  * @param value the `struct ElementEntry` to process
378  * @return #GNUNET_YES (we should continue to iterate)
379  */
380 static int
381 iterator_bf_create (void *cls,
382                     const struct GNUNET_HashCode *key,
383                     void *value)
384 {
385   struct Operation *op = cls;
386   struct ElementEntry *ee = value;
387   struct GNUNET_HashCode mutated_hash;
388
389   GNUNET_BLOCK_mingle_hash (&ee->element_hash,
390                             op->state->salt,
391                             &mutated_hash);
392   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
393               "Initializing BF with hash %s with salt %u\n",
394               GNUNET_h2s (&mutated_hash),
395               op->state->salt);
396   GNUNET_CONTAINER_bloomfilter_add (op->state->local_bf,
397                                     &mutated_hash);
398   return GNUNET_YES;
399 }
400
401
402 /**
403  * Inform the client that the intersection operation has failed,
404  * and proceed to destroy the evaluate operation.
405  *
406  * @param op the intersection operation to fail
407  */
408 static void
409 fail_intersection_operation (struct Operation *op)
410 {
411   struct GNUNET_MQ_Envelope *ev;
412   struct GNUNET_SET_ResultMessage *msg;
413
414   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
415               "Intersection operation failed\n");
416   GNUNET_STATISTICS_update (_GSS_statistics,
417                             "# Intersection operations failed",
418                             1,
419                             GNUNET_NO);
420   if (NULL != op->state->my_elements)
421   {
422     GNUNET_CONTAINER_multihashmap_destroy (op->state->my_elements);
423     op->state->my_elements = NULL;
424   }
425   ev = GNUNET_MQ_msg (msg,
426                       GNUNET_MESSAGE_TYPE_SET_RESULT);
427   msg->result_status = htons (GNUNET_SET_STATUS_FAILURE);
428   msg->request_id = htonl (op->client_request_id);
429   msg->element_type = htons (0);
430   GNUNET_MQ_send (op->set->cs->mq,
431                   ev);
432   _GSS_operation_destroy (op,
433                           GNUNET_YES);
434 }
435
436
437 /**
438  * Send a bloomfilter to our peer.  After the result done message has
439  * been sent to the client, destroy the evaluate operation.
440  *
441  * @param op intersection operation
442  */
443 static void
444 send_bloomfilter (struct Operation *op)
445 {
446   struct GNUNET_MQ_Envelope *ev;
447   struct BFMessage *msg;
448   uint32_t bf_size;
449   uint32_t bf_elementbits;
450   uint32_t chunk_size;
451   char *bf_data;
452   uint32_t offset;
453
454   /* We consider the ratio of the set sizes to determine
455      the number of bits per element, as the smaller set
456      should use more bits to maximize its set reduction
457      potential and minimize overall bandwidth consumption. */
458   bf_elementbits = 2 + ceil (log2((double)
459                              (op->remote_element_count /
460                               (double) op->state->my_element_count)));
461   if (bf_elementbits < 1)
462     bf_elementbits = 1; /* make sure k is not 0 */
463   /* optimize BF-size to ~50% of bits set */
464   bf_size = ceil ((double) (op->state->my_element_count
465                             * bf_elementbits / log(2)));
466   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
467               "Sending Bloom filter (%u) of size %u bytes\n",
468               (unsigned int) bf_elementbits,
469               (unsigned int) bf_size);
470   op->state->local_bf = GNUNET_CONTAINER_bloomfilter_init (NULL,
471                                                            bf_size,
472                                                            bf_elementbits);
473   op->state->salt = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
474                                               UINT32_MAX);
475   GNUNET_CONTAINER_multihashmap_iterate (op->state->my_elements,
476                                          &iterator_bf_create,
477                                          op);
478
479   /* send our Bloom filter */
480   GNUNET_STATISTICS_update (_GSS_statistics,
481                             "# Intersection Bloom filters sent",
482                             1,
483                             GNUNET_NO);
484   chunk_size = 60 * 1024 - sizeof (struct BFMessage);
485   if (bf_size <= chunk_size)
486   {
487     /* singlepart */
488     chunk_size = bf_size;
489     ev = GNUNET_MQ_msg_extra (msg,
490                               chunk_size,
491                               GNUNET_MESSAGE_TYPE_SET_INTERSECTION_P2P_BF);
492     GNUNET_assert (GNUNET_SYSERR !=
493                    GNUNET_CONTAINER_bloomfilter_get_raw_data (op->state->local_bf,
494                                                               (char*) &msg[1],
495                                                               bf_size));
496     msg->sender_element_count = htonl (op->state->my_element_count);
497     msg->bloomfilter_total_length = htonl (bf_size);
498     msg->bits_per_element = htonl (bf_elementbits);
499     msg->sender_mutator = htonl (op->state->salt);
500     msg->element_xor_hash = op->state->my_xor;
501     GNUNET_MQ_send (op->mq, ev);
502   }
503   else
504   {
505     /* multipart */
506     bf_data = GNUNET_malloc (bf_size);
507     GNUNET_assert (GNUNET_SYSERR !=
508                    GNUNET_CONTAINER_bloomfilter_get_raw_data (op->state->local_bf,
509                                                               bf_data,
510                                                               bf_size));
511     offset = 0;
512     while (offset < bf_size)
513     {
514       if (bf_size - chunk_size < offset)
515         chunk_size = bf_size - offset;
516       ev = GNUNET_MQ_msg_extra (msg,
517                                 chunk_size,
518                                 GNUNET_MESSAGE_TYPE_SET_INTERSECTION_P2P_BF);
519       GNUNET_memcpy (&msg[1],
520               &bf_data[offset],
521               chunk_size);
522       offset += chunk_size;
523       msg->sender_element_count = htonl (op->state->my_element_count);
524       msg->bloomfilter_total_length = htonl (bf_size);
525       msg->bits_per_element = htonl (bf_elementbits);
526       msg->sender_mutator = htonl (op->state->salt);
527       msg->element_xor_hash = op->state->my_xor;
528       GNUNET_MQ_send (op->mq, ev);
529     }
530     GNUNET_free (bf_data);
531   }
532   GNUNET_CONTAINER_bloomfilter_free (op->state->local_bf);
533   op->state->local_bf = NULL;
534 }
535
536
537 /**
538  * Signal to the client that the operation has finished and
539  * destroy the operation.
540  *
541  * @param cls operation to destroy
542  */
543 static void
544 send_client_done_and_destroy (void *cls)
545 {
546   struct Operation *op = cls;
547   struct GNUNET_MQ_Envelope *ev;
548   struct GNUNET_SET_ResultMessage *rm;
549
550   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
551               "Intersection succeeded, sending DONE to local client\n");
552   GNUNET_STATISTICS_update (_GSS_statistics,
553                             "# Intersection operations succeeded",
554                             1,
555                             GNUNET_NO);
556   ev = GNUNET_MQ_msg (rm,
557                       GNUNET_MESSAGE_TYPE_SET_RESULT);
558   rm->request_id = htonl (op->client_request_id);
559   rm->result_status = htons (GNUNET_SET_STATUS_DONE);
560   rm->element_type = htons (0);
561   GNUNET_MQ_send (op->set->cs->mq,
562                   ev);
563   _GSS_operation_destroy (op,
564                           GNUNET_YES);
565 }
566
567
568 /**
569  * Remember that we are done dealing with the local client
570  * AND have sent the other peer our message that we are done,
571  * so we are not just waiting for the channel to die before
572  * telling the local client that we are done as our last act.
573  *
574  * @param cls the `struct Operation`.
575  */
576 static void
577 finished_local_operations (void *cls)
578 {
579   struct Operation *op = cls;
580
581   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
582               "DONE sent to other peer, now waiting for other end to close the channel\n");
583   op->state->phase = PHASE_FINISHED;
584   op->state->channel_death_expected = GNUNET_YES;
585 }
586
587
588 /**
589  * Notify the other peer that we are done.  Once this message
590  * is out, we still need to notify the local client that we
591  * are done.
592  *
593  * @param op operation to notify for.
594  */
595 static void
596 send_p2p_done (struct Operation *op)
597 {
598   struct GNUNET_MQ_Envelope *ev;
599   struct IntersectionDoneMessage *idm;
600
601   GNUNET_assert (PHASE_MUST_SEND_DONE == op->state->phase);
602   GNUNET_assert (GNUNET_NO == op->state->channel_death_expected);
603   ev = GNUNET_MQ_msg (idm,
604                       GNUNET_MESSAGE_TYPE_SET_INTERSECTION_P2P_DONE);
605   idm->final_element_count = htonl (op->state->my_element_count);
606   idm->element_xor_hash = op->state->my_xor;
607   GNUNET_MQ_notify_sent (ev,
608                          &finished_local_operations,
609                          op);
610   GNUNET_MQ_send (op->mq,
611                   ev);
612 }
613
614
615 /**
616  * Send all elements in the full result iterator.
617  *
618  * @param cls the `struct Operation *`
619  */
620 static void
621 send_remaining_elements (void *cls)
622 {
623   struct Operation *op = cls;
624   const void *nxt;
625   const struct ElementEntry *ee;
626   struct GNUNET_MQ_Envelope *ev;
627   struct GNUNET_SET_ResultMessage *rm;
628   const struct GNUNET_SET_Element *element;
629   int res;
630
631   res = GNUNET_CONTAINER_multihashmap_iterator_next (op->state->full_result_iter,
632                                                      NULL,
633                                                      &nxt);
634   if (GNUNET_NO == res)
635   {
636     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
637                 "Sending done and destroy because iterator ran out\n");
638     GNUNET_CONTAINER_multihashmap_iterator_destroy (op->state->full_result_iter);
639     op->state->full_result_iter = NULL;
640     if (PHASE_DONE_RECEIVED == op->state->phase)
641     {
642       op->state->phase = PHASE_FINISHED;
643       send_client_done_and_destroy (op);
644     }
645     else if (PHASE_MUST_SEND_DONE == op->state->phase)
646     {
647       send_p2p_done (op);
648     }
649     else
650     {
651       GNUNET_assert (0);
652     }
653     return;
654   }
655   ee = nxt;
656   element = &ee->element;
657   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
658               "Sending element %s:%u to client (full set)\n",
659               GNUNET_h2s (&ee->element_hash),
660               element->size);
661   GNUNET_assert (0 != op->client_request_id);
662   ev = GNUNET_MQ_msg_extra (rm,
663                             element->size,
664                             GNUNET_MESSAGE_TYPE_SET_RESULT);
665   GNUNET_assert (NULL != ev);
666   rm->result_status = htons (GNUNET_SET_STATUS_OK);
667   rm->request_id = htonl (op->client_request_id);
668   rm->element_type = element->element_type;
669   GNUNET_memcpy (&rm[1],
670                  element->data,
671                  element->size);
672   GNUNET_MQ_notify_sent (ev,
673                          &send_remaining_elements,
674                          op);
675   GNUNET_MQ_send (op->set->cs->mq,
676                   ev);
677 }
678
679
680 /**
681  * Fills the "my_elements" hashmap with the initial set of
682  * (non-deleted) elements from the set of the specification.
683  *
684  * @param cls closure with the `struct Operation *`
685  * @param key current key code for the element
686  * @param value value in the hash map with the `struct ElementEntry *`
687  * @return #GNUNET_YES (we should continue to iterate)
688  */
689 static int
690 initialize_map_unfiltered (void *cls,
691                            const struct GNUNET_HashCode *key,
692                            void *value)
693 {
694   struct ElementEntry *ee = value;
695   struct Operation *op = cls;
696
697   if (GNUNET_NO == _GSS_is_element_of_operation (ee, op))
698     return GNUNET_YES; /* element not live in operation's generation */
699   GNUNET_CRYPTO_hash_xor (&op->state->my_xor,
700                           &ee->element_hash,
701                           &op->state->my_xor);
702   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
703               "Initial full initialization of my_elements, adding %s:%u\n",
704               GNUNET_h2s (&ee->element_hash),
705               ee->element.size);
706   GNUNET_break (GNUNET_YES ==
707                 GNUNET_CONTAINER_multihashmap_put (op->state->my_elements,
708                                                    &ee->element_hash,
709                                                    ee,
710                                                    GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
711   return GNUNET_YES;
712 }
713
714
715 /**
716  * Send our element count to the peer, in case our element count is
717  * lower than theirs.
718  *
719  * @param op intersection operation
720  */
721 static void
722 send_element_count (struct Operation *op)
723 {
724   struct GNUNET_MQ_Envelope *ev;
725   struct IntersectionElementInfoMessage *msg;
726
727   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
728               "Sending our element count (%u)\n",
729               op->state->my_element_count);
730   ev = GNUNET_MQ_msg (msg,
731                       GNUNET_MESSAGE_TYPE_SET_INTERSECTION_P2P_ELEMENT_INFO);
732   msg->sender_element_count = htonl (op->state->my_element_count);
733   GNUNET_MQ_send (op->mq, ev);
734 }
735
736
737 /**
738  * We go first, initialize our map with all elements and
739  * send the first Bloom filter.
740  *
741  * @param op operation to start exchange for
742  */
743 static void
744 begin_bf_exchange (struct Operation *op)
745 {
746   op->state->phase = PHASE_BF_EXCHANGE;
747   GNUNET_CONTAINER_multihashmap_iterate (op->set->content->elements,
748                                          &initialize_map_unfiltered,
749                                          op);
750   send_bloomfilter (op);
751 }
752
753
754 /**
755  * Handle the initial `struct IntersectionElementInfoMessage` from a
756  * remote peer.
757  *
758  * @param cls the intersection operation
759  * @param mh the header of the message
760  */
761 void
762 handle_intersection_p2p_element_info (void *cls,
763                                       const struct IntersectionElementInfoMessage *msg)
764 {
765   struct Operation *op = cls;
766
767   if (GNUNET_SET_OPERATION_INTERSECTION != op->set->operation)
768   {
769     GNUNET_break_op (0);
770     fail_intersection_operation(op);
771     return;
772   }
773   op->remote_element_count = ntohl (msg->sender_element_count);
774   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
775               "Received remote element count (%u), I have %u\n",
776               op->remote_element_count,
777               op->state->my_element_count);
778   if ( ( (PHASE_INITIAL != op->state->phase) &&
779          (PHASE_COUNT_SENT != op->state->phase) ) ||
780        (op->state->my_element_count > op->remote_element_count) ||
781        (0 == op->state->my_element_count) ||
782        (0 == op->remote_element_count) )
783   {
784     GNUNET_break_op (0);
785     fail_intersection_operation(op);
786     return;
787   }
788   GNUNET_break (NULL == op->state->remote_bf);
789   begin_bf_exchange (op);
790   GNUNET_CADET_receive_done (op->channel);
791 }
792
793
794 /**
795  * Process a Bloomfilter once we got all the chunks.
796  *
797  * @param op the intersection operation
798  */
799 static void
800 process_bf (struct Operation *op)
801 {
802   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
803               "Received BF in phase %u, foreign count is %u, my element count is %u/%u\n",
804               op->state->phase,
805               op->remote_element_count,
806               op->state->my_element_count,
807               GNUNET_CONTAINER_multihashmap_size (op->set->content->elements));
808   switch (op->state->phase)
809   {
810   case PHASE_INITIAL:
811     GNUNET_break_op (0);
812     fail_intersection_operation(op);
813     return;
814   case PHASE_COUNT_SENT:
815     /* This is the first BF being sent, build our initial map with
816        filtering in place */
817     op->state->my_element_count = 0;
818     GNUNET_CONTAINER_multihashmap_iterate (op->set->content->elements,
819                                            &filtered_map_initialization,
820                                            op);
821     break;
822   case PHASE_BF_EXCHANGE:
823     /* Update our set by reduction */
824     GNUNET_CONTAINER_multihashmap_iterate (op->state->my_elements,
825                                            &iterator_bf_reduce,
826                                            op);
827     break;
828   case PHASE_MUST_SEND_DONE:
829     GNUNET_break_op (0);
830     fail_intersection_operation(op);
831     return;
832   case PHASE_DONE_RECEIVED:
833     GNUNET_break_op (0);
834     fail_intersection_operation(op);
835     return;
836   case PHASE_FINISHED:
837     GNUNET_break_op (0);
838     fail_intersection_operation(op);
839     return;
840   }
841   GNUNET_CONTAINER_bloomfilter_free (op->state->remote_bf);
842   op->state->remote_bf = NULL;
843
844   if ( (0 == op->state->my_element_count) || /* fully disjoint */
845        ( (op->state->my_element_count == op->remote_element_count) &&
846          (0 == memcmp (&op->state->my_xor,
847                        &op->state->other_xor,
848                        sizeof (struct GNUNET_HashCode))) ) )
849   {
850     /* we are done */
851     op->state->phase = PHASE_MUST_SEND_DONE;
852     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
853                 "Intersection succeeded, sending DONE to other peer\n");
854     GNUNET_CONTAINER_bloomfilter_free (op->state->local_bf);
855     op->state->local_bf = NULL;
856     if (GNUNET_SET_RESULT_FULL == op->result_mode)
857     {
858       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
859                   "Sending full result set (%u elements)\n",
860                   GNUNET_CONTAINER_multihashmap_size (op->state->my_elements));
861       op->state->full_result_iter
862         = GNUNET_CONTAINER_multihashmap_iterator_create (op->state->my_elements);
863       send_remaining_elements (op);
864       return;
865     }
866     send_p2p_done (op);
867     return;
868   }
869   op->state->phase = PHASE_BF_EXCHANGE;
870   send_bloomfilter (op);
871 }
872
873
874 /**
875  * Check an BF message from a remote peer.
876  *
877  * @param cls the intersection operation
878  * @param msg the header of the message
879  * @return #GNUNET_OK if @a msg is well-formed
880  */
881 int
882 check_intersection_p2p_bf (void *cls,
883                            const struct BFMessage *msg)
884 {
885   struct Operation *op = cls;
886
887   if (GNUNET_SET_OPERATION_INTERSECTION != op->set->operation)
888   {
889     GNUNET_break_op (0);
890     return GNUNET_SYSERR;
891   }
892   return GNUNET_OK;
893 }
894
895
896 /**
897  * Handle an BF message from a remote peer.
898  *
899  * @param cls the intersection operation
900  * @param msg the header of the message
901  */
902 void
903 handle_intersection_p2p_bf (void *cls,
904                             const struct BFMessage *msg)
905 {
906   struct Operation *op = cls;
907   uint32_t bf_size;
908   uint32_t chunk_size;
909   uint32_t bf_bits_per_element;
910
911   switch (op->state->phase)
912   {
913   case PHASE_INITIAL:
914     GNUNET_break_op (0);
915     fail_intersection_operation (op);
916     return;
917   case PHASE_COUNT_SENT:
918   case PHASE_BF_EXCHANGE:
919     bf_size = ntohl (msg->bloomfilter_total_length);
920     bf_bits_per_element = ntohl (msg->bits_per_element);
921     chunk_size = htons (msg->header.size) - sizeof (struct BFMessage);
922     op->state->other_xor = msg->element_xor_hash;
923     if (bf_size == chunk_size)
924     {
925       if (NULL != op->state->bf_data)
926       {
927         GNUNET_break_op (0);
928         fail_intersection_operation (op);
929         return;
930       }
931       /* single part, done here immediately */
932       op->state->remote_bf
933         = GNUNET_CONTAINER_bloomfilter_init ((const char*) &msg[1],
934                                              bf_size,
935                                              bf_bits_per_element);
936       op->state->salt = ntohl (msg->sender_mutator);
937       op->remote_element_count = ntohl (msg->sender_element_count);
938       process_bf (op);
939       break;
940     }
941     /* multipart chunk */
942     if (NULL == op->state->bf_data)
943     {
944       /* first chunk, initialize */
945       op->state->bf_data = GNUNET_malloc (bf_size);
946       op->state->bf_data_size = bf_size;
947       op->state->bf_bits_per_element = bf_bits_per_element;
948       op->state->bf_data_offset = 0;
949       op->state->salt = ntohl (msg->sender_mutator);
950       op->remote_element_count = ntohl (msg->sender_element_count);
951     }
952     else
953     {
954       /* increment */
955       if ( (op->state->bf_data_size != bf_size) ||
956            (op->state->bf_bits_per_element != bf_bits_per_element) ||
957            (op->state->bf_data_offset + chunk_size > bf_size) ||
958            (op->state->salt != ntohl (msg->sender_mutator)) ||
959            (op->remote_element_count != ntohl (msg->sender_element_count)) )
960       {
961         GNUNET_break_op (0);
962         fail_intersection_operation (op);
963         return;
964       }
965     }
966     GNUNET_memcpy (&op->state->bf_data[op->state->bf_data_offset],
967             (const char*) &msg[1],
968             chunk_size);
969     op->state->bf_data_offset += chunk_size;
970     if (op->state->bf_data_offset == bf_size)
971     {
972       /* last chunk, run! */
973       op->state->remote_bf
974         = GNUNET_CONTAINER_bloomfilter_init (op->state->bf_data,
975                                              bf_size,
976                                              bf_bits_per_element);
977       GNUNET_free (op->state->bf_data);
978       op->state->bf_data = NULL;
979       op->state->bf_data_size = 0;
980       process_bf (op);
981     }
982     break;
983   default:
984     GNUNET_break_op (0);
985     fail_intersection_operation (op);
986     return;
987   }
988   GNUNET_CADET_receive_done (op->channel);
989 }
990
991
992 /**
993  * Remove all elements from our hashmap.
994  *
995  * @param cls closure with the `struct Operation *`
996  * @param key current key code
997  * @param value value in the hash map
998  * @return #GNUNET_YES (we should continue to iterate)
999  */
1000 static int
1001 filter_all (void *cls,
1002             const struct GNUNET_HashCode *key,
1003             void *value)
1004 {
1005   struct Operation *op = cls;
1006   struct ElementEntry *ee = value;
1007
1008   GNUNET_break (0 < op->state->my_element_count);
1009   op->state->my_element_count--;
1010   GNUNET_CRYPTO_hash_xor (&op->state->my_xor,
1011                           &ee->element_hash,
1012                           &op->state->my_xor);
1013   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1014               "Final reduction of my_elements, removing %s:%u\n",
1015               GNUNET_h2s (&ee->element_hash),
1016               ee->element.size);
1017   GNUNET_assert (GNUNET_YES ==
1018                  GNUNET_CONTAINER_multihashmap_remove (op->state->my_elements,
1019                                                        &ee->element_hash,
1020                                                        ee));
1021   send_client_removed_element (op,
1022                                &ee->element);
1023   return GNUNET_YES;
1024 }
1025
1026
1027 /**
1028  * Handle a done message from a remote peer
1029  *
1030  * @param cls the intersection operation
1031  * @param mh the message
1032  */
1033 void
1034 handle_intersection_p2p_done (void *cls,
1035                               const struct IntersectionDoneMessage *idm)
1036 {
1037   struct Operation *op = cls;
1038
1039   if (GNUNET_SET_OPERATION_INTERSECTION != op->set->operation)
1040   {
1041     GNUNET_break_op (0);
1042     fail_intersection_operation (op);
1043     return;
1044   }
1045   if (PHASE_BF_EXCHANGE != op->state->phase)
1046   {
1047     /* wrong phase to conclude? FIXME: Or should we allow this
1048        if the other peer has _initially_ already an empty set? */
1049     GNUNET_break_op (0);
1050     fail_intersection_operation (op);
1051     return;
1052   }
1053   if (0 == ntohl (idm->final_element_count))
1054   {
1055     /* other peer determined empty set is the intersection,
1056        remove all elements */
1057     GNUNET_CONTAINER_multihashmap_iterate (op->state->my_elements,
1058                                            &filter_all,
1059                                            op);
1060   }
1061   if ( (op->state->my_element_count != ntohl (idm->final_element_count)) ||
1062        (0 != memcmp (&op->state->my_xor,
1063                      &idm->element_xor_hash,
1064                      sizeof (struct GNUNET_HashCode))) )
1065   {
1066     /* Other peer thinks we are done, but we disagree on the result! */
1067     GNUNET_break_op (0);
1068     fail_intersection_operation (op);
1069     return;
1070   }
1071   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1072               "Got IntersectionDoneMessage, have %u elements in intersection\n",
1073               op->state->my_element_count);
1074   op->state->phase = PHASE_DONE_RECEIVED;
1075   GNUNET_CADET_receive_done (op->channel);
1076
1077   GNUNET_assert (GNUNET_NO == op->state->client_done_sent);
1078   if (GNUNET_SET_RESULT_FULL == op->result_mode)
1079   {
1080     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1081                 "Sending full result set to client (%u elements)\n",
1082                 GNUNET_CONTAINER_multihashmap_size (op->state->my_elements));
1083     op->state->full_result_iter
1084       = GNUNET_CONTAINER_multihashmap_iterator_create (op->state->my_elements);
1085     send_remaining_elements (op);
1086     return;
1087   }
1088   op->state->phase = PHASE_FINISHED;
1089   send_client_done_and_destroy (op);
1090 }
1091
1092
1093 /**
1094  * Initiate a set intersection operation with a remote peer.
1095  *
1096  * @param op operation that is created, should be initialized to
1097  *        begin the evaluation
1098  * @param opaque_context message to be transmitted to the listener
1099  *        to convince it to accept, may be NULL
1100  * @return operation-specific state to keep in @a op
1101  */
1102 static struct OperationState *
1103 intersection_evaluate (struct Operation *op,
1104                        const struct GNUNET_MessageHeader *opaque_context)
1105 {
1106   struct OperationState *state;
1107   struct GNUNET_MQ_Envelope *ev;
1108   struct OperationRequestMessage *msg;
1109
1110   ev = GNUNET_MQ_msg_nested_mh (msg,
1111                                 GNUNET_MESSAGE_TYPE_SET_P2P_OPERATION_REQUEST,
1112                                 opaque_context);
1113   if (NULL == ev)
1114   {
1115     /* the context message is too large!? */
1116     GNUNET_break (0);
1117     return NULL;
1118   }
1119   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1120               "Initiating intersection operation evaluation\n");
1121   state = GNUNET_new (struct OperationState);
1122   /* we started the operation, thus we have to send the operation request */
1123   state->phase = PHASE_INITIAL;
1124   state->my_element_count = op->set->state->current_set_element_count;
1125   state->my_elements
1126     = GNUNET_CONTAINER_multihashmap_create (state->my_element_count,
1127                                             GNUNET_YES);
1128
1129   msg->operation = htonl (GNUNET_SET_OPERATION_INTERSECTION);
1130   msg->element_count = htonl (state->my_element_count);
1131   GNUNET_MQ_send (op->mq,
1132                   ev);
1133   state->phase = PHASE_COUNT_SENT;
1134   if (NULL != opaque_context)
1135     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1136                 "Sent op request with context message\n");
1137   else
1138     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1139                 "Sent op request without context message\n");
1140   return state;
1141 }
1142
1143
1144 /**
1145  * Accept an intersection operation request from a remote peer.  Only
1146  * initializes the private operation state.
1147  *
1148  * @param op operation that will be accepted as an intersection operation
1149  */
1150 static struct OperationState *
1151 intersection_accept (struct Operation *op)
1152 {
1153   struct OperationState *state;
1154
1155   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1156               "Accepting set intersection operation\n");
1157   state = GNUNET_new (struct OperationState);
1158   state->phase = PHASE_INITIAL;
1159   state->my_element_count
1160     = op->set->state->current_set_element_count;
1161   state->my_elements
1162     = GNUNET_CONTAINER_multihashmap_create (GNUNET_MIN (state->my_element_count,
1163                                                         op->remote_element_count),
1164                                             GNUNET_YES);
1165   op->state = state;
1166   if (op->remote_element_count < state->my_element_count)
1167   {
1168     /* If the other peer (Alice) has fewer elements than us (Bob),
1169        we just send the count as Alice should send the first BF */
1170     send_element_count (op);
1171     state->phase = PHASE_COUNT_SENT;
1172     return state;
1173   }
1174   /* We have fewer elements, so we start with the BF */
1175   begin_bf_exchange (op);
1176   return state;
1177 }
1178
1179
1180 /**
1181  * Destroy the intersection operation.  Only things specific to the
1182  * intersection operation are destroyed.
1183  *
1184  * @param op intersection operation to destroy
1185  */
1186 static void
1187 intersection_op_cancel (struct Operation *op)
1188 {
1189   /* check if the op was canceled twice */
1190   GNUNET_assert (NULL != op->state);
1191   if (NULL != op->state->remote_bf)
1192   {
1193     GNUNET_CONTAINER_bloomfilter_free (op->state->remote_bf);
1194     op->state->remote_bf = NULL;
1195   }
1196   if (NULL != op->state->local_bf)
1197   {
1198     GNUNET_CONTAINER_bloomfilter_free (op->state->local_bf);
1199     op->state->local_bf = NULL;
1200   }
1201   if (NULL != op->state->my_elements)
1202   {
1203     GNUNET_CONTAINER_multihashmap_destroy (op->state->my_elements);
1204     op->state->my_elements = NULL;
1205   }
1206   if (NULL != op->state->full_result_iter)
1207   {
1208     GNUNET_CONTAINER_multihashmap_iterator_destroy (op->state->full_result_iter);
1209     op->state->full_result_iter = NULL;
1210   }
1211   GNUNET_free (op->state);
1212   op->state = NULL;
1213   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1214               "Destroying intersection op state done\n");
1215 }
1216
1217
1218 /**
1219  * Create a new set supporting the intersection operation.
1220  *
1221  * @return the newly created set
1222  */
1223 static struct SetState *
1224 intersection_set_create ()
1225 {
1226   struct SetState *set_state;
1227
1228   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1229               "Intersection set created\n");
1230   set_state = GNUNET_new (struct SetState);
1231   set_state->current_set_element_count = 0;
1232
1233   return set_state;
1234 }
1235
1236
1237 /**
1238  * Add the element from the given element message to the set.
1239  *
1240  * @param set_state state of the set want to add to
1241  * @param ee the element to add to the set
1242  */
1243 static void
1244 intersection_add (struct SetState *set_state,
1245                   struct ElementEntry *ee)
1246 {
1247   set_state->current_set_element_count++;
1248 }
1249
1250
1251 /**
1252  * Destroy a set that supports the intersection operation
1253  *
1254  * @param set_state the set to destroy
1255  */
1256 static void
1257 intersection_set_destroy (struct SetState *set_state)
1258 {
1259   GNUNET_free (set_state);
1260 }
1261
1262
1263 /**
1264  * Remove the element given in the element message from the set.
1265  *
1266  * @param set_state state of the set to remove from
1267  * @param element set element to remove
1268  */
1269 static void
1270 intersection_remove (struct SetState *set_state,
1271                      struct ElementEntry *element)
1272 {
1273   GNUNET_assert (0 < set_state->current_set_element_count);
1274   set_state->current_set_element_count--;
1275 }
1276
1277
1278 /**
1279  * Callback for channel death for the intersection operation.
1280  *
1281  * @param op operation that lost the channel
1282  */
1283 static void
1284 intersection_channel_death (struct Operation *op)
1285 {
1286   if (GNUNET_YES == op->state->channel_death_expected)
1287   {
1288     /* oh goodie, we are done! */
1289     send_client_done_and_destroy (op);
1290   }
1291   else
1292   {
1293     /* sorry, channel went down early, too bad. */
1294     _GSS_operation_destroy (op,
1295                             GNUNET_YES);
1296   }
1297 }
1298
1299
1300 /**
1301  * Get the table with implementing functions for set intersection.
1302  *
1303  * @return the operation specific VTable
1304  */
1305 const struct SetVT *
1306 _GSS_intersection_vt ()
1307 {
1308   static const struct SetVT intersection_vt = {
1309     .create = &intersection_set_create,
1310     .add = &intersection_add,
1311     .remove = &intersection_remove,
1312     .destroy_set = &intersection_set_destroy,
1313     .evaluate = &intersection_evaluate,
1314     .accept = &intersection_accept,
1315     .cancel = &intersection_op_cancel,
1316     .channel_death = &intersection_channel_death,
1317   };
1318
1319   return &intersection_vt;
1320 }