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