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