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