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