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