48e376404fda5638ed9476ad38df77f7515a16a6
[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, method: %s\n",
1520               method_name);
1521   if (GNUNET_OK ==
1522       GNUNET_PSYC_transmit_message (hst->plc.tmit, method_name, env,
1523                                     NULL, notify_data, notify_data_cls, flags))
1524     return (struct GNUNET_SOCIAL_Announcement *) hst->plc.tmit;
1525   else
1526     return NULL;
1527 }
1528
1529
1530 /**
1531  * Resume transmitting announcement.
1532  *
1533  * @param a
1534  *        The announcement to resume.
1535  */
1536 void
1537 GNUNET_SOCIAL_host_announce_resume (struct GNUNET_SOCIAL_Announcement *a)
1538 {
1539   GNUNET_PSYC_transmit_resume ((struct GNUNET_PSYC_TransmitHandle *) a);
1540 }
1541
1542
1543 /**
1544  * Cancel announcement.
1545  *
1546  * @param a
1547  *        The announcement to cancel.
1548  */
1549 void
1550 GNUNET_SOCIAL_host_announce_cancel (struct GNUNET_SOCIAL_Announcement *a)
1551 {
1552   GNUNET_PSYC_transmit_cancel ((struct GNUNET_PSYC_TransmitHandle *) a);
1553 }
1554
1555
1556 /**
1557  * Obtain handle for a hosted place.
1558  *
1559  * The returned handle can be used to access the place API.
1560  *
1561  * @param host  Handle for the host.
1562  *
1563  * @return Handle for the hosted place, valid as long as @a host is valid.
1564  */
1565 struct GNUNET_SOCIAL_Place *
1566 GNUNET_SOCIAL_host_get_place (struct GNUNET_SOCIAL_Host *hst)
1567 {
1568   return &hst->plc;
1569 }
1570
1571
1572 /**
1573  * Disconnect from a home.
1574  *
1575  * Invalidates host handle.
1576  *
1577  * @param hst
1578  *        The host to disconnect.
1579  */
1580 void
1581 GNUNET_SOCIAL_host_disconnect (struct GNUNET_SOCIAL_Host *hst,
1582                                GNUNET_ContinuationCallback disconnect_cb,
1583                                void *cls)
1584 {
1585   struct GNUNET_SOCIAL_Place *plc = &hst->plc;
1586
1587   plc->disconnect_cb = disconnect_cb;
1588   plc->disconnect_cls = cls;
1589   place_disconnect (plc);
1590 }
1591
1592
1593 /**
1594  * Stop hosting the home.
1595  *
1596  * Sends a _notice_place_closing announcement to the home.
1597  * Invalidates host handle.
1598  *
1599  * @param hst
1600  *        The host leaving.
1601  * @param env
1602  *        Environment for the message or NULL.
1603  *        _nym is set to @e nym regardless whether an @e env is provided.
1604  * @param disconnect_cb
1605  *        Function called after the host left the place
1606  *        and disconnected from the social service.
1607  * @param cls
1608  *        Closure for @a disconnect_cb.
1609  */
1610 void
1611 GNUNET_SOCIAL_host_leave (struct GNUNET_SOCIAL_Host *hst,
1612                           const struct GNUNET_PSYC_Environment *env,
1613                           GNUNET_ContinuationCallback disconnect_cb,
1614                           void *cls)
1615 {
1616   struct GNUNET_MQ_Envelope *envelope;
1617
1618   GNUNET_SOCIAL_host_announce (hst, "_notice_place_closing", env, NULL, NULL,
1619                                GNUNET_SOCIAL_ANNOUNCE_NONE);
1620   hst->plc.disconnect_cb = disconnect_cb;
1621   hst->plc.disconnect_cls = cls;
1622   envelope = GNUNET_MQ_msg_header (GNUNET_MESSAGE_TYPE_SOCIAL_PLACE_LEAVE);
1623   GNUNET_MQ_send (hst->plc.mq,
1624                   envelope);
1625 }
1626
1627
1628 /*** GUEST ***/
1629
1630
1631 static void
1632 guest_connect (struct GNUNET_SOCIAL_Guest *gst);
1633
1634
1635 static void
1636 guest_reconnect (void *cls)
1637 {
1638   guest_connect (cls);
1639 }
1640
1641
1642 /**
1643  * Guest client disconnected from service.
1644  *
1645  * Reconnect after backoff period.
1646  */
1647 static void
1648 guest_disconnected (void *cls, enum GNUNET_MQ_Error error)
1649 {
1650   struct GNUNET_SOCIAL_Guest *gst = cls;
1651   struct GNUNET_SOCIAL_Place *plc = &gst->plc;
1652
1653   LOG (GNUNET_ERROR_TYPE_DEBUG,
1654        "Guest client disconnected (%d), re-connecting\n",
1655        (int) error);
1656   if (NULL != plc->tmit)
1657   {
1658     GNUNET_PSYC_transmit_destroy (plc->tmit);
1659     plc->tmit = NULL;
1660   }
1661   if (NULL != plc->mq)
1662   {
1663     GNUNET_MQ_destroy (plc->mq);
1664     plc->mq = NULL;
1665   }
1666
1667   plc->reconnect_task = GNUNET_SCHEDULER_add_delayed (plc->reconnect_delay,
1668                                                       guest_reconnect,
1669                                                       gst);
1670   plc->reconnect_delay = GNUNET_TIME_STD_BACKOFF (plc->reconnect_delay);
1671 }
1672
1673
1674 static void
1675 guest_connect (struct GNUNET_SOCIAL_Guest *gst)
1676 {
1677   struct GNUNET_SOCIAL_Place *plc = &gst->plc;
1678
1679   struct GNUNET_MQ_MessageHandler handlers[] = {
1680     GNUNET_MQ_hd_fixed_size (guest_enter_ack,
1681                              GNUNET_MESSAGE_TYPE_SOCIAL_GUEST_ENTER_ACK,
1682                              struct GNUNET_PSYC_CountersResultMessage,
1683                              gst),
1684     GNUNET_MQ_hd_fixed_size (place_leave_ack,
1685                              GNUNET_MESSAGE_TYPE_SOCIAL_PLACE_LEAVE_ACK,
1686                              struct GNUNET_MessageHeader,
1687                              plc),
1688     GNUNET_MQ_hd_var_size (guest_enter_decision,
1689                            GNUNET_MESSAGE_TYPE_PSYC_JOIN_DECISION,
1690                            struct GNUNET_PSYC_JoinDecisionMessage,
1691                            gst),
1692     GNUNET_MQ_hd_var_size (place_message,
1693                            GNUNET_MESSAGE_TYPE_PSYC_MESSAGE,
1694                            struct GNUNET_PSYC_MessageHeader,
1695                            plc),
1696     GNUNET_MQ_hd_fixed_size (place_message_ack,
1697                              GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_ACK,
1698                              struct GNUNET_MessageHeader,
1699                              plc),
1700     GNUNET_MQ_hd_var_size (place_history_result,
1701                            GNUNET_MESSAGE_TYPE_PSYC_HISTORY_RESULT,
1702                            struct GNUNET_OperationResultMessage,
1703                            plc),
1704     GNUNET_MQ_hd_var_size (place_state_result,
1705                            GNUNET_MESSAGE_TYPE_PSYC_STATE_RESULT,
1706                            struct GNUNET_OperationResultMessage,
1707                            plc),
1708     GNUNET_MQ_hd_var_size (place_result,
1709                            GNUNET_MESSAGE_TYPE_PSYC_RESULT_CODE,
1710                            struct GNUNET_OperationResultMessage,
1711                            plc),
1712     GNUNET_MQ_handler_end ()
1713   };
1714
1715   plc->mq = GNUNET_CLIENT_connect (plc->cfg, "social",
1716                                    handlers, guest_disconnected, gst);
1717   GNUNET_assert (NULL != plc->mq);
1718   plc->tmit = GNUNET_PSYC_transmit_create (plc->mq);
1719
1720   GNUNET_MQ_send_copy (plc->mq, plc->connect_env);
1721 }
1722
1723
1724 static struct GNUNET_MQ_Envelope *
1725 guest_enter_request_create (const char *app_id,
1726                             const struct GNUNET_CRYPTO_EcdsaPublicKey *ego_pub_key,
1727                             const struct GNUNET_CRYPTO_EddsaPublicKey *place_pub_key,
1728                             const struct GNUNET_PeerIdentity *origin,
1729                             size_t relay_count,
1730                             const struct GNUNET_PeerIdentity *relays,
1731                             const struct GNUNET_PSYC_Message *join_msg)
1732 {
1733   uint16_t app_id_size = strlen (app_id) + 1;
1734   uint16_t join_msg_size = ntohs (join_msg->header.size);
1735   uint16_t relay_size = relay_count * sizeof (*relays);
1736
1737   struct GuestEnterRequest *greq;
1738   struct GNUNET_MQ_Envelope *
1739     env = GNUNET_MQ_msg_extra (greq, app_id_size + relay_size + join_msg_size,
1740                                GNUNET_MESSAGE_TYPE_SOCIAL_GUEST_ENTER);
1741   greq->place_pub_key = *place_pub_key;
1742   greq->ego_pub_key = *ego_pub_key;
1743   greq->origin = *origin;
1744   greq->relay_count = htonl (relay_count);
1745
1746   char *p = (char *) &greq[1];
1747   GNUNET_memcpy (p, app_id, app_id_size);
1748   p += app_id_size;
1749
1750   if (0 < relay_size)
1751   {
1752     GNUNET_memcpy (p, relays, relay_size);
1753     p += relay_size;
1754   }
1755
1756   GNUNET_memcpy (p, join_msg, join_msg_size);
1757   return env;
1758 }
1759
1760
1761 /**
1762  * Request entry to a place as a guest.
1763  *
1764  * @param app
1765  *        Application handle.
1766  * @param ego
1767  *        Identity of the guest.
1768  * @param place_pub_key
1769  *        Public key of the place to enter.
1770  * @param flags
1771  *        Flags for the entry.
1772  * @param origin
1773  *        Peer identity of the origin of the underlying multicast group.
1774  * @param relay_count
1775  *        Number of elements in the @a relays array.
1776  * @param relays
1777  *        Relays for the underlying multicast group.
1778  * @param method_name
1779  *        Method name for the message.
1780  * @param env
1781  *        Environment containing variables for the message, or NULL.
1782  * @param data
1783  *        Payload for the message to give to the enter callback.
1784  * @param data_size
1785  *        Number of bytes in @a data.
1786  * @param slicer
1787  *        Slicer to use for processing incoming requests from guests.
1788  *
1789  * @return NULL on errors, otherwise handle for the guest.
1790  */
1791 struct GNUNET_SOCIAL_Guest *
1792 GNUNET_SOCIAL_guest_enter (const struct GNUNET_SOCIAL_App *app,
1793                            const struct GNUNET_SOCIAL_Ego *ego,
1794                            const struct GNUNET_CRYPTO_EddsaPublicKey *place_pub_key,
1795                            enum GNUNET_PSYC_SlaveJoinFlags flags,
1796                            const struct GNUNET_PeerIdentity *origin,
1797                            uint32_t relay_count,
1798                            const struct GNUNET_PeerIdentity *relays,
1799                            const struct GNUNET_PSYC_Message *entry_msg,
1800                            struct GNUNET_PSYC_Slicer *slicer,
1801                            GNUNET_SOCIAL_GuestEnterCallback local_enter_cb,
1802                            GNUNET_SOCIAL_EntryDecisionCallback entry_dcsn_cb,
1803                            void *cls)
1804 {
1805   struct GNUNET_SOCIAL_Guest *gst = GNUNET_malloc (sizeof (*gst));
1806   struct GNUNET_SOCIAL_Place *plc = &gst->plc;
1807
1808   plc->ego_pub_key = ego->pub_key;
1809   plc->pub_key = *place_pub_key;
1810   plc->cfg = app->cfg;
1811   plc->is_host = GNUNET_NO;
1812   plc->slicer = slicer;
1813
1814   plc->op = GNUNET_OP_create ();
1815
1816   plc->connect_env
1817     = guest_enter_request_create (app->id, &ego->pub_key, &plc->pub_key,
1818                                   origin, relay_count, relays, entry_msg);
1819
1820   gst->enter_cb = local_enter_cb;
1821   gst->entry_dcsn_cb = entry_dcsn_cb;
1822   gst->cb_cls = cls;
1823
1824   guest_connect (gst);
1825   return gst;
1826 }
1827
1828
1829 /**
1830  * Request entry to a place by name as a guest.
1831  *
1832  * @param app
1833  *        Application handle.
1834  * @param ego
1835  *        Identity of the guest.
1836  * @param gns_name
1837  *        GNS name of the place to enter.  Either in the form of
1838  *        'room.friend.gnu', or 'NYMPUBKEY.zkey'.  This latter case refers to
1839  *        the 'PLACE' record of the empty label ("+") in the GNS zone with the
1840  *        nym's public key 'NYMPUBKEY', and can be used to request entry to a
1841  *        pseudonym's place directly.
1842  * @param password
1843  *        Password to decrypt the record, or NULL for cleartext records.
1844  * @param join_msg
1845  *        Entry request message or NULL.
1846  * @param slicer
1847  *        Slicer to use for processing incoming requests from guests.
1848  * @param local_enter_cb
1849  *        Called upon connection established to the social service.
1850  * @param entry_decision_cb
1851  *        Called upon receiving entry decision.
1852  *
1853  * @return NULL on errors, otherwise handle for the guest.
1854  */
1855 struct GNUNET_SOCIAL_Guest *
1856 GNUNET_SOCIAL_guest_enter_by_name (const struct GNUNET_SOCIAL_App *app,
1857                                    const struct GNUNET_SOCIAL_Ego *ego,
1858                                    const char *gns_name,
1859                                    const char *password,
1860                                    const struct GNUNET_PSYC_Message *join_msg,
1861                                    struct GNUNET_PSYC_Slicer *slicer,
1862                                    GNUNET_SOCIAL_GuestEnterCallback local_enter_cb,
1863                                    GNUNET_SOCIAL_EntryDecisionCallback entry_decision_cb,
1864                                    void *cls)
1865 {
1866   struct GNUNET_SOCIAL_Guest *gst = GNUNET_malloc (sizeof (*gst));
1867   struct GNUNET_SOCIAL_Place *plc = &gst->plc;
1868
1869   if (NULL == password)
1870     password = "";
1871
1872   uint16_t app_id_size = strlen (app->id) + 1;
1873   uint16_t gns_name_size = strlen (gns_name) + 1;
1874   uint16_t password_size = strlen (password) + 1;
1875
1876   uint16_t join_msg_size = 0;
1877   if (NULL != join_msg)
1878     join_msg_size = ntohs (join_msg->header.size);
1879
1880   struct GuestEnterByNameRequest *greq;
1881   plc->connect_env
1882     = GNUNET_MQ_msg_extra (greq, app_id_size + gns_name_size
1883                            + password_size + join_msg_size,
1884                            GNUNET_MESSAGE_TYPE_SOCIAL_GUEST_ENTER_BY_NAME);
1885
1886   greq->ego_pub_key = ego->pub_key;
1887
1888   char *p = (char *) &greq[1];
1889   GNUNET_memcpy (p, app->id, app_id_size);
1890   p += app_id_size;
1891   GNUNET_memcpy (p, gns_name, gns_name_size);
1892   p += gns_name_size;
1893   GNUNET_memcpy (p, password, password_size);
1894   p += password_size;
1895   if (NULL != join_msg)
1896     GNUNET_memcpy (p, join_msg, join_msg_size);
1897
1898   plc->ego_pub_key = ego->pub_key;
1899   plc->cfg = app->cfg;
1900   plc->is_host = GNUNET_NO;
1901   plc->slicer = slicer;
1902
1903   plc->op = GNUNET_OP_create ();
1904
1905   gst->enter_cb = local_enter_cb;
1906   gst->entry_dcsn_cb = entry_decision_cb;
1907   gst->cb_cls = cls;
1908
1909   guest_connect (gst);
1910   return gst;
1911 }
1912
1913
1914 struct ReconnectContext
1915 {
1916   struct GNUNET_SOCIAL_Guest *guest;
1917   int *result;
1918   int64_t *max_message_id;
1919   GNUNET_SOCIAL_GuestEnterCallback enter_cb;
1920   void *enter_cls;
1921 };
1922
1923
1924 static void
1925 guest_enter_reconnect_cb (void *cls,
1926                           int result,
1927                           const struct GNUNET_CRYPTO_EddsaPublicKey *place_pub_key,
1928                           uint64_t max_message_id)
1929 {
1930   struct ReconnectContext *reconnect_ctx = cls;
1931
1932   GNUNET_assert (NULL != reconnect_ctx);
1933   reconnect_ctx->result = GNUNET_new (int);
1934   *(reconnect_ctx->result) = result; 
1935   reconnect_ctx->max_message_id = GNUNET_new (int64_t);
1936   *(reconnect_ctx->max_message_id) = max_message_id;
1937 }
1938
1939
1940 static void
1941 guest_entry_dcsn_reconnect_cb (void *cls,
1942                                int is_admitted,
1943                                const struct GNUNET_PSYC_Message *entry_resp)
1944 {
1945   struct ReconnectContext *reconnect_ctx = cls;
1946   struct GNUNET_SOCIAL_Guest *gst = reconnect_ctx->guest;
1947
1948   GNUNET_assert (NULL != reconnect_ctx);
1949   GNUNET_assert (NULL != reconnect_ctx->result);
1950   GNUNET_assert (NULL != reconnect_ctx->max_message_id);
1951   if (GNUNET_YES != is_admitted)
1952   {
1953     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1954                 "Guest was rejected after calling "
1955                 "GNUNET_SOCIAL_guest_enter_reconnect ()\n");
1956   }
1957   else if (NULL != reconnect_ctx->enter_cb)
1958   {
1959     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1960                 "guest reconnected!\n");
1961     reconnect_ctx->enter_cb (reconnect_ctx->enter_cls,
1962                              *(reconnect_ctx->result),
1963                              &gst->plc.pub_key,
1964                              *(reconnect_ctx->max_message_id));
1965   }
1966   GNUNET_free (reconnect_ctx->result);
1967   GNUNET_free (reconnect_ctx->max_message_id);
1968   GNUNET_free (reconnect_ctx);
1969 }
1970
1971
1972 /**
1973  * Reconnect to an already entered place as guest.
1974  *
1975  * @param gconn
1976  *        Guest connection handle.
1977  *        @see GNUNET_SOCIAL_app_connect() & GNUNET_SOCIAL_AppGuestPlaceCallback()
1978  * @param flags
1979  *        Flags for the entry.
1980  * @param slicer
1981  *        Slicer to use for processing incoming requests from guests.
1982  * @param enter_cb
1983  *        Called upon re-entering is complete.
1984  * @param entry_decision_cb
1985  *        Called upon receiving entry decision.
1986  *
1987  * @return NULL on errors, otherwise handle for the guest.
1988  */
1989 struct GNUNET_SOCIAL_Guest *
1990 GNUNET_SOCIAL_guest_enter_reconnect (struct GNUNET_SOCIAL_GuestConnection *gconn,
1991                                      enum GNUNET_PSYC_SlaveJoinFlags flags,
1992                                      struct GNUNET_PSYC_Slicer *slicer,
1993                                      GNUNET_SOCIAL_GuestEnterCallback enter_cb,
1994                                      void *cls)
1995 {
1996   struct GNUNET_SOCIAL_Guest *gst = GNUNET_malloc (sizeof (*gst));
1997   struct GNUNET_SOCIAL_Place *plc = &gst->plc;
1998   struct ReconnectContext *reconnect_ctx;
1999
2000   uint16_t app_id_size = strlen (gconn->app->id) + 1;
2001   struct GuestEnterRequest *greq;
2002   plc->connect_env
2003     = GNUNET_MQ_msg_extra (greq, app_id_size,
2004                            GNUNET_MESSAGE_TYPE_SOCIAL_GUEST_ENTER);
2005   greq->ego_pub_key = gconn->plc_msg.ego_pub_key;
2006   greq->place_pub_key = gconn->plc_msg.place_pub_key;
2007   greq->flags = htonl (flags);
2008
2009   GNUNET_memcpy (&greq[1], gconn->app->id, app_id_size);
2010
2011   plc->cfg = gconn->app->cfg;
2012   plc->is_host = GNUNET_NO;
2013   plc->slicer = slicer;
2014   plc->pub_key = gconn->plc_msg.place_pub_key;
2015   plc->ego_pub_key = gconn->plc_msg.ego_pub_key;
2016
2017   reconnect_ctx = GNUNET_new (struct ReconnectContext);
2018   reconnect_ctx->guest = gst;
2019   reconnect_ctx->enter_cb = enter_cb;
2020   reconnect_ctx->enter_cls = cls;
2021
2022   plc->op = GNUNET_OP_create ();
2023   gst->enter_cb = &guest_enter_reconnect_cb;
2024   gst->entry_dcsn_cb = &guest_entry_dcsn_reconnect_cb;
2025   gst->cb_cls = reconnect_ctx;
2026
2027   guest_connect (gst);
2028   return gst;
2029 }
2030
2031
2032 /**
2033  * Talk to the host of the place.
2034  *
2035  * @param place
2036  *        Place where we want to talk to the host.
2037  * @param method_name
2038  *        Method to invoke on the host.
2039  * @param env
2040  *        Environment containing variables for the message, or NULL.
2041  * @param notify_data
2042  *        Function to use to get the payload for the method.
2043  * @param notify_data_cls
2044  *        Closure for @a notify_data.
2045  * @param flags
2046  *        Flags for the message being sent.
2047  *
2048  * @return NULL if we are already trying to talk to the host,
2049  *         otherwise handle to cancel the request.
2050  */
2051 struct GNUNET_SOCIAL_TalkRequest *
2052 GNUNET_SOCIAL_guest_talk (struct GNUNET_SOCIAL_Guest *gst,
2053                           const char *method_name,
2054                           const struct GNUNET_PSYC_Environment *env,
2055                           GNUNET_PSYC_TransmitNotifyData notify_data,
2056                           void *notify_data_cls,
2057                           enum GNUNET_SOCIAL_TalkFlags flags)
2058 {
2059   struct GNUNET_SOCIAL_Place *plc = &gst->plc;
2060   GNUNET_assert (NULL != plc->tmit);
2061
2062   if (GNUNET_OK ==
2063       GNUNET_PSYC_transmit_message (plc->tmit, method_name, env,
2064                                     NULL, notify_data, notify_data_cls, flags))
2065     return (struct GNUNET_SOCIAL_TalkRequest *) plc->tmit;
2066   else
2067     return NULL;
2068 }
2069
2070
2071 /**
2072  * Resume talking to the host of the place.
2073  *
2074  * @param tr
2075  *        Talk request to resume.
2076  */
2077 void
2078 GNUNET_SOCIAL_guest_talk_resume (struct GNUNET_SOCIAL_TalkRequest *tr)
2079 {
2080   GNUNET_PSYC_transmit_resume ((struct GNUNET_PSYC_TransmitHandle *) tr);
2081 }
2082
2083
2084 /**
2085  * Cancel talking to the host of the place.
2086  *
2087  * @param tr
2088  *        Talk request to cancel.
2089  */
2090 void
2091 GNUNET_SOCIAL_guest_talk_cancel (struct GNUNET_SOCIAL_TalkRequest *tr)
2092 {
2093   GNUNET_PSYC_transmit_cancel ( (struct GNUNET_PSYC_TransmitHandle *) tr);
2094 }
2095
2096
2097 /**
2098  * Disconnect from a place.
2099  *
2100  * Invalidates guest handle.
2101  *
2102  * @param gst
2103  *        The guest to disconnect.
2104  */
2105 void
2106 GNUNET_SOCIAL_guest_disconnect (struct GNUNET_SOCIAL_Guest *gst,
2107                                 GNUNET_ContinuationCallback disconnect_cb,
2108                                 void *cls)
2109 {
2110   struct GNUNET_SOCIAL_Place *plc = &gst->plc;
2111
2112   plc->disconnect_cb = disconnect_cb;
2113   plc->disconnect_cls = cls;
2114   place_disconnect (plc);
2115 }
2116
2117
2118 /**
2119  * Leave a place temporarily or permanently.
2120  *
2121  * Notifies the owner of the place about leaving, and destroys the place handle.
2122  *
2123  * @param place
2124  *        Place to leave.
2125  * @param keep_active
2126  *        Keep place active after last application disconnected.
2127  *        #GNUNET_YES or #GNUNET_NO
2128  * @param env
2129  *        Optional environment for the leave message if @a keep_active
2130  *        is #GNUNET_NO.  NULL if not needed.
2131  * @param leave_cb
2132  *        Called upon disconnecting from the social service.
2133  */
2134 void
2135 GNUNET_SOCIAL_guest_leave (struct GNUNET_SOCIAL_Guest *gst,
2136                            struct GNUNET_PSYC_Environment *env,
2137                            GNUNET_ContinuationCallback disconnect_cb,
2138                            void *cls)
2139 {
2140   struct GNUNET_MQ_Envelope *envelope;
2141
2142   GNUNET_SOCIAL_guest_talk (gst, "_notice_place_leave", env, NULL, NULL,
2143                             GNUNET_SOCIAL_TALK_NONE);
2144   gst->plc.disconnect_cb = disconnect_cb;
2145   gst->plc.disconnect_cls = cls;
2146   envelope = GNUNET_MQ_msg_header (GNUNET_MESSAGE_TYPE_SOCIAL_PLACE_LEAVE);
2147   GNUNET_MQ_send (gst->plc.mq,
2148                   envelope);
2149 }
2150
2151
2152 /**
2153  * Obtain handle for a place entered as guest.
2154  *
2155  * The returned handle can be used to access the place API.
2156  *
2157  * @param guest  Handle for the guest.
2158  *
2159  * @return Handle for the place, valid as long as @a guest is valid.
2160  */
2161 struct GNUNET_SOCIAL_Place *
2162 GNUNET_SOCIAL_guest_get_place (struct GNUNET_SOCIAL_Guest *gst)
2163 {
2164   return &gst->plc;
2165 }
2166
2167
2168 /**
2169  * Obtain the public key of a place.
2170  *
2171  * @param plc
2172  *        Place.
2173  *
2174  * @return Public key of the place.
2175  */
2176 const struct GNUNET_CRYPTO_EddsaPublicKey *
2177 GNUNET_SOCIAL_place_get_pub_key (const struct GNUNET_SOCIAL_Place *plc)
2178 {
2179   return &plc->pub_key;
2180 }
2181
2182
2183 /**
2184  * Set message processing @a flags for a @a method_prefix.
2185  *
2186  * @param plc
2187  *        Place.
2188  * @param method_prefix
2189  *        Method prefix @a flags apply to.
2190  * @param flags
2191  *        The flags that apply to a matching @a method_prefix.
2192  */
2193 void
2194 GNUNET_SOCIAL_place_msg_proc_set (struct GNUNET_SOCIAL_Place *plc,
2195                                   const char *method_prefix,
2196                                   enum GNUNET_SOCIAL_MsgProcFlags flags)
2197 {
2198   GNUNET_assert (NULL != method_prefix);
2199   struct MsgProcRequest *mpreq;
2200   uint16_t method_size = strnlen (method_prefix,
2201                                   GNUNET_MAX_MESSAGE_SIZE
2202                                   - sizeof (*mpreq)) + 1;
2203   GNUNET_assert ('\0' == method_prefix[method_size - 1]);
2204
2205   struct GNUNET_MQ_Envelope *
2206     env = GNUNET_MQ_msg_extra (mpreq, method_size,
2207                                GNUNET_MESSAGE_TYPE_SOCIAL_MSG_PROC_SET);
2208   mpreq->flags = htonl (flags);
2209   GNUNET_memcpy (&mpreq[1], method_prefix, method_size);
2210
2211   GNUNET_MQ_send (plc->mq, env);
2212 }
2213
2214
2215 /**
2216  * Clear all message processing flags previously set for this place.
2217  */
2218 void
2219 GNUNET_SOCIAL_place_msg_proc_clear (struct GNUNET_SOCIAL_Place *plc)
2220 {
2221   struct GNUNET_MessageHeader *req;
2222   struct GNUNET_MQ_Envelope *
2223     env = GNUNET_MQ_msg (req, GNUNET_MESSAGE_TYPE_SOCIAL_MSG_PROC_CLEAR);
2224
2225   GNUNET_MQ_send (plc->mq, env);
2226 }
2227
2228
2229 static struct GNUNET_SOCIAL_HistoryRequest *
2230 place_history_replay (struct GNUNET_SOCIAL_Place *plc,
2231                       uint64_t start_message_id,
2232                       uint64_t end_message_id,
2233                       uint64_t message_limit,
2234                       const char *method_prefix,
2235                       uint32_t flags,
2236                       struct GNUNET_PSYC_Slicer *slicer,
2237                       GNUNET_ResultCallback result_cb,
2238                       void *cls)
2239 {
2240   struct GNUNET_PSYC_HistoryRequestMessage *req;
2241   struct GNUNET_SOCIAL_HistoryRequest *hist = GNUNET_malloc (sizeof (*hist));
2242   hist->plc = plc;
2243   hist->slicer = slicer;
2244   hist->result_cb = result_cb;
2245   hist->cls = cls;
2246   hist->op_id = GNUNET_OP_add (plc->op, op_recv_history_result, hist, NULL);
2247
2248   GNUNET_assert (NULL != method_prefix);
2249   uint16_t method_size = strnlen (method_prefix,
2250                                   GNUNET_MAX_MESSAGE_SIZE
2251                                   - sizeof (*req)) + 1;
2252   GNUNET_assert ('\0' == method_prefix[method_size - 1]);
2253
2254   struct GNUNET_MQ_Envelope *
2255     env = GNUNET_MQ_msg_extra (req, method_size,
2256                                GNUNET_MESSAGE_TYPE_PSYC_HISTORY_REPLAY);
2257   req->start_message_id = GNUNET_htonll (start_message_id);
2258   req->end_message_id = GNUNET_htonll (end_message_id);
2259   req->message_limit = GNUNET_htonll (message_limit);
2260   req->flags = htonl (flags);
2261   req->op_id = GNUNET_htonll (hist->op_id);
2262   GNUNET_memcpy (&req[1], method_prefix, method_size);
2263
2264   GNUNET_MQ_send (plc->mq, env);
2265   return hist;
2266 }
2267
2268
2269 /**
2270  * Learn about the history of a place.
2271  *
2272  * Messages are returned through the @a slicer function
2273  * and have the #GNUNET_PSYC_MESSAGE_HISTORIC flag set.
2274  *
2275  * @param place
2276  *        Place we want to learn more about.
2277  * @param start_message_id
2278  *        First historic message we are interested in.
2279  * @param end_message_id
2280  *        Last historic message we are interested in (inclusive).
2281  * @param method_prefix
2282  *        Only retrieve messages with this method prefix.
2283  * @param flags
2284  *        OR'ed GNUNET_PSYC_HistoryReplayFlags
2285  * @param slicer
2286  *        Slicer to use for retrieved messages.
2287  *        Can be the same as the slicer of the place.
2288  * @param result_cb
2289  *        Function called after all messages retrieved.
2290  *        NULL if not needed.
2291  * @param cls Closure for @a result_cb.
2292  */
2293 struct GNUNET_SOCIAL_HistoryRequest *
2294 GNUNET_SOCIAL_place_history_replay (struct GNUNET_SOCIAL_Place *plc,
2295                                     uint64_t start_message_id,
2296                                     uint64_t end_message_id,
2297                                     const char *method_prefix,
2298                                     uint32_t flags,
2299                                     struct GNUNET_PSYC_Slicer *slicer,
2300                                     GNUNET_ResultCallback result_cb,
2301                                     void *cls)
2302 {
2303   return place_history_replay (plc, start_message_id, end_message_id, 0,
2304                                method_prefix, flags, slicer, result_cb, cls);
2305 }
2306
2307
2308 /**
2309  * Learn about the history of a place.
2310  *
2311  * Sends messages through the slicer function of the place where
2312  * start_message_id <= message_id <= end_message_id.
2313  * The messages will have the #GNUNET_PSYC_MESSAGE_HISTORIC flag set.
2314  *
2315  * To get the latest message, use 0 for both the start and end message ID.
2316  *
2317  * @param place
2318  *        Place we want to learn more about.
2319  * @param message_limit
2320  *        Maximum number of historic messages we are interested in.
2321  * @param method_prefix
2322  *        Only retrieve messages with this method prefix.
2323  * @param flags
2324  *        OR'ed GNUNET_PSYC_HistoryReplayFlags
2325  * @param result_cb
2326  *        Function called after all messages retrieved.
2327  *        NULL if not needed.
2328  * @param cls Closure for @a result_cb.
2329  */
2330 struct GNUNET_SOCIAL_HistoryRequest *
2331 GNUNET_SOCIAL_place_history_replay_latest (struct GNUNET_SOCIAL_Place *plc,
2332                                            uint64_t message_limit,
2333                                            const char *method_prefix,
2334                                            uint32_t flags,
2335                                            struct GNUNET_PSYC_Slicer *slicer,
2336                                            GNUNET_ResultCallback result_cb,
2337                                            void *cls)
2338 {
2339   return place_history_replay (plc, 0, 0, message_limit, method_prefix, flags,
2340                                slicer, result_cb, cls);
2341 }
2342
2343
2344 /**
2345  * Cancel learning about the history of a place.
2346  *
2347  * @param hist
2348  *        History lesson to cancel.
2349  */
2350 void
2351 GNUNET_SOCIAL_place_history_replay_cancel (struct GNUNET_SOCIAL_HistoryRequest *hist)
2352 {
2353   GNUNET_OP_remove (hist->plc->op, hist->op_id);
2354   GNUNET_free (hist);
2355 }
2356
2357
2358 /**
2359  * Request matching state variables.
2360  */
2361 static struct GNUNET_SOCIAL_LookHandle *
2362 place_state_get (struct GNUNET_SOCIAL_Place *plc,
2363                  uint16_t type, const char *name,
2364                  GNUNET_PSYC_StateVarCallback var_cb,
2365                  GNUNET_ResultCallback result_cb, void *cls)
2366 {
2367   struct GNUNET_PSYC_StateRequestMessage *req;
2368   struct GNUNET_SOCIAL_LookHandle *look = GNUNET_malloc (sizeof (*look));
2369   look->plc = plc;
2370   look->var_cb = var_cb;
2371   look->result_cb = result_cb;
2372   look->cls = cls;
2373   look->op_id = GNUNET_OP_add (plc->op, &op_recv_state_result, look, NULL);
2374
2375   GNUNET_assert (NULL != name);
2376   size_t name_size = strnlen (name, GNUNET_MAX_MESSAGE_SIZE
2377                               - sizeof (*req)) + 1;
2378   struct GNUNET_MQ_Envelope *
2379     env = GNUNET_MQ_msg_extra (req, name_size, type);
2380   req->op_id = GNUNET_htonll (look->op_id);
2381   GNUNET_memcpy (&req[1], name, name_size);
2382
2383   GNUNET_MQ_send (plc->mq, env);
2384   return look;
2385 }
2386
2387
2388 /**
2389  * Look at a particular object in the place.
2390  *
2391  * The best matching object is returned (its name might be less specific than
2392  * what was requested).
2393  *
2394  * @param place
2395  *        The place where to look.
2396  * @param full_name
2397  *        Full name of the object.
2398  * @param value_size
2399  *        Set to the size of the returned value.
2400  *
2401  * @return NULL if there is no such object at this place.
2402  */
2403 struct GNUNET_SOCIAL_LookHandle *
2404 GNUNET_SOCIAL_place_look_at (struct GNUNET_SOCIAL_Place *plc,
2405                              const char *full_name,
2406                              GNUNET_PSYC_StateVarCallback var_cb,
2407                              GNUNET_ResultCallback result_cb,
2408                              void *cls)
2409 {
2410   return place_state_get (plc, GNUNET_MESSAGE_TYPE_PSYC_STATE_GET,
2411                           full_name, var_cb, result_cb, cls);
2412 }
2413
2414
2415 /**
2416  * Look for objects in the place with a matching name prefix.
2417  *
2418  * @param place
2419  *        The place where to look.
2420  * @param name_prefix
2421  *        Look at objects with names beginning with this value.
2422  * @param var_cb
2423  *        Function to call for each object found.
2424  * @param cls
2425  *        Closure for callback function.
2426  *
2427  * @return Handle that can be used to stop looking at objects.
2428  */
2429 struct GNUNET_SOCIAL_LookHandle *
2430 GNUNET_SOCIAL_place_look_for (struct GNUNET_SOCIAL_Place *plc,
2431                               const char *name_prefix,
2432                               GNUNET_PSYC_StateVarCallback var_cb,
2433                               GNUNET_ResultCallback result_cb,
2434                               void *cls)
2435 {
2436   return place_state_get (plc, GNUNET_MESSAGE_TYPE_PSYC_STATE_GET_PREFIX,
2437                           name_prefix, var_cb, result_cb, cls);
2438 }
2439
2440
2441 /**
2442  * Cancel a state request operation.
2443  *
2444  * @param sr
2445  *        Handle for the operation to cancel.
2446  */
2447 void
2448 GNUNET_SOCIAL_place_look_cancel (struct GNUNET_SOCIAL_LookHandle *look)
2449 {
2450   GNUNET_OP_remove (look->plc->op, look->op_id);
2451   GNUNET_free (look);
2452 }
2453
2454
2455 static void
2456 op_recv_zone_add_place_result (void *cls, int64_t result,
2457                                const void *err_msg, uint16_t err_msg_size)
2458 {
2459   LOG (GNUNET_ERROR_TYPE_DEBUG,
2460        "Received zone add place result: %" PRId64 ".\n", result);
2461
2462   struct ZoneAddPlaceHandle *add_plc = cls;
2463   if (NULL != add_plc->result_cb)
2464     add_plc->result_cb (add_plc->result_cls, result, err_msg, err_msg_size);
2465
2466   GNUNET_free (add_plc);
2467 }
2468
2469
2470 /**
2471  * Advertise @e place in the GNS zone of @e ego.
2472  *
2473  * @param app
2474  *        Application handle.
2475  * @param ego
2476  *        Ego.
2477  * @param place_pub_key
2478  *        Public key of place to add.
2479  * @param name
2480  *        The name for the PLACE record to put in the zone.
2481  * @param password
2482  *        Password used to encrypt the record or NULL to keep it cleartext.
2483  * @param relay_count
2484  *        Number of elements in the @a relays array.
2485  * @param relays
2486  *        List of relays to put in the PLACE record to advertise
2487  *        as entry points to the place in addition to the origin.
2488  * @param expiration_time
2489  *        Expiration time of the record, use 0 to remove the record.
2490  * @param result_cb
2491  *        Function called with the result of the operation.
2492  * @param result_cls
2493  *        Closure for @a result_cb
2494  *
2495  * @return #GNUNET_OK if the request was sent,
2496  *         #GNUNET_SYSERR on error, e.g. the name/password is too long.
2497  */
2498 int
2499 GNUNET_SOCIAL_zone_add_place (const struct GNUNET_SOCIAL_App *app,
2500                               const struct GNUNET_SOCIAL_Ego *ego,
2501                               const char *name,
2502                               const char *password,
2503                               const struct GNUNET_CRYPTO_EddsaPublicKey *place_pub_key,
2504                               const struct GNUNET_PeerIdentity *origin,
2505                               uint32_t relay_count,
2506                               const struct GNUNET_PeerIdentity *relays,
2507                               struct GNUNET_TIME_Absolute expiration_time,
2508                               GNUNET_ResultCallback result_cb,
2509                               void *result_cls)
2510 {
2511   struct ZoneAddPlaceRequest *preq;
2512   size_t name_size = strlen (name) + 1;
2513   size_t password_size = strlen (password) + 1;
2514   size_t relay_size = relay_count * sizeof (*relays);
2515   size_t payload_size = name_size + password_size + relay_size;
2516
2517   if (GNUNET_MAX_MESSAGE_SIZE < sizeof (*preq) + payload_size)
2518     return GNUNET_SYSERR;
2519
2520   struct GNUNET_MQ_Envelope *
2521     env = GNUNET_MQ_msg_extra (preq, payload_size,
2522                                GNUNET_MESSAGE_TYPE_SOCIAL_ZONE_ADD_PLACE);
2523   preq->expiration_time = GNUNET_htonll (expiration_time.abs_value_us);
2524   preq->ego_pub_key = ego->pub_key;
2525   preq->place_pub_key = *place_pub_key;
2526   preq->origin = *origin;
2527   preq->relay_count = htonl (relay_count);
2528
2529   char *p = (char *) &preq[1];
2530   GNUNET_memcpy (p, name, name_size);
2531   p += name_size;
2532   GNUNET_memcpy (p, password, password_size);
2533   p += password_size;
2534   GNUNET_memcpy (p, relays, relay_size);
2535
2536   struct ZoneAddPlaceHandle * add_plc = GNUNET_malloc (sizeof (*add_plc));
2537   add_plc->result_cb = result_cb;
2538   add_plc->result_cls = result_cls;
2539
2540   preq->op_id = GNUNET_htonll (GNUNET_OP_add (app->op,
2541                                               op_recv_zone_add_place_result,
2542                                               add_plc, NULL));
2543
2544   GNUNET_MQ_send (app->mq, env);
2545   return GNUNET_OK;
2546 }
2547
2548
2549 static void
2550 op_recv_zone_add_nym_result (void *cls, int64_t result,
2551                              const void *err_msg, uint16_t err_msg_size)
2552 {
2553   LOG (GNUNET_ERROR_TYPE_DEBUG,
2554        "Received zone add nym result: %" PRId64 ".\n", result);
2555
2556   struct ZoneAddNymHandle *add_nym = cls;
2557   if (NULL != add_nym->result_cb)
2558     add_nym->result_cb (add_nym->result_cls, result, err_msg, err_msg_size);
2559
2560   GNUNET_free (add_nym);
2561 }
2562
2563
2564 /**
2565  * Add nym to the GNS zone of @e ego.
2566  *
2567  * @param cfg
2568  *        Configuration.
2569  * @param ego
2570  *        Ego.
2571  * @param name
2572  *        The name for the PKEY record to put in the zone.
2573  * @param nym_pub_key
2574  *        Public key of nym to add.
2575  * @param expiration_time
2576  *        Expiration time of the record, use 0 to remove the record.
2577  * @param result_cb
2578  *        Function called with the result of the operation.
2579  * @param result_cls
2580  *        Closure for @a result_cb
2581  *
2582  * @return #GNUNET_OK if the request was sent,
2583  *         #GNUNET_SYSERR on error, e.g. the name is too long.
2584  */
2585 int
2586 GNUNET_SOCIAL_zone_add_nym (const struct GNUNET_SOCIAL_App *app,
2587                             const struct GNUNET_SOCIAL_Ego *ego,
2588                             const char *name,
2589                             const struct GNUNET_CRYPTO_EcdsaPublicKey *nym_pub_key,
2590                             struct GNUNET_TIME_Absolute expiration_time,
2591                             GNUNET_ResultCallback result_cb,
2592                             void *result_cls)
2593 {
2594   struct ZoneAddNymRequest *nreq;
2595
2596   size_t name_size = strlen (name) + 1;
2597   if (GNUNET_MAX_MESSAGE_SIZE < sizeof (*nreq) + name_size)
2598     return GNUNET_SYSERR;
2599
2600   struct GNUNET_MQ_Envelope *
2601     env = GNUNET_MQ_msg_extra (nreq, name_size,
2602                                GNUNET_MESSAGE_TYPE_SOCIAL_ZONE_ADD_NYM);
2603   nreq->expiration_time = GNUNET_htonll (expiration_time.abs_value_us);
2604   nreq->ego_pub_key = ego->pub_key;
2605   nreq->nym_pub_key = *nym_pub_key;
2606   GNUNET_memcpy (&nreq[1], name, name_size);
2607
2608   struct ZoneAddNymHandle *add_nym = GNUNET_malloc (sizeof (*add_nym));
2609   add_nym->result_cb = result_cb;
2610   add_nym->result_cls = result_cls;
2611
2612   nreq->op_id = GNUNET_htonll (GNUNET_OP_add (app->op,
2613                                               op_recv_zone_add_nym_result,
2614                                               add_nym, NULL));
2615
2616   GNUNET_MQ_send (app->mq, env);
2617   return GNUNET_OK;
2618 }
2619
2620
2621 /*** APP ***/
2622
2623
2624 static void
2625 app_connect (struct GNUNET_SOCIAL_App *app);
2626
2627
2628 static void
2629 app_reconnect (void *cls)
2630 {
2631   app_connect (cls);
2632 }
2633
2634
2635 /**
2636  * App client disconnected from service.
2637  *
2638  * Reconnect after backoff period.
2639  */
2640 static void
2641 app_disconnected (void *cls, enum GNUNET_MQ_Error error)
2642 {
2643   struct GNUNET_SOCIAL_App *app = cls;
2644
2645   LOG (GNUNET_ERROR_TYPE_DEBUG,
2646        "App client disconnected (%d), re-connecting\n",
2647        (int) error);
2648   if (NULL != app->mq)
2649   {
2650     GNUNET_MQ_destroy (app->mq);
2651     app->mq = NULL;
2652   }
2653
2654   app->reconnect_task = GNUNET_SCHEDULER_add_delayed (app->reconnect_delay,
2655                                                       app_reconnect,
2656                                                       app);
2657   app->reconnect_delay = GNUNET_TIME_STD_BACKOFF (app->reconnect_delay);
2658 }
2659
2660
2661 static void
2662 app_connect (struct GNUNET_SOCIAL_App *app)
2663 {
2664   struct GNUNET_MQ_MessageHandler handlers[] = {
2665     GNUNET_MQ_hd_var_size (app_ego,
2666                            GNUNET_MESSAGE_TYPE_SOCIAL_APP_EGO,
2667                            struct AppEgoMessage,
2668                            app),
2669     GNUNET_MQ_hd_fixed_size (app_ego_end,
2670                              GNUNET_MESSAGE_TYPE_SOCIAL_APP_EGO_END,
2671                              struct GNUNET_MessageHeader,
2672                              app),
2673     GNUNET_MQ_hd_var_size (app_place,
2674                            GNUNET_MESSAGE_TYPE_SOCIAL_APP_PLACE,
2675                            struct AppPlaceMessage,
2676                            app),
2677     GNUNET_MQ_hd_fixed_size (app_place_end,
2678                              GNUNET_MESSAGE_TYPE_SOCIAL_APP_PLACE_END,
2679                              struct GNUNET_MessageHeader,
2680                              app),
2681     GNUNET_MQ_hd_var_size (app_result,
2682                            GNUNET_MESSAGE_TYPE_PSYC_RESULT_CODE,
2683                            struct GNUNET_OperationResultMessage,
2684                            app),
2685     GNUNET_MQ_handler_end ()
2686   };
2687
2688   app->mq = GNUNET_CLIENT_connect (app->cfg, "social",
2689                                    handlers, app_disconnected, app);
2690   GNUNET_assert (NULL != app->mq);
2691   GNUNET_MQ_send_copy (app->mq, app->connect_env);
2692 }
2693
2694
2695 /**
2696  * Connect application to the social service.
2697  *
2698  * The @host_place_cb and @guest_place_cb functions are
2699  * initially called for each entered places,
2700  * then later each time a new place is entered with the current application ID.
2701  *
2702  * @param cfg
2703  *        Configuration.
2704  * @param id
2705  *        Application ID.
2706  * @param ego_cb
2707  *        Function to notify about an available ego.
2708  * @param host_cb
2709  *        Function to notify about a place entered as host.
2710  * @param guest_cb
2711  *        Function to notify about a place entered as guest.
2712  * @param cls
2713  *        Closure for the callbacks.
2714  *
2715  * @return Handle that can be used to stop listening.
2716  */
2717 struct GNUNET_SOCIAL_App *
2718 GNUNET_SOCIAL_app_connect (const struct GNUNET_CONFIGURATION_Handle *cfg,
2719                            const char *id,
2720                            GNUNET_SOCIAL_AppEgoCallback ego_cb,
2721                            GNUNET_SOCIAL_AppHostPlaceCallback host_cb,
2722                            GNUNET_SOCIAL_AppGuestPlaceCallback guest_cb,
2723                            GNUNET_SOCIAL_AppConnectedCallback connected_cb,
2724                            void *cls)
2725 {
2726   uint16_t app_id_size = strnlen (id, GNUNET_SOCIAL_APP_MAX_ID_SIZE);
2727   if (GNUNET_SOCIAL_APP_MAX_ID_SIZE == app_id_size)
2728     return NULL;
2729   app_id_size++;
2730
2731   struct GNUNET_SOCIAL_App *app = GNUNET_malloc (sizeof *app);
2732   app->cfg = cfg;
2733   app->ego_cb = ego_cb;
2734   app->host_cb = host_cb;
2735   app->guest_cb = guest_cb;
2736   app->connected_cb = connected_cb;
2737   app->cb_cls = cls;
2738   app->egos = GNUNET_CONTAINER_multihashmap_create (1, GNUNET_NO);
2739   app->op = GNUNET_OP_create ();
2740   app->id = GNUNET_malloc (app_id_size);
2741   GNUNET_memcpy (app->id, id, app_id_size);
2742
2743   struct AppConnectRequest *creq;
2744   app->connect_env = GNUNET_MQ_msg_extra (creq, app_id_size,
2745                                           GNUNET_MESSAGE_TYPE_SOCIAL_APP_CONNECT);
2746   GNUNET_memcpy (&creq[1], app->id, app_id_size);
2747
2748   app_connect (app);
2749   return app;
2750 }
2751
2752
2753 static void
2754 app_cleanup (struct GNUNET_SOCIAL_App *app)
2755 {
2756   if (NULL != app->mq)
2757   {
2758     GNUNET_MQ_destroy (app->mq);
2759     app->mq = NULL;
2760   }
2761   if (NULL != app->disconnect_cb)
2762   {
2763     app->disconnect_cb (app->disconnect_cls);
2764     app->disconnect_cb = NULL;
2765   }
2766   GNUNET_free (app);
2767 }
2768
2769 /**
2770  * Disconnect application.
2771  *
2772  * @param app
2773  *        Application handle.
2774  * @param disconnect_cb
2775  *        Disconnect callback.
2776  * @param disconnect_cls
2777  *        Disconnect closure.
2778  */
2779 void
2780 GNUNET_SOCIAL_app_disconnect (struct GNUNET_SOCIAL_App *app,
2781                               GNUNET_ContinuationCallback disconnect_cb,
2782                               void *disconnect_cls)
2783 {
2784   app->disconnect_cb = disconnect_cb;
2785   app->disconnect_cls = disconnect_cls;
2786
2787   if (NULL != app->mq)
2788   {
2789     struct GNUNET_MQ_Envelope *env = GNUNET_MQ_get_last_envelope (app->mq);
2790     if (NULL != env)
2791     {
2792       GNUNET_MQ_notify_sent (env, (GNUNET_SCHEDULER_TaskCallback) app_cleanup, app);
2793     }
2794     else
2795     {
2796       app_cleanup (app);
2797     }
2798   }
2799   else
2800   {
2801     app_cleanup (app);
2802   }
2803 }
2804
2805
2806 /**
2807  * Detach application from a place.
2808  *
2809  * Removes the place from the entered places list for this application.
2810  * Note: this does not disconnect from the place.
2811  *
2812  * @see GNUNET_SOCIAL_host_disconnect() and GNUNET_SOCIAL_guest_disconnect()
2813  *
2814  * @param app
2815  *        Application.
2816  * @param plc
2817  *        Place.
2818  */
2819 void
2820 GNUNET_SOCIAL_app_detach (struct GNUNET_SOCIAL_App *app,
2821                           struct GNUNET_SOCIAL_Place *plc)
2822 {
2823   struct AppDetachRequest *dreq;
2824   struct GNUNET_MQ_Envelope *
2825     env = GNUNET_MQ_msg (dreq, GNUNET_MESSAGE_TYPE_SOCIAL_APP_DETACH);
2826   dreq->place_pub_key = plc->pub_key;
2827   dreq->ego_pub_key = plc->ego_pub_key;
2828
2829   GNUNET_MQ_send (app->mq, env);
2830 }
2831
2832
2833 /* end of social_api.c */