finalize protocol change (fixes message loss when leaving a place)
[oweals/gnunet.git] / src / social / social_api.c
1 /*
2  * This file is part of GNUnet
3  * Copyright (C) 2013 GNUnet e.V.
4  *
5  * GNUnet is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published
7  * by the Free Software Foundation; either version 3, or (at your
8  * option) any later version.
9  *
10  * GNUnet is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with GNUnet; see the file COPYING.  If not, write to the
17  * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18  * Boston, MA 02110-1301, USA.
19  */
20
21 /**
22  * @author Gabor X Toth
23  *
24  * @file
25  * Social service; implements social interactions using the PSYC service.
26  */
27
28 #include <inttypes.h>
29 #include <string.h>
30
31 #include "platform.h"
32 #include "gnunet_util_lib.h"
33 #include "gnunet_psyc_service.h"
34 #include "gnunet_psyc_util_lib.h"
35 #include "gnunet_social_service.h"
36 #include "social.h"
37
38 #define LOG(kind,...) GNUNET_log_from (kind, "social-api",__VA_ARGS__)
39
40 /**
41  * Handle for an ego.
42  */
43 struct GNUNET_SOCIAL_Ego
44 {
45   struct GNUNET_CRYPTO_EcdsaPublicKey pub_key;
46   struct GNUNET_HashCode pub_key_hash;
47   char *name;
48 };
49
50
51 /**
52  * Handle for a pseudonym of another user in the network.
53  */
54 struct GNUNET_SOCIAL_Nym
55 {
56   struct GNUNET_CRYPTO_EcdsaPublicKey pub_key;
57   struct GNUNET_HashCode pub_key_hash;
58 };
59
60
61 /**
62  * Handle for an application.
63  */
64 struct GNUNET_SOCIAL_App
65 {
66   /**
67    * Configuration to use.
68    */
69   const struct GNUNET_CONFIGURATION_Handle *cfg;
70
71   /**
72    * Client connection to the service.
73    */
74   struct GNUNET_MQ_Handle *mq;
75
76   /**
77    * Message to send on connect.
78    */
79   struct GNUNET_MQ_Envelope *connect_env;
80
81   /**
82    * Time to wait until we try to reconnect on failure.
83    */
84   struct GNUNET_TIME_Relative reconnect_delay;
85
86   /**
87    * Task for reconnecting when the listener fails.
88    */
89   struct GNUNET_SCHEDULER_Task *reconnect_task;
90
91   /**
92    * Async operations.
93    */
94   struct GNUNET_OP_Handle *op;
95
96   /**
97    * Function called after disconnected from the service.
98    */
99   GNUNET_ContinuationCallback disconnect_cb;
100
101   /**
102    * Closure for @a disconnect_cb.
103    */
104   void *disconnect_cls;
105
106   /**
107    * Application ID.
108    */
109   char *id;
110
111   /**
112    * Hash map of all egos.
113    * pub_key_hash -> struct GNUNET_SOCIAL_Ego *
114    */
115   struct GNUNET_CONTAINER_MultiHashMap *egos;
116
117   GNUNET_SOCIAL_AppEgoCallback ego_cb;
118   GNUNET_SOCIAL_AppHostPlaceCallback host_cb;
119   GNUNET_SOCIAL_AppGuestPlaceCallback guest_cb;
120   GNUNET_SOCIAL_AppConnectedCallback connected_cb;
121   void *cb_cls;
122 };
123
124
125 struct GNUNET_SOCIAL_HostConnection
126 {
127   struct GNUNET_SOCIAL_App *app;
128
129   struct AppPlaceMessage plc_msg;
130 };
131
132
133 struct GNUNET_SOCIAL_GuestConnection
134 {
135   struct GNUNET_SOCIAL_App *app;
136
137   struct AppPlaceMessage plc_msg;
138 };
139
140
141 /**
142  * Handle for a place where social interactions happen.
143  */
144 struct GNUNET_SOCIAL_Place
145 {
146   /**
147    * Configuration to use.
148    */
149   const struct GNUNET_CONFIGURATION_Handle *cfg;
150
151   /**
152    * Client connection to the service.
153    */
154   struct GNUNET_MQ_Handle *mq;
155
156   /**
157    * Message to send on connect.
158    */
159   struct GNUNET_MQ_Envelope *connect_env;
160
161   /**
162    * Time to wait until we try to reconnect on failure.
163    */
164   struct GNUNET_TIME_Relative reconnect_delay;
165
166   /**
167    * Task for reconnecting when the listener fails.
168    */
169   struct GNUNET_SCHEDULER_Task *reconnect_task;
170
171   /**
172    * Async operations.
173    */
174   struct GNUNET_OP_Handle *op;
175
176   /**
177    * Transmission handle.
178    */
179   struct GNUNET_PSYC_TransmitHandle *tmit;
180
181   /**
182    * Slicer for processing incoming messages.
183    */
184   struct GNUNET_PSYC_Slicer *slicer;
185
186   /**
187    * Function called after disconnected from the service.
188    */
189   GNUNET_ContinuationCallback disconnect_cb;
190
191   /**
192    * Closure for @a disconnect_cb.
193    */
194   void *disconnect_cls;
195
196   /**
197    * Public key of the place.
198    */
199   struct GNUNET_CRYPTO_EddsaPublicKey pub_key;
200
201   /**
202    * Public key of the ego.
203    */
204   struct GNUNET_CRYPTO_EcdsaPublicKey ego_pub_key;
205
206   /**
207    * Does this place belong to a host (#GNUNET_YES) or guest (#GNUNET_NO)?
208    */
209   uint8_t is_host;
210 };
211
212
213 /**
214  * Host handle for a place that we entered.
215  */
216 struct GNUNET_SOCIAL_Host
217 {
218   struct GNUNET_SOCIAL_Place plc;
219
220   /**
221    * Slicer for processing incoming messages from guests.
222    */
223   struct GNUNET_PSYC_Slicer *slicer;
224
225   GNUNET_SOCIAL_HostEnterCallback enter_cb;
226
227   GNUNET_SOCIAL_AnswerDoorCallback answer_door_cb;
228
229   GNUNET_SOCIAL_FarewellCallback farewell_cb;
230
231   /**
232    * Closure for callbacks.
233    */
234   void *cb_cls;
235
236   struct GNUNET_SOCIAL_Nym *notice_place_leave_nym;
237   struct GNUNET_PSYC_Environment *notice_place_leave_env;
238 };
239
240
241 /**
242  * Guest handle for place that we entered.
243  */
244 struct GNUNET_SOCIAL_Guest
245 {
246   struct GNUNET_SOCIAL_Place plc;
247
248   GNUNET_SOCIAL_GuestEnterCallback enter_cb;
249
250   GNUNET_SOCIAL_EntryDecisionCallback entry_dcsn_cb;
251
252   /**
253    * Closure for callbacks.
254    */
255   void *cb_cls;
256 };
257
258
259 /**
260  * Hash map of all nyms.
261  * pub_key_hash -> struct GNUNET_SOCIAL_Nym *
262  */
263 struct GNUNET_CONTAINER_MultiHashMap *nyms;
264
265
266 /**
267  * Handle for an announcement request.
268  */
269 struct GNUNET_SOCIAL_Announcement
270 {
271
272 };
273
274
275 /**
276  * A talk request.
277  */
278 struct GNUNET_SOCIAL_TalkRequest
279 {
280
281 };
282
283
284 /**
285  * A history lesson.
286  */
287 struct GNUNET_SOCIAL_HistoryRequest
288 {
289   /**
290    * Place.
291    */
292   struct GNUNET_SOCIAL_Place *plc;
293
294   /**
295    * Operation ID.
296    */
297   uint64_t op_id;
298
299   /**
300    * Slicer for processing incoming messages.
301    */
302   struct GNUNET_PSYC_Slicer *slicer;
303
304   /**
305    * Function to call when the operation finished.
306    */
307   GNUNET_ResultCallback result_cb;
308
309   /**
310    * Closure for @a result_cb.
311    */
312   void *cls;
313 };
314
315
316 struct GNUNET_SOCIAL_LookHandle
317 {
318   /**
319    * Place.
320    */
321   struct GNUNET_SOCIAL_Place *plc;
322
323   /**
324    * Operation ID.
325    */
326   uint64_t op_id;
327
328   /**
329    * State variable result callback.
330    */
331   GNUNET_PSYC_StateVarCallback var_cb;
332
333   /**
334    * Function to call when the operation finished.
335    */
336   GNUNET_ResultCallback result_cb;
337
338   /**
339    * Name of current modifier being received.
340    */
341   char *mod_name;
342
343   /**
344    * Size of current modifier value being received.
345    */
346   size_t mod_value_size;
347
348   /**
349    * Remaining size of current modifier value still to be received.
350    */
351   size_t mod_value_remaining;
352
353   /**
354    * Closure for @a result_cb.
355    */
356   void *cls;
357 };
358
359
360 struct ZoneAddPlaceHandle
361 {
362   GNUNET_ResultCallback result_cb;
363   void *result_cls;
364 };
365
366
367 struct ZoneAddNymHandle
368 {
369   GNUNET_ResultCallback result_cb;
370   void *result_cls;
371 };
372
373
374 /*** CLEANUP / DISCONNECT ***/
375
376
377 static void
378 host_cleanup (struct GNUNET_SOCIAL_Host *hst)
379 {
380   if (NULL != hst->slicer)
381   {
382     GNUNET_PSYC_slicer_destroy (hst->slicer);
383     hst->slicer = NULL;
384   }
385   GNUNET_free (hst);
386 }
387
388
389 static void
390 guest_cleanup (struct GNUNET_SOCIAL_Guest *gst)
391 {
392   GNUNET_free (gst);
393 }
394
395
396 static void
397 place_cleanup (struct GNUNET_SOCIAL_Place *plc)
398 {
399   struct GNUNET_HashCode place_pub_hash;
400
401   GNUNET_CRYPTO_hash (&plc->pub_key, sizeof (plc->pub_key), &place_pub_hash);
402   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
403               "%s place cleanup: %s\n",
404               GNUNET_YES == plc->is_host ? "host" : "guest",
405               GNUNET_h2s (&place_pub_hash));
406
407   if (NULL != plc->tmit)
408   {
409     GNUNET_PSYC_transmit_destroy (plc->tmit);
410     plc->tmit = NULL;
411   }
412   if (NULL != plc->connect_env)
413   {
414     GNUNET_MQ_discard (plc->connect_env);
415     plc->connect_env = NULL;
416   }
417   if (NULL != plc->mq)
418   {
419     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
420                 "destroying MQ (place_cleanup)\n");
421     GNUNET_MQ_destroy (plc->mq);
422     plc->mq = NULL;
423   }
424   if (NULL != plc->disconnect_cb)
425   {
426     plc->disconnect_cb (plc->disconnect_cls);
427     plc->disconnect_cb = NULL;
428   }
429
430   (GNUNET_YES == plc->is_host)
431     ? host_cleanup ((struct GNUNET_SOCIAL_Host *) plc)
432     : guest_cleanup ((struct GNUNET_SOCIAL_Guest *) plc);
433 }
434
435
436 static void
437 place_disconnect (struct GNUNET_SOCIAL_Place *plc)
438 {
439   struct GNUNET_HashCode place_pub_hash;
440
441   GNUNET_CRYPTO_hash (&plc->pub_key,
442                       sizeof (plc->pub_key),
443                       &place_pub_hash);
444   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
445               "place_disconnect, plc = %s\n",
446               GNUNET_h2s (&place_pub_hash));
447   place_cleanup (plc);
448 }
449
450
451 /*** NYM ***/
452
453 static struct GNUNET_SOCIAL_Nym *
454 nym_get_or_create (const struct GNUNET_CRYPTO_EcdsaPublicKey *pub_key)
455 {
456   struct GNUNET_SOCIAL_Nym *nym = NULL;
457   struct GNUNET_HashCode pub_key_hash;
458
459   if (NULL == pub_key)
460     return NULL;
461
462   GNUNET_CRYPTO_hash (pub_key, sizeof (*pub_key), &pub_key_hash);
463
464   if (NULL == nyms)
465     nyms = GNUNET_CONTAINER_multihashmap_create (1, GNUNET_YES);
466   else
467     nym = GNUNET_CONTAINER_multihashmap_get (nyms, &pub_key_hash);
468
469   if (NULL == nym)
470   {
471     nym = GNUNET_new (struct GNUNET_SOCIAL_Nym);
472     nym->pub_key = *pub_key;
473     nym->pub_key_hash = pub_key_hash;
474     GNUNET_CONTAINER_multihashmap_put (nyms, &nym->pub_key_hash, nym,
475                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
476   }
477   return nym;
478 }
479
480
481 static void
482 nym_destroy (struct GNUNET_SOCIAL_Nym *nym)
483 {
484   GNUNET_CONTAINER_multihashmap_remove (nyms, &nym->pub_key_hash, nym);
485   GNUNET_free (nym);
486 }
487
488
489 /*** MESSAGE HANDLERS ***/
490
491 /** _notice_place_leave from guests */
492
493 static void
494 host_recv_notice_place_leave_method (void *cls,
495                                      const struct GNUNET_PSYC_MessageHeader *msg,
496                                      const struct GNUNET_PSYC_MessageMethod *meth,
497                                      uint64_t message_id,
498                                      const char *method_name)
499 {
500   struct GNUNET_SOCIAL_Host *hst = cls;
501
502   if (0 == memcmp (&(struct GNUNET_CRYPTO_EcdsaPublicKey) {},
503                    &msg->slave_pub_key, sizeof (msg->slave_pub_key)))
504     return;
505
506   struct GNUNET_SOCIAL_Nym *nym = nym_get_or_create (&msg->slave_pub_key);
507
508   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
509               "Host received method for message ID %" PRIu64 " from nym %s: %s\n",
510               message_id, GNUNET_h2s (&nym->pub_key_hash), method_name);
511
512   hst->notice_place_leave_nym = (struct GNUNET_SOCIAL_Nym *) nym;
513   hst->notice_place_leave_env = GNUNET_PSYC_env_create ();
514
515   char *str = GNUNET_CRYPTO_ecdsa_public_key_to_string (&hst->notice_place_leave_nym->pub_key);
516   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
517               "_notice_place_leave: got method from nym %s (%s).\n",
518               GNUNET_h2s (&hst->notice_place_leave_nym->pub_key_hash), str);
519   GNUNET_free (str);
520 }
521
522
523 static void
524 host_recv_notice_place_leave_modifier (void *cls,
525                                        const struct GNUNET_PSYC_MessageHeader *msg,
526                                        const struct GNUNET_MessageHeader *pmsg,
527                                        uint64_t message_id,
528                                        enum GNUNET_PSYC_Operator oper,
529                                        const char *name,
530                                        const void *value,
531                                        uint16_t value_size,
532                                        uint16_t full_value_size)
533 {
534   struct GNUNET_SOCIAL_Host *hst = cls;
535   if (NULL == hst->notice_place_leave_env)
536     return;
537
538   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
539               "Host received modifier for _notice_place_leave message with ID %" PRIu64 ":\n"
540               "%c%s: %.*s\n",
541               message_id, oper, name, value_size, (const char *) value);
542
543   /* skip _nym, it's added later in eom() */
544   if (0 == memcmp (name, "_nym", sizeof ("_nym"))
545       || 0 == memcmp (name, "_nym_", sizeof ("_nym_") - 1))
546     return;
547
548   GNUNET_PSYC_env_add (hst->notice_place_leave_env,
549                        GNUNET_PSYC_OP_SET, name, value, value_size);
550 }
551
552
553 static void
554 host_recv_notice_place_leave_eom (void *cls,
555                                   const struct GNUNET_PSYC_MessageHeader *msg,
556                                   const struct GNUNET_MessageHeader *pmsg,
557                                   uint64_t message_id,
558                                   uint8_t is_cancelled)
559 {
560   struct GNUNET_SOCIAL_Host *hst = cls;
561   if (NULL == hst->notice_place_leave_env)
562     return;
563
564   char *str = GNUNET_CRYPTO_ecdsa_public_key_to_string (&hst->notice_place_leave_nym->pub_key);
565   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
566               "_notice_place_leave: got EOM from nym %s (%s).\n",
567               GNUNET_h2s (&hst->notice_place_leave_nym->pub_key_hash), str);
568   GNUNET_free (str);
569
570   if (GNUNET_YES != is_cancelled)
571   {
572     if (NULL != hst->farewell_cb)
573       hst->farewell_cb (hst->cb_cls, hst->notice_place_leave_nym,
574                         hst->notice_place_leave_env);
575     /* announce leaving guest to place */
576     GNUNET_PSYC_env_add (hst->notice_place_leave_env, GNUNET_PSYC_OP_SET,
577                          "_nym", hst->notice_place_leave_nym,
578                          sizeof (*hst->notice_place_leave_nym));
579     GNUNET_SOCIAL_host_announce (hst, "_notice_place_leave",
580                                  hst->notice_place_leave_env,
581                                  NULL, NULL, GNUNET_SOCIAL_ANNOUNCE_NONE);
582     nym_destroy (hst->notice_place_leave_nym);
583   }
584   GNUNET_PSYC_env_destroy (hst->notice_place_leave_env);
585   hst->notice_place_leave_env = NULL;
586 }
587
588
589 /*** PLACE ***/
590
591
592 static int
593 check_place_result (void *cls,
594                     const struct GNUNET_OperationResultMessage *res)
595 {
596   uint16_t size = ntohs (res->header.size);
597   if (size < sizeof (*res))
598   { /* Error, message too small. */
599     GNUNET_break (0);
600     return GNUNET_SYSERR;
601   }
602   return GNUNET_OK;
603 }
604
605
606 static void
607 handle_place_result (void *cls,
608                      const struct GNUNET_OperationResultMessage *res)
609 {
610   struct GNUNET_SOCIAL_Place *plc = cls;
611
612   uint16_t size = ntohs (res->header.size);
613   uint16_t data_size = size - sizeof (*res);
614   const char *data = (0 < data_size) ? (const char *) &res[1] : NULL;
615
616   GNUNET_OP_result (plc->op, GNUNET_ntohll (res->op_id),
617                     GNUNET_ntohll (res->result_code),
618                     data, data_size, NULL);
619 }
620
621
622 static int
623 check_app_result (void *cls,
624                   const struct GNUNET_OperationResultMessage *res)
625 {
626   uint16_t size = ntohs (res->header.size);
627   if (size < sizeof (*res))
628   { /* Error, message too small. */
629     GNUNET_break (0);
630     return GNUNET_SYSERR;
631   }
632   return GNUNET_OK;
633 }
634
635
636 static void
637 handle_app_result (void *cls,
638                    const struct GNUNET_OperationResultMessage *res)
639 {
640   struct GNUNET_SOCIAL_App *app = cls;
641
642   uint16_t size = ntohs (res->header.size);
643   uint16_t data_size = size - sizeof (*res);
644   const char *data = (0 < data_size) ? (const char *) &res[1] : NULL;
645
646   GNUNET_OP_result (app->op, GNUNET_ntohll (res->op_id),
647                     GNUNET_ntohll (res->result_code),
648                     data, data_size, NULL);
649 }
650
651
652 static void
653 op_recv_history_result (void *cls, int64_t result,
654                         const void *err_msg, uint16_t err_msg_size)
655 {
656   LOG (GNUNET_ERROR_TYPE_DEBUG,
657        "Received history replay result: %" PRId64 ".\n", result);
658
659   struct GNUNET_SOCIAL_HistoryRequest *hist = cls;
660
661   if (NULL != hist->result_cb)
662     hist->result_cb (hist->cls, result, err_msg, err_msg_size);
663
664   GNUNET_free (hist);
665 }
666
667
668 static void
669 op_recv_state_result (void *cls, int64_t result,
670                       const void *err_msg, uint16_t err_msg_size)
671 {
672   LOG (GNUNET_ERROR_TYPE_DEBUG,
673        "Received state request result: %" PRId64 ".\n", result);
674
675   struct GNUNET_SOCIAL_LookHandle *look = cls;
676
677   if (NULL != look->result_cb)
678     look->result_cb (look->cls, result, err_msg, err_msg_size);
679
680   GNUNET_free (look);
681 }
682
683
684 static int
685 check_place_history_result (void *cls,
686                             const struct GNUNET_OperationResultMessage *res)
687 {
688   struct GNUNET_PSYC_MessageHeader *
689     pmsg = (struct GNUNET_PSYC_MessageHeader *) GNUNET_MQ_extract_nested_mh (res);
690   uint16_t size = ntohs (res->header.size);
691
692   if (NULL == pmsg || size < sizeof (*res) + sizeof (*pmsg))
693   { /* Error, message too small. */
694     GNUNET_break (0);
695     return GNUNET_SYSERR;
696   }
697   return GNUNET_OK;
698 }
699
700
701 static void
702 handle_place_history_result (void *cls,
703                              const struct GNUNET_OperationResultMessage *res)
704 {
705   struct GNUNET_SOCIAL_Place *plc = cls;
706   struct GNUNET_PSYC_MessageHeader *
707     pmsg = (struct GNUNET_PSYC_MessageHeader *) GNUNET_MQ_extract_nested_mh (res);
708
709   LOG (GNUNET_ERROR_TYPE_DEBUG,
710        "%p Received historic fragment for message #%" PRIu64 ".\n",
711        plc, GNUNET_ntohll (pmsg->message_id));
712
713   GNUNET_ResultCallback result_cb = NULL;
714   struct GNUNET_SOCIAL_HistoryRequest *hist = NULL;
715
716   if (GNUNET_YES != GNUNET_OP_get (plc->op,
717                                    GNUNET_ntohll (res->op_id),
718                                    &result_cb, (void *) &hist, NULL))
719   { /* Operation not found. */
720     LOG (GNUNET_ERROR_TYPE_WARNING,
721          "%p Replay operation not found for historic fragment of message #%"
722          PRIu64 ".\n",
723          plc, GNUNET_ntohll (pmsg->message_id));
724     return;
725   }
726
727   GNUNET_PSYC_slicer_message (hist->slicer,
728                               (const struct GNUNET_PSYC_MessageHeader *) pmsg);
729 }
730
731
732 static int
733 check_place_state_result (void *cls,
734                           const struct GNUNET_OperationResultMessage *res)
735 {
736   const struct GNUNET_MessageHeader *mod = GNUNET_MQ_extract_nested_mh (res);
737   if (NULL == mod)
738   {
739     GNUNET_break_op (0);
740     LOG (GNUNET_ERROR_TYPE_WARNING,
741          "Invalid modifier in state result\n");
742     return GNUNET_SYSERR;
743   }
744
745   uint16_t size = ntohs (res->header.size);
746   uint16_t mod_size = ntohs (mod->size);
747   if (size - sizeof (*res) != mod_size)
748   {
749     GNUNET_break_op (0);
750     LOG (GNUNET_ERROR_TYPE_WARNING,
751          "Invalid modifier size in state result: %u - %u != %u\n",
752          ntohs (res->header.size), sizeof (*res), mod_size);
753     return GNUNET_SYSERR;
754   }
755   return GNUNET_OK;
756 }
757
758
759 static void
760 handle_place_state_result (void *cls,
761                            const struct GNUNET_OperationResultMessage *res)
762 {
763   struct GNUNET_SOCIAL_Place *plc = cls;
764
765   GNUNET_ResultCallback result_cb = NULL;
766   struct GNUNET_SOCIAL_LookHandle *look = NULL;
767
768   if (GNUNET_YES != GNUNET_OP_get (plc->op,
769                                    GNUNET_ntohll (res->op_id),
770                                    &result_cb, (void *) &look, NULL))
771   { /* Operation not found. */
772     return;
773   }
774
775   const struct GNUNET_MessageHeader *mod = GNUNET_MQ_extract_nested_mh (res);
776   uint16_t mod_size = ntohs (mod->size);
777
778   switch (ntohs (mod->type))
779   {
780   case GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_MODIFIER:
781   {
782     const struct GNUNET_PSYC_MessageModifier *
783       pmod = (const struct GNUNET_PSYC_MessageModifier *) mod;
784
785     const char *name = (const char *) &pmod[1];
786     uint16_t name_size = ntohs (pmod->name_size);
787     if (0 == name_size
788         || mod_size - sizeof (*pmod) < name_size
789         || '\0' != name[name_size - 1])
790     {
791       GNUNET_break_op (0);
792       LOG (GNUNET_ERROR_TYPE_WARNING,
793            "Invalid modifier name in state result\n");
794       return;
795     }
796     look->mod_value_size = ntohs (pmod->value_size);
797     look->var_cb (look->cls, mod, name, name + name_size,
798                   mod_size - sizeof (*mod) - name_size,
799                   look->mod_value_size);
800     if (look->mod_value_size > mod_size - sizeof (*mod) - name_size)
801     {
802         look->mod_value_remaining = look->mod_value_size;
803         look->mod_name = GNUNET_malloc (name_size);
804         GNUNET_memcpy (look->mod_name, name, name_size);
805     }
806     break;
807   }
808
809   case GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_MOD_CONT:
810     look->var_cb (look->cls, mod, look->mod_name, (const char *) &mod[1],
811                   mod_size - sizeof (*mod), look->mod_value_size);
812     look->mod_value_remaining -= mod_size - sizeof (*mod);
813     if (0 == look->mod_value_remaining)
814     {
815         GNUNET_free (look->mod_name);
816     }
817     break;
818   }
819 }
820
821
822 static void
823 handle_place_message_ack (void *cls,
824                           const struct GNUNET_MessageHeader *msg)
825 {
826   struct GNUNET_SOCIAL_Place *plc = cls;
827
828   GNUNET_PSYC_transmit_got_ack (plc->tmit);
829 }
830
831
832 static int
833 check_place_message (void *cls,
834                      const struct GNUNET_PSYC_MessageHeader *pmsg)
835 {
836   return GNUNET_OK;
837 }
838
839
840 static void
841 handle_place_message (void *cls,
842                       const struct GNUNET_PSYC_MessageHeader *pmsg)
843 {
844   struct GNUNET_SOCIAL_Place *plc = cls;
845
846   GNUNET_PSYC_slicer_message (plc->slicer, pmsg);
847 }
848
849
850 static int
851 check_host_message (void *cls,
852                     const struct GNUNET_PSYC_MessageHeader *pmsg)
853 {
854   return GNUNET_OK;
855 }
856
857
858 static void
859 handle_host_message (void *cls,
860                      const struct GNUNET_PSYC_MessageHeader *pmsg)
861 {
862   struct GNUNET_SOCIAL_Host *hst = cls;
863
864   GNUNET_PSYC_slicer_message (hst->slicer, pmsg);
865   GNUNET_PSYC_slicer_message (hst->plc.slicer, pmsg);
866 }
867
868
869 static void
870 handle_host_enter_ack (void *cls,
871                        const struct HostEnterAck *hack)
872 {
873   struct GNUNET_SOCIAL_Host *hst = cls;
874
875   hst->plc.pub_key = hack->place_pub_key;
876
877   int32_t result = ntohl (hack->result_code);
878   if (NULL != hst->enter_cb)
879     hst->enter_cb (hst->cb_cls, result, &hack->place_pub_key,
880                    GNUNET_ntohll (hack->max_message_id));
881 }
882
883
884 static int
885 check_host_enter_request (void *cls,
886                           const struct GNUNET_PSYC_JoinRequestMessage *req)
887 {
888   return GNUNET_OK;
889 }
890
891
892 static void
893 handle_host_enter_request (void *cls,
894                            const struct GNUNET_PSYC_JoinRequestMessage *req)
895 {
896   struct GNUNET_SOCIAL_Host *hst = cls;
897
898   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
899               "handle_host_enter_request\n");
900
901   if (NULL == hst->answer_door_cb)
902      return;
903
904   const char *method_name = NULL;
905   struct GNUNET_PSYC_Environment *env = NULL;
906   struct GNUNET_PSYC_MessageHeader *entry_pmsg = NULL;
907   const void *data = NULL;
908   uint16_t data_size = 0;
909   char *str;
910   const struct GNUNET_PSYC_Message *join_msg = NULL;
911
912   do
913   {
914     if (sizeof (*req) + sizeof (*join_msg) <= ntohs (req->header.size))
915     {
916       join_msg = (struct GNUNET_PSYC_Message *) GNUNET_MQ_extract_nested_mh (req);
917       LOG (GNUNET_ERROR_TYPE_DEBUG,
918            "Received join_msg of type %u and size %u.\n",
919            ntohs (join_msg->header.type), ntohs (join_msg->header.size));
920
921       env = GNUNET_PSYC_env_create ();
922       entry_pmsg = GNUNET_PSYC_message_header_create_from_psyc (join_msg);
923       if (GNUNET_OK != GNUNET_PSYC_message_parse (entry_pmsg, &method_name, env,
924                                                   &data, &data_size))
925       {
926         GNUNET_break_op (0);
927         str = GNUNET_CRYPTO_ecdsa_public_key_to_string (&req->slave_pub_key);
928         LOG (GNUNET_ERROR_TYPE_WARNING,
929              "Ignoring invalid entry request from nym %s.\n",
930              str);
931         GNUNET_free (str);
932         break;
933       }
934     }
935
936     struct GNUNET_SOCIAL_Nym *nym = nym_get_or_create (&req->slave_pub_key);
937     hst->answer_door_cb (hst->cb_cls, nym, method_name, env,
938                          data, data_size);
939   } while (0);
940
941   if (NULL != env)
942     GNUNET_PSYC_env_destroy (env);
943   if (NULL != entry_pmsg)
944     GNUNET_free (entry_pmsg);
945 }
946
947
948 static void
949 handle_guest_enter_ack (void *cls,
950                         const struct GNUNET_PSYC_CountersResultMessage *cres)
951 {
952   struct GNUNET_SOCIAL_Guest *gst = cls;
953
954   int32_t result = ntohl (cres->result_code);
955   if (NULL != gst->enter_cb)
956     gst->enter_cb (gst->cb_cls, result, &gst->plc.pub_key,
957                    GNUNET_ntohll (cres->max_message_id));
958 }
959
960
961 static int
962 check_guest_enter_decision (void *cls,
963                             const struct GNUNET_PSYC_JoinDecisionMessage *dcsn)
964 {
965   return GNUNET_OK;
966 }
967
968
969 static void
970 handle_guest_enter_decision (void *cls,
971                              const struct GNUNET_PSYC_JoinDecisionMessage *dcsn)
972 {
973   struct GNUNET_SOCIAL_Guest *gst = cls;
974
975   struct GNUNET_PSYC_Message *pmsg = NULL;
976   if (ntohs (dcsn->header.size) > sizeof (*dcsn))
977     pmsg = (struct GNUNET_PSYC_Message *) GNUNET_MQ_extract_nested_mh (dcsn);
978
979   if (NULL != gst->entry_dcsn_cb)
980     gst->entry_dcsn_cb (gst->cb_cls, ntohl (dcsn->is_admitted), pmsg);
981 }
982
983
984 static int
985 check_app_ego (void *cls,
986                const struct AppEgoMessage *emsg)
987 {
988   return GNUNET_OK;
989 }
990
991
992 static void
993 handle_app_ego (void *cls,
994                 const struct AppEgoMessage *emsg)
995 {
996   struct GNUNET_SOCIAL_App *app = cls;
997
998   uint16_t name_size = ntohs (emsg->header.size) - sizeof (*emsg);
999
1000   struct GNUNET_HashCode ego_pub_hash;
1001   GNUNET_CRYPTO_hash (&emsg->ego_pub_key, sizeof (emsg->ego_pub_key),
1002                       &ego_pub_hash);
1003
1004   struct GNUNET_SOCIAL_Ego *
1005     ego = GNUNET_CONTAINER_multihashmap_get (app->egos, &ego_pub_hash);
1006   if (NULL == ego)
1007   {
1008     ego = GNUNET_malloc (sizeof (*ego));
1009     ego->pub_key = emsg->ego_pub_key;
1010     ego->name = GNUNET_malloc (name_size);
1011     GNUNET_memcpy (ego->name, &emsg[1], name_size);
1012   }
1013   else
1014   {
1015     ego->name = GNUNET_realloc (ego->name, name_size);
1016     GNUNET_memcpy (ego->name, &emsg[1], name_size);
1017   }
1018
1019   GNUNET_CONTAINER_multihashmap_put (app->egos, &ego_pub_hash, ego,
1020                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
1021
1022   if (NULL != app->ego_cb)
1023     app->ego_cb (app->cb_cls, ego, &ego->pub_key, ego->name);
1024 }
1025
1026
1027 static void
1028 handle_app_ego_end (void *cls,
1029                     const struct GNUNET_MessageHeader *msg)
1030 {
1031   //struct GNUNET_SOCIAL_App *app = cls;
1032 }
1033
1034
1035 static int
1036 check_app_place (void *cls,
1037                  const struct AppPlaceMessage *pmsg)
1038 {
1039   return GNUNET_OK;
1040 }
1041
1042
1043 static void
1044 handle_app_place (void *cls,
1045                   const struct AppPlaceMessage *pmsg)
1046 {
1047   struct GNUNET_SOCIAL_App *app = cls;
1048
1049   if ((GNUNET_YES == pmsg->is_host && NULL == app->host_cb)
1050       || (GNUNET_NO == pmsg->is_host && NULL == app->guest_cb))
1051     return;
1052
1053   struct GNUNET_HashCode ego_pub_hash;
1054   GNUNET_CRYPTO_hash (&pmsg->ego_pub_key, sizeof (pmsg->ego_pub_key),
1055                       &ego_pub_hash);
1056   struct GNUNET_SOCIAL_Ego *
1057     ego = GNUNET_CONTAINER_multihashmap_get (app->egos, &ego_pub_hash);
1058   if (NULL == ego)
1059   {
1060     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Failure to obtain ego %s.\n",
1061                 GNUNET_h2s (&ego_pub_hash));
1062     GNUNET_break (0);
1063     return;
1064   }
1065
1066   if (GNUNET_YES == pmsg->is_host)
1067   {
1068     if (NULL != app->host_cb) {
1069       struct GNUNET_SOCIAL_HostConnection *hconn = GNUNET_malloc (sizeof (*hconn));
1070       hconn->app = app;
1071       hconn->plc_msg = *pmsg;
1072       app->host_cb (app->cb_cls, hconn, ego, &pmsg->place_pub_key, pmsg->place_state);
1073       GNUNET_free (hconn);
1074     }
1075   }
1076   else if (NULL != app->guest_cb)
1077   {
1078     struct GNUNET_SOCIAL_GuestConnection *gconn = GNUNET_malloc (sizeof (*gconn));
1079     gconn->app = app;
1080     gconn->plc_msg = *pmsg;
1081     app->guest_cb (app->cb_cls, gconn, ego, &pmsg->place_pub_key, pmsg->place_state);
1082     GNUNET_free (gconn);
1083   }
1084 }
1085
1086
1087 static void
1088 handle_app_place_end (void *cls,
1089                       const struct GNUNET_MessageHeader *msg)
1090 {
1091   struct GNUNET_SOCIAL_App *app = cls;
1092
1093   if (NULL != app->connected_cb)
1094     app->connected_cb (app->cb_cls);
1095 }
1096
1097
1098 /**
1099  * Handler for a #GNUNET_MESSAGE_TYPE_SOCIAL_PLACE_LEAVE_ACK message received
1100  * from the social service.
1101  *
1102  * @param cls the place of type `struct GNUNET_SOCIAL_Place`
1103  * @param msg the message received from the service
1104  */
1105 static void
1106 handle_place_leave_ack (void *cls,
1107                         const struct GNUNET_MessageHeader *msg)
1108 {
1109   struct GNUNET_SOCIAL_Place *plc = cls;
1110
1111   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1112               "%s left place %p\n",
1113               plc->is_host ? "host" : "guest", 
1114               plc);
1115   place_disconnect (plc);  
1116 }
1117
1118
1119 /*** HOST ***/
1120
1121
1122 static void
1123 host_connect (struct GNUNET_SOCIAL_Host *hst);
1124
1125
1126 static void
1127 host_reconnect (void *cls)
1128 {
1129   host_connect (cls);
1130 }
1131
1132
1133 /**
1134  * Host client disconnected from service.
1135  *
1136  * Reconnect after backoff period.
1137  */
1138 static void
1139 host_disconnected (void *cls, enum GNUNET_MQ_Error error)
1140 {
1141   struct GNUNET_SOCIAL_Host *hst = cls;
1142   struct GNUNET_SOCIAL_Place *plc = &hst->plc;
1143
1144   LOG (GNUNET_ERROR_TYPE_DEBUG,
1145        "Host client disconnected (%d), re-connecting\n",
1146        (int) error);
1147   if (NULL != plc->tmit)
1148   {
1149     GNUNET_PSYC_transmit_destroy (plc->tmit);
1150     plc->tmit = NULL;
1151   }
1152   if (NULL != plc->mq)
1153   {
1154     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1155                 "destroying MQ (host_disconnected)\n");
1156     GNUNET_MQ_destroy (plc->mq);
1157     plc->mq = NULL;
1158   }
1159
1160   plc->reconnect_task = GNUNET_SCHEDULER_add_delayed (plc->reconnect_delay,
1161                                                       host_reconnect,
1162                                                       hst);
1163   plc->reconnect_delay = GNUNET_TIME_STD_BACKOFF (plc->reconnect_delay);
1164 }
1165
1166
1167 static void
1168 host_connect (struct GNUNET_SOCIAL_Host *hst)
1169 {
1170   struct GNUNET_SOCIAL_Place *plc = &hst->plc;
1171
1172   struct GNUNET_MQ_MessageHandler handlers[] = {
1173     GNUNET_MQ_hd_fixed_size (host_enter_ack,
1174                              GNUNET_MESSAGE_TYPE_SOCIAL_HOST_ENTER_ACK,
1175                              struct HostEnterAck,
1176                              hst),
1177     GNUNET_MQ_hd_fixed_size (place_leave_ack,
1178                              GNUNET_MESSAGE_TYPE_SOCIAL_PLACE_LEAVE_ACK,
1179                              struct GNUNET_MessageHeader,
1180                              plc),
1181     GNUNET_MQ_hd_var_size (host_enter_request,
1182                            GNUNET_MESSAGE_TYPE_PSYC_JOIN_REQUEST,
1183                            struct GNUNET_PSYC_JoinRequestMessage,
1184                            hst),
1185     GNUNET_MQ_hd_var_size (host_message,
1186                            GNUNET_MESSAGE_TYPE_PSYC_MESSAGE,
1187                            struct GNUNET_PSYC_MessageHeader,
1188                            hst),
1189     GNUNET_MQ_hd_fixed_size (place_message_ack,
1190                              GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_ACK,
1191                              struct GNUNET_MessageHeader,
1192                              plc),
1193     GNUNET_MQ_hd_var_size (place_history_result,
1194                            GNUNET_MESSAGE_TYPE_PSYC_HISTORY_RESULT,
1195                            struct GNUNET_OperationResultMessage,
1196                            plc),
1197     GNUNET_MQ_hd_var_size (place_state_result,
1198                            GNUNET_MESSAGE_TYPE_PSYC_STATE_RESULT,
1199                            struct GNUNET_OperationResultMessage,
1200                            plc),
1201     GNUNET_MQ_hd_var_size (place_result,
1202                            GNUNET_MESSAGE_TYPE_PSYC_RESULT_CODE,
1203                            struct GNUNET_OperationResultMessage,
1204                            plc),
1205     GNUNET_MQ_handler_end ()
1206   };
1207
1208   plc->mq = GNUNET_CLIENT_connect (plc->cfg, "social",
1209                                    handlers, host_disconnected, hst);
1210   GNUNET_assert (NULL != plc->mq);
1211   plc->tmit = GNUNET_PSYC_transmit_create (plc->mq);
1212
1213   GNUNET_MQ_send_copy (plc->mq, plc->connect_env);
1214 }
1215
1216
1217 /**
1218  * Enter a place as host.
1219  *
1220  * A place is created upon first entering, and it is active until permanently
1221  * left using GNUNET_SOCIAL_host_leave().
1222  *
1223  * @param app
1224  *        Application handle.
1225  * @param ego
1226  *        Identity of the host.
1227  * @param policy
1228  *        Policy specifying entry and history restrictions for the place.
1229  * @param slicer
1230  *        Slicer to handle incoming messages.
1231  * @param enter_cb
1232  *        Function called when the place is entered and ready to use.
1233  * @param answer_door_cb
1234  *        Function to handle new nyms that want to enter.
1235  * @param farewell_cb
1236  *        Function to handle departing nyms.
1237  * @param cls
1238  *        Closure for the callbacks.
1239  *
1240  * @return Handle for the host. This handle contains the pubkey.
1241  */
1242 struct GNUNET_SOCIAL_Host *
1243 GNUNET_SOCIAL_host_enter (const struct GNUNET_SOCIAL_App *app,
1244                           const struct GNUNET_SOCIAL_Ego *ego,
1245                           enum GNUNET_PSYC_Policy policy,
1246                           struct GNUNET_PSYC_Slicer *slicer,
1247                           GNUNET_SOCIAL_HostEnterCallback enter_cb,
1248                           GNUNET_SOCIAL_AnswerDoorCallback answer_door_cb,
1249                           GNUNET_SOCIAL_FarewellCallback farewell_cb,
1250                           void *cls)
1251 {
1252   struct GNUNET_SOCIAL_Host *hst = GNUNET_malloc (sizeof (*hst));
1253   struct GNUNET_SOCIAL_Place *plc = &hst->plc;
1254
1255   plc->cfg = app->cfg;
1256   plc->is_host = GNUNET_YES;
1257   plc->slicer = slicer;
1258
1259   hst->enter_cb = enter_cb;
1260   hst->answer_door_cb = answer_door_cb;
1261   hst->farewell_cb = farewell_cb;
1262   hst->cb_cls = cls;
1263
1264   plc->op = GNUNET_OP_create ();
1265
1266   hst->slicer = GNUNET_PSYC_slicer_create ();
1267   GNUNET_PSYC_slicer_method_add (hst->slicer, "_notice_place_leave", NULL,
1268                                  host_recv_notice_place_leave_method,
1269                                  host_recv_notice_place_leave_modifier,
1270                                  NULL, host_recv_notice_place_leave_eom, hst);
1271
1272   uint16_t app_id_size = strlen (app->id) + 1;
1273   struct HostEnterRequest *hreq;
1274   plc->connect_env = GNUNET_MQ_msg_extra (hreq, app_id_size,
1275                                           GNUNET_MESSAGE_TYPE_SOCIAL_HOST_ENTER);
1276   hreq->policy = policy;
1277   hreq->ego_pub_key = ego->pub_key;
1278   GNUNET_memcpy (&hreq[1], app->id, app_id_size);
1279
1280   host_connect (hst);
1281   return hst;
1282 }
1283
1284
1285 /**
1286  * Reconnect to an already entered place as host.
1287  *
1288  * @param hconn
1289  *        Host connection handle.
1290  *        @see GNUNET_SOCIAL_app_connect() & GNUNET_SOCIAL_AppHostPlaceCallback()
1291  * @param slicer
1292  *        Slicer to handle incoming messages.
1293  * @param enter_cb
1294  *        Function called when the place is entered and ready to use.
1295  * @param answer_door_cb
1296  *        Function to handle new nyms that want to enter.
1297  * @param farewell_cb
1298  *        Function to handle departing nyms.
1299  * @param cls
1300  *        Closure for the callbacks.
1301  *
1302  * @return Handle for the host.
1303  */
1304  struct GNUNET_SOCIAL_Host *
1305 GNUNET_SOCIAL_host_enter_reconnect (struct GNUNET_SOCIAL_HostConnection *hconn,
1306                                     struct GNUNET_PSYC_Slicer *slicer,
1307                                     GNUNET_SOCIAL_HostEnterCallback enter_cb,
1308                                     GNUNET_SOCIAL_AnswerDoorCallback answer_door_cb,
1309                                     GNUNET_SOCIAL_FarewellCallback farewell_cb,
1310                                     void *cls)
1311 {
1312   struct GNUNET_SOCIAL_Host *hst = GNUNET_malloc (sizeof (*hst));
1313   struct GNUNET_SOCIAL_Place *plc = &hst->plc;
1314
1315   hst->enter_cb = enter_cb;
1316   hst->answer_door_cb = answer_door_cb;
1317   hst->farewell_cb = farewell_cb;
1318   hst->cb_cls = cls;
1319
1320   plc->cfg = hconn->app->cfg;
1321   plc->is_host = GNUNET_YES;
1322   plc->slicer = slicer;
1323   plc->pub_key = hconn->plc_msg.place_pub_key;
1324   plc->ego_pub_key = hconn->plc_msg.ego_pub_key;
1325
1326   plc->op = GNUNET_OP_create ();
1327
1328   hst->slicer = GNUNET_PSYC_slicer_create ();
1329   GNUNET_PSYC_slicer_method_add (hst->slicer, "_notice_place_leave", NULL,
1330                                  host_recv_notice_place_leave_method,
1331                                  host_recv_notice_place_leave_modifier,
1332                                  NULL, host_recv_notice_place_leave_eom, hst);
1333
1334   size_t app_id_size = strlen (hconn->app->id) + 1;
1335   struct HostEnterRequest *hreq;
1336   plc->connect_env = GNUNET_MQ_msg_extra (hreq, app_id_size,
1337                                           GNUNET_MESSAGE_TYPE_SOCIAL_HOST_ENTER);
1338   hreq->place_pub_key = hconn->plc_msg.place_pub_key;
1339   hreq->ego_pub_key = hconn->plc_msg.ego_pub_key;
1340   GNUNET_memcpy (&hreq[1], hconn->app->id, app_id_size);
1341
1342   host_connect (hst);
1343   return hst;
1344 }
1345
1346
1347 /**
1348  * Decision whether to admit @a nym into the place or refuse entry.
1349  *
1350  * @param hst
1351  *        Host of the place.
1352  * @param nym
1353  *        Handle for the entity that wanted to enter.
1354  * @param is_admitted
1355  *        #GNUNET_YES    if @a nym is admitted,
1356  *        #GNUNET_NO     if @a nym is refused entry,
1357  *        #GNUNET_SYSERR if we cannot answer the request.
1358  * @param method_name
1359  *        Method name for the rejection message.
1360  * @param env
1361  *        Environment containing variables for the message, or NULL.
1362  * @param data
1363  *        Data for the rejection message to send back.
1364  * @param data_size
1365  *        Number of bytes in @a data for method.
1366  * @return #GNUNET_OK on success,
1367  *         #GNUNET_SYSERR if the message is too large.
1368  */
1369 int
1370 GNUNET_SOCIAL_host_entry_decision (struct GNUNET_SOCIAL_Host *hst,
1371                                    struct GNUNET_SOCIAL_Nym *nym,
1372                                    int is_admitted,
1373                                    const struct GNUNET_PSYC_Message *entry_resp)
1374 {
1375   struct GNUNET_SOCIAL_Place *plc = &hst->plc;
1376   struct GNUNET_PSYC_JoinDecisionMessage *dcsn;
1377   uint16_t entry_resp_size
1378     = (NULL != entry_resp) ? ntohs (entry_resp->header.size) : 0;
1379
1380   if (GNUNET_MULTICAST_FRAGMENT_MAX_PAYLOAD < sizeof (*dcsn) + entry_resp_size)
1381     return GNUNET_SYSERR;
1382
1383   struct GNUNET_MQ_Envelope *
1384     env = GNUNET_MQ_msg_extra (dcsn, entry_resp_size,
1385                                GNUNET_MESSAGE_TYPE_PSYC_JOIN_DECISION);
1386   dcsn->is_admitted = htonl (is_admitted);
1387   dcsn->slave_pub_key = nym->pub_key;
1388
1389   if (0 < entry_resp_size)
1390     GNUNET_memcpy (&dcsn[1], entry_resp, entry_resp_size);
1391
1392   GNUNET_MQ_send (plc->mq, env);
1393   return GNUNET_OK;
1394 }
1395
1396
1397 /**
1398  * Throw @a nym out of the place.
1399  *
1400  * The @a nym reference will remain valid until the
1401  * #GNUNET_SOCIAL_FarewellCallback is invoked,
1402  * which should be very soon after this call.
1403  *
1404  * @param host
1405  *        Host of the place.
1406  * @param nym
1407  *        Handle for the entity to be ejected.
1408  * @param env
1409  *        Environment for the message or NULL.
1410  */
1411 void
1412 GNUNET_SOCIAL_host_eject (struct GNUNET_SOCIAL_Host *hst,
1413                           const struct GNUNET_SOCIAL_Nym *nym,
1414                           struct GNUNET_PSYC_Environment *e)
1415 {
1416   struct GNUNET_PSYC_Environment *env = e;
1417   if (NULL == env)
1418     env = GNUNET_PSYC_env_create ();
1419   GNUNET_PSYC_env_add (env, GNUNET_PSYC_OP_SET,
1420                        "_nym", &nym->pub_key, sizeof (nym->pub_key));
1421   GNUNET_SOCIAL_host_announce (hst, "_notice_place_leave", env, NULL, NULL,
1422                                GNUNET_SOCIAL_ANNOUNCE_NONE);
1423   if (NULL == e)
1424     GNUNET_PSYC_env_destroy (env);
1425 }
1426
1427
1428 /**
1429  * Get the public key of @a ego.
1430  *
1431  * @param ego
1432  *        Ego.
1433  *
1434  * @return Public key of ego.
1435  */
1436 const struct GNUNET_CRYPTO_EcdsaPublicKey *
1437 GNUNET_SOCIAL_ego_get_pub_key (const struct GNUNET_SOCIAL_Ego *ego)
1438 {
1439   return &ego->pub_key;
1440 }
1441
1442
1443 /**
1444  * Get the hash of the public key of @a ego.
1445  *
1446  * @param ego
1447  *        Ego.
1448  *
1449  * @return Hash of the public key of @a ego.
1450  */
1451 const struct GNUNET_HashCode *
1452 GNUNET_SOCIAL_ego_get_pub_key_hash (const struct GNUNET_SOCIAL_Ego *ego)
1453 {
1454   return &ego->pub_key_hash;
1455 }
1456
1457
1458 /**
1459  * Get the name of @a ego.
1460  *
1461  * @param ego
1462  *        Ego.
1463  *
1464  * @return Public key of @a ego.
1465  */
1466 const char *
1467 GNUNET_SOCIAL_ego_get_name (const struct GNUNET_SOCIAL_Ego *ego)
1468 {
1469   return ego->name;
1470 }
1471
1472
1473 /**
1474  * Get the public key of @a nym.
1475  *
1476  * Suitable, for example, to be used with GNUNET_SOCIAL_zone_add_nym().
1477  *
1478  * @param nym
1479  *        Pseudonym.
1480  *
1481  * @return Public key of @a nym.
1482  */
1483 const struct GNUNET_CRYPTO_EcdsaPublicKey *
1484 GNUNET_SOCIAL_nym_get_pub_key (const struct GNUNET_SOCIAL_Nym *nym)
1485 {
1486   return &nym->pub_key;
1487 }
1488
1489
1490 /**
1491  * Get the hash of the public key of @a nym.
1492  *
1493  * @param nym
1494  *        Pseudonym.
1495  *
1496  * @return Hash of the public key of @a nym.
1497  */
1498 const struct GNUNET_HashCode *
1499 GNUNET_SOCIAL_nym_get_pub_key_hash (const struct GNUNET_SOCIAL_Nym *nym)
1500 {
1501   return &nym->pub_key_hash;
1502 }
1503
1504
1505 /**
1506  * Send a message to all nyms that are present in the place.
1507  *
1508  * This function is restricted to the host.  Nyms can only send requests
1509  * to the host who can decide to relay it to everyone in the place.
1510  *
1511  * @param host  Host of the place.
1512  * @param method_name Method to use for the announcement.
1513  * @param env  Environment containing variables for the message and operations
1514  *          on objects of the place.  Can be NULL.
1515  * @param notify Function to call to get the payload of the announcement.
1516  * @param notify_cls Closure for @a notify.
1517  * @param flags Flags for this announcement.
1518  *
1519  * @return NULL on error (announcement already in progress?).
1520  */
1521 struct GNUNET_SOCIAL_Announcement *
1522 GNUNET_SOCIAL_host_announce (struct GNUNET_SOCIAL_Host *hst,
1523                              const char *method_name,
1524                              const struct GNUNET_PSYC_Environment *env,
1525                              GNUNET_PSYC_TransmitNotifyData notify_data,
1526                              void *notify_data_cls,
1527                              enum GNUNET_SOCIAL_AnnounceFlags flags)
1528 {
1529   if (GNUNET_OK ==
1530       GNUNET_PSYC_transmit_message (hst->plc.tmit, method_name, env,
1531                                     NULL, notify_data, notify_data_cls, flags))
1532     return (struct GNUNET_SOCIAL_Announcement *) hst->plc.tmit;
1533   else
1534     return NULL;
1535 }
1536
1537
1538 /**
1539  * Resume transmitting announcement.
1540  *
1541  * @param a
1542  *        The announcement to resume.
1543  */
1544 void
1545 GNUNET_SOCIAL_host_announce_resume (struct GNUNET_SOCIAL_Announcement *a)
1546 {
1547   GNUNET_PSYC_transmit_resume ((struct GNUNET_PSYC_TransmitHandle *) a);
1548 }
1549
1550
1551 /**
1552  * Cancel announcement.
1553  *
1554  * @param a
1555  *        The announcement to cancel.
1556  */
1557 void
1558 GNUNET_SOCIAL_host_announce_cancel (struct GNUNET_SOCIAL_Announcement *a)
1559 {
1560   GNUNET_PSYC_transmit_cancel ((struct GNUNET_PSYC_TransmitHandle *) a);
1561 }
1562
1563
1564 /**
1565  * Obtain handle for a hosted place.
1566  *
1567  * The returned handle can be used to access the place API.
1568  *
1569  * @param host  Handle for the host.
1570  *
1571  * @return Handle for the hosted place, valid as long as @a host is valid.
1572  */
1573 struct GNUNET_SOCIAL_Place *
1574 GNUNET_SOCIAL_host_get_place (struct GNUNET_SOCIAL_Host *hst)
1575 {
1576   return &hst->plc;
1577 }
1578
1579
1580 /**
1581  * Disconnect from a home.
1582  *
1583  * Invalidates host handle.
1584  *
1585  * @param hst
1586  *        The host to disconnect.
1587  */
1588 void
1589 GNUNET_SOCIAL_host_disconnect (struct GNUNET_SOCIAL_Host *hst,
1590                                GNUNET_ContinuationCallback disconnect_cb,
1591                                void *cls)
1592 {
1593   struct GNUNET_SOCIAL_Place *plc = &hst->plc;
1594
1595   plc->disconnect_cb = disconnect_cb;
1596   plc->disconnect_cls = cls;
1597   place_disconnect (plc);
1598 }
1599
1600
1601 /**
1602  * Stop hosting the home.
1603  *
1604  * Sends a _notice_place_closing announcement to the home.
1605  * Invalidates host handle.
1606  *
1607  * @param hst
1608  *        The host leaving.
1609  * @param env
1610  *        Environment for the message or NULL.
1611  *        _nym is set to @e nym regardless whether an @e env is provided.
1612  * @param disconnect_cb
1613  *        Function called after the host left the place
1614  *        and disconnected from the social service.
1615  * @param cls
1616  *        Closure for @a disconnect_cb.
1617  */
1618 void
1619 GNUNET_SOCIAL_host_leave (struct GNUNET_SOCIAL_Host *hst,
1620                           const struct GNUNET_PSYC_Environment *env,
1621                           GNUNET_ContinuationCallback disconnect_cb,
1622                           void *cls)
1623 {
1624   struct GNUNET_MessageHeader *msg;
1625   struct GNUNET_MQ_Envelope *envelope;
1626
1627   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1628               "GNUNET_SOCIAL_host_leave\n");
1629   GNUNET_SOCIAL_host_announce (hst, "_notice_place_closing", env, NULL, NULL,
1630                                GNUNET_SOCIAL_ANNOUNCE_NONE);
1631   hst->plc.disconnect_cb = disconnect_cb;
1632   hst->plc.disconnect_cls = cls;
1633   envelope = GNUNET_MQ_msg (msg,
1634                             GNUNET_MESSAGE_TYPE_SOCIAL_PLACE_LEAVE);
1635   GNUNET_MQ_send (hst->plc.mq,
1636                   envelope);
1637 }
1638
1639
1640 /*** GUEST ***/
1641
1642
1643 static void
1644 guest_connect (struct GNUNET_SOCIAL_Guest *gst);
1645
1646
1647 static void
1648 guest_reconnect (void *cls)
1649 {
1650   guest_connect (cls);
1651 }
1652
1653
1654 /**
1655  * Guest client disconnected from service.
1656  *
1657  * Reconnect after backoff period.
1658  */
1659 static void
1660 guest_disconnected (void *cls, enum GNUNET_MQ_Error error)
1661 {
1662   struct GNUNET_SOCIAL_Guest *gst = cls;
1663   struct GNUNET_SOCIAL_Place *plc = &gst->plc;
1664
1665   LOG (GNUNET_ERROR_TYPE_DEBUG,
1666        "Guest client disconnected (%d), re-connecting\n",
1667        (int) error);
1668   if (NULL != plc->tmit)
1669   {
1670     GNUNET_PSYC_transmit_destroy (plc->tmit);
1671     plc->tmit = NULL;
1672   }
1673   if (NULL != plc->mq)
1674   {
1675     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1676                 "destroying MQ (guest_disconnected)\n");
1677     GNUNET_MQ_destroy (plc->mq);
1678     plc->mq = NULL;
1679   }
1680
1681   plc->reconnect_task = GNUNET_SCHEDULER_add_delayed (plc->reconnect_delay,
1682                                                       guest_reconnect,
1683                                                       gst);
1684   plc->reconnect_delay = GNUNET_TIME_STD_BACKOFF (plc->reconnect_delay);
1685 }
1686
1687
1688 static void
1689 guest_connect (struct GNUNET_SOCIAL_Guest *gst)
1690 {
1691   struct GNUNET_SOCIAL_Place *plc = &gst->plc;
1692
1693   struct GNUNET_MQ_MessageHandler handlers[] = {
1694     GNUNET_MQ_hd_fixed_size (guest_enter_ack,
1695                              GNUNET_MESSAGE_TYPE_SOCIAL_GUEST_ENTER_ACK,
1696                              struct GNUNET_PSYC_CountersResultMessage,
1697                              gst),
1698     GNUNET_MQ_hd_fixed_size (place_leave_ack,
1699                              GNUNET_MESSAGE_TYPE_SOCIAL_PLACE_LEAVE_ACK,
1700                              struct GNUNET_MessageHeader,
1701                              plc),
1702     GNUNET_MQ_hd_var_size (guest_enter_decision,
1703                            GNUNET_MESSAGE_TYPE_PSYC_JOIN_DECISION,
1704                            struct GNUNET_PSYC_JoinDecisionMessage,
1705                            gst),
1706     GNUNET_MQ_hd_var_size (place_message,
1707                            GNUNET_MESSAGE_TYPE_PSYC_MESSAGE,
1708                            struct GNUNET_PSYC_MessageHeader,
1709                            plc),
1710     GNUNET_MQ_hd_fixed_size (place_message_ack,
1711                              GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_ACK,
1712                              struct GNUNET_MessageHeader,
1713                              plc),
1714     GNUNET_MQ_hd_var_size (place_history_result,
1715                            GNUNET_MESSAGE_TYPE_PSYC_HISTORY_RESULT,
1716                            struct GNUNET_OperationResultMessage,
1717                            plc),
1718     GNUNET_MQ_hd_var_size (place_state_result,
1719                            GNUNET_MESSAGE_TYPE_PSYC_STATE_RESULT,
1720                            struct GNUNET_OperationResultMessage,
1721                            plc),
1722     GNUNET_MQ_hd_var_size (place_result,
1723                            GNUNET_MESSAGE_TYPE_PSYC_RESULT_CODE,
1724                            struct GNUNET_OperationResultMessage,
1725                            plc),
1726     GNUNET_MQ_handler_end ()
1727   };
1728
1729   plc->mq = GNUNET_CLIENT_connect (plc->cfg, "social",
1730                                    handlers, guest_disconnected, gst);
1731   GNUNET_assert (NULL != plc->mq);
1732   plc->tmit = GNUNET_PSYC_transmit_create (plc->mq);
1733
1734   GNUNET_MQ_send_copy (plc->mq, plc->connect_env);
1735 }
1736
1737
1738 static struct GNUNET_MQ_Envelope *
1739 guest_enter_request_create (const char *app_id,
1740                             const struct GNUNET_CRYPTO_EcdsaPublicKey *ego_pub_key,
1741                             const struct GNUNET_CRYPTO_EddsaPublicKey *place_pub_key,
1742                             const struct GNUNET_PeerIdentity *origin,
1743                             size_t relay_count,
1744                             const struct GNUNET_PeerIdentity *relays,
1745                             const struct GNUNET_PSYC_Message *join_msg)
1746 {
1747   uint16_t app_id_size = strlen (app_id) + 1;
1748   uint16_t join_msg_size = ntohs (join_msg->header.size);
1749   uint16_t relay_size = relay_count * sizeof (*relays);
1750
1751   struct GuestEnterRequest *greq;
1752   struct GNUNET_MQ_Envelope *
1753     env = GNUNET_MQ_msg_extra (greq, app_id_size + relay_size + join_msg_size,
1754                                GNUNET_MESSAGE_TYPE_SOCIAL_GUEST_ENTER);
1755   greq->place_pub_key = *place_pub_key;
1756   greq->ego_pub_key = *ego_pub_key;
1757   greq->origin = *origin;
1758   greq->relay_count = htonl (relay_count);
1759
1760   char *p = (char *) &greq[1];
1761   GNUNET_memcpy (p, app_id, app_id_size);
1762   p += app_id_size;
1763
1764   if (0 < relay_size)
1765   {
1766     GNUNET_memcpy (p, relays, relay_size);
1767     p += relay_size;
1768   }
1769
1770   GNUNET_memcpy (p, join_msg, join_msg_size);
1771   return env;
1772 }
1773
1774
1775 /**
1776  * Request entry to a place as a guest.
1777  *
1778  * @param app
1779  *        Application handle.
1780  * @param ego
1781  *        Identity of the guest.
1782  * @param place_pub_key
1783  *        Public key of the place to enter.
1784  * @param flags
1785  *        Flags for the entry.
1786  * @param origin
1787  *        Peer identity of the origin of the underlying multicast group.
1788  * @param relay_count
1789  *        Number of elements in the @a relays array.
1790  * @param relays
1791  *        Relays for the underlying multicast group.
1792  * @param method_name
1793  *        Method name for the message.
1794  * @param env
1795  *        Environment containing variables for the message, or NULL.
1796  * @param data
1797  *        Payload for the message to give to the enter callback.
1798  * @param data_size
1799  *        Number of bytes in @a data.
1800  * @param slicer
1801  *        Slicer to use for processing incoming requests from guests.
1802  *
1803  * @return NULL on errors, otherwise handle for the guest.
1804  */
1805 struct GNUNET_SOCIAL_Guest *
1806 GNUNET_SOCIAL_guest_enter (const struct GNUNET_SOCIAL_App *app,
1807                            const struct GNUNET_SOCIAL_Ego *ego,
1808                            const struct GNUNET_CRYPTO_EddsaPublicKey *place_pub_key,
1809                            enum GNUNET_PSYC_SlaveJoinFlags flags,
1810                            const struct GNUNET_PeerIdentity *origin,
1811                            uint32_t relay_count,
1812                            const struct GNUNET_PeerIdentity *relays,
1813                            const struct GNUNET_PSYC_Message *entry_msg,
1814                            struct GNUNET_PSYC_Slicer *slicer,
1815                            GNUNET_SOCIAL_GuestEnterCallback local_enter_cb,
1816                            GNUNET_SOCIAL_EntryDecisionCallback entry_dcsn_cb,
1817                            void *cls)
1818 {
1819   struct GNUNET_SOCIAL_Guest *gst = GNUNET_malloc (sizeof (*gst));
1820   struct GNUNET_SOCIAL_Place *plc = &gst->plc;
1821
1822   plc->ego_pub_key = ego->pub_key;
1823   plc->pub_key = *place_pub_key;
1824   plc->cfg = app->cfg;
1825   plc->is_host = GNUNET_NO;
1826   plc->slicer = slicer;
1827
1828   plc->op = GNUNET_OP_create ();
1829
1830   plc->connect_env
1831     = guest_enter_request_create (app->id, &ego->pub_key, &plc->pub_key,
1832                                   origin, relay_count, relays, entry_msg);
1833
1834   gst->enter_cb = local_enter_cb;
1835   gst->entry_dcsn_cb = entry_dcsn_cb;
1836   gst->cb_cls = cls;
1837
1838   guest_connect (gst);
1839   return gst;
1840 }
1841
1842
1843 /**
1844  * Request entry to a place by name as a guest.
1845  *
1846  * @param app
1847  *        Application handle.
1848  * @param ego
1849  *        Identity of the guest.
1850  * @param gns_name
1851  *        GNS name of the place to enter.  Either in the form of
1852  *        'room.friend.gnu', or 'NYMPUBKEY.zkey'.  This latter case refers to
1853  *        the 'PLACE' record of the empty label ("+") in the GNS zone with the
1854  *        nym's public key 'NYMPUBKEY', and can be used to request entry to a
1855  *        pseudonym's place directly.
1856  * @param password
1857  *        Password to decrypt the record, or NULL for cleartext records.
1858  * @param join_msg
1859  *        Entry request message or NULL.
1860  * @param slicer
1861  *        Slicer to use for processing incoming requests from guests.
1862  * @param local_enter_cb
1863  *        Called upon connection established to the social service.
1864  * @param entry_decision_cb
1865  *        Called upon receiving entry decision.
1866  *
1867  * @return NULL on errors, otherwise handle for the guest.
1868  */
1869 struct GNUNET_SOCIAL_Guest *
1870 GNUNET_SOCIAL_guest_enter_by_name (const struct GNUNET_SOCIAL_App *app,
1871                                    const struct GNUNET_SOCIAL_Ego *ego,
1872                                    const char *gns_name,
1873                                    const char *password,
1874                                    const struct GNUNET_PSYC_Message *join_msg,
1875                                    struct GNUNET_PSYC_Slicer *slicer,
1876                                    GNUNET_SOCIAL_GuestEnterCallback local_enter_cb,
1877                                    GNUNET_SOCIAL_EntryDecisionCallback entry_decision_cb,
1878                                    void *cls)
1879 {
1880   struct GNUNET_SOCIAL_Guest *gst = GNUNET_malloc (sizeof (*gst));
1881   struct GNUNET_SOCIAL_Place *plc = &gst->plc;
1882
1883   if (NULL == password)
1884     password = "";
1885
1886   uint16_t app_id_size = strlen (app->id) + 1;
1887   uint16_t gns_name_size = strlen (gns_name) + 1;
1888   uint16_t password_size = strlen (password) + 1;
1889
1890   uint16_t join_msg_size = 0;
1891   if (NULL != join_msg)
1892     join_msg_size = ntohs (join_msg->header.size);
1893
1894   struct GuestEnterByNameRequest *greq;
1895   plc->connect_env
1896     = GNUNET_MQ_msg_extra (greq, app_id_size + gns_name_size
1897                            + password_size + join_msg_size,
1898                            GNUNET_MESSAGE_TYPE_SOCIAL_GUEST_ENTER_BY_NAME);
1899
1900   greq->ego_pub_key = ego->pub_key;
1901
1902   char *p = (char *) &greq[1];
1903   GNUNET_memcpy (p, app->id, app_id_size);
1904   p += app_id_size;
1905   GNUNET_memcpy (p, gns_name, gns_name_size);
1906   p += gns_name_size;
1907   GNUNET_memcpy (p, password, password_size);
1908   p += password_size;
1909   if (NULL != join_msg)
1910     GNUNET_memcpy (p, join_msg, join_msg_size);
1911
1912   plc->ego_pub_key = ego->pub_key;
1913   plc->cfg = app->cfg;
1914   plc->is_host = GNUNET_NO;
1915   plc->slicer = slicer;
1916
1917   plc->op = GNUNET_OP_create ();
1918
1919   gst->enter_cb = local_enter_cb;
1920   gst->entry_dcsn_cb = entry_decision_cb;
1921   gst->cb_cls = cls;
1922
1923   guest_connect (gst);
1924   return gst;
1925 }
1926
1927
1928 /**
1929  * Reconnect to an already entered place as guest.
1930  *
1931  * @param gconn
1932  *        Guest connection handle.
1933  *        @see GNUNET_SOCIAL_app_connect() & GNUNET_SOCIAL_AppGuestPlaceCallback()
1934  * @param flags
1935  *        Flags for the entry.
1936  * @param slicer
1937  *        Slicer to use for processing incoming requests from guests.
1938  * @param local_enter_cb
1939  *        Called upon connection established to the social service.
1940  * @param entry_decision_cb
1941  *        Called upon receiving entry decision.
1942  *
1943  * @return NULL on errors, otherwise handle for the guest.
1944  */
1945 struct GNUNET_SOCIAL_Guest *
1946 GNUNET_SOCIAL_guest_enter_reconnect (struct GNUNET_SOCIAL_GuestConnection *gconn,
1947                                      enum GNUNET_PSYC_SlaveJoinFlags flags,
1948                                      struct GNUNET_PSYC_Slicer *slicer,
1949                                      GNUNET_SOCIAL_GuestEnterCallback local_enter_cb,
1950                                      void *cls)
1951 {
1952   struct GNUNET_SOCIAL_Guest *gst = GNUNET_malloc (sizeof (*gst));
1953   struct GNUNET_SOCIAL_Place *plc = &gst->plc;
1954
1955   uint16_t app_id_size = strlen (gconn->app->id) + 1;
1956   struct GuestEnterRequest *greq;
1957   plc->connect_env
1958     = GNUNET_MQ_msg_extra (greq, app_id_size,
1959                            GNUNET_MESSAGE_TYPE_SOCIAL_GUEST_ENTER);
1960   greq->ego_pub_key = gconn->plc_msg.ego_pub_key;
1961   greq->place_pub_key = gconn->plc_msg.place_pub_key;
1962   greq->flags = htonl (flags);
1963
1964   GNUNET_memcpy (&greq[1], gconn->app->id, app_id_size);
1965
1966   plc->cfg = gconn->app->cfg;
1967   plc->is_host = GNUNET_NO;
1968   plc->slicer = slicer;
1969   plc->pub_key = gconn->plc_msg.place_pub_key;
1970   plc->ego_pub_key = gconn->plc_msg.ego_pub_key;
1971
1972   plc->op = GNUNET_OP_create ();
1973
1974   gst->enter_cb = local_enter_cb;
1975   gst->cb_cls = cls;
1976
1977   guest_connect (gst);
1978   return gst;
1979 }
1980
1981
1982 /**
1983  * Talk to the host of the place.
1984  *
1985  * @param place
1986  *        Place where we want to talk to the host.
1987  * @param method_name
1988  *        Method to invoke on the host.
1989  * @param env
1990  *        Environment containing variables for the message, or NULL.
1991  * @param notify_data
1992  *        Function to use to get the payload for the method.
1993  * @param notify_data_cls
1994  *        Closure for @a notify_data.
1995  * @param flags
1996  *        Flags for the message being sent.
1997  *
1998  * @return NULL if we are already trying to talk to the host,
1999  *         otherwise handle to cancel the request.
2000  */
2001 struct GNUNET_SOCIAL_TalkRequest *
2002 GNUNET_SOCIAL_guest_talk (struct GNUNET_SOCIAL_Guest *gst,
2003                           const char *method_name,
2004                           const struct GNUNET_PSYC_Environment *env,
2005                           GNUNET_PSYC_TransmitNotifyData notify_data,
2006                           void *notify_data_cls,
2007                           enum GNUNET_SOCIAL_TalkFlags flags)
2008 {
2009   struct GNUNET_SOCIAL_Place *plc = &gst->plc;
2010   GNUNET_assert (NULL != plc->tmit);
2011
2012   if (GNUNET_OK ==
2013       GNUNET_PSYC_transmit_message (plc->tmit, method_name, env,
2014                                     NULL, notify_data, notify_data_cls, flags))
2015     return (struct GNUNET_SOCIAL_TalkRequest *) plc->tmit;
2016   else
2017     return NULL;
2018 }
2019
2020
2021 /**
2022  * Resume talking to the host of the place.
2023  *
2024  * @param tr
2025  *        Talk request to resume.
2026  */
2027 void
2028 GNUNET_SOCIAL_guest_talk_resume (struct GNUNET_SOCIAL_TalkRequest *tr)
2029 {
2030   GNUNET_PSYC_transmit_resume ((struct GNUNET_PSYC_TransmitHandle *) tr);
2031 }
2032
2033
2034 /**
2035  * Cancel talking to the host of the place.
2036  *
2037  * @param tr
2038  *        Talk request to cancel.
2039  */
2040 void
2041 GNUNET_SOCIAL_guest_talk_cancel (struct GNUNET_SOCIAL_TalkRequest *tr)
2042 {
2043   GNUNET_PSYC_transmit_cancel ( (struct GNUNET_PSYC_TransmitHandle *) tr);
2044 }
2045
2046
2047 /**
2048  * Disconnect from a place.
2049  *
2050  * Invalidates guest handle.
2051  *
2052  * @param gst
2053  *        The guest to disconnect.
2054  */
2055 void
2056 GNUNET_SOCIAL_guest_disconnect (struct GNUNET_SOCIAL_Guest *gst,
2057                                 GNUNET_ContinuationCallback disconnect_cb,
2058                                 void *cls)
2059 {
2060   struct GNUNET_SOCIAL_Place *plc = &gst->plc;
2061
2062   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2063               "GNUNET_SOCIAL_guest_disconnect, gst = %p\n",
2064               gst);
2065   plc->disconnect_cb = disconnect_cb;
2066   plc->disconnect_cls = cls;
2067   place_disconnect (plc);
2068 }
2069
2070
2071 /**
2072  * Leave a place temporarily or permanently.
2073  *
2074  * Notifies the owner of the place about leaving, and destroys the place handle.
2075  *
2076  * @param place
2077  *        Place to leave.
2078  * @param keep_active
2079  *        Keep place active after last application disconnected.
2080  *        #GNUNET_YES or #GNUNET_NO
2081  * @param env
2082  *        Optional environment for the leave message if @a keep_active
2083  *        is #GNUNET_NO.  NULL if not needed.
2084  * @param leave_cb
2085  *        Called upon disconnecting from the social service.
2086  */
2087 void
2088 GNUNET_SOCIAL_guest_leave (struct GNUNET_SOCIAL_Guest *gst,
2089                            struct GNUNET_PSYC_Environment *env,
2090                            GNUNET_ContinuationCallback disconnect_cb,
2091                            void *cls)
2092 {
2093   struct GNUNET_MessageHeader *msg;
2094   struct GNUNET_MQ_Envelope *envelope;
2095
2096   GNUNET_SOCIAL_guest_talk (gst, "_notice_place_leave", env, NULL, NULL,
2097                             GNUNET_SOCIAL_TALK_NONE);
2098
2099
2100   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2101               "social_api: place_leave\n");
2102   gst->plc.disconnect_cb = disconnect_cb;
2103   gst->plc.disconnect_cls = cls;
2104   envelope = GNUNET_MQ_msg (msg,
2105                             GNUNET_MESSAGE_TYPE_SOCIAL_PLACE_LEAVE);
2106   GNUNET_MQ_send (gst->plc.mq,
2107                   envelope);
2108 }
2109
2110
2111 /**
2112  * Obtain handle for a place entered as guest.
2113  *
2114  * The returned handle can be used to access the place API.
2115  *
2116  * @param guest  Handle for the guest.
2117  *
2118  * @return Handle for the place, valid as long as @a guest is valid.
2119  */
2120 struct GNUNET_SOCIAL_Place *
2121 GNUNET_SOCIAL_guest_get_place (struct GNUNET_SOCIAL_Guest *gst)
2122 {
2123   return &gst->plc;
2124 }
2125
2126
2127 /**
2128  * Obtain the public key of a place.
2129  *
2130  * @param plc
2131  *        Place.
2132  *
2133  * @return Public key of the place.
2134  */
2135 const struct GNUNET_CRYPTO_EddsaPublicKey *
2136 GNUNET_SOCIAL_place_get_pub_key (const struct GNUNET_SOCIAL_Place *plc)
2137 {
2138   return &plc->pub_key;
2139 }
2140
2141
2142 /**
2143  * Set message processing @a flags for a @a method_prefix.
2144  *
2145  * @param plc
2146  *        Place.
2147  * @param method_prefix
2148  *        Method prefix @a flags apply to.
2149  * @param flags
2150  *        The flags that apply to a matching @a method_prefix.
2151  */
2152 void
2153 GNUNET_SOCIAL_place_msg_proc_set (struct GNUNET_SOCIAL_Place *plc,
2154                                   const char *method_prefix,
2155                                   enum GNUNET_SOCIAL_MsgProcFlags flags)
2156 {
2157   GNUNET_assert (NULL != method_prefix);
2158   struct MsgProcRequest *mpreq;
2159   uint16_t method_size = strnlen (method_prefix,
2160                                   GNUNET_MAX_MESSAGE_SIZE
2161                                   - sizeof (*mpreq)) + 1;
2162   GNUNET_assert ('\0' == method_prefix[method_size - 1]);
2163
2164   struct GNUNET_MQ_Envelope *
2165     env = GNUNET_MQ_msg_extra (mpreq, method_size,
2166                                GNUNET_MESSAGE_TYPE_SOCIAL_MSG_PROC_SET);
2167   mpreq->flags = htonl (flags);
2168   GNUNET_memcpy (&mpreq[1], method_prefix, method_size);
2169
2170   GNUNET_MQ_send (plc->mq, env);
2171 }
2172
2173
2174 /**
2175  * Clear all message processing flags previously set for this place.
2176  */
2177 void
2178 GNUNET_SOCIAL_place_msg_proc_clear (struct GNUNET_SOCIAL_Place *plc)
2179 {
2180   struct GNUNET_MessageHeader *req;
2181   struct GNUNET_MQ_Envelope *
2182     env = GNUNET_MQ_msg (req, GNUNET_MESSAGE_TYPE_SOCIAL_MSG_PROC_CLEAR);
2183
2184   GNUNET_MQ_send (plc->mq, env);
2185 }
2186
2187
2188 static struct GNUNET_SOCIAL_HistoryRequest *
2189 place_history_replay (struct GNUNET_SOCIAL_Place *plc,
2190                       uint64_t start_message_id,
2191                       uint64_t end_message_id,
2192                       uint64_t message_limit,
2193                       const char *method_prefix,
2194                       uint32_t flags,
2195                       struct GNUNET_PSYC_Slicer *slicer,
2196                       GNUNET_ResultCallback result_cb,
2197                       void *cls)
2198 {
2199   struct GNUNET_PSYC_HistoryRequestMessage *req;
2200   struct GNUNET_SOCIAL_HistoryRequest *hist = GNUNET_malloc (sizeof (*hist));
2201   hist->plc = plc;
2202   hist->slicer = slicer;
2203   hist->result_cb = result_cb;
2204   hist->cls = cls;
2205   hist->op_id = GNUNET_OP_add (plc->op, op_recv_history_result, hist, NULL);
2206
2207   GNUNET_assert (NULL != method_prefix);
2208   uint16_t method_size = strnlen (method_prefix,
2209                                   GNUNET_MAX_MESSAGE_SIZE
2210                                   - sizeof (*req)) + 1;
2211   GNUNET_assert ('\0' == method_prefix[method_size - 1]);
2212
2213   struct GNUNET_MQ_Envelope *
2214     env = GNUNET_MQ_msg_extra (req, method_size,
2215                                GNUNET_MESSAGE_TYPE_PSYC_HISTORY_REPLAY);
2216   req->start_message_id = GNUNET_htonll (start_message_id);
2217   req->end_message_id = GNUNET_htonll (end_message_id);
2218   req->message_limit = GNUNET_htonll (message_limit);
2219   req->flags = htonl (flags);
2220   req->op_id = GNUNET_htonll (hist->op_id);
2221   GNUNET_memcpy (&req[1], method_prefix, method_size);
2222
2223   GNUNET_MQ_send (plc->mq, env);
2224   return hist;
2225 }
2226
2227
2228 /**
2229  * Learn about the history of a place.
2230  *
2231  * Messages are returned through the @a slicer function
2232  * and have the #GNUNET_PSYC_MESSAGE_HISTORIC flag set.
2233  *
2234  * @param place
2235  *        Place we want to learn more about.
2236  * @param start_message_id
2237  *        First historic message we are interested in.
2238  * @param end_message_id
2239  *        Last historic message we are interested in (inclusive).
2240  * @param method_prefix
2241  *        Only retrieve messages with this method prefix.
2242  * @param flags
2243  *        OR'ed GNUNET_PSYC_HistoryReplayFlags
2244  * @param slicer
2245  *        Slicer to use for retrieved messages.
2246  *        Can be the same as the slicer of the place.
2247  * @param result_cb
2248  *        Function called after all messages retrieved.
2249  *        NULL if not needed.
2250  * @param cls Closure for @a result_cb.
2251  */
2252 struct GNUNET_SOCIAL_HistoryRequest *
2253 GNUNET_SOCIAL_place_history_replay (struct GNUNET_SOCIAL_Place *plc,
2254                                     uint64_t start_message_id,
2255                                     uint64_t end_message_id,
2256                                     const char *method_prefix,
2257                                     uint32_t flags,
2258                                     struct GNUNET_PSYC_Slicer *slicer,
2259                                     GNUNET_ResultCallback result_cb,
2260                                     void *cls)
2261 {
2262   return place_history_replay (plc, start_message_id, end_message_id, 0,
2263                                method_prefix, flags, slicer, result_cb, cls);
2264 }
2265
2266
2267 /**
2268  * Learn about the history of a place.
2269  *
2270  * Sends messages through the slicer function of the place where
2271  * start_message_id <= message_id <= end_message_id.
2272  * The messages will have the #GNUNET_PSYC_MESSAGE_HISTORIC flag set.
2273  *
2274  * To get the latest message, use 0 for both the start and end message ID.
2275  *
2276  * @param place
2277  *        Place we want to learn more about.
2278  * @param message_limit
2279  *        Maximum number of historic messages we are interested in.
2280  * @param method_prefix
2281  *        Only retrieve messages with this method prefix.
2282  * @param flags
2283  *        OR'ed GNUNET_PSYC_HistoryReplayFlags
2284  * @param result_cb
2285  *        Function called after all messages retrieved.
2286  *        NULL if not needed.
2287  * @param cls Closure for @a result_cb.
2288  */
2289 struct GNUNET_SOCIAL_HistoryRequest *
2290 GNUNET_SOCIAL_place_history_replay_latest (struct GNUNET_SOCIAL_Place *plc,
2291                                            uint64_t message_limit,
2292                                            const char *method_prefix,
2293                                            uint32_t flags,
2294                                            struct GNUNET_PSYC_Slicer *slicer,
2295                                            GNUNET_ResultCallback result_cb,
2296                                            void *cls)
2297 {
2298   return place_history_replay (plc, 0, 0, message_limit, method_prefix, flags,
2299                                slicer, result_cb, cls);
2300 }
2301
2302
2303 /**
2304  * Cancel learning about the history of a place.
2305  *
2306  * @param hist
2307  *        History lesson to cancel.
2308  */
2309 void
2310 GNUNET_SOCIAL_place_history_replay_cancel (struct GNUNET_SOCIAL_HistoryRequest *hist)
2311 {
2312   GNUNET_OP_remove (hist->plc->op, hist->op_id);
2313   GNUNET_free (hist);
2314 }
2315
2316
2317 /**
2318  * Request matching state variables.
2319  */
2320 static struct GNUNET_SOCIAL_LookHandle *
2321 place_state_get (struct GNUNET_SOCIAL_Place *plc,
2322                  uint16_t type, const char *name,
2323                  GNUNET_PSYC_StateVarCallback var_cb,
2324                  GNUNET_ResultCallback result_cb, void *cls)
2325 {
2326   struct GNUNET_PSYC_StateRequestMessage *req;
2327   struct GNUNET_SOCIAL_LookHandle *look = GNUNET_malloc (sizeof (*look));
2328   look->plc = plc;
2329   look->var_cb = var_cb;
2330   look->result_cb = result_cb;
2331   look->cls = cls;
2332   look->op_id = GNUNET_OP_add (plc->op, &op_recv_state_result, look, NULL);
2333
2334   GNUNET_assert (NULL != name);
2335   size_t name_size = strnlen (name, GNUNET_MAX_MESSAGE_SIZE
2336                               - sizeof (*req)) + 1;
2337   struct GNUNET_MQ_Envelope *
2338     env = GNUNET_MQ_msg_extra (req, name_size, type);
2339   req->op_id = GNUNET_htonll (look->op_id);
2340   GNUNET_memcpy (&req[1], name, name_size);
2341
2342   GNUNET_MQ_send (plc->mq, env);
2343   return look;
2344 }
2345
2346
2347 /**
2348  * Look at a particular object in the place.
2349  *
2350  * The best matching object is returned (its name might be less specific than
2351  * what was requested).
2352  *
2353  * @param place
2354  *        The place where to look.
2355  * @param full_name
2356  *        Full name of the object.
2357  * @param value_size
2358  *        Set to the size of the returned value.
2359  *
2360  * @return NULL if there is no such object at this place.
2361  */
2362 struct GNUNET_SOCIAL_LookHandle *
2363 GNUNET_SOCIAL_place_look_at (struct GNUNET_SOCIAL_Place *plc,
2364                              const char *full_name,
2365                              GNUNET_PSYC_StateVarCallback var_cb,
2366                              GNUNET_ResultCallback result_cb,
2367                              void *cls)
2368 {
2369   return place_state_get (plc, GNUNET_MESSAGE_TYPE_PSYC_STATE_GET,
2370                           full_name, var_cb, result_cb, cls);
2371 }
2372
2373
2374 /**
2375  * Look for objects in the place with a matching name prefix.
2376  *
2377  * @param place
2378  *        The place where to look.
2379  * @param name_prefix
2380  *        Look at objects with names beginning with this value.
2381  * @param var_cb
2382  *        Function to call for each object found.
2383  * @param cls
2384  *        Closure for callback function.
2385  *
2386  * @return Handle that can be used to stop looking at objects.
2387  */
2388 struct GNUNET_SOCIAL_LookHandle *
2389 GNUNET_SOCIAL_place_look_for (struct GNUNET_SOCIAL_Place *plc,
2390                               const char *name_prefix,
2391                               GNUNET_PSYC_StateVarCallback var_cb,
2392                               GNUNET_ResultCallback result_cb,
2393                               void *cls)
2394 {
2395   return place_state_get (plc, GNUNET_MESSAGE_TYPE_PSYC_STATE_GET_PREFIX,
2396                           name_prefix, var_cb, result_cb, cls);
2397 }
2398
2399
2400 /**
2401  * Cancel a state request operation.
2402  *
2403  * @param sr
2404  *        Handle for the operation to cancel.
2405  */
2406 void
2407 GNUNET_SOCIAL_place_look_cancel (struct GNUNET_SOCIAL_LookHandle *look)
2408 {
2409   GNUNET_OP_remove (look->plc->op, look->op_id);
2410   GNUNET_free (look);
2411 }
2412
2413
2414 static void
2415 op_recv_zone_add_place_result (void *cls, int64_t result,
2416                                const void *err_msg, uint16_t err_msg_size)
2417 {
2418   LOG (GNUNET_ERROR_TYPE_DEBUG,
2419        "Received zone add place result: %" PRId64 ".\n", result);
2420
2421   struct ZoneAddPlaceHandle *add_plc = cls;
2422   if (NULL != add_plc->result_cb)
2423     add_plc->result_cb (add_plc->result_cls, result, err_msg, err_msg_size);
2424
2425   GNUNET_free (add_plc);
2426 }
2427
2428
2429 /**
2430  * Advertise @e place in the GNS zone of @e ego.
2431  *
2432  * @param app
2433  *        Application handle.
2434  * @param ego
2435  *        Ego.
2436  * @param place_pub_key
2437  *        Public key of place to add.
2438  * @param name
2439  *        The name for the PLACE record to put in the zone.
2440  * @param password
2441  *        Password used to encrypt the record or NULL to keep it cleartext.
2442  * @param relay_count
2443  *        Number of elements in the @a relays array.
2444  * @param relays
2445  *        List of relays to put in the PLACE record to advertise
2446  *        as entry points to the place in addition to the origin.
2447  * @param expiration_time
2448  *        Expiration time of the record, use 0 to remove the record.
2449  * @param result_cb
2450  *        Function called with the result of the operation.
2451  * @param result_cls
2452  *        Closure for @a result_cb
2453  *
2454  * @return #GNUNET_OK if the request was sent,
2455  *         #GNUNET_SYSERR on error, e.g. the name/password is too long.
2456  */
2457 int
2458 GNUNET_SOCIAL_zone_add_place (const struct GNUNET_SOCIAL_App *app,
2459                               const struct GNUNET_SOCIAL_Ego *ego,
2460                               const char *name,
2461                               const char *password,
2462                               const struct GNUNET_CRYPTO_EddsaPublicKey *place_pub_key,
2463                               const struct GNUNET_PeerIdentity *origin,
2464                               uint32_t relay_count,
2465                               const struct GNUNET_PeerIdentity *relays,
2466                               struct GNUNET_TIME_Absolute expiration_time,
2467                               GNUNET_ResultCallback result_cb,
2468                               void *result_cls)
2469 {
2470   struct ZoneAddPlaceRequest *preq;
2471   size_t name_size = strlen (name) + 1;
2472   size_t password_size = strlen (password) + 1;
2473   size_t relay_size = relay_count * sizeof (*relays);
2474   size_t payload_size = name_size + password_size + relay_size;
2475
2476   if (GNUNET_MAX_MESSAGE_SIZE < sizeof (*preq) + payload_size)
2477     return GNUNET_SYSERR;
2478
2479   struct GNUNET_MQ_Envelope *
2480     env = GNUNET_MQ_msg_extra (preq, payload_size,
2481                                GNUNET_MESSAGE_TYPE_SOCIAL_ZONE_ADD_PLACE);
2482   preq->expiration_time = GNUNET_htonll (expiration_time.abs_value_us);
2483   preq->ego_pub_key = ego->pub_key;
2484   preq->place_pub_key = *place_pub_key;
2485   preq->origin = *origin;
2486   preq->relay_count = htonl (relay_count);
2487
2488   char *p = (char *) &preq[1];
2489   GNUNET_memcpy (p, name, name_size);
2490   p += name_size;
2491   GNUNET_memcpy (p, password, password_size);
2492   p += password_size;
2493   GNUNET_memcpy (p, relays, relay_size);
2494
2495   struct ZoneAddPlaceHandle * add_plc = GNUNET_malloc (sizeof (*add_plc));
2496   add_plc->result_cb = result_cb;
2497   add_plc->result_cls = result_cls;
2498
2499   preq->op_id = GNUNET_htonll (GNUNET_OP_add (app->op,
2500                                               op_recv_zone_add_place_result,
2501                                               add_plc, NULL));
2502
2503   GNUNET_MQ_send (app->mq, env);
2504   return GNUNET_OK;
2505 }
2506
2507
2508 static void
2509 op_recv_zone_add_nym_result (void *cls, int64_t result,
2510                              const void *err_msg, uint16_t err_msg_size)
2511 {
2512   LOG (GNUNET_ERROR_TYPE_DEBUG,
2513        "Received zone add nym result: %" PRId64 ".\n", result);
2514
2515   struct ZoneAddNymHandle *add_nym = cls;
2516   if (NULL != add_nym->result_cb)
2517     add_nym->result_cb (add_nym->result_cls, result, err_msg, err_msg_size);
2518
2519   GNUNET_free (add_nym);
2520 }
2521
2522
2523 /**
2524  * Add nym to the GNS zone of @e ego.
2525  *
2526  * @param cfg
2527  *        Configuration.
2528  * @param ego
2529  *        Ego.
2530  * @param name
2531  *        The name for the PKEY record to put in the zone.
2532  * @param nym_pub_key
2533  *        Public key of nym to add.
2534  * @param expiration_time
2535  *        Expiration time of the record, use 0 to remove the record.
2536  * @param result_cb
2537  *        Function called with the result of the operation.
2538  * @param result_cls
2539  *        Closure for @a result_cb
2540  *
2541  * @return #GNUNET_OK if the request was sent,
2542  *         #GNUNET_SYSERR on error, e.g. the name is too long.
2543  */
2544 int
2545 GNUNET_SOCIAL_zone_add_nym (const struct GNUNET_SOCIAL_App *app,
2546                             const struct GNUNET_SOCIAL_Ego *ego,
2547                             const char *name,
2548                             const struct GNUNET_CRYPTO_EcdsaPublicKey *nym_pub_key,
2549                             struct GNUNET_TIME_Absolute expiration_time,
2550                             GNUNET_ResultCallback result_cb,
2551                             void *result_cls)
2552 {
2553   struct ZoneAddNymRequest *nreq;
2554
2555   size_t name_size = strlen (name) + 1;
2556   if (GNUNET_MAX_MESSAGE_SIZE < sizeof (*nreq) + name_size)
2557     return GNUNET_SYSERR;
2558
2559   struct GNUNET_MQ_Envelope *
2560     env = GNUNET_MQ_msg_extra (nreq, name_size,
2561                                GNUNET_MESSAGE_TYPE_SOCIAL_ZONE_ADD_NYM);
2562   nreq->expiration_time = GNUNET_htonll (expiration_time.abs_value_us);
2563   nreq->ego_pub_key = ego->pub_key;
2564   nreq->nym_pub_key = *nym_pub_key;
2565   GNUNET_memcpy (&nreq[1], name, name_size);
2566
2567   struct ZoneAddNymHandle *add_nym = GNUNET_malloc (sizeof (*add_nym));
2568   add_nym->result_cb = result_cb;
2569   add_nym->result_cls = result_cls;
2570
2571   nreq->op_id = GNUNET_htonll (GNUNET_OP_add (app->op,
2572                                               op_recv_zone_add_nym_result,
2573                                               add_nym, NULL));
2574
2575   GNUNET_MQ_send (app->mq, env);
2576   return GNUNET_OK;
2577 }
2578
2579
2580 /*** APP ***/
2581
2582
2583 static void
2584 app_connect (struct GNUNET_SOCIAL_App *app);
2585
2586
2587 static void
2588 app_reconnect (void *cls)
2589 {
2590   app_connect (cls);
2591 }
2592
2593
2594 /**
2595  * App client disconnected from service.
2596  *
2597  * Reconnect after backoff period.
2598  */
2599 static void
2600 app_disconnected (void *cls, enum GNUNET_MQ_Error error)
2601 {
2602   struct GNUNET_SOCIAL_App *app = cls;
2603
2604   LOG (GNUNET_ERROR_TYPE_DEBUG,
2605        "App client disconnected (%d), re-connecting\n",
2606        (int) error);
2607   if (NULL != app->mq)
2608   {
2609     GNUNET_MQ_destroy (app->mq);
2610     app->mq = NULL;
2611   }
2612
2613   app->reconnect_task = GNUNET_SCHEDULER_add_delayed (app->reconnect_delay,
2614                                                       app_reconnect,
2615                                                       app);
2616   app->reconnect_delay = GNUNET_TIME_STD_BACKOFF (app->reconnect_delay);
2617 }
2618
2619
2620 static void
2621 app_connect (struct GNUNET_SOCIAL_App *app)
2622 {
2623   struct GNUNET_MQ_MessageHandler handlers[] = {
2624     GNUNET_MQ_hd_var_size (app_ego,
2625                            GNUNET_MESSAGE_TYPE_SOCIAL_APP_EGO,
2626                            struct AppEgoMessage,
2627                            app),
2628     GNUNET_MQ_hd_fixed_size (app_ego_end,
2629                              GNUNET_MESSAGE_TYPE_SOCIAL_APP_EGO_END,
2630                              struct GNUNET_MessageHeader,
2631                              app),
2632     GNUNET_MQ_hd_var_size (app_place,
2633                            GNUNET_MESSAGE_TYPE_SOCIAL_APP_PLACE,
2634                            struct AppPlaceMessage,
2635                            app),
2636     GNUNET_MQ_hd_fixed_size (app_place_end,
2637                              GNUNET_MESSAGE_TYPE_SOCIAL_APP_PLACE_END,
2638                              struct GNUNET_MessageHeader,
2639                              app),
2640     GNUNET_MQ_hd_var_size (app_result,
2641                            GNUNET_MESSAGE_TYPE_PSYC_RESULT_CODE,
2642                            struct GNUNET_OperationResultMessage,
2643                            app),
2644     GNUNET_MQ_handler_end ()
2645   };
2646
2647   app->mq = GNUNET_CLIENT_connect (app->cfg, "social",
2648                                    handlers, app_disconnected, app);
2649   GNUNET_assert (NULL != app->mq);
2650   GNUNET_MQ_send_copy (app->mq, app->connect_env);
2651 }
2652
2653
2654 /**
2655  * Connect application to the social service.
2656  *
2657  * The @host_place_cb and @guest_place_cb functions are
2658  * initially called for each entered places,
2659  * then later each time a new place is entered with the current application ID.
2660  *
2661  * @param cfg
2662  *        Configuration.
2663  * @param id
2664  *        Application ID.
2665  * @param ego_cb
2666  *        Function to notify about an available ego.
2667  * @param host_cb
2668  *        Function to notify about a place entered as host.
2669  * @param guest_cb
2670  *        Function to notify about a place entered as guest.
2671  * @param cls
2672  *        Closure for the callbacks.
2673  *
2674  * @return Handle that can be used to stop listening.
2675  */
2676 struct GNUNET_SOCIAL_App *
2677 GNUNET_SOCIAL_app_connect (const struct GNUNET_CONFIGURATION_Handle *cfg,
2678                            const char *id,
2679                            GNUNET_SOCIAL_AppEgoCallback ego_cb,
2680                            GNUNET_SOCIAL_AppHostPlaceCallback host_cb,
2681                            GNUNET_SOCIAL_AppGuestPlaceCallback guest_cb,
2682                            GNUNET_SOCIAL_AppConnectedCallback connected_cb,
2683                            void *cls)
2684 {
2685   uint16_t app_id_size = strnlen (id, GNUNET_SOCIAL_APP_MAX_ID_SIZE);
2686   if (GNUNET_SOCIAL_APP_MAX_ID_SIZE == app_id_size)
2687     return NULL;
2688   app_id_size++;
2689
2690   struct GNUNET_SOCIAL_App *app = GNUNET_malloc (sizeof *app);
2691   app->cfg = cfg;
2692   app->ego_cb = ego_cb;
2693   app->host_cb = host_cb;
2694   app->guest_cb = guest_cb;
2695   app->connected_cb = connected_cb;
2696   app->cb_cls = cls;
2697   app->egos = GNUNET_CONTAINER_multihashmap_create (1, GNUNET_NO);
2698   app->op = GNUNET_OP_create ();
2699   app->id = GNUNET_malloc (app_id_size);
2700   GNUNET_memcpy (app->id, id, app_id_size);
2701
2702   struct AppConnectRequest *creq;
2703   app->connect_env = GNUNET_MQ_msg_extra (creq, app_id_size,
2704                                           GNUNET_MESSAGE_TYPE_SOCIAL_APP_CONNECT);
2705   GNUNET_memcpy (&creq[1], app->id, app_id_size);
2706
2707   app_connect (app);
2708   return app;
2709 }
2710
2711
2712 static void
2713 app_cleanup (struct GNUNET_SOCIAL_App *app)
2714 {
2715   if (NULL != app->mq)
2716   {
2717     GNUNET_MQ_destroy (app->mq);
2718     app->mq = NULL;
2719   }
2720   if (NULL != app->disconnect_cb)
2721   {
2722     app->disconnect_cb (app->disconnect_cls);
2723     app->disconnect_cb = NULL;
2724   }
2725   GNUNET_free (app);
2726 }
2727
2728 /**
2729  * Disconnect application.
2730  *
2731  * @param app
2732  *        Application handle.
2733  * @param disconnect_cb
2734  *        Disconnect callback.
2735  * @param disconnect_cls
2736  *        Disconnect closure.
2737  */
2738 void
2739 GNUNET_SOCIAL_app_disconnect (struct GNUNET_SOCIAL_App *app,
2740                               GNUNET_ContinuationCallback disconnect_cb,
2741                               void *disconnect_cls)
2742 {
2743   app->disconnect_cb = disconnect_cb;
2744   app->disconnect_cls = disconnect_cls;
2745
2746   if (NULL != app->mq)
2747   {
2748     struct GNUNET_MQ_Envelope *env = GNUNET_MQ_get_last_envelope (app->mq);
2749     if (NULL != env)
2750     {
2751       GNUNET_MQ_notify_sent (env, (GNUNET_SCHEDULER_TaskCallback) app_cleanup, app);
2752     }
2753     else
2754     {
2755       app_cleanup (app);
2756     }
2757   }
2758   else
2759   {
2760     app_cleanup (app);
2761   }
2762 }
2763
2764
2765 /**
2766  * Detach application from a place.
2767  *
2768  * Removes the place from the entered places list for this application.
2769  * Note: this does not disconnect from the place.
2770  *
2771  * @see GNUNET_SOCIAL_host_disconnect() and GNUNET_SOCIAL_guest_disconnect()
2772  *
2773  * @param app
2774  *        Application.
2775  * @param plc
2776  *        Place.
2777  */
2778 void
2779 GNUNET_SOCIAL_app_detach (struct GNUNET_SOCIAL_App *app,
2780                           struct GNUNET_SOCIAL_Place *plc)
2781 {
2782   struct AppDetachRequest *dreq;
2783   struct GNUNET_MQ_Envelope *
2784     env = GNUNET_MQ_msg (dreq, GNUNET_MESSAGE_TYPE_SOCIAL_APP_DETACH);
2785   dreq->place_pub_key = plc->pub_key;
2786   dreq->ego_pub_key = plc->ego_pub_key;
2787
2788   GNUNET_MQ_send (app->mq, env);
2789 }
2790
2791
2792 /* end of social_api.c */