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