social: fix various warnings
[oweals/gnunet.git] / src / social / gnunet-service-social.c
1 /*
2  * This file is part of GNUnet
3  * Copyright (C) 2013 GNUnet e.V.
4  *
5  * GNUnet is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published
7  * by the Free Software Foundation; either version 3, or (at your
8  * option) any later version.
9  *
10  * GNUnet is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with GNUnet; see the file COPYING.  If not, write to the
17  * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18  * Boston, MA 02110-1301, USA.
19  */
20
21 /**
22  * @file social/gnunet-service-social.c
23  * @brief Social service
24  * @author Gabor X Toth
25  */
26
27 #include <inttypes.h>
28 #include <strings.h>
29
30 #include "platform.h"
31 #include "gnunet_util_lib.h"
32 #include "gnunet_constants.h"
33 #include "gnunet_protocols.h"
34 #include "gnunet_core_service.h"
35 #include "gnunet_identity_service.h"
36 #include "gnunet_namestore_service.h"
37 #include "gnunet_gns_service.h"
38 #include "gnunet_statistics_service.h"
39 #include "gnunet_psyc_service.h"
40 #include "gnunet_psyc_util_lib.h"
41 #include "gnunet_social_service.h"
42 #include "social.h"
43
44
45 /**
46  * Handle to our current configuration.
47  */
48 static const struct GNUNET_CONFIGURATION_Handle *cfg;
49
50 /* Handles to other services */
51 static struct GNUNET_CORE_Handle *core;
52 static struct GNUNET_IDENTITY_Handle *id;
53 static struct GNUNET_GNS_Handle *gns;
54 static struct GNUNET_NAMESTORE_Handle *namestore;
55 static struct GNUNET_STATISTICS_Handle *stats;
56
57 /**
58  * ID of this peer.
59  */
60 static struct GNUNET_PeerIdentity this_peer;
61
62 /**
63  * Notification context, simplifies client broadcasts.
64  */
65 static struct GNUNET_SERVER_NotificationContext *nc;
66
67 /**
68  * All connected hosts.
69  * H(place_pub_key) -> struct Host
70  */
71 static struct GNUNET_CONTAINER_MultiHashMap *hosts;
72
73 /**
74  * All connected guests.
75  * H(place_pub_key) -> struct Guest
76  */
77 static struct GNUNET_CONTAINER_MultiHashMap *guests;
78
79 /**
80  * Connected guests per place.
81  * H(place_pub_key) -> ego_pub_key -> struct Guest
82  */
83 static struct GNUNET_CONTAINER_MultiHashMap *place_guests;
84
85 /**
86  * Places entered as host or guest.
87  * H(place_pub_key) -> struct HostEnterRequest OR struct GuestEnterRequest
88  */
89 static struct GNUNET_CONTAINER_MultiHashMap *places;
90
91 /**
92  * Places entered per application.
93  * H(app_id) -> H(place_pub_key) -> NULL
94  */
95 static struct GNUNET_CONTAINER_MultiHashMap *apps_places;
96
97 /**
98  * Application subscriptions per place.
99  * H(place_pub_key) -> H(app_id)
100  */
101 static struct GNUNET_CONTAINER_MultiHashMap *places_apps;
102
103 /**
104  * Connected applications.
105  * H(app_id) -> struct Application
106  */
107 static struct GNUNET_CONTAINER_MultiHashMap *apps;
108
109 /**
110  * All egos.
111  * H(ego_pub_key) -> struct Ego
112  */
113 static struct GNUNET_CONTAINER_MultiHashMap *egos;
114
115 /**
116  * Directory for storing social data.
117  * Default: $GNUNET_DATA_HOME/social
118  */
119 static char *dir_social;
120
121 /**
122  * Directory for storing place data.
123  * $dir_social/places
124  */
125 static char *dir_places;
126
127 /**
128  * Directory for storing app data.
129  * $dir_social/apps
130  */
131 static char *dir_apps;
132
133
134 /**
135  * Message fragment transmission queue.
136  */
137 struct FragmentTransmitQueue
138 {
139   struct FragmentTransmitQueue *prev;
140   struct FragmentTransmitQueue *next;
141
142   struct GNUNET_SERVER_Client *client;
143
144   /**
145    * Pointer to the next message part inside the data after this struct.
146    */
147   struct GNUNET_MessageHeader *next_part;
148
149   /**
150    * Size of message.
151    */
152   uint16_t size;
153
154   /**
155    * @see enum GNUNET_PSYC_MessageState
156    */
157   uint8_t state;
158
159   /* Followed by one or more message parts. */
160 };
161
162
163 /**
164  * Message transmission queue.
165  */
166 struct MessageTransmitQueue
167 {
168   struct MessageTransmitQueue *prev;
169   struct MessageTransmitQueue *next;
170
171   struct FragmentTransmitQueue *frags_head;
172   struct FragmentTransmitQueue *frags_tail;
173
174   struct GNUNET_SERVER_Client *client;
175 };
176
177 /**
178  * List of connected clients.
179  */
180 struct ClientListItem
181 {
182   struct ClientListItem *prev;
183   struct ClientListItem *next;
184
185   struct GNUNET_SERVER_Client *client;
186 };
187
188
189 /**
190  * Common part of the client context for both a host and guest.
191  */
192 struct Place
193 {
194   struct ClientListItem *clients_head;
195   struct ClientListItem *clients_tail;
196
197   struct MessageTransmitQueue *tmit_msgs_head;
198   struct MessageTransmitQueue *tmit_msgs_tail;
199
200   struct GNUNET_PSYC_Channel *channel;
201
202   /**
203    * Private key of home in case of a host.
204    */
205   struct GNUNET_CRYPTO_EddsaPublicKey key;
206
207   /**
208    * Public key of place.
209    */
210   struct GNUNET_CRYPTO_EddsaPublicKey pub_key;
211
212   /**
213    * Hash of @a pub_key.
214    */
215   struct GNUNET_HashCode pub_key_hash;
216
217   /**
218    * Private key of ego.
219    */
220   struct GNUNET_CRYPTO_EcdsaPrivateKey ego_key;
221
222   /**
223    * Public key of ego.
224    */
225   struct GNUNET_CRYPTO_EcdsaPublicKey ego_pub_key;
226
227   /**
228    * Hash of @a ego_pub_key.
229    */
230   struct GNUNET_HashCode ego_pub_hash;
231
232   /**
233    * Slicer for processing incoming messages.
234    */
235   struct GNUNET_PSYC_Slicer *slicer;
236
237   /**
238    * Last message ID received for the place.
239    * 0 if there is no such message.
240    */
241   uint64_t max_message_id;
242
243   /**
244    * Offset where the file is currently being written.
245    */
246   uint64_t file_offset;
247
248   /**
249    * Whether or not to save the file (#GNUNET_YES or #GNUNET_NO)
250    */
251   uint8_t file_save;
252
253   /**
254    * Is this a host (#GNUNET_YES), or guest (#GNUNET_NO)?
255    */
256   uint8_t is_host;
257
258   /**
259    * Is this place ready to receive messages from client?
260    * #GNUNET_YES or #GNUNET_NO
261    */
262   uint8_t is_ready;
263
264   /**
265    * Is the client disconnected?
266    * #GNUNET_YES or #GNUNET_NO
267    */
268   uint8_t is_disconnected;
269 };
270
271
272 /**
273  * Client context for a host.
274  */
275 struct Host
276 {
277   /**
278    * Place struct common for Host and Guest
279    */
280   struct Place plc;
281
282   /**
283    * Handle for the multicast origin.
284    */
285   struct GNUNET_PSYC_Master *master;
286
287   /**
288    * Transmit handle for multicast.
289    */
290   struct GNUNET_PSYC_MasterTransmitHandle *tmit_handle;
291
292   /**
293    * Incoming join requests.
294    * guest_key -> struct GNUNET_PSYC_JoinHandle *
295    */
296   struct GNUNET_CONTAINER_MultiHashMap *join_reqs;
297
298   /**
299    * Messages being relayed.
300    */
301   struct GNUNET_CONTAINER_MultiHashMap *relay_msgs;
302
303   /**
304    * @see enum GNUNET_PSYC_Policy
305    */
306   enum GNUNET_PSYC_Policy policy;
307 };
308
309
310 /**
311  * Client context for a guest.
312  */
313 struct Guest
314 {
315   /**
316    * Place struct common for Host and Guest.
317    */
318   struct Place plc;
319
320   /**
321    * Handle for the PSYC slave.
322    */
323   struct GNUNET_PSYC_Slave *slave;
324
325   /**
326    * Transmit handle for multicast.
327    */
328   struct GNUNET_PSYC_SlaveTransmitHandle *tmit_handle;
329
330   /**
331    * Peer identity of the origin.
332    */
333   struct GNUNET_PeerIdentity origin;
334
335   /**
336    * Number of items in @a relays.
337    */
338   uint32_t relay_count;
339
340   /**
341    * Relays that multicast can use to connect.
342    */
343   struct GNUNET_PeerIdentity *relays;
344
345   /**
346    * Join request to be transmitted to the master on join.
347    */
348   struct GNUNET_MessageHeader *join_req;
349
350   /**
351    * Join decision received from PSYC.
352    */
353   struct GNUNET_PSYC_JoinDecisionMessage *join_dcsn;
354
355   /**
356    * Join flags for the PSYC service.
357    */
358   enum GNUNET_PSYC_SlaveJoinFlags join_flags;
359 };
360
361
362 /**
363  * Context for a client.
364  */
365 struct Client
366 {
367   /**
368    * Place where the client entered.
369    */
370   struct Place *plc;
371
372   /**
373    * Message queue for the message currently being transmitted
374    * by this client.
375    */
376   struct MessageTransmitQueue *tmit_msg;
377
378   /**
379    * ID for application clients.
380    */
381   char *app_id;
382 };
383
384
385 struct Application
386 {
387   struct ClientListItem *clients_head;
388   struct ClientListItem *clients_tail;
389 };
390
391
392 struct Ego {
393   struct GNUNET_CRYPTO_EcdsaPrivateKey key;
394   char *name;
395 };
396
397
398 struct OperationClosure
399 {
400   struct GNUNET_SERVER_Client *client;
401   struct Place *plc;
402   uint64_t op_id;
403   uint32_t flags;
404 };
405
406
407 static int
408 psyc_transmit_message (struct Place *plc);
409
410
411 /**
412  * Clean up place data structures after a client disconnected.
413  *
414  * @param cls the `struct Place` to clean up
415  */
416 static void
417 cleanup_place (void *cls);
418
419
420 static struct MessageTransmitQueue *
421 psyc_transmit_queue_message (struct Place *plc,
422                              struct GNUNET_SERVER_Client *client,
423                              size_t data_size,
424                              const void *data,
425                              uint16_t first_ptype, uint16_t last_ptype,
426                              struct MessageTransmitQueue *tmit_msg);
427
428
429 static int
430 place_entry_cleanup (void *cls,
431                      const struct GNUNET_HashCode *key,
432                      void *value)
433 {
434   struct Place *plc = value;
435
436   cleanup_place (plc);
437   return GNUNET_YES;
438 }
439
440
441 /**
442  * Task run during shutdown.
443  *
444  * @param cls unused
445  */
446 static void
447 shutdown_task (void *cls)
448 {
449   GNUNET_CONTAINER_multihashmap_iterate (hosts, place_entry_cleanup, NULL);
450   GNUNET_CONTAINER_multihashmap_iterate (guests, place_entry_cleanup, NULL);
451
452   if (NULL != nc)
453   {
454     GNUNET_SERVER_notification_context_destroy (nc);
455     nc = NULL;
456   }
457   if (NULL != core)
458   {
459     GNUNET_CORE_disconnect (core);
460     core = NULL;
461   }
462   if (NULL != id)
463   {
464     GNUNET_IDENTITY_disconnect (id);
465     id = NULL;
466   }
467   if (NULL != namestore)
468   {
469     GNUNET_NAMESTORE_disconnect (namestore);
470     namestore = NULL;
471   }
472   if (NULL != gns)
473   {
474     GNUNET_GNS_disconnect (gns);
475     gns = NULL;
476   }
477   if (NULL != stats)
478   {
479     GNUNET_STATISTICS_destroy (stats, GNUNET_YES);
480     stats = NULL;
481   }
482 }
483
484
485 /**
486  * Clean up host data structures after a client disconnected.
487  */
488 static void
489 cleanup_host (struct Host *hst)
490 {
491   struct Place *plc = &hst->plc;
492
493   if (NULL != hst->master)
494     GNUNET_PSYC_master_stop (hst->master, GNUNET_NO, NULL, NULL); // FIXME
495   GNUNET_CONTAINER_multihashmap_destroy (hst->join_reqs);
496   GNUNET_CONTAINER_multihashmap_destroy (hst->relay_msgs);
497   GNUNET_CONTAINER_multihashmap_remove (hosts, &plc->pub_key_hash, plc);
498 }
499
500
501 /**
502  * Clean up guest data structures after a client disconnected.
503  */
504 static void
505 cleanup_guest (struct Guest *gst)
506 {
507   struct Place *plc = &gst->plc;
508   struct GNUNET_CONTAINER_MultiHashMap *
509     plc_gst = GNUNET_CONTAINER_multihashmap_get (place_guests,
510                                                 &plc->pub_key_hash);
511   GNUNET_assert (NULL != plc_gst); // FIXME
512   GNUNET_CONTAINER_multihashmap_remove (plc_gst, &plc->ego_pub_hash, gst);
513
514   if (0 == GNUNET_CONTAINER_multihashmap_size (plc_gst))
515   {
516     GNUNET_CONTAINER_multihashmap_remove (place_guests, &plc->pub_key_hash,
517                                           plc_gst);
518     GNUNET_CONTAINER_multihashmap_destroy (plc_gst);
519   }
520   GNUNET_CONTAINER_multihashmap_remove (guests, &plc->pub_key_hash, gst);
521
522   if (NULL != gst->join_req)
523     GNUNET_free (gst->join_req);
524   if (NULL != gst->relays)
525     GNUNET_free (gst->relays);
526   if (NULL != gst->slave)
527     GNUNET_PSYC_slave_part (gst->slave, GNUNET_NO, NULL, NULL); // FIXME
528   GNUNET_CONTAINER_multihashmap_remove (guests, &plc->pub_key_hash, plc);
529 }
530
531
532 /**
533  * Clean up place data structures after a client disconnected.
534  *
535  * @param cls the `struct Place` to clean up
536  */
537 static void
538 cleanup_place (void *cls)
539 {
540   struct Place *plc = cls;
541
542   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
543               "%p Cleaning up place %s\n",
544               plc, GNUNET_h2s (&plc->pub_key_hash));
545
546   (GNUNET_YES == plc->is_host)
547     ? cleanup_host ((struct Host *) plc)
548     : cleanup_guest ((struct Guest *) plc);
549
550   GNUNET_PSYC_slicer_destroy (plc->slicer);
551   GNUNET_free (plc);
552 }
553
554
555 /**
556  * Called whenever a client is disconnected.
557  * Frees our resources associated with that client.
558  *
559  * @param cls Closure.
560  * @param client Identification of the client.
561  */
562 static void
563 client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
564 {
565   if (NULL == client)
566     return;
567
568   struct Client *
569     ctx = GNUNET_SERVER_client_get_user_context (client, struct Client);
570   if (NULL == ctx)
571   {
572     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
573                 "%p User context is NULL in client_disconnect()\n", ctx);
574     return;
575   }
576
577   struct Place *plc = ctx->plc;
578
579   if (NULL != ctx->app_id)
580     GNUNET_free (ctx->app_id);
581
582   GNUNET_free (ctx);
583
584   if (NULL == plc)
585     return; // application client, nothing to do
586
587   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
588               "%p Client (%s) disconnected from place %s\n",
589               plc, (GNUNET_YES == plc->is_host) ? "host" : "guest",
590               GNUNET_h2s (&plc->pub_key_hash));
591
592   struct ClientListItem *cli = plc->clients_head;
593   while (NULL != cli)
594   {
595     if (cli->client == client)
596     {
597       GNUNET_CONTAINER_DLL_remove (plc->clients_head, plc->clients_tail, cli);
598       GNUNET_free (cli);
599       break;
600     }
601     cli = cli->next;
602   }
603 }
604
605
606 /**
607  * Send message to a client.
608  */
609 static inline void
610 client_send_msg (struct GNUNET_SERVER_Client *client,
611                  const struct GNUNET_MessageHeader *msg)
612 {
613   GNUNET_SERVER_notification_context_add (nc, client);
614   GNUNET_SERVER_notification_context_unicast (nc, client, msg, GNUNET_NO);
615 }
616
617
618 /**
619  * Send message to all clients connected to a place.
620  */
621 static void
622 place_send_msg (const struct Place *plc,
623                  const struct GNUNET_MessageHeader *msg)
624 {
625   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
626               "%p Sending message to clients of place.\n", plc);
627
628   struct ClientListItem *cli = plc->clients_head;
629   while (NULL != cli)
630   {
631     client_send_msg (cli->client, msg);
632     cli = cli->next;
633   }
634 }
635
636
637 /**
638  * Send a result code back to the client.
639  *
640  * @param client
641  *        Client that should receive the result code.
642  * @param result_code
643  *        Code to transmit.
644  * @param op_id
645  *        Operation ID in network byte order.
646  * @param data
647  *        Data payload or NULL.
648  * @param data_size
649  *        Size of @a data.
650  */
651 static void
652 client_send_result (struct GNUNET_SERVER_Client *client, uint64_t op_id,
653                     int64_t result_code, const void *data, uint16_t data_size)
654 {
655   struct GNUNET_OperationResultMessage *res;
656
657   res = GNUNET_malloc (sizeof (*res) + data_size);
658   res->header.type = htons (GNUNET_MESSAGE_TYPE_PSYC_RESULT_CODE);
659   res->header.size = htons (sizeof (*res) + data_size);
660   res->result_code = GNUNET_htonll (result_code);
661   res->op_id = op_id;
662   if (0 < data_size)
663     GNUNET_memcpy (&res[1], data, data_size);
664
665   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
666               "%p Sending result to client for operation #%" PRIu64 ": "
667               "%" PRId64 " (size: %u)\n",
668               client, GNUNET_ntohll (op_id), result_code, data_size);
669
670   client_send_msg (client, &res->header);
671   GNUNET_free (res);
672 }
673
674
675 static void
676 client_send_host_enter_ack (struct GNUNET_SERVER_Client *client,
677                             struct Host *hst, uint32_t result)
678 {
679   struct Place *plc = &hst->plc;
680
681   struct HostEnterAck hack;
682   hack.header.type = htons (GNUNET_MESSAGE_TYPE_SOCIAL_HOST_ENTER_ACK);
683   hack.header.size = htons (sizeof (hack));
684   hack.result_code = htonl (result);
685   hack.max_message_id = GNUNET_htonll (plc->max_message_id);
686   hack.place_pub_key = plc->pub_key;
687
688   if (NULL != client)
689     client_send_msg (client, &hack.header);
690   else
691     place_send_msg (plc, &hack.header);
692 }
693
694
695 /**
696  * Called after a PSYC master is started.
697  */
698 static void
699 psyc_master_started (void *cls, int result, uint64_t max_message_id)
700 {
701   struct Host *hst = cls;
702   struct Place *plc = &hst->plc;
703   plc->max_message_id = max_message_id;
704   plc->is_ready = GNUNET_YES;
705
706   client_send_host_enter_ack (NULL, hst, result);
707 }
708
709
710 /**
711  * Called when a PSYC master receives a join request.
712  */
713 static void
714 psyc_recv_join_request (void *cls,
715                         const struct GNUNET_PSYC_JoinRequestMessage *req,
716                         const struct GNUNET_CRYPTO_EcdsaPublicKey *slave_key,
717                         const struct GNUNET_PSYC_Message *join_msg,
718                         struct GNUNET_PSYC_JoinHandle *jh)
719 {
720   struct Host *hst = cls;
721   struct GNUNET_HashCode slave_key_hash;
722   GNUNET_CRYPTO_hash (slave_key, sizeof (*slave_key), &slave_key_hash);
723   GNUNET_CONTAINER_multihashmap_put (hst->join_reqs, &slave_key_hash, jh,
724                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
725   place_send_msg (&hst->plc, &req->header);
726 }
727
728
729 /**
730  * Called after a PSYC slave is connected.
731  */
732 static void
733 psyc_slave_connected (void *cls, int result, uint64_t max_message_id)
734 {
735   struct Guest *gst = cls;
736   struct Place *plc = &gst->plc;
737   plc->max_message_id = max_message_id;
738   plc->is_ready = GNUNET_YES;
739
740   struct GNUNET_PSYC_CountersResultMessage res;
741   res.header.type = htons (GNUNET_MESSAGE_TYPE_SOCIAL_GUEST_ENTER_ACK);
742   res.header.size = htons (sizeof (res));
743   res.result_code = htonl (result);
744   res.max_message_id = GNUNET_htonll (plc->max_message_id);
745
746   place_send_msg (plc, &res.header);
747 }
748
749
750 /**
751  * Called when a PSYC slave receives a join decision.
752  */
753 static void
754 psyc_recv_join_dcsn (void *cls,
755                      const struct GNUNET_PSYC_JoinDecisionMessage *dcsn,
756                      int is_admitted,
757                      const struct GNUNET_PSYC_Message *join_msg)
758 {
759   struct Guest *gst = cls;
760   place_send_msg (&gst->plc, &dcsn->header);
761 }
762
763
764 /**
765  * Called when a PSYC master or slave receives a message.
766  */
767 static void
768 psyc_recv_message (void *cls,
769                    const struct GNUNET_PSYC_MessageHeader *msg)
770 {
771   struct Place *plc = cls;
772
773   char *str = GNUNET_CRYPTO_ecdsa_public_key_to_string (&msg->slave_pub_key);
774   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
775               "%p Received PSYC message of size %u from %s.\n",
776               plc, ntohs (msg->header.size), str);
777   GNUNET_free (str);
778
779   GNUNET_PSYC_slicer_message (plc->slicer, msg);
780
781   place_send_msg (plc, &msg->header);
782 }
783
784
785 /**
786  * Relay a message part received from a guest to the the place.
787  *
788  * @param hst
789  *        Host.
790  * @param pmsg
791  *        Message part.
792  * @param nym_pub_key
793  *        Nym the message is received from.
794  */
795 static void
796 host_relay_message_part (struct Host *hst,
797                          const struct GNUNET_MessageHeader *pmsg,
798                          const struct GNUNET_CRYPTO_EcdsaPublicKey *nym_pub_key)
799 {
800   /* separate queue per nym */
801   struct GNUNET_HashCode nym_pub_hash;
802   GNUNET_CRYPTO_hash (nym_pub_key, sizeof (*nym_pub_key), &nym_pub_hash);
803
804   struct MessageTransmitQueue *
805     tmit_msg = GNUNET_CONTAINER_multihashmap_get (hst->relay_msgs, &nym_pub_hash);
806
807   uint16_t ptype = ntohs (pmsg->type);
808
809   if (GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_METHOD == ptype)
810   {
811     /* FIXME: last message was unfinished, cancel & remove from queue */
812   }
813
814   tmit_msg = psyc_transmit_queue_message (&hst->plc, NULL, ntohs (pmsg->size),
815                                           pmsg, ptype, ptype, tmit_msg);
816
817   switch (ptype)
818   {
819   case GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_METHOD:
820     GNUNET_CONTAINER_multihashmap_put (hst->relay_msgs, &nym_pub_hash, tmit_msg,
821                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
822     break;
823   case GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_END:
824   case GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_CANCEL:
825     GNUNET_CONTAINER_multihashmap_remove (hst->relay_msgs, &nym_pub_hash, tmit_msg);
826     break;
827   }
828 }
829
830
831 /**
832  * Received a method to be relayed from a guest.
833  */
834 static void
835 place_recv_relay_method (void *cls,
836                          const struct GNUNET_PSYC_MessageHeader *msg,
837                          const struct GNUNET_PSYC_MessageMethod *meth,
838                          uint64_t message_id,
839                          const char *method_name)
840 {
841   struct Place *plc = cls;
842
843   if (GNUNET_PSYC_MESSAGE_REQUEST & ntohs (msg->flags)
844       && GNUNET_YES == plc->is_host)
845   {
846     struct Host *hst = cls;
847     host_relay_message_part (hst, &meth->header, &msg->slave_pub_key);
848   }
849 }
850
851
852 /**
853  * Received a modifier to be relayed from a guest.
854  */
855 static void
856 place_recv_relay_modifier (void *cls,
857                            const struct GNUNET_PSYC_MessageHeader *msg,
858                            const struct GNUNET_MessageHeader *pmsg,
859                            uint64_t message_id,
860                            enum GNUNET_PSYC_Operator oper,
861                            const char *name,
862                            const void *value,
863                            uint16_t value_size,
864                            uint16_t full_value_size)
865 {
866   struct Place *plc = cls;
867
868   if (GNUNET_PSYC_MESSAGE_REQUEST & ntohs (msg->flags)
869       && GNUNET_YES == plc->is_host)
870   {
871     struct Host *hst = cls;
872     host_relay_message_part (hst, pmsg, &msg->slave_pub_key);
873   }
874 }
875
876 /**
877  * Received a data fragment to be relayed from a guest.
878  */
879 static void
880 place_recv_relay_data (void *cls,
881                        const struct GNUNET_PSYC_MessageHeader *msg,
882                        const struct GNUNET_MessageHeader *pmsg,
883                        uint64_t message_id,
884                        const void *data,
885                        uint16_t data_size)
886 {
887   struct Place *plc = cls;
888
889   if (GNUNET_PSYC_MESSAGE_REQUEST & ntohs (msg->flags)
890       && GNUNET_YES == plc->is_host)
891   {
892     struct Host *hst = cls;
893     host_relay_message_part (hst, pmsg, &msg->slave_pub_key);
894   }
895 }
896
897
898 /**
899  * Received end of message to be relayed from a guest.
900  */
901 static void
902 place_recv_relay_eom (void *cls,
903                       const struct GNUNET_PSYC_MessageHeader *msg,
904                       const struct GNUNET_MessageHeader *pmsg,
905                       uint64_t message_id,
906                       uint8_t is_cancelled)
907 {
908   struct Place *plc = cls;
909
910   if (GNUNET_PSYC_MESSAGE_REQUEST & ntohs (msg->flags)
911       && GNUNET_YES == plc->is_host)
912   {
913     struct Host *hst = cls;
914     host_relay_message_part (hst, pmsg, &msg->slave_pub_key);
915   }
916 }
917
918
919 /**
920  * Received a method to be saved to disk.
921  *
922  * Create a new file for writing the data part of the message into,
923  * if the file does not yet exist.
924  */
925 static void
926 place_recv_save_method (void *cls,
927                         const struct GNUNET_PSYC_MessageHeader *msg,
928                         const struct GNUNET_PSYC_MessageMethod *meth,
929                         uint64_t message_id,
930                         const char *method_name)
931 {
932   struct Place *plc = cls;
933   plc->file_offset = 0;
934   plc->file_save = GNUNET_NO;
935
936   char *place_pub_str = GNUNET_CRYPTO_eddsa_public_key_to_string (&plc->pub_key);
937   char *filename = NULL;
938   GNUNET_asprintf (&filename, "%s%c" "%s%c" "%s%c" "%" PRIu64 ".part",
939                    dir_social, DIR_SEPARATOR,
940                    "files", DIR_SEPARATOR,
941                    place_pub_str, DIR_SEPARATOR,
942                    GNUNET_ntohll (msg->message_id));
943   GNUNET_free (place_pub_str);
944
945   /* save if does not already exist */
946   if (GNUNET_YES != GNUNET_DISK_file_test (filename))
947   {
948     if (0 == GNUNET_DISK_fn_write (filename, NULL, 0,
949                                    GNUNET_DISK_PERM_USER_READ
950                                    | GNUNET_DISK_PERM_USER_WRITE))
951     {
952       plc->file_save = GNUNET_YES;
953     }
954     else
955     {
956       GNUNET_break (0);
957     }
958   }
959   GNUNET_free (filename);
960 }
961
962
963 /**
964  * Received a data fragment to be saved to disk.
965  *
966  * Append data fragment to the file.
967  */
968 static void
969 place_recv_save_data (void *cls,
970                       const struct GNUNET_PSYC_MessageHeader *msg,
971                       const struct GNUNET_MessageHeader *pmsg,
972                       uint64_t message_id,
973                       const void *data,
974                       uint16_t data_size)
975 {
976   struct Place *plc = cls;
977   if (GNUNET_YES != plc->file_save)
978     return;
979
980   char *place_pub_str = GNUNET_CRYPTO_eddsa_public_key_to_string (&plc->pub_key);
981   char *filename = NULL;
982   GNUNET_asprintf (&filename, "%s%c" "%s%c" "%s%c" "%" PRIu64 ".part",
983                    dir_social, DIR_SEPARATOR,
984                    "files", DIR_SEPARATOR,
985                    place_pub_str, DIR_SEPARATOR,
986                    GNUNET_ntohll (msg->message_id));
987   GNUNET_free (place_pub_str);
988   GNUNET_DISK_directory_create_for_file (filename);
989   struct GNUNET_DISK_FileHandle *
990     fh = GNUNET_DISK_file_open (filename, GNUNET_DISK_OPEN_WRITE,
991                                 GNUNET_DISK_PERM_NONE);
992   if (NULL != fh)
993   {
994     if (plc->file_offset != GNUNET_DISK_file_seek
995           (fh, plc->file_offset, GNUNET_DISK_SEEK_SET)) {
996         GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "seek", filename);
997         GNUNET_free (filename);
998         return;
999     }
1000     GNUNET_DISK_file_write (fh, data, data_size);
1001     GNUNET_DISK_file_close (fh);
1002     GNUNET_free (filename);
1003   }
1004   else
1005   {
1006     GNUNET_free (filename);
1007     GNUNET_break (0);
1008   }
1009   plc->file_offset += data_size;
1010 }
1011
1012
1013 /**
1014  * Received end of message to be saved to disk.
1015  *
1016  * Remove .part ending from the filename.
1017  */
1018 static void
1019 place_recv_save_eom (void *cls,
1020                      const struct GNUNET_PSYC_MessageHeader *msg,
1021                      const struct GNUNET_MessageHeader *pmsg,
1022                      uint64_t message_id,
1023                      uint8_t is_cancelled)
1024 {
1025   struct Place *plc = cls;
1026   if (GNUNET_YES != plc->file_save)
1027     return;
1028
1029   char *place_pub_str = GNUNET_CRYPTO_eddsa_public_key_to_string (&plc->pub_key);
1030   char *fn = NULL;
1031   GNUNET_asprintf (&fn, "%s%c%s%c%s%c%" PRIu64,
1032                    dir_social, DIR_SEPARATOR,
1033                    "files", DIR_SEPARATOR,
1034                    place_pub_str, DIR_SEPARATOR,
1035                    GNUNET_ntohll (msg->message_id));
1036   GNUNET_free (place_pub_str);
1037   char *fn_part = NULL;
1038   GNUNET_asprintf (&fn_part, "%s.part", fn);
1039
1040   if (rename (fn_part, fn)) {
1041       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1042                   "Failed to rename %s into %s: %s (%d)\n",
1043                   fn_part, fn, strerror (errno), errno);
1044   }
1045
1046   GNUNET_free (fn);
1047   GNUNET_free (fn_part);
1048 }
1049
1050
1051 /**
1052  * Initialize place data structure.
1053  */
1054 static void
1055 place_init (struct Place *plc)
1056 {
1057   plc->slicer = GNUNET_PSYC_slicer_create ();
1058 }
1059
1060
1061 /**
1062  * Add a place to the @e places hash map.
1063  *
1064  * @param ereq
1065  *        Entry request.
1066  *
1067  * @return #GNUNET_OK if the place was added
1068  *         #GNUNET_NO if the place already exists in the hash map
1069  *         #GNUNET_SYSERR on error
1070  */
1071 static int
1072 place_add (const struct PlaceEnterRequest *ereq)
1073 {
1074   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1075               "Adding place to hashmap:\n");
1076
1077   struct EgoPlacePublicKey ego_place_pub_key = {
1078     .ego_pub_key = ereq->ego_pub_key,
1079     .place_pub_key = ereq->place_pub_key,
1080   };
1081   struct GNUNET_HashCode ego_place_pub_hash;
1082   GNUNET_CRYPTO_hash (&ego_place_pub_key, sizeof (ego_place_pub_key), &ego_place_pub_hash);
1083
1084   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1085               "  ego_place_pub_hash = %s\n", GNUNET_h2s (&ego_place_pub_hash));
1086
1087   struct GNUNET_MessageHeader *
1088     place_msg = GNUNET_CONTAINER_multihashmap_get (places, &ego_place_pub_hash);
1089   if (NULL != place_msg)
1090     return GNUNET_NO;
1091
1092   place_msg = GNUNET_copy_message (&ereq->header);
1093   if (GNUNET_OK != GNUNET_CONTAINER_multihashmap_put (places, &ego_place_pub_hash, place_msg,
1094                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
1095   {
1096     GNUNET_break (0);
1097     GNUNET_free (place_msg);
1098     return GNUNET_SYSERR;
1099   }
1100
1101   return GNUNET_OK;
1102 }
1103
1104 /**
1105  * Add a place to the @e app_places hash map.
1106  *
1107  * @param app_id
1108  *        Application ID.
1109  * @param ereq
1110  *        Entry request.
1111  *
1112  * @return #GNUNET_OK if the place was added
1113  *         #GNUNET_NO if the place already exists in the hash map
1114  *         #GNUNET_SYSERR on error
1115  */
1116 static int
1117 app_place_add (const char *app_id,
1118                const struct PlaceEnterRequest *ereq)
1119 {
1120   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1121               "Adding app place to hashmap:\n");
1122   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1123               "  app_id = %s\n", app_id);
1124
1125   struct GNUNET_HashCode app_id_hash;
1126   GNUNET_CRYPTO_hash (app_id, strlen (app_id) + 1, &app_id_hash);
1127
1128   struct EgoPlacePublicKey ego_place_pub_key = {
1129     .ego_pub_key = ereq->ego_pub_key,
1130     .place_pub_key = ereq->place_pub_key,
1131   };
1132   struct GNUNET_HashCode ego_place_pub_hash;
1133   GNUNET_CRYPTO_hash (&ego_place_pub_key, sizeof (ego_place_pub_key), &ego_place_pub_hash);
1134
1135   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1136               "  ego_place_pub_hash = %s\n", GNUNET_h2s (&ego_place_pub_hash));
1137
1138   struct GNUNET_CONTAINER_MultiHashMap *
1139     app_places = GNUNET_CONTAINER_multihashmap_get (apps_places, &app_id_hash);
1140   if (NULL == app_places)
1141   {
1142     app_places = GNUNET_CONTAINER_multihashmap_create (1, GNUNET_NO);
1143     GNUNET_CONTAINER_multihashmap_put (apps_places, &app_id_hash, app_places,
1144                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
1145   }
1146
1147   if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains (app_places, &ego_place_pub_hash))
1148     return GNUNET_NO;
1149
1150   if (GNUNET_SYSERR == place_add (ereq))
1151     return GNUNET_SYSERR;
1152
1153   if (GNUNET_OK != GNUNET_CONTAINER_multihashmap_put (app_places, &ego_place_pub_hash, NULL,
1154                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
1155   {
1156     GNUNET_break (0);
1157     return GNUNET_SYSERR;
1158   }
1159
1160   struct GNUNET_HashCode place_pub_hash;
1161   GNUNET_CRYPTO_hash (&ereq->place_pub_key, sizeof (ereq->place_pub_key), &place_pub_hash);
1162
1163   struct GNUNET_CONTAINER_MultiHashMap *
1164     place_apps = GNUNET_CONTAINER_multihashmap_get (places_apps, &place_pub_hash);
1165   if (NULL == place_apps)
1166   {
1167     place_apps = GNUNET_CONTAINER_multihashmap_create (1, GNUNET_NO);
1168     if (GNUNET_OK != GNUNET_CONTAINER_multihashmap_put (places_apps, &place_pub_hash, place_apps,
1169                                                         GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
1170     {
1171       GNUNET_break (0);
1172     }
1173   }
1174
1175   size_t app_id_size = strlen (app_id) + 1;
1176   void *app_id_value = GNUNET_malloc (app_id_size);
1177   GNUNET_memcpy (app_id_value, app_id, app_id_size);
1178
1179   if (GNUNET_OK != GNUNET_CONTAINER_multihashmap_put (place_apps, &app_id_hash, app_id_value,
1180                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
1181   {
1182     GNUNET_break (0);
1183   }
1184
1185   return GNUNET_OK;
1186 }
1187
1188
1189 /**
1190  * Save place entry message to disk.
1191  *
1192  * @param app_id
1193  *        Application ID.
1194  * @param ereq
1195  *        Entry request message.
1196  */
1197 static int
1198 app_place_save (const char *app_id,
1199                 const struct PlaceEnterRequest *ereq)
1200 {
1201   app_place_add (app_id, ereq);
1202
1203   if (NULL == dir_places)
1204     return GNUNET_SYSERR;
1205
1206   char *ego_pub_str = GNUNET_CRYPTO_ecdsa_public_key_to_string (&ereq->ego_pub_key);
1207   char *place_pub_str = GNUNET_CRYPTO_eddsa_public_key_to_string (&ereq->place_pub_key);
1208   char *filename = NULL;
1209   GNUNET_asprintf (&filename, "%s%c" "%s%c" "%s%c" "%s",
1210                    dir_social, DIR_SEPARATOR,
1211                    "places", DIR_SEPARATOR,
1212                    ego_pub_str, DIR_SEPARATOR,
1213                    place_pub_str);
1214   int ret = GNUNET_DISK_directory_create_for_file (filename);
1215   if (GNUNET_OK != ret
1216       || 0 > GNUNET_DISK_fn_write (filename, ereq, ntohs (ereq->header.size),
1217                                    GNUNET_DISK_PERM_USER_READ
1218                                    | GNUNET_DISK_PERM_USER_WRITE))
1219   {
1220     GNUNET_break (0);
1221     ret = GNUNET_SYSERR;
1222   }
1223   GNUNET_free (filename);
1224
1225   if (ret == GNUNET_OK)
1226   {
1227     GNUNET_asprintf (&filename, "%s%c" "%s%c" "%s%c" "%s%c" "%s",
1228                      dir_social, DIR_SEPARATOR,
1229                      "apps", DIR_SEPARATOR,
1230                      app_id, DIR_SEPARATOR,
1231                      ego_pub_str, DIR_SEPARATOR,
1232                      place_pub_str);
1233     ret = GNUNET_DISK_directory_create_for_file (filename);
1234     if (GNUNET_OK != ret
1235         || 0 > GNUNET_DISK_fn_write (filename, "", 0,
1236                                      GNUNET_DISK_PERM_USER_READ
1237                                      | GNUNET_DISK_PERM_USER_WRITE))
1238     {
1239       GNUNET_break (0);
1240       ret = GNUNET_SYSERR;
1241     }
1242     GNUNET_free (filename);
1243   }
1244   GNUNET_free (ego_pub_str);
1245   GNUNET_free (place_pub_str);
1246   return ret;
1247 }
1248
1249
1250 int
1251 app_place_remove (const char *app_id,
1252                   const struct GNUNET_CRYPTO_EcdsaPublicKey *ego_pub_key,
1253                   const struct GNUNET_CRYPTO_EddsaPublicKey *place_pub_key)
1254 {
1255   struct GNUNET_HashCode ego_pub_hash;
1256   struct GNUNET_HashCode place_pub_hash;
1257   GNUNET_CRYPTO_hash (ego_pub_key, sizeof (*ego_pub_key), &ego_pub_hash);
1258   GNUNET_CRYPTO_hash (place_pub_key, sizeof (*place_pub_key), &place_pub_hash);
1259
1260   char *ego_pub_str = GNUNET_CRYPTO_ecdsa_public_key_to_string (ego_pub_key);
1261   char *place_pub_str = GNUNET_CRYPTO_eddsa_public_key_to_string (place_pub_key);
1262   char *app_place_filename = NULL;
1263   GNUNET_asprintf (&app_place_filename,
1264                    "%s%c" "%s%c" "%s%c" "%s%c" "%s",
1265                    dir_social, DIR_SEPARATOR,
1266                    "apps", DIR_SEPARATOR,
1267                    app_id, DIR_SEPARATOR,
1268                    ego_pub_str, DIR_SEPARATOR,
1269                    place_pub_str);
1270   GNUNET_free (ego_pub_str);
1271   GNUNET_free (place_pub_str);
1272
1273   struct GNUNET_HashCode app_id_hash;
1274   GNUNET_CRYPTO_hash (app_id, strlen (app_id) + 1, &app_id_hash);
1275
1276   struct GNUNET_CONTAINER_MultiHashMap *
1277     app_places = GNUNET_CONTAINER_multihashmap_get (apps_places, &app_id_hash);
1278
1279   if (NULL != app_places)
1280     GNUNET_CONTAINER_multihashmap_remove (app_places, &place_pub_hash, NULL);
1281
1282   struct GNUNET_CONTAINER_MultiHashMap *
1283     place_apps = GNUNET_CONTAINER_multihashmap_get (places_apps, &place_pub_hash);
1284   if (NULL != place_apps)
1285   {
1286     void *app_id_value = GNUNET_CONTAINER_multihashmap_get (place_apps, &app_id_hash);
1287     if (NULL != app_id_value)
1288     {
1289       GNUNET_CONTAINER_multihashmap_remove (place_apps, &app_id_hash, app_id_value);
1290       GNUNET_free (app_id_value);
1291     }
1292   }
1293
1294   int ret = GNUNET_OK;
1295
1296   if (0 != unlink (app_place_filename))
1297   {
1298     GNUNET_break (0);
1299     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1300                 "Error removing app place file: %s: %s (%d)\n",
1301                 app_place_filename, strerror (errno), errno);
1302     ret = GNUNET_SYSERR;
1303   }
1304   GNUNET_free (app_place_filename);
1305
1306   return ret;
1307 }
1308
1309
1310 /**
1311  * Enter place as host.
1312  *
1313  * @param hreq
1314  *        Host entry request.
1315  * @param[out] ret_hst
1316  *        Returned Host struct.
1317  *
1318  * @return #GNUNET_YES if the host entered the place just now,
1319  *         #GNUNET_NO  if the place is already entered,
1320  *         #GNUNET_SYSERR if place_pub_key was set
1321  *                        but its private key was not found
1322  */
1323 static int
1324 host_enter (const struct HostEnterRequest *hreq, struct Host **ret_hst)
1325 {
1326   int ret = GNUNET_NO;
1327   struct GNUNET_HashCode place_pub_hash;
1328   GNUNET_CRYPTO_hash (&hreq->place_pub_key, sizeof (hreq->place_pub_key),
1329                       &place_pub_hash);
1330   struct Host *hst = GNUNET_CONTAINER_multihashmap_get (hosts, &place_pub_hash);
1331
1332   if (NULL == hst)
1333   {
1334     hst = GNUNET_new (struct Host);
1335     hst->policy = hreq->policy;
1336     hst->join_reqs = GNUNET_CONTAINER_multihashmap_create (1, GNUNET_NO);
1337     hst->relay_msgs = GNUNET_CONTAINER_multihashmap_create (1, GNUNET_NO);
1338
1339     struct Place *plc = &hst->plc;
1340     place_init (plc);
1341     plc->is_host = GNUNET_YES;
1342     plc->pub_key = hreq->place_pub_key;
1343     plc->pub_key_hash = place_pub_hash;
1344
1345     GNUNET_CONTAINER_multihashmap_put (hosts, &plc->pub_key_hash, plc,
1346                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1347     hst->master = GNUNET_PSYC_master_start (cfg, &hreq->place_key, hst->policy,
1348                                             &psyc_master_started,
1349                                             &psyc_recv_join_request,
1350                                             &psyc_recv_message, NULL, hst);
1351     plc->channel = GNUNET_PSYC_master_get_channel (hst->master);
1352     ret = GNUNET_YES;
1353   }
1354
1355   if (NULL != ret_hst)
1356     *ret_hst = hst;
1357   return ret;
1358 }
1359
1360
1361 const struct MsgProcRequest *
1362 msg_proc_parse (const struct GNUNET_MessageHeader *msg,
1363                 uint32_t *flags,
1364                 const char **method_prefix,
1365                 struct GNUNET_HashCode *method_hash)
1366 {
1367   const struct MsgProcRequest *mpreq = (const struct MsgProcRequest *) msg;
1368   uint8_t method_size = ntohs (mpreq->header.size) - sizeof (*mpreq);
1369   uint16_t offset = GNUNET_STRINGS_buffer_tokenize ((const char *) &mpreq[1],
1370                                                     method_size, 1, method_prefix);
1371
1372   if (0 == offset || offset != method_size || *method_prefix == NULL)
1373   {
1374     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1375                 "offset = %u, method_size = %u, method_name = %s\n",
1376                 offset, method_size, *method_prefix);
1377     return NULL;
1378   }
1379
1380   GNUNET_CRYPTO_hash (*method_prefix, method_size, method_hash);
1381   *flags = ntohl (mpreq->flags);
1382   return mpreq;
1383 }
1384
1385
1386 /**
1387  * Handle a client setting message proccesing flags for a method prefix.
1388  */
1389 static void
1390 client_recv_msg_proc_set (void *cls, struct GNUNET_SERVER_Client *client,
1391                           const struct GNUNET_MessageHeader *msg)
1392 {
1393   struct Client *
1394     ctx = GNUNET_SERVER_client_get_user_context (client, struct Client);
1395   GNUNET_assert (NULL != ctx);
1396   struct Place *plc = ctx->plc;
1397
1398   const char *method_prefix = NULL;
1399   uint32_t flags = 0;
1400   struct GNUNET_HashCode method_hash;
1401   const struct MsgProcRequest *
1402     mpreq = msg_proc_parse (msg, &flags, &method_prefix, &method_hash);
1403
1404   if (NULL == mpreq) {
1405     GNUNET_break (0);
1406     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1407     return;
1408   }
1409 #if 0
1410   GNUNET_PSYC_slicer_method_remove (plc->slicer, method_prefix,
1411                                     place_recv_relay_method,
1412                                     place_recv_relay_modifier,
1413                                     place_recv_relay_data,
1414                                     place_recv_relay_eom);
1415   GNUNET_PSYC_slicer_method_remove (plc->slicer, method_prefix,
1416                                     place_recv_save_method,
1417                                     NULL,
1418                                     place_recv_save_data,
1419                                     place_recv_save_eom);
1420 #endif
1421   if (flags & GNUNET_SOCIAL_MSG_PROC_RELAY)
1422   {
1423     GNUNET_PSYC_slicer_method_add (plc->slicer, method_prefix, NULL,
1424                                    place_recv_relay_method,
1425                                    place_recv_relay_modifier,
1426                                    place_recv_relay_data,
1427                                    place_recv_relay_eom,
1428                                    plc);
1429   }
1430   if (flags & GNUNET_SOCIAL_MSG_PROC_SAVE)
1431   {
1432     GNUNET_PSYC_slicer_method_add (plc->slicer, method_prefix, NULL,
1433                                    place_recv_save_method,
1434                                    NULL,
1435                                    place_recv_save_data,
1436                                    place_recv_save_eom,
1437                                    plc);
1438   }
1439
1440   /** @todo Save flags to be able to resume relaying/saving after restart */
1441
1442   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1443 }
1444
1445
1446 /**
1447  * Handle a connecting client requesting to clear all relay rules.
1448  */
1449 static void
1450 client_recv_msg_proc_clear (void *cls, struct GNUNET_SERVER_Client *client,
1451                             const struct GNUNET_MessageHeader *msg)
1452 {
1453   struct Client *
1454     ctx = GNUNET_SERVER_client_get_user_context (client, struct Client);
1455   GNUNET_assert (NULL != ctx);
1456   struct Place *plc = ctx->plc;
1457   if (GNUNET_YES != plc->is_host) {
1458     GNUNET_break (0);
1459     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1460     return;
1461   }
1462   GNUNET_PSYC_slicer_clear (plc->slicer);
1463
1464   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1465 }
1466
1467
1468 /**
1469  * Handle a connecting client entering a place as host.
1470  */
1471 static void
1472 client_recv_host_enter (void *cls, struct GNUNET_SERVER_Client *client,
1473                         const struct GNUNET_MessageHeader *msg)
1474 {
1475   struct HostEnterRequest *hreq
1476     = (struct HostEnterRequest *) GNUNET_copy_message (msg);
1477
1478   uint8_t app_id_size = ntohs (hreq->header.size) - sizeof (*hreq);
1479   const char *app_id = NULL;
1480   uint16_t offset = GNUNET_STRINGS_buffer_tokenize ((const char *) &hreq[1],
1481                                                     app_id_size, 1, &app_id);
1482   if (0 == offset || offset != app_id_size || app_id == NULL)
1483   {
1484     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1485                 "offset = %u, app_id_size = %u, app_id = %s\n",
1486                 offset, app_id_size, app_id);
1487     GNUNET_break (0);
1488     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1489     return;
1490   }
1491
1492   struct Host *hst = NULL;
1493   struct Place *plc = NULL;
1494   int ret = GNUNET_OK;
1495
1496   struct GNUNET_CRYPTO_EddsaPublicKey empty_pub_key;
1497   memset (&empty_pub_key, 0, sizeof (empty_pub_key));
1498
1499   if (0 == memcmp (&hreq->place_pub_key, &empty_pub_key, sizeof (empty_pub_key)))
1500   { // no public key set: create new private key & save the place
1501     struct GNUNET_CRYPTO_EddsaPrivateKey *
1502       place_key = GNUNET_CRYPTO_eddsa_key_create ();
1503     hreq->place_key = *place_key;
1504     GNUNET_CRYPTO_eddsa_key_get_public (place_key, &hreq->place_pub_key);
1505     GNUNET_CRYPTO_eddsa_key_clear (place_key);
1506     GNUNET_free (place_key);
1507
1508     app_place_save (app_id, (const struct PlaceEnterRequest *) hreq);
1509   }
1510
1511   switch (host_enter (hreq, &hst))
1512   {
1513   case GNUNET_YES:
1514     plc = &hst->plc;
1515     break;
1516
1517   case GNUNET_NO:
1518   {
1519     plc = &hst->plc;
1520     client_send_host_enter_ack (client, hst, GNUNET_OK);
1521     break;
1522   }
1523   case GNUNET_SYSERR:
1524     ret = GNUNET_SYSERR;
1525   }
1526
1527   if (ret != GNUNET_SYSERR)
1528   {
1529
1530     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1531                 "%p Client connected as host to place %s.\n",
1532                 hst, GNUNET_h2s (&plc->pub_key_hash));
1533
1534     struct ClientListItem *cli = GNUNET_new (struct ClientListItem);
1535     cli->client = client;
1536     GNUNET_CONTAINER_DLL_insert (plc->clients_head, plc->clients_tail, cli);
1537
1538     struct Client *ctx = GNUNET_new (struct Client);
1539     ctx->plc = plc;
1540     GNUNET_SERVER_client_set_user_context (client, ctx);
1541   }
1542
1543   GNUNET_CRYPTO_eddsa_key_clear (&hreq->place_key);
1544   GNUNET_free (hreq);
1545   GNUNET_SERVER_receive_done (client, ret);
1546 }
1547
1548
1549 /**
1550  * Enter place as guest.
1551  *
1552  * @param greq
1553  *        Guest entry request.
1554  * @param[out] ret_gst
1555  *        Returned Guest struct.
1556  *
1557  * @return #GNUNET_YES if the guest entered the place just now,
1558  *         #GNUNET_NO  if the place is already entered,
1559  *         #GNUNET_SYSERR on error.
1560  */
1561 static int
1562 guest_enter (const struct GuestEnterRequest *greq, struct Guest **ret_gst)
1563 {
1564   int ret = GNUNET_NO;
1565   uint16_t greq_size = ntohs (greq->header.size);
1566
1567   struct GNUNET_CRYPTO_EcdsaPublicKey ego_pub_key = greq->ego_pub_key;
1568   struct GNUNET_HashCode ego_pub_hash;
1569   GNUNET_CRYPTO_hash (&ego_pub_key, sizeof (ego_pub_key), &ego_pub_hash);
1570   struct Ego *ego = GNUNET_CONTAINER_multihashmap_get (egos, &ego_pub_hash);
1571
1572   if (NULL == ego)
1573     return GNUNET_SYSERR;
1574
1575   struct GNUNET_HashCode place_pub_hash;
1576   GNUNET_CRYPTO_hash (&greq->place_pub_key, sizeof (greq->place_pub_key),
1577                       &place_pub_hash);
1578
1579   struct GNUNET_CONTAINER_MultiHashMap *
1580     plc_gst = GNUNET_CONTAINER_multihashmap_get (place_guests, &place_pub_hash);
1581   struct Guest *gst = NULL;
1582
1583   if (NULL != plc_gst)
1584     gst = GNUNET_CONTAINER_multihashmap_get (plc_gst, &ego_pub_hash);
1585
1586   if (NULL == gst || NULL == gst->slave)
1587   {
1588     gst = GNUNET_new (struct Guest);
1589     gst->origin = greq->origin;
1590     gst->relay_count = ntohl (greq->relay_count);
1591
1592     uint16_t len;
1593     uint16_t remaining = ntohs (greq->header.size) - sizeof (*greq);
1594     const char *app_id = (const char *) &greq[1];
1595     const char *p = app_id;
1596
1597     len = strnlen (app_id, remaining);
1598     if (len == remaining)
1599     {
1600       GNUNET_free (gst);
1601       GNUNET_break (0);
1602       return GNUNET_SYSERR;
1603     }
1604     p += len + 1;
1605     remaining -= len + 1;
1606
1607     const struct GNUNET_PeerIdentity *relays = NULL;
1608     uint16_t relay_size = gst->relay_count * sizeof (*relays);
1609     if (remaining < relay_size)
1610     {
1611       GNUNET_free (gst);
1612       GNUNET_break (0);
1613       return GNUNET_SYSERR;
1614     }
1615     if (0 < relay_size)
1616       relays = (const struct GNUNET_PeerIdentity *) p;
1617     p += relay_size;
1618     remaining -= relay_size;
1619
1620     struct GNUNET_PSYC_Message *join_msg = NULL;
1621     uint16_t join_msg_size = 0;
1622
1623     if (sizeof (struct GNUNET_MessageHeader) <= remaining)
1624     {
1625       join_msg = (struct GNUNET_PSYC_Message *) p;
1626       join_msg_size = ntohs (join_msg->header.size);
1627       p += join_msg_size;
1628       remaining -= join_msg_size;
1629     }
1630     if (0 != remaining)
1631     {
1632       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1633                   "%zu + %u + %u != %u\n",
1634                   sizeof (*greq), relay_size, join_msg_size, greq_size);
1635       GNUNET_free (gst);
1636       GNUNET_break (0);
1637       return GNUNET_SYSERR;
1638     }
1639     if (0 < relay_size)
1640     {
1641       gst->relays = GNUNET_malloc (relay_size);
1642       GNUNET_memcpy (gst->relays, relays, relay_size);
1643     }
1644
1645     gst->join_flags = ntohl (greq->flags);
1646
1647     struct Place *plc = &gst->plc;
1648     place_init (plc);
1649     plc->is_host = GNUNET_NO;
1650     plc->pub_key = greq->place_pub_key;
1651     plc->pub_key_hash = place_pub_hash;
1652     plc->ego_pub_key = ego_pub_key;
1653     plc->ego_pub_hash = ego_pub_hash;
1654     plc->ego_key = ego->key;
1655
1656     if (NULL == plc_gst)
1657     {
1658       plc_gst = GNUNET_CONTAINER_multihashmap_create (1, GNUNET_YES);
1659       (void) GNUNET_CONTAINER_multihashmap_put (place_guests, &plc->pub_key_hash, plc_gst,
1660                                                 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
1661     }
1662     (void) GNUNET_CONTAINER_multihashmap_put (plc_gst, &plc->ego_pub_hash, gst,
1663                                               GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
1664     (void) GNUNET_CONTAINER_multihashmap_put (guests, &plc->pub_key_hash, gst,
1665                                               GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1666     gst->slave
1667       = GNUNET_PSYC_slave_join (cfg, &plc->pub_key, &plc->ego_key,
1668                                 gst->join_flags, &gst->origin,
1669                                 gst->relay_count, gst->relays,
1670                                 &psyc_recv_message, NULL,
1671                                 &psyc_slave_connected,
1672                                 &psyc_recv_join_dcsn,
1673                                 gst, join_msg);
1674     plc->channel = GNUNET_PSYC_slave_get_channel (gst->slave);
1675     ret = GNUNET_YES;
1676   }
1677
1678   if (NULL != ret_gst)
1679     *ret_gst = gst;
1680   return ret;
1681 }
1682
1683
1684 /**
1685  * Handle a connecting client entering a place as guest.
1686  */
1687 static void
1688 client_recv_guest_enter (void *cls, struct GNUNET_SERVER_Client *client,
1689                          const struct GNUNET_MessageHeader *msg)
1690 {
1691   const struct GuestEnterRequest *
1692     greq = (const struct GuestEnterRequest *) msg;
1693
1694   uint16_t remaining = ntohs (greq->header.size) - sizeof (*greq);
1695   const char *app_id = NULL;
1696   uint16_t offset = GNUNET_STRINGS_buffer_tokenize ((const char *) &greq[1],
1697                                                     remaining, 1, &app_id);
1698   if (0 == offset)
1699   {
1700     GNUNET_break (0);
1701     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1702     return;
1703   }
1704
1705   struct Guest *gst = NULL;
1706   struct Place *plc = NULL;
1707
1708   switch (guest_enter (greq, &gst))
1709   {
1710   case GNUNET_YES:
1711     plc = &gst->plc;
1712     app_place_save (app_id, (const struct PlaceEnterRequest *) greq);
1713     break;
1714
1715   case GNUNET_NO:
1716   {
1717     plc = &gst->plc;
1718
1719     struct GNUNET_PSYC_CountersResultMessage res;
1720     res.header.type = htons (GNUNET_MESSAGE_TYPE_SOCIAL_GUEST_ENTER_ACK);
1721     res.header.size = htons (sizeof (res));
1722     res.result_code = htonl (GNUNET_OK);
1723     res.max_message_id = GNUNET_htonll (plc->max_message_id);
1724
1725     client_send_msg (client, &res.header);
1726     if (NULL != gst->join_dcsn)
1727       client_send_msg (client, &gst->join_dcsn->header);
1728
1729     break;
1730   }
1731   case GNUNET_SYSERR:
1732     GNUNET_break (0);
1733     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1734     return;
1735   }
1736
1737   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1738               "%p Client connected as guest to place %s.\n",
1739               gst, GNUNET_h2s (&plc->pub_key_hash));
1740
1741   struct ClientListItem *cli = GNUNET_new (struct ClientListItem);
1742   cli->client = client;
1743   GNUNET_CONTAINER_DLL_insert (plc->clients_head, plc->clients_tail, cli);
1744
1745   struct Client *ctx = GNUNET_new (struct Client);
1746   ctx->plc = plc;
1747   GNUNET_SERVER_client_set_user_context (client, ctx);
1748   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1749 }
1750
1751
1752 struct GuestEnterByNameClosure
1753 {
1754   struct GNUNET_SERVER_Client *client;
1755   char *app_id;
1756   char *password;
1757   struct GNUNET_CRYPTO_EcdsaPublicKey ego_pub_key;
1758   struct GNUNET_MessageHeader *join_msg;
1759 };
1760
1761
1762 /**
1763  * Result of a GNS name lookup for entering a place.
1764  *
1765  * @see GNUNET_SOCIAL_guest_enter_by_name
1766  */
1767 static void
1768 gns_result_guest_enter (void *cls, uint32_t rd_count,
1769                         const struct GNUNET_GNSRECORD_Data *rd)
1770 {
1771   struct GuestEnterByNameClosure *gcls = cls;
1772   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1773               "%p GNS result: %u records.\n", gcls->client, rd_count);
1774
1775   const struct GNUNET_GNSRECORD_PlaceData *
1776     rec = (const struct GNUNET_GNSRECORD_PlaceData *) rd->data;
1777
1778   if (0 == rd_count || rd->data_size < sizeof (*rec))
1779   {
1780     GNUNET_break (0);
1781     GNUNET_SERVER_receive_done (gcls->client, GNUNET_SYSERR);
1782     return;
1783   }
1784
1785   uint16_t relay_count = ntohl (rec->relay_count);
1786   struct GNUNET_PeerIdentity *relays = NULL;
1787
1788   if (0 < relay_count)
1789   {
1790     if (rd->data_size == sizeof (*rec) + relay_count * sizeof (struct GNUNET_PeerIdentity))
1791     {
1792       relays = (struct GNUNET_PeerIdentity *) &rec[1];
1793     }
1794     else
1795     {
1796       relay_count = 0;
1797       GNUNET_break_op (0);
1798     }
1799   }
1800
1801   uint16_t app_id_size = strlen (gcls->app_id) + 1;
1802   uint16_t relay_size = relay_count * sizeof (*relays);
1803   uint16_t join_msg_size = 0;
1804   if (NULL != gcls->join_msg)
1805     join_msg_size = ntohs (gcls->join_msg->size);
1806   uint16_t greq_size = sizeof (struct GuestEnterRequest)
1807     + app_id_size + relay_size + join_msg_size;
1808   struct GuestEnterRequest *greq = GNUNET_malloc (greq_size);
1809   greq->header.size = htons (greq_size);
1810   greq->header.type = htons (GNUNET_MESSAGE_TYPE_SOCIAL_GUEST_ENTER);
1811   greq->ego_pub_key = gcls->ego_pub_key;
1812   greq->place_pub_key = rec->place_pub_key;
1813   greq->origin = rec->origin;
1814   greq->relay_count = rec->relay_count;
1815
1816   void *p = &greq[1];
1817   GNUNET_memcpy (p, gcls->app_id, app_id_size);
1818   p += app_id_size;
1819   GNUNET_memcpy (p, relays, relay_size);
1820   p += relay_size;
1821   GNUNET_memcpy (p, gcls->join_msg, join_msg_size);
1822
1823   client_recv_guest_enter (NULL, gcls->client, &greq->header);
1824
1825   GNUNET_free (gcls->app_id);
1826   if (NULL != gcls->password)
1827     GNUNET_free (gcls->password);
1828   if (NULL != gcls->join_msg)
1829     GNUNET_free (gcls->join_msg);
1830   GNUNET_free (gcls);
1831   GNUNET_free (greq);
1832 }
1833
1834
1835 /**
1836  * Handle a connecting client entering a place as guest using a GNS address.
1837  *
1838  * Look up GNS address and generate a GuestEnterRequest from that.
1839  */
1840 static void
1841 client_recv_guest_enter_by_name (void *cls, struct GNUNET_SERVER_Client *client,
1842                                  const struct GNUNET_MessageHeader *msg)
1843 {
1844   const struct GuestEnterByNameRequest *
1845     greq = (const struct GuestEnterByNameRequest *) msg;
1846
1847   struct GuestEnterByNameClosure *gcls = GNUNET_malloc (sizeof (*gcls));
1848   gcls->client = client;
1849   gcls->ego_pub_key = greq->ego_pub_key;
1850
1851   const char *p = (const char *) &greq[1];
1852   const char *app_id = NULL, *password = NULL, *gns_name = NULL;
1853   uint16_t remaining = ntohs (greq->header.size) - sizeof (*greq);
1854   uint16_t offset = GNUNET_STRINGS_buffer_tokenize (p, remaining, 3,
1855                                                     &app_id,
1856                                                     &gns_name,
1857                                                     &password);
1858   p += offset;
1859   remaining -= offset;
1860
1861   if (0 != offset && sizeof (*gcls->join_msg) <= remaining)
1862   {
1863     gcls->join_msg = GNUNET_copy_message ((struct GNUNET_MessageHeader *) p);
1864     remaining -= ntohs (gcls->join_msg->size);
1865   }
1866
1867   if (0 == offset || 0 != remaining)
1868   {
1869     if (NULL != gcls->join_msg)
1870       GNUNET_free (gcls->join_msg);
1871     GNUNET_free (gcls);
1872     GNUNET_break (0);
1873     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1874     return;
1875   }
1876
1877   uint16_t app_id_size = strlen (app_id) + 1;
1878   gcls->app_id = GNUNET_malloc (app_id_size);
1879   GNUNET_memcpy (gcls->app_id, app_id, app_id_size);
1880
1881   uint16_t password_size = strlen (password);
1882   if (0 < password_size++)
1883   {
1884     gcls->password = GNUNET_malloc (password_size);
1885     GNUNET_memcpy (gcls->password, password, password_size);
1886   }
1887
1888   GNUNET_GNS_lookup (gns, gns_name, &greq->ego_pub_key,
1889                      GNUNET_GNSRECORD_TYPE_PLACE, GNUNET_GNS_LO_DEFAULT,
1890                      NULL, gns_result_guest_enter, gcls);
1891 }
1892
1893
1894 void
1895 app_notify_place (struct GNUNET_MessageHeader *msg,
1896                   struct GNUNET_SERVER_Client *client)
1897 {
1898   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1899               "%p Sending place notification of type %u to client.\n",
1900               client, ntohs (msg->type));
1901
1902   uint16_t msg_size = ntohs (msg->size);
1903   struct AppPlaceMessage amsg;
1904   amsg.header.type = htons (GNUNET_MESSAGE_TYPE_SOCIAL_APP_PLACE);
1905   amsg.header.size = htons (sizeof (amsg));
1906   // FIXME: also notify about not entered places
1907   amsg.place_state = GNUNET_SOCIAL_PLACE_STATE_ENTERED;
1908
1909   switch (ntohs (msg->type))
1910   {
1911   case GNUNET_MESSAGE_TYPE_SOCIAL_HOST_ENTER:
1912     if (msg_size < sizeof (struct HostEnterRequest))
1913       return;
1914     struct HostEnterRequest *hreq = (struct HostEnterRequest *) msg;
1915     amsg.is_host = GNUNET_YES;
1916     amsg.ego_pub_key = hreq->ego_pub_key;
1917     amsg.place_pub_key = hreq->place_pub_key;
1918     break;
1919
1920   case GNUNET_MESSAGE_TYPE_SOCIAL_GUEST_ENTER:
1921     if (msg_size < sizeof (struct GuestEnterRequest))
1922       return;
1923     struct GuestEnterRequest *greq = (struct GuestEnterRequest *) msg;
1924     amsg.is_host = GNUNET_NO;
1925     amsg.ego_pub_key = greq->ego_pub_key;
1926     amsg.place_pub_key = greq->place_pub_key;
1927     break;
1928
1929   default:
1930     return;
1931   }
1932
1933   client_send_msg (client, &amsg.header);
1934 }
1935
1936
1937 void
1938 app_notify_place_end (struct GNUNET_SERVER_Client *client)
1939 {
1940   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1941               "%p Sending end of place list notification to client\n",
1942               client);
1943
1944   struct GNUNET_MessageHeader msg;
1945   msg.type = htons (GNUNET_MESSAGE_TYPE_SOCIAL_APP_PLACE_END);
1946   msg.size = htons (sizeof (msg));
1947
1948   client_send_msg (client, &msg);
1949 }
1950
1951
1952 void
1953 app_notify_ego (struct Ego *ego, struct GNUNET_SERVER_Client *client)
1954 {
1955   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1956               "%p Sending ego notification to client: %s\n",
1957               client, ego->name);
1958
1959   size_t name_size = strlen (ego->name) + 1;
1960   struct AppEgoMessage *emsg = GNUNET_malloc (sizeof (*emsg) + name_size);
1961   emsg->header.type = htons (GNUNET_MESSAGE_TYPE_SOCIAL_APP_EGO);
1962   emsg->header.size = htons (sizeof (*emsg) + name_size);
1963
1964   GNUNET_CRYPTO_ecdsa_key_get_public (&ego->key, &emsg->ego_pub_key);
1965   GNUNET_memcpy (&emsg[1], ego->name, name_size);
1966
1967   client_send_msg (client, &emsg->header);
1968   GNUNET_free (emsg);
1969 }
1970
1971
1972 void
1973 app_notify_ego_end (struct GNUNET_SERVER_Client *client)
1974 {
1975   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1976               "%p Sending end of ego list notification to client\n",
1977               client);
1978
1979   struct GNUNET_MessageHeader msg;
1980   msg.type = htons (GNUNET_MESSAGE_TYPE_SOCIAL_APP_EGO_END);
1981   msg.size = htons (sizeof (msg));
1982
1983   client_send_msg (client, &msg);
1984 }
1985
1986
1987 int
1988 app_place_entry_notify (void *cls, const struct GNUNET_HashCode *key, void *value)
1989 {
1990   struct GNUNET_MessageHeader *
1991     msg = GNUNET_CONTAINER_multihashmap_get (places, key);
1992   if (NULL != msg)
1993     app_notify_place (msg, cls);
1994   return GNUNET_YES;
1995 }
1996
1997
1998 int
1999 ego_entry (void *cls, const struct GNUNET_HashCode *key, void *value)
2000 {
2001   app_notify_ego (value, cls);
2002   return GNUNET_YES;
2003 }
2004
2005
2006 /**
2007  * Handle application connection.
2008  */
2009 static void
2010 client_recv_app_connect (void *cls, struct GNUNET_SERVER_Client *client,
2011                          const struct GNUNET_MessageHeader *msg)
2012 {
2013   const struct AppConnectRequest *creq
2014     = (const struct AppConnectRequest *) msg;
2015
2016   uint8_t app_id_size = ntohs (creq->header.size) - sizeof (*creq);
2017   const char *app_id = NULL;
2018   uint16_t offset = GNUNET_STRINGS_buffer_tokenize ((const char *) &creq[1],
2019                                                     app_id_size, 1, &app_id);
2020   if (0 == offset || offset != app_id_size)
2021   {
2022     GNUNET_break (0);
2023     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2024     return;
2025   }
2026
2027   struct GNUNET_HashCode app_id_hash;
2028   GNUNET_CRYPTO_hash (app_id, app_id_size, &app_id_hash);
2029
2030   GNUNET_CONTAINER_multihashmap_iterate (egos, ego_entry, client);
2031   app_notify_ego_end (client);
2032
2033   struct GNUNET_CONTAINER_MultiHashMap *
2034     app_places = GNUNET_CONTAINER_multihashmap_get (apps_places, &app_id_hash);
2035   if (NULL != app_places)
2036     GNUNET_CONTAINER_multihashmap_iterate (app_places, app_place_entry_notify, client);
2037   app_notify_place_end (client);
2038
2039   struct ClientListItem *cli = GNUNET_new (struct ClientListItem);
2040   cli->client = client;
2041   struct Application *app = GNUNET_CONTAINER_multihashmap_get (apps,
2042                                                                &app_id_hash);
2043   if (NULL == app) {
2044     app = GNUNET_malloc (sizeof (*app));
2045     (void) GNUNET_CONTAINER_multihashmap_put (apps, &app_id_hash, app,
2046                                               GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
2047   }
2048   GNUNET_CONTAINER_DLL_insert (app->clients_head, app->clients_tail, cli);
2049
2050   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2051               "%p Application %s connected.\n", app, app_id);
2052
2053   struct Client *ctx = GNUNET_new (struct Client);
2054   ctx->app_id = GNUNET_malloc (app_id_size);
2055   GNUNET_memcpy (ctx->app_id, app_id, app_id_size);
2056
2057   GNUNET_SERVER_client_set_user_context (client, ctx);
2058   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2059 }
2060
2061
2062 /**
2063  * Handle application detach request.
2064  */
2065 static void
2066 client_recv_app_detach (void *cls, struct GNUNET_SERVER_Client *client,
2067                         const struct GNUNET_MessageHeader *msg)
2068 {
2069   struct Client *
2070     ctx = GNUNET_SERVER_client_get_user_context (client, struct Client);
2071   GNUNET_assert (NULL != ctx);
2072
2073   struct Place *plc = ctx->plc;
2074
2075   const struct AppDetachRequest *req
2076     = (const struct AppDetachRequest *) msg;
2077
2078   int ret = app_place_remove (ctx->app_id, &plc->ego_pub_key, &req->place_pub_key);
2079   client_send_result (client, req->op_id, ret, NULL, 0);
2080
2081   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2082 }
2083
2084
2085 int
2086 app_places_entry_remove (void *cls, const struct GNUNET_HashCode *key, void *value)
2087 {
2088   struct Place *plc = cls;
2089   const char *app_id = value;
2090   app_place_remove (app_id, &plc->ego_pub_key, &plc->pub_key);
2091   return GNUNET_YES;
2092 }
2093
2094
2095 /**
2096  * Handle application detach request.
2097  */
2098 static void
2099 client_recv_place_leave (void *cls, struct GNUNET_SERVER_Client *client,
2100                          const struct GNUNET_MessageHeader *msg)
2101 {
2102   struct Client *
2103     ctx = GNUNET_SERVER_client_get_user_context (client, struct Client);
2104   GNUNET_assert (NULL != ctx);
2105   struct Place *plc = ctx->plc;
2106
2107   /* FIXME: remove all app subscriptions and leave this place  */
2108
2109   struct GNUNET_CONTAINER_MultiHashMap *
2110     place_apps = GNUNET_CONTAINER_multihashmap_get (places_apps, &plc->pub_key_hash);
2111   if (NULL != place_apps)
2112   {
2113     GNUNET_CONTAINER_multihashmap_iterate (place_apps, app_places_entry_remove, plc);
2114   }
2115
2116   /* FIXME: disconnect from the network, but keep local connection for history access */
2117
2118   /* Disconnect all clients connected to the place */
2119   struct ClientListItem *cli = plc->clients_head, *next;
2120   while (NULL != cli)
2121   {
2122     GNUNET_CONTAINER_DLL_remove (plc->clients_head, plc->clients_tail, cli);
2123     GNUNET_SERVER_client_disconnect (cli->client);
2124     next = cli->next;
2125     GNUNET_free (cli);
2126     cli = next;
2127   }
2128
2129   if (GNUNET_YES != plc->is_disconnected)
2130   {
2131     plc->is_disconnected = GNUNET_YES;
2132     if (NULL != plc->tmit_msgs_head)
2133     { /* Send pending messages to PSYC before cleanup. */
2134       psyc_transmit_message (plc);
2135     }
2136     else
2137     {
2138       cleanup_place (plc);
2139     }
2140   }
2141 }
2142
2143
2144 struct JoinDecisionClosure
2145 {
2146   int32_t is_admitted;
2147   struct GNUNET_PSYC_Message *msg;
2148 };
2149
2150
2151 /**
2152  * Iterator callback for responding to join requests.
2153  */
2154 static int
2155 psyc_send_join_decision (void *cls, const struct GNUNET_HashCode *pub_key_hash,
2156                          void *value)
2157 {
2158   struct JoinDecisionClosure *jcls = cls;
2159   struct GNUNET_PSYC_JoinHandle *jh = value;
2160   // FIXME: add relays
2161   GNUNET_PSYC_join_decision (jh, jcls->is_admitted, 0, NULL, jcls->msg);
2162   return GNUNET_YES;
2163 }
2164
2165
2166 /**
2167  * Handle an entry decision from a host client.
2168  */
2169 static void
2170 client_recv_join_decision (void *cls, struct GNUNET_SERVER_Client *client,
2171                            const struct GNUNET_MessageHeader *msg)
2172 {
2173   struct Client *
2174     ctx = GNUNET_SERVER_client_get_user_context (client, struct Client);
2175   GNUNET_assert (NULL != ctx);
2176   struct Place *plc = ctx->plc;
2177   if (GNUNET_YES != plc->is_host) {
2178     GNUNET_break (0);
2179     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2180     return;
2181   }
2182   struct Host *hst = (struct Host *) plc;
2183
2184   struct GNUNET_PSYC_JoinDecisionMessage *
2185     dcsn = (struct GNUNET_PSYC_JoinDecisionMessage *) msg;
2186   struct JoinDecisionClosure jcls;
2187   jcls.is_admitted = ntohl (dcsn->is_admitted);
2188   jcls.msg
2189     = (sizeof (*dcsn) + sizeof (*jcls.msg) <= ntohs (msg->size))
2190     ? (struct GNUNET_PSYC_Message *) &dcsn[1]
2191     : NULL;
2192
2193   struct GNUNET_HashCode slave_pub_hash;
2194   GNUNET_CRYPTO_hash (&dcsn->slave_pub_key, sizeof (dcsn->slave_pub_key),
2195                       &slave_pub_hash);
2196
2197   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2198               "%p Got join decision (%d) from client for place %s..\n",
2199               hst, jcls.is_admitted, GNUNET_h2s (&plc->pub_key_hash));
2200   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2201               "%p ..and slave %s.\n",
2202               hst, GNUNET_h2s (&slave_pub_hash));
2203
2204   GNUNET_CONTAINER_multihashmap_get_multiple (hst->join_reqs, &slave_pub_hash,
2205                                               &psyc_send_join_decision, &jcls);
2206   GNUNET_CONTAINER_multihashmap_remove_all (hst->join_reqs, &slave_pub_hash);
2207   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2208 }
2209
2210
2211 /**
2212  * Send acknowledgement to a client.
2213  *
2214  * Sent after a message fragment has been passed on to multicast.
2215  *
2216  * @param plc The place struct for the client.
2217  */
2218 static void
2219 send_message_ack (struct Place *plc, struct GNUNET_SERVER_Client *client)
2220 {
2221   struct GNUNET_MessageHeader res;
2222   res.size = htons (sizeof (res));
2223   res.type = htons (GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_ACK);
2224   client_send_msg (client, &res);
2225 }
2226
2227
2228 /**
2229  * Proceed to the next message part in the transmission queue.
2230  *
2231  * @param plc
2232  *        Place where the transmission is going on.
2233  * @param tmit_msg
2234  *        Currently transmitted message.
2235  * @param tmit_frag
2236  *        Currently transmitted message fragment.
2237  *
2238  * @return @a tmit_frag, or NULL if reached the end of fragment.
2239  */
2240 static struct FragmentTransmitQueue *
2241 psyc_transmit_queue_next_part (struct Place *plc,
2242                                struct MessageTransmitQueue *tmit_msg,
2243                                struct FragmentTransmitQueue *tmit_frag)
2244 {
2245   uint16_t psize = ntohs (tmit_frag->next_part->size);
2246   if ((char *) tmit_frag->next_part + psize - ((char *) &tmit_frag[1])
2247       < tmit_frag->size)
2248   {
2249     tmit_frag->next_part
2250       = (struct GNUNET_MessageHeader *) ((char *) tmit_frag->next_part + psize);
2251   }
2252   else /* Reached end of current fragment. */
2253   {
2254     if (NULL != tmit_frag->client)
2255       send_message_ack (plc, tmit_frag->client);
2256     GNUNET_CONTAINER_DLL_remove (tmit_msg->frags_head, tmit_msg->frags_tail, tmit_frag);
2257     GNUNET_free (tmit_frag);
2258     tmit_frag = NULL;
2259   }
2260   return tmit_frag;
2261 }
2262
2263
2264 /**
2265  * Proceed to next message in transmission queue.
2266  *
2267  * @param plc
2268  *        Place where the transmission is going on.
2269  * @param tmit_msg
2270  *        Currently transmitted message.
2271  *
2272  * @return The next message in queue, or NULL if queue is empty.
2273  */
2274 static struct MessageTransmitQueue *
2275 psyc_transmit_queue_next_msg (struct Place *plc,
2276                               struct MessageTransmitQueue *tmit_msg)
2277 {
2278   GNUNET_CONTAINER_DLL_remove (plc->tmit_msgs_head, plc->tmit_msgs_tail, tmit_msg);
2279   GNUNET_free (tmit_msg);
2280   return plc->tmit_msgs_head;
2281 }
2282
2283
2284 /**
2285  * Callback for data transmission to PSYC.
2286  */
2287 static int
2288 psyc_transmit_notify_data (void *cls, uint16_t *data_size, void *data)
2289 {
2290   struct Place *plc = cls;
2291   struct MessageTransmitQueue *tmit_msg = plc->tmit_msgs_head;
2292   GNUNET_assert (NULL != tmit_msg);
2293   struct FragmentTransmitQueue *tmit_frag = tmit_msg->frags_head;
2294   if (NULL == tmit_frag)
2295   { /* Rest of the message have not arrived yet, pause transmission */
2296     *data_size = 0;
2297     return GNUNET_NO;
2298   }
2299   struct GNUNET_MessageHeader *pmsg = tmit_frag->next_part;
2300   if (NULL == pmsg)
2301   {
2302     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2303                 "%p psyc_transmit_notify_data: nothing to send.\n", plc);
2304     *data_size = 0;
2305     return GNUNET_NO;
2306   }
2307
2308   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2309               "%p psyc_transmit_notify_data()\n", plc);
2310   GNUNET_PSYC_log_message (GNUNET_ERROR_TYPE_DEBUG, pmsg);
2311
2312   uint16_t ptype = ntohs (pmsg->type);
2313   uint16_t pdata_size = ntohs (pmsg->size) - sizeof (*pmsg);
2314   int ret;
2315
2316   switch (ptype)
2317   {
2318   case GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_DATA:
2319     if (*data_size < pdata_size)
2320     {
2321       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2322                 "%p psyc_transmit_notify_data: buffer size too small for data.\n", plc);
2323       *data_size = 0;
2324       return GNUNET_NO;
2325     }
2326     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2327                 "%p psyc_transmit_notify_data: sending %u bytes.\n",
2328                 plc, pdata_size);
2329
2330     *data_size = pdata_size;
2331     GNUNET_memcpy (data, &pmsg[1], *data_size);
2332     ret = GNUNET_NO;
2333     break;
2334
2335   case GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_END:
2336     *data_size = 0;
2337     ret = GNUNET_YES;
2338     break;
2339
2340   case GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_CANCEL:
2341     *data_size = 0;
2342     ret = GNUNET_SYSERR;
2343     break;
2344
2345   default:
2346     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2347                 "%p psyc_transmit_notify_data: unexpected message part of type %u.\n",
2348                 plc, ptype);
2349     ret = GNUNET_SYSERR;
2350   }
2351
2352   if (GNUNET_SYSERR == ret && GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_CANCEL != ptype)
2353   {
2354     *data_size = 0;
2355     tmit_msg = psyc_transmit_queue_next_msg (plc, tmit_msg);
2356     plc->is_disconnected = GNUNET_YES;
2357     GNUNET_SERVER_client_disconnect (tmit_frag->client);
2358     GNUNET_SCHEDULER_add_now (&cleanup_place, plc);
2359     return ret;
2360   }
2361   else
2362   {
2363     tmit_frag = psyc_transmit_queue_next_part (plc, tmit_msg, tmit_frag);
2364     if (NULL != tmit_frag)
2365     {
2366       struct GNUNET_MessageHeader *pmsg = tmit_frag->next_part;
2367       ptype = ntohs (pmsg->type);
2368       switch (ptype)
2369       {
2370       case GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_END:
2371         ret = GNUNET_YES;
2372         break;
2373       case GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_CANCEL:
2374         ret = GNUNET_SYSERR;
2375         break;
2376       }
2377       switch (ptype)
2378       {
2379       case GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_END:
2380       case GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_CANCEL:
2381         tmit_frag = psyc_transmit_queue_next_part (plc, tmit_msg, tmit_frag);
2382       }
2383     }
2384
2385     if (NULL == tmit_msg->frags_head
2386         && GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_END <= ptype)
2387     { /* Reached end of current message. */
2388       tmit_msg = psyc_transmit_queue_next_msg (plc, tmit_msg);
2389     }
2390   }
2391
2392   if (ret != GNUNET_NO)
2393   {
2394     if (NULL != tmit_msg)
2395     {
2396       psyc_transmit_message (plc);
2397     }
2398     else if (GNUNET_YES == plc->is_disconnected)
2399     {
2400       /* FIXME: handle partial message (when still in_transmit) */
2401       cleanup_place (plc);
2402     }
2403   }
2404   return ret;
2405 }
2406
2407
2408 /**
2409  * Callback for modifier transmission to PSYC.
2410  */
2411 static int
2412 psyc_transmit_notify_mod (void *cls, uint16_t *data_size, void *data,
2413                           uint8_t *oper, uint32_t *full_value_size)
2414 {
2415   struct Place *plc = cls;
2416   struct MessageTransmitQueue *tmit_msg = plc->tmit_msgs_head;
2417   GNUNET_assert (NULL != tmit_msg);
2418   struct FragmentTransmitQueue *tmit_frag = tmit_msg->frags_head;
2419   if (NULL == tmit_frag)
2420   { /* Rest of the message have not arrived yet, pause transmission */
2421     *data_size = 0;
2422     return GNUNET_NO;
2423   }
2424   struct GNUNET_MessageHeader *pmsg = tmit_frag->next_part;
2425   if (NULL == pmsg)
2426   {
2427     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2428                 "%p psyc_transmit_notify_mod: nothing to send.\n", plc);
2429     *data_size = 0;
2430     return GNUNET_NO;
2431   }
2432
2433   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2434               "%p psyc_transmit_notify_mod()\n", plc);
2435   GNUNET_PSYC_log_message (GNUNET_ERROR_TYPE_DEBUG, pmsg);
2436
2437   uint16_t ptype = ntohs (pmsg->type);
2438   int ret;
2439
2440   switch (ptype)
2441   {
2442   case GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_MODIFIER:
2443   {
2444     if (NULL == oper)
2445     {
2446       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2447                   "%p psyc_transmit_notify_mod: oper is NULL.\n", plc);
2448       ret = GNUNET_SYSERR;
2449       break;
2450     }
2451     struct GNUNET_PSYC_MessageModifier *
2452       pmod = (struct GNUNET_PSYC_MessageModifier *) tmit_frag->next_part;
2453     uint16_t mod_size = ntohs (pmod->header.size) - sizeof (*pmod);
2454
2455     if (*data_size < mod_size)
2456     {
2457       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2458                 "%p psyc_transmit_notify_mod: buffer size too small for data.\n", plc);
2459       *data_size = 0;
2460       return GNUNET_NO;
2461     }
2462
2463     *full_value_size = ntohl (pmod->value_size);
2464     *oper = pmod->oper;
2465     *data_size = mod_size;
2466     GNUNET_memcpy (data, &pmod[1], mod_size);
2467     ret = GNUNET_NO;
2468     break;
2469   }
2470
2471   case GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_MOD_CONT:
2472   {
2473     if (NULL != oper)
2474     {
2475       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2476                   "%p psyc_transmit_notify_mod: oper is not NULL.\n", plc);
2477       ret = GNUNET_SYSERR;
2478       break;
2479     }
2480     uint16_t mod_size = ntohs (pmsg->size) - sizeof (*pmsg);
2481     if (*data_size < mod_size)
2482     {
2483       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2484                 "%p psyc_transmit_notify_mod: buffer size too small for data.\n", plc);
2485       *data_size = 0;
2486       return GNUNET_NO;
2487     }
2488     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2489                 "%p psyc_transmit_notify_mod: sending %u bytes.\n", plc, mod_size);
2490
2491     *data_size = mod_size;
2492     GNUNET_memcpy (data, &pmsg[1], *data_size);
2493     ret = GNUNET_NO;
2494     break;
2495   }
2496
2497   case GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_DATA:
2498   case GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_END:
2499   case GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_CANCEL:
2500     *data_size = 0;
2501     ret = GNUNET_YES;
2502     break;
2503
2504   default:
2505     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2506                 "%p psyc_transmit_notify_mod: unexpected message part of type %u.\n",
2507                 plc, ptype);
2508     ret = GNUNET_SYSERR;
2509   }
2510
2511   if (GNUNET_SYSERR == ret)
2512   {
2513     *data_size = 0;
2514     ret = GNUNET_SYSERR;
2515     tmit_msg = psyc_transmit_queue_next_msg (plc, tmit_msg);
2516     plc->is_disconnected = GNUNET_YES;
2517     GNUNET_SERVER_client_disconnect (tmit_frag->client);
2518     GNUNET_SCHEDULER_add_now (&cleanup_place, plc);
2519   }
2520   else
2521   {
2522     if (GNUNET_YES != ret)
2523       psyc_transmit_queue_next_part (plc, tmit_msg, tmit_frag);
2524
2525     if (NULL == tmit_msg->frags_head
2526         && GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_END <= ptype)
2527     { /* Reached end of current message. */
2528       tmit_msg = psyc_transmit_queue_next_msg (plc, tmit_msg);
2529     }
2530   }
2531   return ret;
2532 }
2533
2534 /**
2535  * Callback for data transmission from a host to PSYC.
2536  */
2537 static int
2538 host_transmit_notify_data (void *cls, uint16_t *data_size, void *data)
2539 {
2540   int ret = psyc_transmit_notify_data (cls, data_size, data);
2541
2542   if (GNUNET_NO != ret)
2543   {
2544     struct Host *hst = cls;
2545     hst->tmit_handle = NULL;
2546   }
2547   return ret;
2548 }
2549
2550
2551 /**
2552  * Callback for the transmit functions of multicast.
2553  */
2554 static int
2555 guest_transmit_notify_data (void *cls, uint16_t *data_size, void *data)
2556 {
2557   int ret = psyc_transmit_notify_data (cls, data_size, data);
2558
2559   if (GNUNET_NO != ret)
2560   {
2561     struct Guest *gst = cls;
2562     gst->tmit_handle = NULL;
2563   }
2564   return ret;
2565 }
2566
2567
2568 /**
2569  * Callback for modifier transmission from a host to PSYC.
2570  */
2571 static int
2572 host_transmit_notify_mod (void *cls, uint16_t *data_size, void *data,
2573                           uint8_t *oper, uint32_t *full_value_size)
2574 {
2575   int ret = psyc_transmit_notify_mod (cls, data_size, data,
2576                                       oper, full_value_size);
2577   if (GNUNET_SYSERR == ret)
2578   {
2579     struct Host *hst = cls;
2580     hst->tmit_handle = NULL;
2581   }
2582   return ret;
2583 }
2584
2585
2586 /**
2587  * Callback for modifier transmission from a guest to PSYC.
2588  */
2589 static int
2590 guest_transmit_notify_mod (void *cls, uint16_t *data_size, void *data,
2591                            uint8_t *oper, uint32_t *full_value_size)
2592 {
2593   int ret = psyc_transmit_notify_mod (cls, data_size, data,
2594                                       oper, full_value_size);
2595   if (GNUNET_SYSERR == ret)
2596   {
2597     struct Guest *gst = cls;
2598     gst->tmit_handle = NULL;
2599   }
2600   return ret;
2601 }
2602
2603
2604 /**
2605  * Get method part of next message from transmission queue.
2606  *
2607  * @param plc
2608  *        Place
2609  *
2610  * @return #GNUNET_OK on success
2611  *         #GNUNET_NO if there are no more messages in queue.
2612  *         #GNUNET_SYSERR if the next message is malformed.
2613  */
2614 static struct GNUNET_PSYC_MessageMethod *
2615 psyc_transmit_queue_next_method (struct Place *plc)
2616 {
2617   struct MessageTransmitQueue *tmit_msg = plc->tmit_msgs_head;
2618   if (NULL == tmit_msg)
2619     return GNUNET_NO;
2620
2621   struct FragmentTransmitQueue *tmit_frag = tmit_msg->frags_head;
2622   if (NULL == tmit_frag)
2623   {
2624     GNUNET_break (0);
2625     return GNUNET_NO;
2626   }
2627
2628   struct GNUNET_MessageHeader *pmsg = tmit_frag->next_part;
2629   if (NULL == pmsg
2630       || GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_METHOD != ntohs (pmsg->type))
2631   {
2632     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2633                 "%p psyc_transmit_queue_next_method: unexpected message part of type %u.\n",
2634                 plc, NULL != pmsg ? ntohs (pmsg->type) : 0);
2635     GNUNET_break (0);
2636     return NULL;
2637   }
2638
2639   uint16_t psize = ntohs (pmsg->size);
2640   struct GNUNET_PSYC_MessageMethod *
2641     pmeth = (struct GNUNET_PSYC_MessageMethod *) GNUNET_copy_message (pmsg);
2642
2643   if (psize < sizeof (*pmeth) + 1 || '\0' != *((char *) pmeth + psize - 1))
2644   {
2645     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2646                 "%p psyc_transmit_queue_next_method: invalid method name.\n",
2647                 plc);
2648     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2649                 "%zu <= %u || NUL != %u\n",
2650                 sizeof (*pmeth), psize, *((char *) pmeth + psize - 1));
2651     GNUNET_break (0);
2652     GNUNET_free (pmeth);
2653     return NULL;
2654   }
2655
2656   psyc_transmit_queue_next_part (plc, tmit_msg, tmit_frag);
2657   return pmeth;
2658 }
2659
2660
2661 /**
2662  * Transmit the next message in queue from the host to the PSYC channel.
2663  */
2664 static int
2665 psyc_master_transmit_message (struct Host *hst)
2666 {
2667   struct Place *plc = &hst->plc;
2668
2669   if (NULL == hst->tmit_handle)
2670   {
2671     struct GNUNET_PSYC_MessageMethod *
2672       pmeth = psyc_transmit_queue_next_method (plc);
2673     if (NULL == pmeth)
2674       return GNUNET_SYSERR;
2675
2676     hst->tmit_handle = (void *) &hst->tmit_handle;
2677     struct GNUNET_PSYC_MasterTransmitHandle *
2678       tmit_handle = GNUNET_PSYC_master_transmit (hst->master, (const char *) &pmeth[1],
2679                                                  &host_transmit_notify_mod,
2680                                                  &host_transmit_notify_data, hst,
2681                                                  pmeth->flags);
2682     if (NULL != hst->tmit_handle)
2683       hst->tmit_handle = tmit_handle;
2684     GNUNET_free (pmeth);
2685   }
2686   else
2687   {
2688     GNUNET_PSYC_master_transmit_resume (hst->tmit_handle);
2689   }
2690   return GNUNET_OK;
2691 }
2692
2693
2694 /**
2695  * Transmit the next message in queue from a guest to the PSYC channel.
2696  */
2697 static int
2698 psyc_slave_transmit_message (struct Guest *gst)
2699 {
2700   struct Place *plc = &gst->plc;
2701
2702   if (NULL == gst->tmit_handle)
2703   {
2704     struct GNUNET_PSYC_MessageMethod *
2705       pmeth = psyc_transmit_queue_next_method (plc);
2706     if (NULL == pmeth)
2707       return GNUNET_SYSERR;
2708
2709     gst->tmit_handle = (void *) &gst->tmit_handle;
2710     struct GNUNET_PSYC_SlaveTransmitHandle *
2711       tmit_handle = GNUNET_PSYC_slave_transmit (gst->slave, (const char *) &pmeth[1],
2712                                                  &guest_transmit_notify_mod,
2713                                                  &guest_transmit_notify_data, gst,
2714                                                  pmeth->flags);
2715     if (NULL != gst->tmit_handle)
2716       gst->tmit_handle = tmit_handle;
2717     GNUNET_free (pmeth);
2718   }
2719   else
2720   {
2721     GNUNET_PSYC_slave_transmit_resume (gst->tmit_handle);
2722   }
2723   return GNUNET_OK;
2724 }
2725
2726
2727 /**
2728  * Transmit a message to PSYC.
2729  */
2730 static int
2731 psyc_transmit_message (struct Place *plc)
2732 {
2733   return
2734     (plc->is_host)
2735     ? psyc_master_transmit_message ((struct Host *) plc)
2736     : psyc_slave_transmit_message ((struct Guest *) plc);
2737 }
2738
2739
2740 /**
2741  * Queue message parts for sending to PSYC.
2742  *
2743  * @param plc          Place to send to.
2744  * @param client       Client the message originates from.
2745  * @param data_size    Size of @a data.
2746  * @param data         Concatenated message parts.
2747  * @param first_ptype  First message part type in @a data.
2748  * @param last_ptype   Last message part type in @a data.
2749  */
2750 static struct MessageTransmitQueue *
2751 psyc_transmit_queue_message (struct Place *plc,
2752                              struct GNUNET_SERVER_Client *client,
2753                              size_t data_size,
2754                              const void *data,
2755                              uint16_t first_ptype, uint16_t last_ptype,
2756                              struct MessageTransmitQueue *tmit_msg)
2757 {
2758   if (GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_METHOD == first_ptype)
2759   {
2760     tmit_msg = GNUNET_malloc (sizeof (*tmit_msg));
2761     GNUNET_CONTAINER_DLL_insert_tail (plc->tmit_msgs_head, plc->tmit_msgs_tail, tmit_msg);
2762   }
2763   else if (NULL == tmit_msg)
2764   {
2765     return NULL;
2766   }
2767
2768   struct FragmentTransmitQueue *
2769     tmit_frag = GNUNET_malloc (sizeof (*tmit_frag) + data_size);
2770   GNUNET_memcpy (&tmit_frag[1], data, data_size);
2771   tmit_frag->next_part = (struct GNUNET_MessageHeader *) &tmit_frag[1];
2772   tmit_frag->client = client;
2773   tmit_frag->size = data_size;
2774
2775   GNUNET_CONTAINER_DLL_insert_tail (tmit_msg->frags_head, tmit_msg->frags_tail, tmit_frag);
2776   tmit_msg->client = client;
2777   return tmit_msg;
2778 }
2779
2780
2781 /**
2782  * Cancel transmission of current message to PSYC.
2783  *
2784  * @param plc     Place to send to.
2785  * @param client  Client the message originates from.
2786  */
2787 static void
2788 psyc_transmit_cancel (struct Place *plc, struct GNUNET_SERVER_Client *client)
2789 {
2790   uint16_t type = GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_CANCEL;
2791
2792   struct GNUNET_MessageHeader msg;
2793   msg.size = htons (sizeof (msg));
2794   msg.type = htons (type);
2795
2796   psyc_transmit_queue_message (plc, client, sizeof (msg), &msg, type, type, NULL);
2797   psyc_transmit_message (plc);
2798
2799   /* FIXME: cleanup */
2800 }
2801
2802
2803 /**
2804  * Handle an incoming message from a client, to be transmitted to the place.
2805  */
2806 static void
2807 client_recv_psyc_message (void *cls, struct GNUNET_SERVER_Client *client,
2808                           const struct GNUNET_MessageHeader *msg)
2809 {
2810   struct Client *
2811     ctx = GNUNET_SERVER_client_get_user_context (client, struct Client);
2812   GNUNET_assert (NULL != ctx);
2813   struct Place *plc = ctx->plc;
2814   int ret = GNUNET_SYSERR;
2815
2816   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2817               "%p Received message from client.\n", plc);
2818   GNUNET_PSYC_log_message (GNUNET_ERROR_TYPE_DEBUG, msg);
2819
2820   if (GNUNET_YES != plc->is_ready)
2821   {
2822     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2823                 "%p Place is not ready yet, disconnecting client.\n", plc);
2824     GNUNET_break (0);
2825     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2826     return;
2827   }
2828
2829   uint16_t size = ntohs (msg->size);
2830   uint16_t psize = size - sizeof (*msg);
2831   if (psize < sizeof (struct GNUNET_MessageHeader)
2832       || GNUNET_MULTICAST_FRAGMENT_MAX_PAYLOAD < psize)
2833   {
2834     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2835                 "%p Received message with invalid payload size (%u) from client.\n",
2836                 plc, psize);
2837     GNUNET_break (0);
2838     psyc_transmit_cancel (plc, client);
2839     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2840     return;
2841   }
2842
2843   uint16_t first_ptype = 0, last_ptype = 0;
2844   if (GNUNET_SYSERR
2845       == GNUNET_PSYC_receive_check_parts (psize, (const char *) &msg[1],
2846                                           &first_ptype, &last_ptype))
2847   {
2848     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2849                 "%p Received invalid message part from client.\n", plc);
2850     GNUNET_break (0);
2851     psyc_transmit_cancel (plc, client);
2852     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2853     return;
2854   }
2855   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2856               "%p Received message with first part type %u and last part type %u.\n",
2857               plc, first_ptype, last_ptype);
2858
2859   ctx->tmit_msg
2860     = psyc_transmit_queue_message (plc, client, psize, &msg[1],
2861                                    first_ptype, last_ptype, ctx->tmit_msg);
2862   if (NULL != ctx->tmit_msg)
2863   {
2864     if (GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_END <= last_ptype)
2865       ctx->tmit_msg = NULL;
2866     ret = psyc_transmit_message (plc);
2867   }
2868
2869   if (GNUNET_OK != ret)
2870   {
2871     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2872                 "%p Received invalid message part from client.\n", plc);
2873     GNUNET_break (0);
2874     psyc_transmit_cancel (plc, client);
2875     ret = GNUNET_SYSERR;
2876   }
2877   GNUNET_SERVER_receive_done (client, ret);
2878 }
2879
2880
2881 /**
2882  * A historic message arrived from PSYC.
2883  */
2884 static void
2885 psyc_recv_history_message (void *cls, const struct GNUNET_PSYC_MessageHeader *msg)
2886 {
2887   struct OperationClosure *opcls = cls;
2888   struct Place *plc = opcls->plc;
2889
2890   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2891               "%p Received historic message #%" PRId64 " (flags: %x)\n",
2892               plc, GNUNET_ntohll (msg->message_id), ntohl (msg->flags));
2893
2894   uint16_t size = ntohs (msg->header.size);
2895
2896   struct GNUNET_OperationResultMessage *
2897     res = GNUNET_malloc (sizeof (*res) + size);
2898   res->header.size = htons (sizeof (*res) + size);
2899   res->header.type = htons (GNUNET_MESSAGE_TYPE_PSYC_HISTORY_RESULT);
2900   res->op_id = opcls->op_id;
2901   res->result_code = GNUNET_htonll (GNUNET_OK);
2902
2903   GNUNET_memcpy (&res[1], msg, size);
2904
2905   /** @todo FIXME: send only to requesting client */
2906   place_send_msg (plc, &res->header);
2907
2908   GNUNET_free (res);
2909 }
2910
2911
2912 /**
2913  * Result of message history replay from PSYC.
2914  */
2915 static void
2916 psyc_recv_history_result (void *cls, int64_t result,
2917                           const void *err_msg, uint16_t err_msg_size)
2918 {
2919   struct OperationClosure *opcls = cls;
2920   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2921               "%p History replay #%" PRIu64 ": "
2922               "PSYCstore returned %" PRId64 " (%.*s)\n",
2923               opcls->plc, GNUNET_ntohll (opcls->op_id), result,
2924               err_msg_size, (const char *) err_msg);
2925
2926   // FIXME: place might have been destroyed
2927   client_send_result (opcls->client, opcls->op_id, result, err_msg, err_msg_size);
2928 }
2929
2930
2931 /**
2932  * Client requests channel history.
2933  */
2934 static void
2935 client_recv_history_replay (void *cls, struct GNUNET_SERVER_Client *client,
2936                             const struct GNUNET_MessageHeader *msg)
2937 {
2938   struct Client *
2939     ctx = GNUNET_SERVER_client_get_user_context (client, struct Client);
2940   GNUNET_assert (NULL != ctx);
2941   struct Place *plc = ctx->plc;
2942
2943   const struct GNUNET_PSYC_HistoryRequestMessage *
2944     req = (const struct GNUNET_PSYC_HistoryRequestMessage *) msg;
2945   uint16_t size = ntohs (msg->size);
2946   const char *method_prefix = (const char *) &req[1];
2947
2948   if (size < sizeof (*req) + 1
2949       || '\0' != method_prefix[size - sizeof (*req) - 1])
2950   {
2951     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2952                 "%p History replay #%" PRIu64 ": "
2953                 "invalid method prefix. size: %u < %zu?\n",
2954                 plc, GNUNET_ntohll (req->op_id), size, sizeof (*req) + 1);
2955     GNUNET_break (0);
2956     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2957     return;
2958   }
2959
2960   struct OperationClosure *opcls = GNUNET_malloc (sizeof (*opcls));
2961   opcls->client = client;
2962   opcls->plc = plc;
2963   opcls->op_id = req->op_id;
2964   opcls->flags = ntohl (req->flags);
2965
2966   if (0 == req->message_limit)
2967     GNUNET_PSYC_channel_history_replay (plc->channel,
2968                                         GNUNET_ntohll (req->start_message_id),
2969                                         GNUNET_ntohll (req->end_message_id),
2970                                         method_prefix, opcls->flags,
2971                                         psyc_recv_history_message, NULL,
2972                                         psyc_recv_history_result, opcls);
2973   else
2974     GNUNET_PSYC_channel_history_replay_latest (plc->channel,
2975                                                GNUNET_ntohll (req->message_limit),
2976                                                method_prefix, opcls->flags,
2977                                                psyc_recv_history_message, NULL,
2978                                                psyc_recv_history_result, opcls);
2979
2980   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2981 }
2982
2983
2984 /**
2985  * A state variable part arrived from PSYC.
2986  */
2987 void
2988 psyc_recv_state_var (void *cls,
2989                      const struct GNUNET_MessageHeader *mod,
2990                      const char *name,
2991                      const void *value,
2992                      uint32_t value_size,
2993                      uint32_t full_value_size)
2994 {
2995   struct OperationClosure *opcls = cls;
2996   struct Place *plc = opcls->plc;
2997
2998   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2999               "%p Received state variable %s from PSYC\n",
3000               plc, name);
3001
3002   uint16_t size = ntohs (mod->size);
3003
3004   struct GNUNET_OperationResultMessage *
3005     res = GNUNET_malloc (sizeof (*res) + size);
3006   res->header.size = htons (sizeof (*res) + size);
3007   res->header.type = htons (GNUNET_MESSAGE_TYPE_PSYC_STATE_RESULT);
3008   res->op_id = opcls->op_id;
3009   res->result_code = GNUNET_htonll (GNUNET_OK);
3010
3011   GNUNET_memcpy (&res[1], mod, size);
3012
3013   /** @todo FIXME: send only to requesting client */
3014   place_send_msg (plc, &res->header);
3015
3016   GNUNET_free (res);
3017 }
3018
3019
3020 /**
3021  * Result of retrieving state variable from PSYC.
3022  */
3023 static void
3024 psyc_recv_state_result (void *cls, int64_t result,
3025                         const void *err_msg, uint16_t err_msg_size)
3026 {
3027   struct OperationClosure *opcls = cls;
3028   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3029               "%p State get #%" PRIu64 ": "
3030               "PSYCstore returned %" PRId64 " (%.*s)\n",
3031               opcls->plc, GNUNET_ntohll (opcls->op_id), result,
3032               err_msg_size, (const char *) err_msg);
3033
3034   // FIXME: place might have been destroyed
3035   client_send_result (opcls->client, opcls->op_id, result, err_msg, err_msg_size);
3036 }
3037
3038
3039 /**
3040  * Client requests channel history.
3041  */
3042 static void
3043 client_recv_state_get (void *cls, struct GNUNET_SERVER_Client *client,
3044                        const struct GNUNET_MessageHeader *msg)
3045 {
3046   struct Client *
3047     ctx = GNUNET_SERVER_client_get_user_context (client, struct Client);
3048   GNUNET_assert (NULL != ctx);
3049   struct Place *plc = ctx->plc;
3050
3051   const struct GNUNET_PSYC_StateRequestMessage *
3052     req = (const struct GNUNET_PSYC_StateRequestMessage *) msg;
3053   uint16_t size = ntohs (msg->size);
3054   const char *name = (const char *) &req[1];
3055
3056   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3057               "%p State get #%" PRIu64 ": %s\n",
3058               plc, GNUNET_ntohll (req->op_id), name);
3059
3060   if (size < sizeof (*req) + 1
3061       || '\0' != name[size - sizeof (*req) - 1])
3062   {
3063     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3064                 "%p State get #%" PRIu64 ": "
3065                 "invalid name. size: %u < %zu?\n",
3066                 plc, GNUNET_ntohll (req->op_id), size, sizeof (*req) + 1);
3067     GNUNET_break (0);
3068     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3069     return;
3070   }
3071
3072   struct OperationClosure *opcls = GNUNET_malloc (sizeof (*opcls));
3073   opcls->client = client;
3074   opcls->plc = plc;
3075   opcls->op_id = req->op_id;
3076
3077   switch (ntohs (msg->type))
3078   {
3079   case GNUNET_MESSAGE_TYPE_PSYC_STATE_GET:
3080       GNUNET_PSYC_channel_state_get (plc->channel, name,
3081                                      psyc_recv_state_var,
3082                                      psyc_recv_state_result, opcls);
3083       break;
3084
3085   case GNUNET_MESSAGE_TYPE_PSYC_STATE_GET_PREFIX:
3086       GNUNET_PSYC_channel_state_get_prefix (plc->channel, name,
3087                                             psyc_recv_state_var,
3088                                             psyc_recv_state_result, opcls);
3089       break;
3090
3091   default:
3092       GNUNET_assert (0);
3093   }
3094
3095   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3096 }
3097
3098
3099 static void
3100 namestore_recv_records_store_result (void *cls, int32_t result,
3101                                      const char *err_msg)
3102 {
3103   struct OperationClosure *ocls = cls;
3104   client_send_result (ocls->client, ocls->op_id, result, err_msg,
3105                       (NULL != err_msg) ? strlen (err_msg) : 0);
3106   GNUNET_free (ocls);
3107 }
3108
3109
3110 /**
3111  * Handle request to add PLACE record to GNS zone.
3112  */
3113 static void
3114 client_recv_zone_add_place (void *cls, struct GNUNET_SERVER_Client *client,
3115                              const struct GNUNET_MessageHeader *msg)
3116 {
3117   const struct ZoneAddPlaceRequest *preq
3118     = (const struct ZoneAddPlaceRequest *) msg;
3119
3120   uint16_t remaining = ntohs (preq->header.size) - sizeof (*preq);
3121   const char *p = (const char *) &preq[1];
3122   const char *name = NULL, *password = NULL;
3123   uint16_t offset = GNUNET_STRINGS_buffer_tokenize (p, remaining, 2,
3124                                                     &name, &password);
3125   remaining -= offset;
3126   p += offset;
3127   const struct GNUNET_PeerIdentity *
3128     relays = (const struct GNUNET_PeerIdentity *) p;
3129   uint16_t relay_size = ntohl (preq->relay_count) * sizeof (*relays);
3130
3131   if (0 == offset || remaining != relay_size)
3132   {
3133     GNUNET_break (0);
3134     client_send_result (client, preq->op_id, GNUNET_SYSERR, NULL, 0);
3135     GNUNET_SERVER_receive_done (client, GNUNET_OK);
3136     return;
3137   }
3138
3139   struct GNUNET_GNSRECORD_Data rd = { };
3140   rd.record_type = GNUNET_GNSRECORD_TYPE_PLACE;
3141   rd.flags = GNUNET_GNSRECORD_RF_RELATIVE_EXPIRATION;
3142   rd.expiration_time = GNUNET_ntohll (preq->expiration_time);
3143
3144   struct GNUNET_GNSRECORD_PlaceData *
3145     rec = GNUNET_malloc (sizeof (*rec) + relay_size);
3146   rec->place_pub_key = preq->place_pub_key;
3147   rec->origin = this_peer;
3148   rec->relay_count = preq->relay_count;
3149   GNUNET_memcpy (&rec[1], relays, relay_size);
3150
3151   rd.data = rec;
3152   rd.data_size = sizeof (*rec) + relay_size;
3153
3154   struct GNUNET_HashCode ego_pub_hash;
3155   GNUNET_CRYPTO_hash (&preq->ego_pub_key, sizeof (preq->ego_pub_key), &ego_pub_hash);
3156   struct Ego *ego = GNUNET_CONTAINER_multihashmap_get (egos, &ego_pub_hash);
3157   if (NULL == ego)
3158   {
3159     client_send_result (client, preq->op_id, GNUNET_SYSERR, NULL, 0);
3160   }
3161   else
3162   {
3163     struct OperationClosure *ocls = GNUNET_malloc (sizeof (*ocls));
3164     ocls->client = client;
3165     ocls->op_id = preq->op_id;
3166     GNUNET_NAMESTORE_records_store (namestore, &ego->key,
3167                                     name, 1, &rd,
3168                                     namestore_recv_records_store_result, ocls);
3169     /** @todo refresh stored records later */
3170   }
3171   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3172 }
3173
3174
3175 /**
3176  * Handle request to add PLACE record to GNS zone.
3177  */
3178 static void
3179 client_recv_zone_add_nym (void *cls, struct GNUNET_SERVER_Client *client,
3180                           const struct GNUNET_MessageHeader *msg)
3181 {
3182   const struct ZoneAddNymRequest *nreq
3183     = (const struct ZoneAddNymRequest *) msg;
3184
3185   uint16_t name_size = ntohs (nreq->header.size) - sizeof (*nreq);
3186   const char *name = NULL;
3187   uint16_t offset = GNUNET_STRINGS_buffer_tokenize ((const char *) &nreq[1],
3188                                                     name_size, 1, &name);
3189   if (0 == offset || offset != name_size)
3190   {
3191     GNUNET_break (0);
3192     client_send_result (client, nreq->op_id, GNUNET_SYSERR, NULL, 0);
3193     GNUNET_SERVER_receive_done (client, GNUNET_OK);
3194     return;
3195   }
3196
3197   struct GNUNET_GNSRECORD_Data rd = { };
3198   rd.record_type = GNUNET_GNSRECORD_TYPE_PKEY;
3199   rd.flags = GNUNET_GNSRECORD_RF_RELATIVE_EXPIRATION;
3200   rd.expiration_time = GNUNET_ntohll (nreq->expiration_time);
3201   rd.data = &nreq->nym_pub_key;
3202   rd.data_size = sizeof (nreq->nym_pub_key);
3203
3204   struct GNUNET_HashCode ego_pub_hash;
3205   GNUNET_CRYPTO_hash (&nreq->ego_pub_key, sizeof (nreq->ego_pub_key), &ego_pub_hash);
3206   struct Ego *ego = GNUNET_CONTAINER_multihashmap_get (egos, &ego_pub_hash);
3207   if (NULL == ego)
3208   {
3209     client_send_result (client, nreq->op_id, GNUNET_SYSERR, NULL, 0);
3210   }
3211   else
3212   {
3213     struct OperationClosure *ocls = GNUNET_malloc (sizeof (*ocls));
3214     ocls->client = client;
3215     ocls->op_id = nreq->op_id;
3216     GNUNET_NAMESTORE_records_store (namestore, &ego->key,
3217                                     name, 1, &rd,
3218                                     namestore_recv_records_store_result, ocls);
3219     /** @todo refresh stored records later */
3220   }
3221   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3222 }
3223
3224
3225 static const struct GNUNET_SERVER_MessageHandler handlers[] = {
3226   { client_recv_host_enter, NULL,
3227     GNUNET_MESSAGE_TYPE_SOCIAL_HOST_ENTER, 0 },
3228
3229   { client_recv_guest_enter, NULL,
3230     GNUNET_MESSAGE_TYPE_SOCIAL_GUEST_ENTER, 0 },
3231
3232   { client_recv_guest_enter_by_name, NULL,
3233     GNUNET_MESSAGE_TYPE_SOCIAL_GUEST_ENTER_BY_NAME, 0 },
3234
3235   { client_recv_join_decision, NULL,
3236     GNUNET_MESSAGE_TYPE_PSYC_JOIN_DECISION, 0 },
3237
3238   { client_recv_psyc_message, NULL,
3239     GNUNET_MESSAGE_TYPE_PSYC_MESSAGE, 0 },
3240
3241   { client_recv_history_replay, NULL,
3242     GNUNET_MESSAGE_TYPE_PSYC_HISTORY_REPLAY, 0 },
3243
3244   { client_recv_state_get, NULL,
3245     GNUNET_MESSAGE_TYPE_PSYC_STATE_GET, 0 },
3246
3247   { client_recv_state_get, NULL,
3248     GNUNET_MESSAGE_TYPE_PSYC_STATE_GET_PREFIX, 0 },
3249
3250   { client_recv_zone_add_place, NULL,
3251     GNUNET_MESSAGE_TYPE_SOCIAL_ZONE_ADD_PLACE, 0 },
3252
3253   { client_recv_zone_add_nym, NULL,
3254     GNUNET_MESSAGE_TYPE_SOCIAL_ZONE_ADD_NYM, 0 },
3255
3256   { client_recv_app_connect, NULL,
3257     GNUNET_MESSAGE_TYPE_SOCIAL_APP_CONNECT, 0 },
3258
3259   { client_recv_app_detach, NULL,
3260     GNUNET_MESSAGE_TYPE_SOCIAL_APP_DETACH, 0 },
3261
3262   { client_recv_place_leave, NULL,
3263     GNUNET_MESSAGE_TYPE_SOCIAL_PLACE_LEAVE, 0 },
3264
3265   { client_recv_msg_proc_set, NULL,
3266     GNUNET_MESSAGE_TYPE_SOCIAL_MSG_PROC_SET, 0 },
3267
3268   { client_recv_msg_proc_clear, NULL,
3269     GNUNET_MESSAGE_TYPE_SOCIAL_MSG_PROC_CLEAR, 0 },
3270
3271   { NULL, NULL, 0, 0 }
3272 };
3273
3274
3275 const char *
3276 path_basename (const char *path)
3277 {
3278   const char *basename = strrchr (path, DIR_SEPARATOR);
3279   if (NULL != basename)
3280     basename++;
3281
3282   if (NULL == basename || '\0' == basename)
3283     return NULL;
3284
3285   return basename;
3286 }
3287
3288
3289 struct PlaceLoadClosure
3290 {
3291   const char *app_id;
3292   const char *ego_pub_str;
3293 };
3294
3295
3296 /** Load a place file */
3297 int
3298 file_place_load (void *cls, const char *place_filename)
3299 {
3300   struct PlaceLoadClosure *plcls = cls;
3301
3302   const char *place_pub_str = path_basename (place_filename);
3303   if (NULL == place_pub_str)
3304   {
3305     GNUNET_break (0);
3306     return GNUNET_OK;
3307   }
3308
3309   char *filename = NULL;
3310   GNUNET_asprintf (&filename, "%s%c" "%s%c" "%s%c" "%s",
3311                    dir_social, DIR_SEPARATOR,
3312                    "places", DIR_SEPARATOR,
3313                    plcls->ego_pub_str, DIR_SEPARATOR,
3314                    place_pub_str);
3315
3316   uint64_t file_size = 0;
3317   if (GNUNET_OK !=
3318       GNUNET_DISK_file_size (filename, &file_size, GNUNET_YES, GNUNET_YES)
3319       || file_size < sizeof (struct PlaceEnterRequest))
3320   {
3321     GNUNET_free (filename);
3322     return GNUNET_OK;
3323   }
3324
3325   struct PlaceEnterRequest *ereq = GNUNET_malloc (file_size);
3326   ssize_t read_size = GNUNET_DISK_fn_read (filename, ereq, file_size);
3327   GNUNET_free (filename);
3328   if (read_size < 0 || read_size < sizeof (*ereq))
3329   {
3330     GNUNET_free (ereq);
3331     return GNUNET_OK;
3332   }
3333
3334   uint16_t ereq_size = ntohs (ereq->header.size);
3335   if (read_size != ereq_size)
3336   {
3337     GNUNET_free (ereq);
3338     return GNUNET_OK;
3339   }
3340
3341   switch (ntohs (ereq->header.type))
3342   {
3343   case GNUNET_MESSAGE_TYPE_SOCIAL_HOST_ENTER:
3344     if (ereq_size < sizeof (struct HostEnterRequest))
3345     {
3346       GNUNET_free (ereq);
3347       return GNUNET_OK;
3348     }
3349     struct HostEnterRequest *hreq = (struct HostEnterRequest *) ereq;
3350     host_enter (hreq, NULL);
3351     break;
3352
3353   case GNUNET_MESSAGE_TYPE_SOCIAL_GUEST_ENTER:
3354     if (ereq_size < sizeof (struct GuestEnterRequest))
3355     {
3356       GNUNET_free (ereq);
3357       return GNUNET_OK;
3358     }
3359     struct GuestEnterRequest *greq = (struct GuestEnterRequest *) ereq;
3360     guest_enter (greq, NULL);
3361     break;
3362
3363   default:
3364     GNUNET_free (ereq);
3365     return GNUNET_OK;
3366   }
3367
3368   app_place_add (plcls->app_id, ereq);
3369   GNUNET_free (ereq);
3370   return GNUNET_OK;
3371 }
3372
3373
3374 /**
3375  * Read @e place_pub_str entries in @a dir_ego
3376  *
3377  * @param dir_ego
3378  *        Data directory of an application ego.
3379  *        $GNUNET_DATA_HOME/social/apps/$app_id/$ego_pub_str/
3380  */
3381 int
3382 scan_app_ego_dir (void *cls, const char *dir_ego)
3383 {
3384   struct PlaceLoadClosure *plcls = cls;
3385   plcls->ego_pub_str = path_basename (dir_ego);
3386
3387   if (NULL != plcls->ego_pub_str)
3388     GNUNET_DISK_directory_scan (dir_ego, file_place_load, plcls);
3389
3390   return GNUNET_OK;
3391 }
3392
3393 /**
3394  * Read @e ego_pub_str entries in @a dir_app
3395  *
3396  * @param dir_app
3397  *        Data directory of an application.
3398  *        $GNUNET_DATA_HOME/social/apps/$app_id/
3399  */
3400 int
3401 scan_app_dir (void *cls, const char *dir_app)
3402 {
3403   if (GNUNET_YES != GNUNET_DISK_directory_test (dir_app, GNUNET_YES))
3404     return GNUNET_OK;
3405
3406   struct PlaceLoadClosure plcls;
3407   plcls.app_id = path_basename (dir_app);
3408
3409   if (NULL != plcls.app_id)
3410     GNUNET_DISK_directory_scan (dir_app, scan_app_ego_dir, &plcls);
3411
3412   return GNUNET_OK;
3413 }
3414
3415
3416 static void
3417 identity_recv_ego (void *cls, struct GNUNET_IDENTITY_Ego *id_ego,
3418                    void **ctx, const char *name)
3419 {
3420   if (NULL == id_ego) // end of initial list of egos
3421     return;
3422
3423   struct GNUNET_CRYPTO_EcdsaPublicKey ego_pub_key;
3424   GNUNET_IDENTITY_ego_get_public_key (id_ego, &ego_pub_key);
3425
3426   struct GNUNET_HashCode ego_pub_hash;
3427   GNUNET_CRYPTO_hash (&ego_pub_key, sizeof (ego_pub_key), &ego_pub_hash);
3428
3429   struct Ego *ego = GNUNET_CONTAINER_multihashmap_get (egos, &ego_pub_hash);
3430   if (NULL != ego)
3431   {
3432     GNUNET_free (ego->name);
3433     if (NULL == name) // deleted
3434     {
3435       GNUNET_CONTAINER_multihashmap_remove (egos, &ego_pub_hash, ego);
3436       GNUNET_free (ego);
3437       ego = NULL;
3438     }
3439   }
3440   else
3441   {
3442     ego = GNUNET_malloc (sizeof (*ego));
3443   }
3444   if (NULL != ego)
3445   {
3446     ego->key = *(GNUNET_IDENTITY_ego_get_private_key (id_ego));
3447     size_t name_size = strlen (name) + 1;
3448     ego->name = GNUNET_malloc (name_size);
3449     GNUNET_memcpy (ego->name, name, name_size);
3450
3451     GNUNET_CONTAINER_multihashmap_put (egos, &ego_pub_hash, ego,
3452                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
3453   }
3454
3455   // FIXME: notify clients about changed ego
3456 }
3457
3458
3459 /**
3460  * Connected to core service.
3461  */
3462 static void
3463 core_connected (void *cls, const struct GNUNET_PeerIdentity *my_identity)
3464 {
3465   this_peer = *my_identity;
3466 }
3467
3468
3469 /**
3470  * Initialize the PSYC service.
3471  *
3472  * @param cls Closure.
3473  * @param server The initialized server.
3474  * @param c Configuration to use.
3475  */
3476 static void
3477 run (void *cls, struct GNUNET_SERVER_Handle *server,
3478      const struct GNUNET_CONFIGURATION_Handle *c)
3479 {
3480   cfg = c;
3481
3482   hosts = GNUNET_CONTAINER_multihashmap_create (1, GNUNET_YES);
3483   guests = GNUNET_CONTAINER_multihashmap_create (1, GNUNET_YES);
3484   place_guests = GNUNET_CONTAINER_multihashmap_create (1, GNUNET_NO);
3485
3486   egos = GNUNET_CONTAINER_multihashmap_create (1, GNUNET_NO);
3487   apps = GNUNET_CONTAINER_multihashmap_create (1, GNUNET_NO);
3488   places = GNUNET_CONTAINER_multihashmap_create(1, GNUNET_NO);
3489   apps_places = GNUNET_CONTAINER_multihashmap_create(1, GNUNET_NO);
3490   places_apps = GNUNET_CONTAINER_multihashmap_create(1, GNUNET_NO);
3491
3492   core = GNUNET_CORE_connect (cfg, NULL, core_connected, NULL, NULL,
3493                               NULL, GNUNET_NO, NULL, GNUNET_NO, NULL);
3494   id = GNUNET_IDENTITY_connect (cfg, &identity_recv_ego, NULL);
3495   gns = GNUNET_GNS_connect (cfg);
3496   namestore = GNUNET_NAMESTORE_connect (cfg);
3497   stats = GNUNET_STATISTICS_create ("social", cfg);
3498
3499   if (GNUNET_OK !=
3500       GNUNET_CONFIGURATION_get_value_filename (cfg, "social", "DATA_HOME",
3501                                                &dir_social))
3502   {
3503     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
3504                                "social", "DATA_HOME");
3505     GNUNET_break (0);
3506     return;
3507   }
3508   GNUNET_asprintf (&dir_places, "%s%c%s",
3509                    dir_social, DIR_SEPARATOR, "places");
3510   GNUNET_asprintf (&dir_apps, "%s%c%s",
3511                    dir_social, DIR_SEPARATOR, "apps");
3512
3513   GNUNET_DISK_directory_scan (dir_apps, scan_app_dir, NULL);
3514
3515   nc = GNUNET_SERVER_notification_context_create (server, 1);
3516   GNUNET_SERVER_add_handlers (server, handlers);
3517   GNUNET_SERVER_disconnect_notify (server, &client_disconnect, NULL);
3518   GNUNET_SCHEDULER_add_shutdown (&shutdown_task, NULL);
3519 }
3520
3521
3522 /**
3523  * The main function for the service.
3524  *
3525  * @param argc number of arguments from the command line
3526  * @param argv command line arguments
3527  * @return 0 ok, 1 on error
3528  */
3529 int
3530 main (int argc, char *const *argv)
3531 {
3532   return (GNUNET_OK ==
3533           GNUNET_SERVICE_run (argc, argv, "social",
3534                               GNUNET_SERVICE_OPTION_NONE,
3535                               &run, NULL)) ? 0 : 1;
3536 }
3537
3538 /* end of gnunet-service-social.c */