leaks & warns
[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     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
813                 "FIXME: last message was unfinished.\n");
814   }
815
816   tmit_msg = psyc_transmit_queue_message (&hst->plc, NULL, ntohs (pmsg->size),
817                                           pmsg, ptype, ptype, tmit_msg);
818
819   switch (ptype)
820   {
821   case GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_METHOD:
822     GNUNET_assert (GNUNET_YES == GNUNET_CONTAINER_multihashmap_put
823                                       (hst->relay_msgs, &nym_pub_hash, tmit_msg,
824                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
825     break;
826   case GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_END:
827   case GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_CANCEL:
828     GNUNET_assert (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove
829                                      (hst->relay_msgs, &nym_pub_hash, tmit_msg));
830     break;
831   }
832 }
833
834
835 /**
836  * Received a method to be relayed from a guest.
837  */
838 static void
839 place_recv_relay_method (void *cls,
840                          const struct GNUNET_PSYC_MessageHeader *msg,
841                          const struct GNUNET_PSYC_MessageMethod *meth,
842                          uint64_t message_id,
843                          const char *method_name)
844 {
845   struct Place *plc = cls;
846
847   if (GNUNET_PSYC_MESSAGE_REQUEST & ntohs (msg->flags)
848       && GNUNET_YES == plc->is_host)
849   {
850     struct Host *hst = cls;
851     host_relay_message_part (hst, &meth->header, &msg->slave_pub_key);
852   }
853 }
854
855
856 /**
857  * Received a modifier to be relayed from a guest.
858  */
859 static void
860 place_recv_relay_modifier (void *cls,
861                            const struct GNUNET_PSYC_MessageHeader *msg,
862                            const struct GNUNET_MessageHeader *pmsg,
863                            uint64_t message_id,
864                            enum GNUNET_PSYC_Operator oper,
865                            const char *name,
866                            const void *value,
867                            uint16_t value_size,
868                            uint16_t full_value_size)
869 {
870   struct Place *plc = cls;
871
872   if (GNUNET_PSYC_MESSAGE_REQUEST & ntohs (msg->flags)
873       && GNUNET_YES == plc->is_host)
874   {
875     struct Host *hst = cls;
876     host_relay_message_part (hst, pmsg, &msg->slave_pub_key);
877   }
878 }
879
880 /**
881  * Received a data fragment to be relayed from a guest.
882  */
883 static void
884 place_recv_relay_data (void *cls,
885                        const struct GNUNET_PSYC_MessageHeader *msg,
886                        const struct GNUNET_MessageHeader *pmsg,
887                        uint64_t message_id,
888                        const void *data,
889                        uint16_t data_size)
890 {
891   struct Place *plc = cls;
892
893   if (GNUNET_PSYC_MESSAGE_REQUEST & ntohs (msg->flags)
894       && GNUNET_YES == plc->is_host)
895   {
896     struct Host *hst = cls;
897     host_relay_message_part (hst, pmsg, &msg->slave_pub_key);
898   }
899 }
900
901
902 /**
903  * Received end of message to be relayed from a guest.
904  */
905 static void
906 place_recv_relay_eom (void *cls,
907                       const struct GNUNET_PSYC_MessageHeader *msg,
908                       const struct GNUNET_MessageHeader *pmsg,
909                       uint64_t message_id,
910                       uint8_t is_cancelled)
911 {
912   struct Place *plc = cls;
913
914   if (GNUNET_PSYC_MESSAGE_REQUEST & ntohs (msg->flags)
915       && GNUNET_YES == plc->is_host)
916   {
917     struct Host *hst = cls;
918     host_relay_message_part (hst, pmsg, &msg->slave_pub_key);
919   }
920 }
921
922
923 /**
924  * Received a method to be saved to disk.
925  *
926  * Create a new file for writing the data part of the message into,
927  * if the file does not yet exist.
928  */
929 static void
930 place_recv_save_method (void *cls,
931                         const struct GNUNET_PSYC_MessageHeader *msg,
932                         const struct GNUNET_PSYC_MessageMethod *meth,
933                         uint64_t message_id,
934                         const char *method_name)
935 {
936   struct Place *plc = cls;
937   plc->file_offset = 0;
938   plc->file_save = GNUNET_NO;
939
940   char *place_pub_str = GNUNET_CRYPTO_eddsa_public_key_to_string (&plc->pub_key);
941   char *filename = NULL;
942   GNUNET_asprintf (&filename, "%s%c" "%s%c" "%s%c" "%" PRIu64 ".part",
943                    dir_social, DIR_SEPARATOR,
944                    "files", DIR_SEPARATOR,
945                    place_pub_str, DIR_SEPARATOR,
946                    GNUNET_ntohll (msg->message_id));
947   GNUNET_free (place_pub_str);
948
949   /* save if does not already exist */
950   if (GNUNET_YES != GNUNET_DISK_file_test (filename))
951   {
952     if (0 == GNUNET_DISK_fn_write (filename, NULL, 0,
953                                    GNUNET_DISK_PERM_USER_READ
954                                    | GNUNET_DISK_PERM_USER_WRITE))
955     {
956       plc->file_save = GNUNET_YES;
957     }
958     else
959     {
960       GNUNET_break (0);
961     }
962   }
963   GNUNET_free (filename);
964 }
965
966
967 /**
968  * Received a data fragment to be saved to disk.
969  *
970  * Append data fragment to the file.
971  */
972 static void
973 place_recv_save_data (void *cls,
974                       const struct GNUNET_PSYC_MessageHeader *msg,
975                       const struct GNUNET_MessageHeader *pmsg,
976                       uint64_t message_id,
977                       const void *data,
978                       uint16_t data_size)
979 {
980   struct Place *plc = cls;
981   if (GNUNET_YES != plc->file_save)
982     return;
983
984   char *place_pub_str = GNUNET_CRYPTO_eddsa_public_key_to_string (&plc->pub_key);
985   char *filename = NULL;
986   GNUNET_asprintf (&filename, "%s%c" "%s%c" "%s%c" "%" PRIu64 ".part",
987                    dir_social, DIR_SEPARATOR,
988                    "files", DIR_SEPARATOR,
989                    place_pub_str, DIR_SEPARATOR,
990                    GNUNET_ntohll (msg->message_id));
991   GNUNET_free (place_pub_str);
992   if (GNUNET_SYSERR == GNUNET_DISK_directory_create_for_file (filename))
993   {
994     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "create", filename);
995     GNUNET_free (filename);
996     return;
997   }
998
999   struct GNUNET_DISK_FileHandle *
1000     fh = GNUNET_DISK_file_open (filename, GNUNET_DISK_OPEN_WRITE,
1001                                 GNUNET_DISK_PERM_NONE);
1002   if (NULL != fh)
1003   {
1004     if (plc->file_offset != GNUNET_DISK_file_seek
1005                             (fh, plc->file_offset, GNUNET_DISK_SEEK_SET)) {
1006       GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "seek", filename);
1007       GNUNET_DISK_file_close (fh);
1008       GNUNET_free (filename);
1009       return;
1010     }
1011     GNUNET_DISK_file_write (fh, data, data_size);
1012     GNUNET_DISK_file_close (fh);
1013     GNUNET_free (filename);
1014   }
1015   else
1016   {
1017     GNUNET_free (filename);
1018     GNUNET_break (0);
1019   }
1020   plc->file_offset += data_size;
1021 }
1022
1023
1024 /**
1025  * Received end of message to be saved to disk.
1026  *
1027  * Remove .part ending from the filename.
1028  */
1029 static void
1030 place_recv_save_eom (void *cls,
1031                      const struct GNUNET_PSYC_MessageHeader *msg,
1032                      const struct GNUNET_MessageHeader *pmsg,
1033                      uint64_t message_id,
1034                      uint8_t is_cancelled)
1035 {
1036   struct Place *plc = cls;
1037   if (GNUNET_YES != plc->file_save)
1038     return;
1039
1040   char *place_pub_str = GNUNET_CRYPTO_eddsa_public_key_to_string (&plc->pub_key);
1041   char *fn = NULL;
1042   GNUNET_asprintf (&fn, "%s%c%s%c%s%c%" PRIu64,
1043                    dir_social, DIR_SEPARATOR,
1044                    "files", DIR_SEPARATOR,
1045                    place_pub_str, DIR_SEPARATOR,
1046                    GNUNET_ntohll (msg->message_id));
1047   GNUNET_free (place_pub_str);
1048   char *fn_part = NULL;
1049   GNUNET_asprintf (&fn_part, "%s.part", fn);
1050
1051   if (rename (fn_part, fn)) {
1052       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1053                   "Failed to rename %s into %s: %s (%d)\n",
1054                   fn_part, fn, strerror (errno), errno);
1055   }
1056
1057   GNUNET_free (fn);
1058   GNUNET_free (fn_part);
1059 }
1060
1061
1062 /**
1063  * Initialize place data structure.
1064  */
1065 static void
1066 place_init (struct Place *plc)
1067 {
1068   plc->slicer = GNUNET_PSYC_slicer_create ();
1069 }
1070
1071
1072 /**
1073  * Add a place to the @e places hash map.
1074  *
1075  * @param ereq
1076  *        Entry request.
1077  *
1078  * @return #GNUNET_OK if the place was added
1079  *         #GNUNET_NO if the place already exists in the hash map
1080  *         #GNUNET_SYSERR on error
1081  */
1082 static int
1083 place_add (const struct PlaceEnterRequest *ereq)
1084 {
1085   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1086               "Adding place to hashmap:\n");
1087
1088   struct EgoPlacePublicKey ego_place_pub_key = {
1089     .ego_pub_key = ereq->ego_pub_key,
1090     .place_pub_key = ereq->place_pub_key,
1091   };
1092   struct GNUNET_HashCode ego_place_pub_hash;
1093   GNUNET_CRYPTO_hash (&ego_place_pub_key, sizeof (ego_place_pub_key), &ego_place_pub_hash);
1094
1095   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1096               "  ego_place_pub_hash = %s\n", GNUNET_h2s (&ego_place_pub_hash));
1097
1098   struct GNUNET_MessageHeader *
1099     place_msg = GNUNET_CONTAINER_multihashmap_get (places, &ego_place_pub_hash);
1100   if (NULL != place_msg)
1101     return GNUNET_NO;
1102
1103   place_msg = GNUNET_copy_message (&ereq->header);
1104   if (GNUNET_OK != GNUNET_CONTAINER_multihashmap_put (places, &ego_place_pub_hash, place_msg,
1105                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
1106   {
1107     GNUNET_break (0);
1108     GNUNET_free (place_msg);
1109     return GNUNET_SYSERR;
1110   }
1111
1112   return GNUNET_OK;
1113 }
1114
1115 /**
1116  * Add a place to the @e app_places hash map.
1117  *
1118  * @param app_id
1119  *        Application ID.
1120  * @param ereq
1121  *        Entry request.
1122  *
1123  * @return #GNUNET_OK if the place was added
1124  *         #GNUNET_NO if the place already exists in the hash map
1125  *         #GNUNET_SYSERR on error
1126  */
1127 static int
1128 app_place_add (const char *app_id,
1129                const struct PlaceEnterRequest *ereq)
1130 {
1131   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1132               "Adding app place to hashmap:\n");
1133   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1134               "  app_id = %s\n", app_id);
1135
1136   struct GNUNET_HashCode app_id_hash;
1137   GNUNET_CRYPTO_hash (app_id, strlen (app_id) + 1, &app_id_hash);
1138
1139   struct EgoPlacePublicKey ego_place_pub_key = {
1140     .ego_pub_key = ereq->ego_pub_key,
1141     .place_pub_key = ereq->place_pub_key,
1142   };
1143   struct GNUNET_HashCode ego_place_pub_hash;
1144   GNUNET_CRYPTO_hash (&ego_place_pub_key, sizeof (ego_place_pub_key), &ego_place_pub_hash);
1145
1146   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1147               "  ego_place_pub_hash = %s\n", GNUNET_h2s (&ego_place_pub_hash));
1148
1149   struct GNUNET_CONTAINER_MultiHashMap *
1150     app_places = GNUNET_CONTAINER_multihashmap_get (apps_places, &app_id_hash);
1151   if (NULL == app_places)
1152   {
1153     app_places = GNUNET_CONTAINER_multihashmap_create (1, GNUNET_NO);
1154     GNUNET_CONTAINER_multihashmap_put (apps_places, &app_id_hash, app_places,
1155                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
1156   }
1157
1158   if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains (app_places, &ego_place_pub_hash))
1159     return GNUNET_NO;
1160
1161   if (GNUNET_SYSERR == place_add (ereq))
1162     return GNUNET_SYSERR;
1163
1164   if (GNUNET_OK != GNUNET_CONTAINER_multihashmap_put (app_places, &ego_place_pub_hash, NULL,
1165                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
1166   {
1167     GNUNET_break (0);
1168     return GNUNET_SYSERR;
1169   }
1170
1171   struct GNUNET_HashCode place_pub_hash;
1172   GNUNET_CRYPTO_hash (&ereq->place_pub_key, sizeof (ereq->place_pub_key), &place_pub_hash);
1173
1174   struct GNUNET_CONTAINER_MultiHashMap *
1175     place_apps = GNUNET_CONTAINER_multihashmap_get (places_apps, &place_pub_hash);
1176   if (NULL == place_apps)
1177   {
1178     place_apps = GNUNET_CONTAINER_multihashmap_create (1, GNUNET_NO);
1179     if (GNUNET_OK != GNUNET_CONTAINER_multihashmap_put (places_apps, &place_pub_hash, place_apps,
1180                                                         GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
1181     {
1182       GNUNET_break (0);
1183     }
1184   }
1185
1186   size_t app_id_size = strlen (app_id) + 1;
1187   void *app_id_value = GNUNET_malloc (app_id_size);
1188   GNUNET_memcpy (app_id_value, app_id, app_id_size);
1189
1190   if (GNUNET_OK != GNUNET_CONTAINER_multihashmap_put (place_apps, &app_id_hash, app_id_value,
1191                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
1192   {
1193     GNUNET_break (0);
1194   }
1195
1196   return GNUNET_OK;
1197 }
1198
1199
1200 /**
1201  * Save place entry message to disk.
1202  *
1203  * @param app_id
1204  *        Application ID.
1205  * @param ereq
1206  *        Entry request message.
1207  */
1208 static int
1209 app_place_save (const char *app_id,
1210                 const struct PlaceEnterRequest *ereq)
1211 {
1212   app_place_add (app_id, ereq);
1213
1214   if (NULL == dir_places)
1215     return GNUNET_SYSERR;
1216
1217   char *ego_pub_str = GNUNET_CRYPTO_ecdsa_public_key_to_string (&ereq->ego_pub_key);
1218   char *place_pub_str = GNUNET_CRYPTO_eddsa_public_key_to_string (&ereq->place_pub_key);
1219   char *filename = NULL;
1220   GNUNET_asprintf (&filename, "%s%c" "%s%c" "%s%c" "%s",
1221                    dir_social, DIR_SEPARATOR,
1222                    "places", DIR_SEPARATOR,
1223                    ego_pub_str, DIR_SEPARATOR,
1224                    place_pub_str);
1225   int ret = GNUNET_DISK_directory_create_for_file (filename);
1226   if (GNUNET_OK != ret
1227       || 0 > GNUNET_DISK_fn_write (filename, ereq, ntohs (ereq->header.size),
1228                                    GNUNET_DISK_PERM_USER_READ
1229                                    | GNUNET_DISK_PERM_USER_WRITE))
1230   {
1231     GNUNET_break (0);
1232     ret = GNUNET_SYSERR;
1233   }
1234   GNUNET_free (filename);
1235
1236   if (ret == GNUNET_OK)
1237   {
1238     GNUNET_asprintf (&filename, "%s%c" "%s%c" "%s%c" "%s%c" "%s",
1239                      dir_social, DIR_SEPARATOR,
1240                      "apps", DIR_SEPARATOR,
1241                      app_id, DIR_SEPARATOR,
1242                      ego_pub_str, DIR_SEPARATOR,
1243                      place_pub_str);
1244     ret = GNUNET_DISK_directory_create_for_file (filename);
1245     if (GNUNET_OK != ret
1246         || 0 > GNUNET_DISK_fn_write (filename, "", 0,
1247                                      GNUNET_DISK_PERM_USER_READ
1248                                      | GNUNET_DISK_PERM_USER_WRITE))
1249     {
1250       GNUNET_break (0);
1251       ret = GNUNET_SYSERR;
1252     }
1253     GNUNET_free (filename);
1254   }
1255   GNUNET_free (ego_pub_str);
1256   GNUNET_free (place_pub_str);
1257   return ret;
1258 }
1259
1260
1261 int
1262 app_place_remove (const char *app_id,
1263                   const struct GNUNET_CRYPTO_EcdsaPublicKey *ego_pub_key,
1264                   const struct GNUNET_CRYPTO_EddsaPublicKey *place_pub_key)
1265 {
1266   struct GNUNET_HashCode ego_pub_hash;
1267   struct GNUNET_HashCode place_pub_hash;
1268   GNUNET_CRYPTO_hash (ego_pub_key, sizeof (*ego_pub_key), &ego_pub_hash);
1269   GNUNET_CRYPTO_hash (place_pub_key, sizeof (*place_pub_key), &place_pub_hash);
1270
1271   char *ego_pub_str = GNUNET_CRYPTO_ecdsa_public_key_to_string (ego_pub_key);
1272   char *place_pub_str = GNUNET_CRYPTO_eddsa_public_key_to_string (place_pub_key);
1273   char *app_place_filename = NULL;
1274   GNUNET_asprintf (&app_place_filename,
1275                    "%s%c" "%s%c" "%s%c" "%s%c" "%s",
1276                    dir_social, DIR_SEPARATOR,
1277                    "apps", DIR_SEPARATOR,
1278                    app_id, DIR_SEPARATOR,
1279                    ego_pub_str, DIR_SEPARATOR,
1280                    place_pub_str);
1281   GNUNET_free (ego_pub_str);
1282   GNUNET_free (place_pub_str);
1283
1284   struct GNUNET_HashCode app_id_hash;
1285   GNUNET_CRYPTO_hash (app_id, strlen (app_id) + 1, &app_id_hash);
1286
1287   struct GNUNET_CONTAINER_MultiHashMap *
1288     app_places = GNUNET_CONTAINER_multihashmap_get (apps_places, &app_id_hash);
1289
1290   if (NULL != app_places)
1291     GNUNET_CONTAINER_multihashmap_remove (app_places, &place_pub_hash, NULL);
1292
1293   struct GNUNET_CONTAINER_MultiHashMap *
1294     place_apps = GNUNET_CONTAINER_multihashmap_get (places_apps, &place_pub_hash);
1295   if (NULL != place_apps)
1296   {
1297     void *app_id_value = GNUNET_CONTAINER_multihashmap_get (place_apps, &app_id_hash);
1298     if (NULL != app_id_value)
1299     {
1300       GNUNET_CONTAINER_multihashmap_remove (place_apps, &app_id_hash, app_id_value);
1301       GNUNET_free (app_id_value);
1302     }
1303   }
1304
1305   int ret = GNUNET_OK;
1306
1307   if (0 != unlink (app_place_filename))
1308   {
1309     GNUNET_break (0);
1310     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1311                 "Error removing app place file: %s: %s (%d)\n",
1312                 app_place_filename, strerror (errno), errno);
1313     ret = GNUNET_SYSERR;
1314   }
1315   GNUNET_free (app_place_filename);
1316
1317   return ret;
1318 }
1319
1320
1321 /**
1322  * Enter place as host.
1323  *
1324  * @param hreq
1325  *        Host entry request.
1326  * @param[out] ret_hst
1327  *        Returned Host struct.
1328  *
1329  * @return #GNUNET_YES if the host entered the place just now,
1330  *         #GNUNET_NO  if the place is already entered,
1331  *         #GNUNET_SYSERR if place_pub_key was set
1332  *                        but its private key was not found
1333  */
1334 static int
1335 host_enter (const struct HostEnterRequest *hreq, struct Host **ret_hst)
1336 {
1337   int ret = GNUNET_NO;
1338   struct GNUNET_HashCode place_pub_hash;
1339   GNUNET_CRYPTO_hash (&hreq->place_pub_key, sizeof (hreq->place_pub_key),
1340                       &place_pub_hash);
1341   struct Host *hst = GNUNET_CONTAINER_multihashmap_get (hosts, &place_pub_hash);
1342
1343   if (NULL == hst)
1344   {
1345     hst = GNUNET_new (struct Host);
1346     hst->policy = hreq->policy;
1347     hst->join_reqs = GNUNET_CONTAINER_multihashmap_create (1, GNUNET_NO);
1348     hst->relay_msgs = GNUNET_CONTAINER_multihashmap_create (1, GNUNET_NO);
1349
1350     struct Place *plc = &hst->plc;
1351     place_init (plc);
1352     plc->is_host = GNUNET_YES;
1353     plc->pub_key = hreq->place_pub_key;
1354     plc->pub_key_hash = place_pub_hash;
1355
1356     GNUNET_CONTAINER_multihashmap_put (hosts, &plc->pub_key_hash, plc,
1357                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1358     hst->master = GNUNET_PSYC_master_start (cfg, &hreq->place_key, hst->policy,
1359                                             &psyc_master_started,
1360                                             &psyc_recv_join_request,
1361                                             &psyc_recv_message, NULL, hst);
1362     plc->channel = GNUNET_PSYC_master_get_channel (hst->master);
1363     ret = GNUNET_YES;
1364   }
1365
1366   if (NULL != ret_hst)
1367     *ret_hst = hst;
1368   return ret;
1369 }
1370
1371
1372 const struct MsgProcRequest *
1373 msg_proc_parse (const struct GNUNET_MessageHeader *msg,
1374                 uint32_t *flags,
1375                 const char **method_prefix,
1376                 struct GNUNET_HashCode *method_hash)
1377 {
1378   const struct MsgProcRequest *mpreq = (const struct MsgProcRequest *) msg;
1379   uint8_t method_size = ntohs (mpreq->header.size) - sizeof (*mpreq);
1380   uint16_t offset = GNUNET_STRINGS_buffer_tokenize ((const char *) &mpreq[1],
1381                                                     method_size, 1, method_prefix);
1382
1383   if (0 == offset || offset != method_size || *method_prefix == NULL)
1384   {
1385     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1386                 "offset = %u, method_size = %u, method_name = %s\n",
1387                 offset, method_size, *method_prefix);
1388     return NULL;
1389   }
1390
1391   GNUNET_CRYPTO_hash (*method_prefix, method_size, method_hash);
1392   *flags = ntohl (mpreq->flags);
1393   return mpreq;
1394 }
1395
1396
1397 /**
1398  * Handle a client setting message proccesing flags for a method prefix.
1399  */
1400 static void
1401 client_recv_msg_proc_set (void *cls, struct GNUNET_SERVER_Client *client,
1402                           const struct GNUNET_MessageHeader *msg)
1403 {
1404   struct Client *
1405     ctx = GNUNET_SERVER_client_get_user_context (client, struct Client);
1406   GNUNET_assert (NULL != ctx);
1407   struct Place *plc = ctx->plc;
1408
1409   const char *method_prefix = NULL;
1410   uint32_t flags = 0;
1411   struct GNUNET_HashCode method_hash;
1412   const struct MsgProcRequest *
1413     mpreq = msg_proc_parse (msg, &flags, &method_prefix, &method_hash);
1414
1415   if (NULL == mpreq) {
1416     GNUNET_break (0);
1417     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1418     return;
1419   }
1420 #if 0
1421   GNUNET_PSYC_slicer_method_remove (plc->slicer, method_prefix,
1422                                     place_recv_relay_method,
1423                                     place_recv_relay_modifier,
1424                                     place_recv_relay_data,
1425                                     place_recv_relay_eom);
1426   GNUNET_PSYC_slicer_method_remove (plc->slicer, method_prefix,
1427                                     place_recv_save_method,
1428                                     NULL,
1429                                     place_recv_save_data,
1430                                     place_recv_save_eom);
1431 #endif
1432   if (flags & GNUNET_SOCIAL_MSG_PROC_RELAY)
1433   {
1434     GNUNET_PSYC_slicer_method_add (plc->slicer, method_prefix, NULL,
1435                                    place_recv_relay_method,
1436                                    place_recv_relay_modifier,
1437                                    place_recv_relay_data,
1438                                    place_recv_relay_eom,
1439                                    plc);
1440   }
1441   if (flags & GNUNET_SOCIAL_MSG_PROC_SAVE)
1442   {
1443     GNUNET_PSYC_slicer_method_add (plc->slicer, method_prefix, NULL,
1444                                    place_recv_save_method,
1445                                    NULL,
1446                                    place_recv_save_data,
1447                                    place_recv_save_eom,
1448                                    plc);
1449   }
1450
1451   /** @todo Save flags to be able to resume relaying/saving after restart */
1452
1453   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1454 }
1455
1456
1457 /**
1458  * Handle a connecting client requesting to clear all relay rules.
1459  */
1460 static void
1461 client_recv_msg_proc_clear (void *cls, struct GNUNET_SERVER_Client *client,
1462                             const struct GNUNET_MessageHeader *msg)
1463 {
1464   struct Client *
1465     ctx = GNUNET_SERVER_client_get_user_context (client, struct Client);
1466   GNUNET_assert (NULL != ctx);
1467   struct Place *plc = ctx->plc;
1468   if (GNUNET_YES != plc->is_host) {
1469     GNUNET_break (0);
1470     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1471     return;
1472   }
1473   GNUNET_PSYC_slicer_clear (plc->slicer);
1474
1475   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1476 }
1477
1478
1479 /**
1480  * Handle a connecting client entering a place as host.
1481  */
1482 static void
1483 client_recv_host_enter (void *cls, struct GNUNET_SERVER_Client *client,
1484                         const struct GNUNET_MessageHeader *msg)
1485 {
1486   struct HostEnterRequest *hreq
1487     = (struct HostEnterRequest *) GNUNET_copy_message (msg);
1488
1489   uint8_t app_id_size = ntohs (hreq->header.size) - sizeof (*hreq);
1490   const char *app_id = NULL;
1491   uint16_t offset = GNUNET_STRINGS_buffer_tokenize ((const char *) &hreq[1],
1492                                                     app_id_size, 1, &app_id);
1493   if (0 == offset || offset != app_id_size || app_id == NULL)
1494   {
1495     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1496                 "offset = %u, app_id_size = %u, app_id = %s\n",
1497                 offset, app_id_size, app_id);
1498     GNUNET_break (0);
1499     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1500     return;
1501   }
1502
1503   struct Host *hst = NULL;
1504   struct Place *plc = NULL;
1505   int ret = GNUNET_OK;
1506
1507   struct GNUNET_CRYPTO_EddsaPublicKey empty_pub_key;
1508   memset (&empty_pub_key, 0, sizeof (empty_pub_key));
1509
1510   if (0 == memcmp (&hreq->place_pub_key, &empty_pub_key, sizeof (empty_pub_key)))
1511   { // no public key set: create new private key & save the place
1512     struct GNUNET_CRYPTO_EddsaPrivateKey *
1513       place_key = GNUNET_CRYPTO_eddsa_key_create ();
1514     hreq->place_key = *place_key;
1515     GNUNET_CRYPTO_eddsa_key_get_public (place_key, &hreq->place_pub_key);
1516     GNUNET_CRYPTO_eddsa_key_clear (place_key);
1517     GNUNET_free (place_key);
1518
1519     app_place_save (app_id, (const struct PlaceEnterRequest *) hreq);
1520   }
1521
1522   switch (host_enter (hreq, &hst))
1523   {
1524   case GNUNET_YES:
1525     plc = &hst->plc;
1526     break;
1527
1528   case GNUNET_NO:
1529   {
1530     plc = &hst->plc;
1531     client_send_host_enter_ack (client, hst, GNUNET_OK);
1532     break;
1533   }
1534   case GNUNET_SYSERR:
1535     ret = GNUNET_SYSERR;
1536   }
1537
1538   if (ret != GNUNET_SYSERR)
1539   {
1540
1541     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1542                 "%p Client connected as host to place %s.\n",
1543                 hst, GNUNET_h2s (&plc->pub_key_hash));
1544
1545     struct ClientListItem *cli = GNUNET_new (struct ClientListItem);
1546     cli->client = client;
1547     GNUNET_CONTAINER_DLL_insert (plc->clients_head, plc->clients_tail, cli);
1548
1549     struct Client *ctx = GNUNET_new (struct Client);
1550     ctx->plc = plc;
1551     GNUNET_SERVER_client_set_user_context (client, ctx);
1552   }
1553
1554   GNUNET_CRYPTO_eddsa_key_clear (&hreq->place_key);
1555   GNUNET_free (hreq);
1556   GNUNET_SERVER_receive_done (client, ret);
1557 }
1558
1559
1560 /**
1561  * Enter place as guest.
1562  *
1563  * @param greq
1564  *        Guest entry request.
1565  * @param[out] ret_gst
1566  *        Returned Guest struct.
1567  *
1568  * @return #GNUNET_YES if the guest entered the place just now,
1569  *         #GNUNET_NO  if the place is already entered,
1570  *         #GNUNET_SYSERR on error.
1571  */
1572 static int
1573 guest_enter (const struct GuestEnterRequest *greq, struct Guest **ret_gst)
1574 {
1575   int ret = GNUNET_NO;
1576   uint16_t greq_size = ntohs (greq->header.size);
1577
1578   struct GNUNET_CRYPTO_EcdsaPublicKey ego_pub_key = greq->ego_pub_key;
1579   struct GNUNET_HashCode ego_pub_hash;
1580   GNUNET_CRYPTO_hash (&ego_pub_key, sizeof (ego_pub_key), &ego_pub_hash);
1581   struct Ego *ego = GNUNET_CONTAINER_multihashmap_get (egos, &ego_pub_hash);
1582
1583   if (NULL == ego)
1584     return GNUNET_SYSERR;
1585
1586   struct GNUNET_HashCode place_pub_hash;
1587   GNUNET_CRYPTO_hash (&greq->place_pub_key, sizeof (greq->place_pub_key),
1588                       &place_pub_hash);
1589
1590   struct GNUNET_CONTAINER_MultiHashMap *
1591     plc_gst = GNUNET_CONTAINER_multihashmap_get (place_guests, &place_pub_hash);
1592   struct Guest *gst = NULL;
1593
1594   if (NULL != plc_gst)
1595     gst = GNUNET_CONTAINER_multihashmap_get (plc_gst, &ego_pub_hash);
1596
1597   if (NULL == gst || NULL == gst->slave)
1598   {
1599     gst = GNUNET_new (struct Guest);
1600     gst->origin = greq->origin;
1601     gst->relay_count = ntohl (greq->relay_count);
1602
1603     uint16_t len;
1604     uint16_t remaining = ntohs (greq->header.size) - sizeof (*greq);
1605     const char *app_id = (const char *) &greq[1];
1606     const char *p = app_id;
1607
1608     len = strnlen (app_id, remaining);
1609     if (len == remaining)
1610     {
1611       GNUNET_free (gst);
1612       GNUNET_break (0);
1613       return GNUNET_SYSERR;
1614     }
1615     p += len + 1;
1616     remaining -= len + 1;
1617
1618     const struct GNUNET_PeerIdentity *relays = NULL;
1619     uint16_t relay_size = gst->relay_count * sizeof (*relays);
1620     if (remaining < relay_size)
1621     {
1622       GNUNET_free (gst);
1623       GNUNET_break (0);
1624       return GNUNET_SYSERR;
1625     }
1626     if (0 < relay_size)
1627       relays = (const struct GNUNET_PeerIdentity *) p;
1628     p += relay_size;
1629     remaining -= relay_size;
1630
1631     struct GNUNET_PSYC_Message *join_msg = NULL;
1632     uint16_t join_msg_size = 0;
1633
1634     if (sizeof (struct GNUNET_MessageHeader) <= remaining)
1635     {
1636       join_msg = (struct GNUNET_PSYC_Message *) p;
1637       join_msg_size = ntohs (join_msg->header.size);
1638       p += join_msg_size;
1639       remaining -= join_msg_size;
1640     }
1641     if (0 != remaining)
1642     {
1643       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1644                   "%zu + %u + %u != %u\n",
1645                   sizeof (*greq), relay_size, join_msg_size, greq_size);
1646       GNUNET_free (gst);
1647       GNUNET_break (0);
1648       return GNUNET_SYSERR;
1649     }
1650     if (0 < relay_size)
1651     {
1652       gst->relays = GNUNET_malloc (relay_size);
1653       GNUNET_memcpy (gst->relays, relays, relay_size);
1654     }
1655
1656     gst->join_flags = ntohl (greq->flags);
1657
1658     struct Place *plc = &gst->plc;
1659     place_init (plc);
1660     plc->is_host = GNUNET_NO;
1661     plc->pub_key = greq->place_pub_key;
1662     plc->pub_key_hash = place_pub_hash;
1663     plc->ego_pub_key = ego_pub_key;
1664     plc->ego_pub_hash = ego_pub_hash;
1665     plc->ego_key = ego->key;
1666
1667     if (NULL == plc_gst)
1668     {
1669       plc_gst = GNUNET_CONTAINER_multihashmap_create (1, GNUNET_YES);
1670       (void) GNUNET_CONTAINER_multihashmap_put (place_guests, &plc->pub_key_hash, plc_gst,
1671                                                 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
1672     }
1673     (void) GNUNET_CONTAINER_multihashmap_put (plc_gst, &plc->ego_pub_hash, gst,
1674                                               GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
1675     (void) GNUNET_CONTAINER_multihashmap_put (guests, &plc->pub_key_hash, gst,
1676                                               GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1677     gst->slave
1678       = GNUNET_PSYC_slave_join (cfg, &plc->pub_key, &plc->ego_key,
1679                                 gst->join_flags, &gst->origin,
1680                                 gst->relay_count, gst->relays,
1681                                 &psyc_recv_message, NULL,
1682                                 &psyc_slave_connected,
1683                                 &psyc_recv_join_dcsn,
1684                                 gst, join_msg);
1685     plc->channel = GNUNET_PSYC_slave_get_channel (gst->slave);
1686     ret = GNUNET_YES;
1687   }
1688
1689   if (NULL != ret_gst)
1690     *ret_gst = gst;
1691   return ret;
1692 }
1693
1694
1695 /**
1696  * Handle a connecting client entering a place as guest.
1697  */
1698 static void
1699 client_recv_guest_enter (void *cls, struct GNUNET_SERVER_Client *client,
1700                          const struct GNUNET_MessageHeader *msg)
1701 {
1702   const struct GuestEnterRequest *
1703     greq = (const struct GuestEnterRequest *) msg;
1704
1705   uint16_t remaining = ntohs (greq->header.size) - sizeof (*greq);
1706   const char *app_id = NULL;
1707   uint16_t offset = GNUNET_STRINGS_buffer_tokenize ((const char *) &greq[1],
1708                                                     remaining, 1, &app_id);
1709   if (0 == offset)
1710   {
1711     GNUNET_break (0);
1712     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1713     return;
1714   }
1715
1716   struct Guest *gst = NULL;
1717   struct Place *plc = NULL;
1718
1719   switch (guest_enter (greq, &gst))
1720   {
1721   case GNUNET_YES:
1722     plc = &gst->plc;
1723     app_place_save (app_id, (const struct PlaceEnterRequest *) greq);
1724     break;
1725
1726   case GNUNET_NO:
1727   {
1728     plc = &gst->plc;
1729
1730     struct GNUNET_PSYC_CountersResultMessage res;
1731     res.header.type = htons (GNUNET_MESSAGE_TYPE_SOCIAL_GUEST_ENTER_ACK);
1732     res.header.size = htons (sizeof (res));
1733     res.result_code = htonl (GNUNET_OK);
1734     res.max_message_id = GNUNET_htonll (plc->max_message_id);
1735
1736     client_send_msg (client, &res.header);
1737     if (NULL != gst->join_dcsn)
1738       client_send_msg (client, &gst->join_dcsn->header);
1739
1740     break;
1741   }
1742   case GNUNET_SYSERR:
1743     GNUNET_break (0);
1744     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1745     return;
1746   }
1747
1748   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1749               "%p Client connected as guest to place %s.\n",
1750               gst, GNUNET_h2s (&plc->pub_key_hash));
1751
1752   struct ClientListItem *cli = GNUNET_new (struct ClientListItem);
1753   cli->client = client;
1754   GNUNET_CONTAINER_DLL_insert (plc->clients_head, plc->clients_tail, cli);
1755
1756   struct Client *ctx = GNUNET_new (struct Client);
1757   ctx->plc = plc;
1758   GNUNET_SERVER_client_set_user_context (client, ctx);
1759   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1760 }
1761
1762
1763 struct GuestEnterByNameClosure
1764 {
1765   struct GNUNET_SERVER_Client *client;
1766   char *app_id;
1767   char *password;
1768   struct GNUNET_CRYPTO_EcdsaPublicKey ego_pub_key;
1769   struct GNUNET_MessageHeader *join_msg;
1770 };
1771
1772
1773 /**
1774  * Result of a GNS name lookup for entering a place.
1775  *
1776  * @see GNUNET_SOCIAL_guest_enter_by_name
1777  */
1778 static void
1779 gns_result_guest_enter (void *cls, uint32_t rd_count,
1780                         const struct GNUNET_GNSRECORD_Data *rd)
1781 {
1782   struct GuestEnterByNameClosure *gcls = cls;
1783   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1784               "%p GNS result: %u records.\n", gcls->client, rd_count);
1785
1786   const struct GNUNET_GNSRECORD_PlaceData *
1787     rec = (const struct GNUNET_GNSRECORD_PlaceData *) rd->data;
1788
1789   if (0 == rd_count || rd->data_size < sizeof (*rec))
1790   {
1791     GNUNET_break (0);
1792     GNUNET_SERVER_receive_done (gcls->client, GNUNET_SYSERR);
1793     return;
1794   }
1795
1796   uint16_t relay_count = ntohl (rec->relay_count);
1797   struct GNUNET_PeerIdentity *relays = NULL;
1798
1799   if (0 < relay_count)
1800   {
1801     if (rd->data_size == sizeof (*rec) + relay_count * sizeof (struct GNUNET_PeerIdentity))
1802     {
1803       relays = (struct GNUNET_PeerIdentity *) &rec[1];
1804     }
1805     else
1806     {
1807       relay_count = 0;
1808       GNUNET_break_op (0);
1809     }
1810   }
1811
1812   uint16_t app_id_size = strlen (gcls->app_id) + 1;
1813   uint16_t relay_size = relay_count * sizeof (*relays);
1814   uint16_t join_msg_size = 0;
1815   if (NULL != gcls->join_msg)
1816     join_msg_size = ntohs (gcls->join_msg->size);
1817   uint16_t greq_size = sizeof (struct GuestEnterRequest)
1818     + app_id_size + relay_size + join_msg_size;
1819   struct GuestEnterRequest *greq = GNUNET_malloc (greq_size);
1820   greq->header.size = htons (greq_size);
1821   greq->header.type = htons (GNUNET_MESSAGE_TYPE_SOCIAL_GUEST_ENTER);
1822   greq->ego_pub_key = gcls->ego_pub_key;
1823   greq->place_pub_key = rec->place_pub_key;
1824   greq->origin = rec->origin;
1825   greq->relay_count = rec->relay_count;
1826
1827   void *p = &greq[1];
1828   GNUNET_memcpy (p, gcls->app_id, app_id_size);
1829   p += app_id_size;
1830   GNUNET_memcpy (p, relays, relay_size);
1831   p += relay_size;
1832   GNUNET_memcpy (p, gcls->join_msg, join_msg_size);
1833
1834   client_recv_guest_enter (NULL, gcls->client, &greq->header);
1835
1836   GNUNET_free (gcls->app_id);
1837   if (NULL != gcls->password)
1838     GNUNET_free (gcls->password);
1839   if (NULL != gcls->join_msg)
1840     GNUNET_free (gcls->join_msg);
1841   GNUNET_free (gcls);
1842   GNUNET_free (greq);
1843 }
1844
1845
1846 /**
1847  * Handle a connecting client entering a place as guest using a GNS address.
1848  *
1849  * Look up GNS address and generate a GuestEnterRequest from that.
1850  */
1851 static void
1852 client_recv_guest_enter_by_name (void *cls, struct GNUNET_SERVER_Client *client,
1853                                  const struct GNUNET_MessageHeader *msg)
1854 {
1855   const struct GuestEnterByNameRequest *
1856     greq = (const struct GuestEnterByNameRequest *) msg;
1857
1858   struct GuestEnterByNameClosure *gcls = GNUNET_malloc (sizeof (*gcls));
1859   gcls->client = client;
1860   gcls->ego_pub_key = greq->ego_pub_key;
1861
1862   const char *p = (const char *) &greq[1];
1863   const char *app_id = NULL, *password = NULL, *gns_name = NULL;
1864   uint16_t remaining = ntohs (greq->header.size) - sizeof (*greq);
1865   uint16_t offset = GNUNET_STRINGS_buffer_tokenize (p, remaining, 3,
1866                                                     &app_id,
1867                                                     &gns_name,
1868                                                     &password);
1869   p += offset;
1870   remaining -= offset;
1871
1872   if (0 != offset && sizeof (*gcls->join_msg) <= remaining)
1873   {
1874     gcls->join_msg = GNUNET_copy_message ((struct GNUNET_MessageHeader *) p);
1875     remaining -= ntohs (gcls->join_msg->size);
1876   }
1877
1878   if (0 == offset || 0 != remaining)
1879   {
1880     if (NULL != gcls->join_msg)
1881       GNUNET_free (gcls->join_msg);
1882     GNUNET_free (gcls);
1883     GNUNET_break (0);
1884     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1885     return;
1886   }
1887
1888   uint16_t app_id_size = strlen (app_id) + 1;
1889   gcls->app_id = GNUNET_malloc (app_id_size);
1890   GNUNET_memcpy (gcls->app_id, app_id, app_id_size);
1891
1892   uint16_t password_size = strlen (password);
1893   if (0 < password_size++)
1894   {
1895     gcls->password = GNUNET_malloc (password_size);
1896     GNUNET_memcpy (gcls->password, password, password_size);
1897   }
1898
1899   GNUNET_GNS_lookup (gns, gns_name, &greq->ego_pub_key,
1900                      GNUNET_GNSRECORD_TYPE_PLACE, GNUNET_GNS_LO_DEFAULT,
1901                      NULL, gns_result_guest_enter, gcls);
1902 }
1903
1904
1905 void
1906 app_notify_place (struct GNUNET_MessageHeader *msg,
1907                   struct GNUNET_SERVER_Client *client)
1908 {
1909   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1910               "%p Sending place notification of type %u to client.\n",
1911               client, ntohs (msg->type));
1912
1913   uint16_t msg_size = ntohs (msg->size);
1914   struct AppPlaceMessage amsg;
1915   amsg.header.type = htons (GNUNET_MESSAGE_TYPE_SOCIAL_APP_PLACE);
1916   amsg.header.size = htons (sizeof (amsg));
1917   // FIXME: also notify about not entered places
1918   amsg.place_state = GNUNET_SOCIAL_PLACE_STATE_ENTERED;
1919
1920   switch (ntohs (msg->type))
1921   {
1922   case GNUNET_MESSAGE_TYPE_SOCIAL_HOST_ENTER:
1923     if (msg_size < sizeof (struct HostEnterRequest))
1924       return;
1925     struct HostEnterRequest *hreq = (struct HostEnterRequest *) msg;
1926     amsg.is_host = GNUNET_YES;
1927     amsg.ego_pub_key = hreq->ego_pub_key;
1928     amsg.place_pub_key = hreq->place_pub_key;
1929     break;
1930
1931   case GNUNET_MESSAGE_TYPE_SOCIAL_GUEST_ENTER:
1932     if (msg_size < sizeof (struct GuestEnterRequest))
1933       return;
1934     struct GuestEnterRequest *greq = (struct GuestEnterRequest *) msg;
1935     amsg.is_host = GNUNET_NO;
1936     amsg.ego_pub_key = greq->ego_pub_key;
1937     amsg.place_pub_key = greq->place_pub_key;
1938     break;
1939
1940   default:
1941     return;
1942   }
1943
1944   client_send_msg (client, &amsg.header);
1945 }
1946
1947
1948 void
1949 app_notify_place_end (struct GNUNET_SERVER_Client *client)
1950 {
1951   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1952               "%p Sending end of place list notification to client\n",
1953               client);
1954
1955   struct GNUNET_MessageHeader msg;
1956   msg.type = htons (GNUNET_MESSAGE_TYPE_SOCIAL_APP_PLACE_END);
1957   msg.size = htons (sizeof (msg));
1958
1959   client_send_msg (client, &msg);
1960 }
1961
1962
1963 void
1964 app_notify_ego (struct Ego *ego, struct GNUNET_SERVER_Client *client)
1965 {
1966   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1967               "%p Sending ego notification to client: %s\n",
1968               client, ego->name);
1969
1970   size_t name_size = strlen (ego->name) + 1;
1971   struct AppEgoMessage *emsg = GNUNET_malloc (sizeof (*emsg) + name_size);
1972   emsg->header.type = htons (GNUNET_MESSAGE_TYPE_SOCIAL_APP_EGO);
1973   emsg->header.size = htons (sizeof (*emsg) + name_size);
1974
1975   GNUNET_CRYPTO_ecdsa_key_get_public (&ego->key, &emsg->ego_pub_key);
1976   GNUNET_memcpy (&emsg[1], ego->name, name_size);
1977
1978   client_send_msg (client, &emsg->header);
1979   GNUNET_free (emsg);
1980 }
1981
1982
1983 void
1984 app_notify_ego_end (struct GNUNET_SERVER_Client *client)
1985 {
1986   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1987               "%p Sending end of ego list notification to client\n",
1988               client);
1989
1990   struct GNUNET_MessageHeader msg;
1991   msg.type = htons (GNUNET_MESSAGE_TYPE_SOCIAL_APP_EGO_END);
1992   msg.size = htons (sizeof (msg));
1993
1994   client_send_msg (client, &msg);
1995 }
1996
1997
1998 int
1999 app_place_entry_notify (void *cls, const struct GNUNET_HashCode *key, void *value)
2000 {
2001   struct GNUNET_MessageHeader *
2002     msg = GNUNET_CONTAINER_multihashmap_get (places, key);
2003   if (NULL != msg)
2004     app_notify_place (msg, cls);
2005   return GNUNET_YES;
2006 }
2007
2008
2009 int
2010 ego_entry (void *cls, const struct GNUNET_HashCode *key, void *value)
2011 {
2012   app_notify_ego (value, cls);
2013   return GNUNET_YES;
2014 }
2015
2016
2017 /**
2018  * Handle application connection.
2019  */
2020 static void
2021 client_recv_app_connect (void *cls, struct GNUNET_SERVER_Client *client,
2022                          const struct GNUNET_MessageHeader *msg)
2023 {
2024   const struct AppConnectRequest *creq
2025     = (const struct AppConnectRequest *) msg;
2026
2027   uint8_t app_id_size = ntohs (creq->header.size) - sizeof (*creq);
2028   const char *app_id = NULL;
2029   uint16_t offset = GNUNET_STRINGS_buffer_tokenize ((const char *) &creq[1],
2030                                                     app_id_size, 1, &app_id);
2031   if (0 == offset || offset != app_id_size)
2032   {
2033     GNUNET_break (0);
2034     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2035     return;
2036   }
2037
2038   struct GNUNET_HashCode app_id_hash;
2039   GNUNET_CRYPTO_hash (app_id, app_id_size, &app_id_hash);
2040
2041   GNUNET_CONTAINER_multihashmap_iterate (egos, ego_entry, client);
2042   app_notify_ego_end (client);
2043
2044   struct GNUNET_CONTAINER_MultiHashMap *
2045     app_places = GNUNET_CONTAINER_multihashmap_get (apps_places, &app_id_hash);
2046   if (NULL != app_places)
2047     GNUNET_CONTAINER_multihashmap_iterate (app_places, app_place_entry_notify, client);
2048   app_notify_place_end (client);
2049
2050   struct ClientListItem *cli = GNUNET_new (struct ClientListItem);
2051   cli->client = client;
2052   struct Application *app = GNUNET_CONTAINER_multihashmap_get (apps,
2053                                                                &app_id_hash);
2054   if (NULL == app) {
2055     app = GNUNET_malloc (sizeof (*app));
2056     (void) GNUNET_CONTAINER_multihashmap_put (apps, &app_id_hash, app,
2057                                               GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
2058   }
2059   GNUNET_CONTAINER_DLL_insert (app->clients_head, app->clients_tail, cli);
2060
2061   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2062               "%p Application %s connected.\n", app, app_id);
2063
2064   struct Client *ctx = GNUNET_new (struct Client);
2065   ctx->app_id = GNUNET_malloc (app_id_size);
2066   GNUNET_memcpy (ctx->app_id, app_id, app_id_size);
2067
2068   GNUNET_SERVER_client_set_user_context (client, ctx);
2069   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2070 }
2071
2072
2073 /**
2074  * Handle application detach request.
2075  */
2076 static void
2077 client_recv_app_detach (void *cls, struct GNUNET_SERVER_Client *client,
2078                         const struct GNUNET_MessageHeader *msg)
2079 {
2080   struct Client *
2081     ctx = GNUNET_SERVER_client_get_user_context (client, struct Client);
2082   GNUNET_assert (NULL != ctx);
2083
2084   struct Place *plc = ctx->plc;
2085
2086   const struct AppDetachRequest *req
2087     = (const struct AppDetachRequest *) msg;
2088
2089   int ret = app_place_remove (ctx->app_id, &plc->ego_pub_key, &req->place_pub_key);
2090   client_send_result (client, req->op_id, ret, NULL, 0);
2091
2092   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2093 }
2094
2095
2096 int
2097 app_places_entry_remove (void *cls, const struct GNUNET_HashCode *key, void *value)
2098 {
2099   struct Place *plc = cls;
2100   const char *app_id = value;
2101   app_place_remove (app_id, &plc->ego_pub_key, &plc->pub_key);
2102   return GNUNET_YES;
2103 }
2104
2105
2106 /**
2107  * Handle application detach request.
2108  */
2109 static void
2110 client_recv_place_leave (void *cls, struct GNUNET_SERVER_Client *client,
2111                          const struct GNUNET_MessageHeader *msg)
2112 {
2113   struct Client *
2114     ctx = GNUNET_SERVER_client_get_user_context (client, struct Client);
2115   GNUNET_assert (NULL != ctx);
2116   struct Place *plc = ctx->plc;
2117
2118   /* FIXME: remove all app subscriptions and leave this place  */
2119
2120   struct GNUNET_CONTAINER_MultiHashMap *
2121     place_apps = GNUNET_CONTAINER_multihashmap_get (places_apps, &plc->pub_key_hash);
2122   if (NULL != place_apps)
2123   {
2124     GNUNET_CONTAINER_multihashmap_iterate (place_apps, app_places_entry_remove, plc);
2125   }
2126
2127   /* FIXME: disconnect from the network, but keep local connection for history access */
2128
2129   /* Disconnect all clients connected to the place */
2130   struct ClientListItem *cli = plc->clients_head, *next;
2131   while (NULL != cli)
2132   {
2133     GNUNET_CONTAINER_DLL_remove (plc->clients_head, plc->clients_tail, cli);
2134     GNUNET_SERVER_client_disconnect (cli->client);
2135     next = cli->next;
2136     GNUNET_free (cli);
2137     cli = next;
2138   }
2139
2140   if (GNUNET_YES != plc->is_disconnected)
2141   {
2142     plc->is_disconnected = GNUNET_YES;
2143     if (NULL != plc->tmit_msgs_head)
2144     { /* Send pending messages to PSYC before cleanup. */
2145       psyc_transmit_message (plc);
2146     }
2147     else
2148     {
2149       cleanup_place (plc);
2150     }
2151   }
2152 }
2153
2154
2155 struct JoinDecisionClosure
2156 {
2157   int32_t is_admitted;
2158   struct GNUNET_PSYC_Message *msg;
2159 };
2160
2161
2162 /**
2163  * Iterator callback for responding to join requests.
2164  */
2165 static int
2166 psyc_send_join_decision (void *cls, const struct GNUNET_HashCode *pub_key_hash,
2167                          void *value)
2168 {
2169   struct JoinDecisionClosure *jcls = cls;
2170   struct GNUNET_PSYC_JoinHandle *jh = value;
2171   // FIXME: add relays
2172   GNUNET_PSYC_join_decision (jh, jcls->is_admitted, 0, NULL, jcls->msg);
2173   return GNUNET_YES;
2174 }
2175
2176
2177 /**
2178  * Handle an entry decision from a host client.
2179  */
2180 static void
2181 client_recv_join_decision (void *cls, struct GNUNET_SERVER_Client *client,
2182                            const struct GNUNET_MessageHeader *msg)
2183 {
2184   struct Client *
2185     ctx = GNUNET_SERVER_client_get_user_context (client, struct Client);
2186   GNUNET_assert (NULL != ctx);
2187   struct Place *plc = ctx->plc;
2188   if (GNUNET_YES != plc->is_host) {
2189     GNUNET_break (0);
2190     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2191     return;
2192   }
2193   struct Host *hst = (struct Host *) plc;
2194
2195   struct GNUNET_PSYC_JoinDecisionMessage *
2196     dcsn = (struct GNUNET_PSYC_JoinDecisionMessage *) msg;
2197   struct JoinDecisionClosure jcls;
2198   jcls.is_admitted = ntohl (dcsn->is_admitted);
2199   jcls.msg
2200     = (sizeof (*dcsn) + sizeof (*jcls.msg) <= ntohs (msg->size))
2201     ? (struct GNUNET_PSYC_Message *) &dcsn[1]
2202     : NULL;
2203
2204   struct GNUNET_HashCode slave_pub_hash;
2205   GNUNET_CRYPTO_hash (&dcsn->slave_pub_key, sizeof (dcsn->slave_pub_key),
2206                       &slave_pub_hash);
2207
2208   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2209               "%p Got join decision (%d) from client for place %s..\n",
2210               hst, jcls.is_admitted, GNUNET_h2s (&plc->pub_key_hash));
2211   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2212               "%p ..and slave %s.\n",
2213               hst, GNUNET_h2s (&slave_pub_hash));
2214
2215   GNUNET_CONTAINER_multihashmap_get_multiple (hst->join_reqs, &slave_pub_hash,
2216                                               &psyc_send_join_decision, &jcls);
2217   GNUNET_CONTAINER_multihashmap_remove_all (hst->join_reqs, &slave_pub_hash);
2218   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2219 }
2220
2221
2222 /**
2223  * Send acknowledgement to a client.
2224  *
2225  * Sent after a message fragment has been passed on to multicast.
2226  *
2227  * @param plc The place struct for the client.
2228  */
2229 static void
2230 send_message_ack (struct Place *plc, struct GNUNET_SERVER_Client *client)
2231 {
2232   struct GNUNET_MessageHeader res;
2233   res.size = htons (sizeof (res));
2234   res.type = htons (GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_ACK);
2235   client_send_msg (client, &res);
2236 }
2237
2238
2239 /**
2240  * Proceed to the next message part in the transmission queue.
2241  *
2242  * @param plc
2243  *        Place where the transmission is going on.
2244  * @param tmit_msg
2245  *        Currently transmitted message.
2246  * @param tmit_frag
2247  *        Currently transmitted message fragment.
2248  *
2249  * @return @a tmit_frag, or NULL if reached the end of fragment.
2250  */
2251 static struct FragmentTransmitQueue *
2252 psyc_transmit_queue_next_part (struct Place *plc,
2253                                struct MessageTransmitQueue *tmit_msg,
2254                                struct FragmentTransmitQueue *tmit_frag)
2255 {
2256   uint16_t psize = ntohs (tmit_frag->next_part->size);
2257   if ((char *) tmit_frag->next_part + psize - ((char *) &tmit_frag[1])
2258       < tmit_frag->size)
2259   {
2260     tmit_frag->next_part
2261       = (struct GNUNET_MessageHeader *) ((char *) tmit_frag->next_part + psize);
2262   }
2263   else /* Reached end of current fragment. */
2264   {
2265     if (NULL != tmit_frag->client)
2266       send_message_ack (plc, tmit_frag->client);
2267     GNUNET_CONTAINER_DLL_remove (tmit_msg->frags_head, tmit_msg->frags_tail, tmit_frag);
2268     GNUNET_free (tmit_frag);
2269     tmit_frag = NULL;
2270   }
2271   return tmit_frag;
2272 }
2273
2274
2275 /**
2276  * Proceed to next message in transmission queue.
2277  *
2278  * @param plc
2279  *        Place where the transmission is going on.
2280  * @param tmit_msg
2281  *        Currently transmitted message.
2282  *
2283  * @return The next message in queue, or NULL if queue is empty.
2284  */
2285 static struct MessageTransmitQueue *
2286 psyc_transmit_queue_next_msg (struct Place *plc,
2287                               struct MessageTransmitQueue *tmit_msg)
2288 {
2289   GNUNET_CONTAINER_DLL_remove (plc->tmit_msgs_head, plc->tmit_msgs_tail, tmit_msg);
2290   GNUNET_free (tmit_msg);
2291   return plc->tmit_msgs_head;
2292 }
2293
2294
2295 /**
2296  * Callback for data transmission to PSYC.
2297  */
2298 static int
2299 psyc_transmit_notify_data (void *cls, uint16_t *data_size, void *data)
2300 {
2301   struct Place *plc = cls;
2302   struct MessageTransmitQueue *tmit_msg = plc->tmit_msgs_head;
2303   GNUNET_assert (NULL != tmit_msg);
2304   struct FragmentTransmitQueue *tmit_frag = tmit_msg->frags_head;
2305   if (NULL == tmit_frag)
2306   { /* Rest of the message have not arrived yet, pause transmission */
2307     *data_size = 0;
2308     return GNUNET_NO;
2309   }
2310   struct GNUNET_MessageHeader *pmsg = tmit_frag->next_part;
2311   if (NULL == pmsg)
2312   {
2313     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2314                 "%p psyc_transmit_notify_data: nothing to send.\n", plc);
2315     *data_size = 0;
2316     return GNUNET_NO;
2317   }
2318
2319   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2320               "%p psyc_transmit_notify_data()\n", plc);
2321   GNUNET_PSYC_log_message (GNUNET_ERROR_TYPE_DEBUG, pmsg);
2322
2323   uint16_t ptype = ntohs (pmsg->type);
2324   uint16_t pdata_size = ntohs (pmsg->size) - sizeof (*pmsg);
2325   int ret;
2326
2327   switch (ptype)
2328   {
2329   case GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_DATA:
2330     if (*data_size < pdata_size)
2331     {
2332       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2333                 "%p psyc_transmit_notify_data: buffer size too small for data.\n", plc);
2334       *data_size = 0;
2335       return GNUNET_NO;
2336     }
2337     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2338                 "%p psyc_transmit_notify_data: sending %u bytes.\n",
2339                 plc, pdata_size);
2340
2341     *data_size = pdata_size;
2342     GNUNET_memcpy (data, &pmsg[1], *data_size);
2343     ret = GNUNET_NO;
2344     break;
2345
2346   case GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_END:
2347     *data_size = 0;
2348     ret = GNUNET_YES;
2349     break;
2350
2351   case GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_CANCEL:
2352     *data_size = 0;
2353     ret = GNUNET_SYSERR;
2354     break;
2355
2356   default:
2357     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2358                 "%p psyc_transmit_notify_data: unexpected message part of type %u.\n",
2359                 plc, ptype);
2360     ret = GNUNET_SYSERR;
2361   }
2362
2363   if (GNUNET_SYSERR == ret && GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_CANCEL != ptype)
2364   {
2365     *data_size = 0;
2366     tmit_msg = psyc_transmit_queue_next_msg (plc, tmit_msg);
2367     plc->is_disconnected = GNUNET_YES;
2368     GNUNET_SERVER_client_disconnect (tmit_frag->client);
2369     GNUNET_SCHEDULER_add_now (&cleanup_place, plc);
2370     return ret;
2371   }
2372   else
2373   {
2374     tmit_frag = psyc_transmit_queue_next_part (plc, tmit_msg, tmit_frag);
2375     if (NULL != tmit_frag)
2376     {
2377       struct GNUNET_MessageHeader *pmsg = tmit_frag->next_part;
2378       ptype = ntohs (pmsg->type);
2379       switch (ptype)
2380       {
2381       case GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_END:
2382         ret = GNUNET_YES;
2383         break;
2384       case GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_CANCEL:
2385         ret = GNUNET_SYSERR;
2386         break;
2387       }
2388       switch (ptype)
2389       {
2390       case GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_END:
2391       case GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_CANCEL:
2392         tmit_frag = psyc_transmit_queue_next_part (plc, tmit_msg, tmit_frag);
2393       }
2394     }
2395
2396     if (NULL == tmit_msg->frags_head
2397         && GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_END <= ptype)
2398     { /* Reached end of current message. */
2399       tmit_msg = psyc_transmit_queue_next_msg (plc, tmit_msg);
2400     }
2401   }
2402
2403   if (ret != GNUNET_NO)
2404   {
2405     if (NULL != tmit_msg)
2406     {
2407       psyc_transmit_message (plc);
2408     }
2409     else if (GNUNET_YES == plc->is_disconnected)
2410     {
2411       /* FIXME: handle partial message (when still in_transmit) */
2412       cleanup_place (plc);
2413     }
2414   }
2415   return ret;
2416 }
2417
2418
2419 /**
2420  * Callback for modifier transmission to PSYC.
2421  */
2422 static int
2423 psyc_transmit_notify_mod (void *cls, uint16_t *data_size, void *data,
2424                           uint8_t *oper, uint32_t *full_value_size)
2425 {
2426   struct Place *plc = cls;
2427   struct MessageTransmitQueue *tmit_msg = plc->tmit_msgs_head;
2428   GNUNET_assert (NULL != tmit_msg);
2429   struct FragmentTransmitQueue *tmit_frag = tmit_msg->frags_head;
2430   if (NULL == tmit_frag)
2431   { /* Rest of the message have not arrived yet, pause transmission */
2432     *data_size = 0;
2433     return GNUNET_NO;
2434   }
2435   struct GNUNET_MessageHeader *pmsg = tmit_frag->next_part;
2436   if (NULL == pmsg)
2437   {
2438     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2439                 "%p psyc_transmit_notify_mod: nothing to send.\n", plc);
2440     *data_size = 0;
2441     return GNUNET_NO;
2442   }
2443
2444   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2445               "%p psyc_transmit_notify_mod()\n", plc);
2446   GNUNET_PSYC_log_message (GNUNET_ERROR_TYPE_DEBUG, pmsg);
2447
2448   uint16_t ptype = ntohs (pmsg->type);
2449   int ret;
2450
2451   switch (ptype)
2452   {
2453   case GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_MODIFIER:
2454   {
2455     if (NULL == oper)
2456     {
2457       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2458                   "%p psyc_transmit_notify_mod: oper is NULL.\n", plc);
2459       ret = GNUNET_SYSERR;
2460       break;
2461     }
2462     struct GNUNET_PSYC_MessageModifier *
2463       pmod = (struct GNUNET_PSYC_MessageModifier *) tmit_frag->next_part;
2464     uint16_t mod_size = ntohs (pmod->header.size) - sizeof (*pmod);
2465
2466     if (*data_size < mod_size)
2467     {
2468       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2469                 "%p psyc_transmit_notify_mod: buffer size too small for data.\n", plc);
2470       *data_size = 0;
2471       return GNUNET_NO;
2472     }
2473
2474     *full_value_size = ntohl (pmod->value_size);
2475     *oper = pmod->oper;
2476     *data_size = mod_size;
2477     GNUNET_memcpy (data, &pmod[1], mod_size);
2478     ret = GNUNET_NO;
2479     break;
2480   }
2481
2482   case GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_MOD_CONT:
2483   {
2484     if (NULL != oper)
2485     {
2486       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2487                   "%p psyc_transmit_notify_mod: oper is not NULL.\n", plc);
2488       ret = GNUNET_SYSERR;
2489       break;
2490     }
2491     uint16_t mod_size = ntohs (pmsg->size) - sizeof (*pmsg);
2492     if (*data_size < mod_size)
2493     {
2494       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2495                 "%p psyc_transmit_notify_mod: buffer size too small for data.\n", plc);
2496       *data_size = 0;
2497       return GNUNET_NO;
2498     }
2499     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2500                 "%p psyc_transmit_notify_mod: sending %u bytes.\n", plc, mod_size);
2501
2502     *data_size = mod_size;
2503     GNUNET_memcpy (data, &pmsg[1], *data_size);
2504     ret = GNUNET_NO;
2505     break;
2506   }
2507
2508   case GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_DATA:
2509   case GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_END:
2510   case GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_CANCEL:
2511     *data_size = 0;
2512     ret = GNUNET_YES;
2513     break;
2514
2515   default:
2516     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2517                 "%p psyc_transmit_notify_mod: unexpected message part of type %u.\n",
2518                 plc, ptype);
2519     ret = GNUNET_SYSERR;
2520   }
2521
2522   if (GNUNET_SYSERR == ret)
2523   {
2524     *data_size = 0;
2525     ret = GNUNET_SYSERR;
2526     tmit_msg = psyc_transmit_queue_next_msg (plc, tmit_msg);
2527     plc->is_disconnected = GNUNET_YES;
2528     GNUNET_SERVER_client_disconnect (tmit_frag->client);
2529     GNUNET_SCHEDULER_add_now (&cleanup_place, plc);
2530   }
2531   else
2532   {
2533     if (GNUNET_YES != ret)
2534       psyc_transmit_queue_next_part (plc, tmit_msg, tmit_frag);
2535
2536     if (NULL == tmit_msg->frags_head
2537         && GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_END <= ptype)
2538     { /* Reached end of current message. */
2539       tmit_msg = psyc_transmit_queue_next_msg (plc, tmit_msg);
2540     }
2541   }
2542   return ret;
2543 }
2544
2545 /**
2546  * Callback for data transmission from a host to PSYC.
2547  */
2548 static int
2549 host_transmit_notify_data (void *cls, uint16_t *data_size, void *data)
2550 {
2551   int ret = psyc_transmit_notify_data (cls, data_size, data);
2552
2553   if (GNUNET_NO != ret)
2554   {
2555     struct Host *hst = cls;
2556     hst->tmit_handle = NULL;
2557   }
2558   return ret;
2559 }
2560
2561
2562 /**
2563  * Callback for the transmit functions of multicast.
2564  */
2565 static int
2566 guest_transmit_notify_data (void *cls, uint16_t *data_size, void *data)
2567 {
2568   int ret = psyc_transmit_notify_data (cls, data_size, data);
2569
2570   if (GNUNET_NO != ret)
2571   {
2572     struct Guest *gst = cls;
2573     gst->tmit_handle = NULL;
2574   }
2575   return ret;
2576 }
2577
2578
2579 /**
2580  * Callback for modifier transmission from a host to PSYC.
2581  */
2582 static int
2583 host_transmit_notify_mod (void *cls, uint16_t *data_size, void *data,
2584                           uint8_t *oper, uint32_t *full_value_size)
2585 {
2586   int ret = psyc_transmit_notify_mod (cls, data_size, data,
2587                                       oper, full_value_size);
2588   if (GNUNET_SYSERR == ret)
2589   {
2590     struct Host *hst = cls;
2591     hst->tmit_handle = NULL;
2592   }
2593   return ret;
2594 }
2595
2596
2597 /**
2598  * Callback for modifier transmission from a guest to PSYC.
2599  */
2600 static int
2601 guest_transmit_notify_mod (void *cls, uint16_t *data_size, void *data,
2602                            uint8_t *oper, uint32_t *full_value_size)
2603 {
2604   int ret = psyc_transmit_notify_mod (cls, data_size, data,
2605                                       oper, full_value_size);
2606   if (GNUNET_SYSERR == ret)
2607   {
2608     struct Guest *gst = cls;
2609     gst->tmit_handle = NULL;
2610   }
2611   return ret;
2612 }
2613
2614
2615 /**
2616  * Get method part of next message from transmission queue.
2617  *
2618  * @param plc
2619  *        Place
2620  *
2621  * @return #GNUNET_OK on success
2622  *         #GNUNET_NO if there are no more messages in queue.
2623  *         #GNUNET_SYSERR if the next message is malformed.
2624  */
2625 static struct GNUNET_PSYC_MessageMethod *
2626 psyc_transmit_queue_next_method (struct Place *plc)
2627 {
2628   struct MessageTransmitQueue *tmit_msg = plc->tmit_msgs_head;
2629   if (NULL == tmit_msg)
2630     return GNUNET_NO;
2631
2632   struct FragmentTransmitQueue *tmit_frag = tmit_msg->frags_head;
2633   if (NULL == tmit_frag)
2634   {
2635     GNUNET_break (0);
2636     return GNUNET_NO;
2637   }
2638
2639   struct GNUNET_MessageHeader *pmsg = tmit_frag->next_part;
2640   if (NULL == pmsg
2641       || GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_METHOD != ntohs (pmsg->type))
2642   {
2643     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2644                 "%p psyc_transmit_queue_next_method: unexpected message part of type %u.\n",
2645                 plc, NULL != pmsg ? ntohs (pmsg->type) : 0);
2646     GNUNET_break (0);
2647     return NULL;
2648   }
2649
2650   uint16_t psize = ntohs (pmsg->size);
2651   struct GNUNET_PSYC_MessageMethod *
2652     pmeth = (struct GNUNET_PSYC_MessageMethod *) GNUNET_copy_message (pmsg);
2653
2654   if (psize < sizeof (*pmeth) + 1 || '\0' != *((char *) pmeth + psize - 1))
2655   {
2656     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2657                 "%p psyc_transmit_queue_next_method: invalid method name.\n",
2658                 plc);
2659     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2660                 "%zu <= %u || NUL != %u\n",
2661                 sizeof (*pmeth), psize, *((char *) pmeth + psize - 1));
2662     GNUNET_break (0);
2663     GNUNET_free (pmeth);
2664     return NULL;
2665   }
2666
2667   psyc_transmit_queue_next_part (plc, tmit_msg, tmit_frag);
2668   return pmeth;
2669 }
2670
2671
2672 /**
2673  * Transmit the next message in queue from the host to the PSYC channel.
2674  */
2675 static int
2676 psyc_master_transmit_message (struct Host *hst)
2677 {
2678   struct Place *plc = &hst->plc;
2679
2680   if (NULL == hst->tmit_handle)
2681   {
2682     struct GNUNET_PSYC_MessageMethod *
2683       pmeth = psyc_transmit_queue_next_method (plc);
2684     if (NULL == pmeth)
2685       return GNUNET_SYSERR;
2686
2687     hst->tmit_handle = (void *) &hst->tmit_handle;
2688     struct GNUNET_PSYC_MasterTransmitHandle *
2689       tmit_handle = GNUNET_PSYC_master_transmit (hst->master, (const char *) &pmeth[1],
2690                                                  &host_transmit_notify_mod,
2691                                                  &host_transmit_notify_data, hst,
2692                                                  pmeth->flags);
2693     if (NULL != hst->tmit_handle)
2694       hst->tmit_handle = tmit_handle;
2695     GNUNET_free (pmeth);
2696   }
2697   else
2698   {
2699     GNUNET_PSYC_master_transmit_resume (hst->tmit_handle);
2700   }
2701   return GNUNET_OK;
2702 }
2703
2704
2705 /**
2706  * Transmit the next message in queue from a guest to the PSYC channel.
2707  */
2708 static int
2709 psyc_slave_transmit_message (struct Guest *gst)
2710 {
2711   struct Place *plc = &gst->plc;
2712
2713   if (NULL == gst->tmit_handle)
2714   {
2715     struct GNUNET_PSYC_MessageMethod *
2716       pmeth = psyc_transmit_queue_next_method (plc);
2717     if (NULL == pmeth)
2718       return GNUNET_SYSERR;
2719
2720     gst->tmit_handle = (void *) &gst->tmit_handle;
2721     struct GNUNET_PSYC_SlaveTransmitHandle *
2722       tmit_handle = GNUNET_PSYC_slave_transmit (gst->slave, (const char *) &pmeth[1],
2723                                                  &guest_transmit_notify_mod,
2724                                                  &guest_transmit_notify_data, gst,
2725                                                  pmeth->flags);
2726     if (NULL != gst->tmit_handle)
2727       gst->tmit_handle = tmit_handle;
2728     GNUNET_free (pmeth);
2729   }
2730   else
2731   {
2732     GNUNET_PSYC_slave_transmit_resume (gst->tmit_handle);
2733   }
2734   return GNUNET_OK;
2735 }
2736
2737
2738 /**
2739  * Transmit a message to PSYC.
2740  */
2741 static int
2742 psyc_transmit_message (struct Place *plc)
2743 {
2744   return
2745     (plc->is_host)
2746     ? psyc_master_transmit_message ((struct Host *) plc)
2747     : psyc_slave_transmit_message ((struct Guest *) plc);
2748 }
2749
2750
2751 /**
2752  * Queue message parts for sending to PSYC.
2753  *
2754  * @param plc          Place to send to.
2755  * @param client       Client the message originates from.
2756  * @param data_size    Size of @a data.
2757  * @param data         Concatenated message parts.
2758  * @param first_ptype  First message part type in @a data.
2759  * @param last_ptype   Last message part type in @a data.
2760  */
2761 static struct MessageTransmitQueue *
2762 psyc_transmit_queue_message (struct Place *plc,
2763                              struct GNUNET_SERVER_Client *client,
2764                              size_t data_size,
2765                              const void *data,
2766                              uint16_t first_ptype, uint16_t last_ptype,
2767                              struct MessageTransmitQueue *tmit_msg)
2768 {
2769   if (GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_METHOD == first_ptype)
2770   {
2771     tmit_msg = GNUNET_malloc (sizeof (*tmit_msg));
2772     GNUNET_CONTAINER_DLL_insert_tail (plc->tmit_msgs_head, plc->tmit_msgs_tail, tmit_msg);
2773   }
2774   else if (NULL == tmit_msg)
2775   {
2776     return NULL;
2777   }
2778
2779   struct FragmentTransmitQueue *
2780     tmit_frag = GNUNET_malloc (sizeof (*tmit_frag) + data_size);
2781   GNUNET_memcpy (&tmit_frag[1], data, data_size);
2782   tmit_frag->next_part = (struct GNUNET_MessageHeader *) &tmit_frag[1];
2783   tmit_frag->client = client;
2784   tmit_frag->size = data_size;
2785
2786   GNUNET_CONTAINER_DLL_insert_tail (tmit_msg->frags_head, tmit_msg->frags_tail, tmit_frag);
2787   tmit_msg->client = client;
2788   return tmit_msg;
2789 }
2790
2791
2792 /**
2793  * Cancel transmission of current message to PSYC.
2794  *
2795  * @param plc     Place to send to.
2796  * @param client  Client the message originates from.
2797  */
2798 static void
2799 psyc_transmit_cancel (struct Place *plc, struct GNUNET_SERVER_Client *client)
2800 {
2801   uint16_t type = GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_CANCEL;
2802
2803   struct GNUNET_MessageHeader msg;
2804   msg.size = htons (sizeof (msg));
2805   msg.type = htons (type);
2806
2807   psyc_transmit_queue_message (plc, client, sizeof (msg), &msg, type, type, NULL);
2808   psyc_transmit_message (plc);
2809
2810   /* FIXME: cleanup */
2811 }
2812
2813
2814 /**
2815  * Handle an incoming message from a client, to be transmitted to the place.
2816  */
2817 static void
2818 client_recv_psyc_message (void *cls, struct GNUNET_SERVER_Client *client,
2819                           const struct GNUNET_MessageHeader *msg)
2820 {
2821   struct Client *
2822     ctx = GNUNET_SERVER_client_get_user_context (client, struct Client);
2823   GNUNET_assert (NULL != ctx);
2824   struct Place *plc = ctx->plc;
2825   int ret = GNUNET_SYSERR;
2826
2827   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2828               "%p Received message from client.\n", plc);
2829   GNUNET_PSYC_log_message (GNUNET_ERROR_TYPE_DEBUG, msg);
2830
2831   if (GNUNET_YES != plc->is_ready)
2832   {
2833     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2834                 "%p Place is not ready yet, disconnecting client.\n", plc);
2835     GNUNET_break (0);
2836     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2837     return;
2838   }
2839
2840   uint16_t size = ntohs (msg->size);
2841   uint16_t psize = size - sizeof (*msg);
2842   if (psize < sizeof (struct GNUNET_MessageHeader)
2843       || GNUNET_MULTICAST_FRAGMENT_MAX_PAYLOAD < psize)
2844   {
2845     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2846                 "%p Received message with invalid payload size (%u) from client.\n",
2847                 plc, psize);
2848     GNUNET_break (0);
2849     psyc_transmit_cancel (plc, client);
2850     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2851     return;
2852   }
2853
2854   uint16_t first_ptype = 0, last_ptype = 0;
2855   if (GNUNET_SYSERR
2856       == GNUNET_PSYC_receive_check_parts (psize, (const char *) &msg[1],
2857                                           &first_ptype, &last_ptype))
2858   {
2859     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2860                 "%p Received invalid message part from client.\n", plc);
2861     GNUNET_break (0);
2862     psyc_transmit_cancel (plc, client);
2863     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2864     return;
2865   }
2866   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2867               "%p Received message with first part type %u and last part type %u.\n",
2868               plc, first_ptype, last_ptype);
2869
2870   ctx->tmit_msg
2871     = psyc_transmit_queue_message (plc, client, psize, &msg[1],
2872                                    first_ptype, last_ptype, ctx->tmit_msg);
2873   if (NULL != ctx->tmit_msg)
2874   {
2875     if (GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_END <= last_ptype)
2876       ctx->tmit_msg = NULL;
2877     ret = psyc_transmit_message (plc);
2878   }
2879
2880   if (GNUNET_OK != ret)
2881   {
2882     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2883                 "%p Received invalid message part from client.\n", plc);
2884     GNUNET_break (0);
2885     psyc_transmit_cancel (plc, client);
2886     ret = GNUNET_SYSERR;
2887   }
2888   GNUNET_SERVER_receive_done (client, ret);
2889 }
2890
2891
2892 /**
2893  * A historic message arrived from PSYC.
2894  */
2895 static void
2896 psyc_recv_history_message (void *cls, const struct GNUNET_PSYC_MessageHeader *msg)
2897 {
2898   struct OperationClosure *opcls = cls;
2899   struct Place *plc = opcls->plc;
2900
2901   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2902               "%p Received historic message #%" PRId64 " (flags: %x)\n",
2903               plc, GNUNET_ntohll (msg->message_id), ntohl (msg->flags));
2904
2905   uint16_t size = ntohs (msg->header.size);
2906
2907   struct GNUNET_OperationResultMessage *
2908     res = GNUNET_malloc (sizeof (*res) + size);
2909   res->header.size = htons (sizeof (*res) + size);
2910   res->header.type = htons (GNUNET_MESSAGE_TYPE_PSYC_HISTORY_RESULT);
2911   res->op_id = opcls->op_id;
2912   res->result_code = GNUNET_htonll (GNUNET_OK);
2913
2914   GNUNET_memcpy (&res[1], msg, size);
2915
2916   /** @todo FIXME: send only to requesting client */
2917   place_send_msg (plc, &res->header);
2918
2919   GNUNET_free (res);
2920 }
2921
2922
2923 /**
2924  * Result of message history replay from PSYC.
2925  */
2926 static void
2927 psyc_recv_history_result (void *cls, int64_t result,
2928                           const void *err_msg, uint16_t err_msg_size)
2929 {
2930   struct OperationClosure *opcls = cls;
2931   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2932               "%p History replay #%" PRIu64 ": "
2933               "PSYCstore returned %" PRId64 " (%.*s)\n",
2934               opcls->plc, GNUNET_ntohll (opcls->op_id), result,
2935               err_msg_size, (const char *) err_msg);
2936
2937   // FIXME: place might have been destroyed
2938   client_send_result (opcls->client, opcls->op_id, result, err_msg, err_msg_size);
2939 }
2940
2941
2942 /**
2943  * Client requests channel history.
2944  */
2945 static void
2946 client_recv_history_replay (void *cls, struct GNUNET_SERVER_Client *client,
2947                             const struct GNUNET_MessageHeader *msg)
2948 {
2949   struct Client *
2950     ctx = GNUNET_SERVER_client_get_user_context (client, struct Client);
2951   GNUNET_assert (NULL != ctx);
2952   struct Place *plc = ctx->plc;
2953
2954   const struct GNUNET_PSYC_HistoryRequestMessage *
2955     req = (const struct GNUNET_PSYC_HistoryRequestMessage *) msg;
2956   uint16_t size = ntohs (msg->size);
2957   const char *method_prefix = (const char *) &req[1];
2958
2959   if (size < sizeof (*req) + 1
2960       || '\0' != method_prefix[size - sizeof (*req) - 1])
2961   {
2962     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2963                 "%p History replay #%" PRIu64 ": "
2964                 "invalid method prefix. size: %u < %zu?\n",
2965                 plc, GNUNET_ntohll (req->op_id), size, sizeof (*req) + 1);
2966     GNUNET_break (0);
2967     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
2968     return;
2969   }
2970
2971   struct OperationClosure *opcls = GNUNET_malloc (sizeof (*opcls));
2972   opcls->client = client;
2973   opcls->plc = plc;
2974   opcls->op_id = req->op_id;
2975   opcls->flags = ntohl (req->flags);
2976
2977   if (0 == req->message_limit)
2978     GNUNET_PSYC_channel_history_replay (plc->channel,
2979                                         GNUNET_ntohll (req->start_message_id),
2980                                         GNUNET_ntohll (req->end_message_id),
2981                                         method_prefix, opcls->flags,
2982                                         psyc_recv_history_message, NULL,
2983                                         psyc_recv_history_result, opcls);
2984   else
2985     GNUNET_PSYC_channel_history_replay_latest (plc->channel,
2986                                                GNUNET_ntohll (req->message_limit),
2987                                                method_prefix, opcls->flags,
2988                                                psyc_recv_history_message, NULL,
2989                                                psyc_recv_history_result, opcls);
2990
2991   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2992 }
2993
2994
2995 /**
2996  * A state variable part arrived from PSYC.
2997  */
2998 void
2999 psyc_recv_state_var (void *cls,
3000                      const struct GNUNET_MessageHeader *mod,
3001                      const char *name,
3002                      const void *value,
3003                      uint32_t value_size,
3004                      uint32_t full_value_size)
3005 {
3006   struct OperationClosure *opcls = cls;
3007   struct Place *plc = opcls->plc;
3008
3009   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3010               "%p Received state variable %s from PSYC\n",
3011               plc, name);
3012
3013   uint16_t size = ntohs (mod->size);
3014
3015   struct GNUNET_OperationResultMessage *
3016     res = GNUNET_malloc (sizeof (*res) + size);
3017   res->header.size = htons (sizeof (*res) + size);
3018   res->header.type = htons (GNUNET_MESSAGE_TYPE_PSYC_STATE_RESULT);
3019   res->op_id = opcls->op_id;
3020   res->result_code = GNUNET_htonll (GNUNET_OK);
3021
3022   GNUNET_memcpy (&res[1], mod, size);
3023
3024   /** @todo FIXME: send only to requesting client */
3025   place_send_msg (plc, &res->header);
3026
3027   GNUNET_free (res);
3028 }
3029
3030
3031 /**
3032  * Result of retrieving state variable from PSYC.
3033  */
3034 static void
3035 psyc_recv_state_result (void *cls, int64_t result,
3036                         const void *err_msg, uint16_t err_msg_size)
3037 {
3038   struct OperationClosure *opcls = cls;
3039   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3040               "%p State get #%" PRIu64 ": "
3041               "PSYCstore returned %" PRId64 " (%.*s)\n",
3042               opcls->plc, GNUNET_ntohll (opcls->op_id), result,
3043               err_msg_size, (const char *) err_msg);
3044
3045   // FIXME: place might have been destroyed
3046   client_send_result (opcls->client, opcls->op_id, result, err_msg, err_msg_size);
3047 }
3048
3049
3050 /**
3051  * Client requests channel history.
3052  */
3053 static void
3054 client_recv_state_get (void *cls, struct GNUNET_SERVER_Client *client,
3055                        const struct GNUNET_MessageHeader *msg)
3056 {
3057   struct Client *
3058     ctx = GNUNET_SERVER_client_get_user_context (client, struct Client);
3059   GNUNET_assert (NULL != ctx);
3060   struct Place *plc = ctx->plc;
3061
3062   const struct GNUNET_PSYC_StateRequestMessage *
3063     req = (const struct GNUNET_PSYC_StateRequestMessage *) msg;
3064   uint16_t size = ntohs (msg->size);
3065   const char *name = (const char *) &req[1];
3066
3067   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3068               "%p State get #%" PRIu64 ": %s\n",
3069               plc, GNUNET_ntohll (req->op_id), name);
3070
3071   if (size < sizeof (*req) + 1
3072       || '\0' != name[size - sizeof (*req) - 1])
3073   {
3074     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3075                 "%p State get #%" PRIu64 ": "
3076                 "invalid name. size: %u < %zu?\n",
3077                 plc, GNUNET_ntohll (req->op_id), size, sizeof (*req) + 1);
3078     GNUNET_break (0);
3079     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
3080     return;
3081   }
3082
3083   struct OperationClosure *opcls = GNUNET_malloc (sizeof (*opcls));
3084   opcls->client = client;
3085   opcls->plc = plc;
3086   opcls->op_id = req->op_id;
3087
3088   switch (ntohs (msg->type))
3089   {
3090   case GNUNET_MESSAGE_TYPE_PSYC_STATE_GET:
3091       GNUNET_PSYC_channel_state_get (plc->channel, name,
3092                                      psyc_recv_state_var,
3093                                      psyc_recv_state_result, opcls);
3094       break;
3095
3096   case GNUNET_MESSAGE_TYPE_PSYC_STATE_GET_PREFIX:
3097       GNUNET_PSYC_channel_state_get_prefix (plc->channel, name,
3098                                             psyc_recv_state_var,
3099                                             psyc_recv_state_result, opcls);
3100       break;
3101
3102   default:
3103       GNUNET_assert (0);
3104   }
3105
3106   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3107 }
3108
3109
3110 static void
3111 namestore_recv_records_store_result (void *cls, int32_t result,
3112                                      const char *err_msg)
3113 {
3114   struct OperationClosure *ocls = cls;
3115   client_send_result (ocls->client, ocls->op_id, result, err_msg,
3116                       (NULL != err_msg) ? strlen (err_msg) : 0);
3117   GNUNET_free (ocls);
3118 }
3119
3120
3121 /**
3122  * Handle request to add PLACE record to GNS zone.
3123  */
3124 static void
3125 client_recv_zone_add_place (void *cls, struct GNUNET_SERVER_Client *client,
3126                              const struct GNUNET_MessageHeader *msg)
3127 {
3128   const struct ZoneAddPlaceRequest *preq
3129     = (const struct ZoneAddPlaceRequest *) msg;
3130
3131   uint16_t remaining = ntohs (preq->header.size) - sizeof (*preq);
3132   const char *p = (const char *) &preq[1];
3133   const char *name = NULL, *password = NULL;
3134   uint16_t offset = GNUNET_STRINGS_buffer_tokenize (p, remaining, 2,
3135                                                     &name, &password);
3136   remaining -= offset;
3137   p += offset;
3138   const struct GNUNET_PeerIdentity *
3139     relays = (const struct GNUNET_PeerIdentity *) p;
3140   uint16_t relay_size = ntohl (preq->relay_count) * sizeof (*relays);
3141
3142   if (0 == offset || remaining != relay_size)
3143   {
3144     GNUNET_break (0);
3145     client_send_result (client, preq->op_id, GNUNET_SYSERR, NULL, 0);
3146     GNUNET_SERVER_receive_done (client, GNUNET_OK);
3147     return;
3148   }
3149
3150   struct GNUNET_GNSRECORD_Data rd = { };
3151   rd.record_type = GNUNET_GNSRECORD_TYPE_PLACE;
3152   rd.flags = GNUNET_GNSRECORD_RF_RELATIVE_EXPIRATION;
3153   rd.expiration_time = GNUNET_ntohll (preq->expiration_time);
3154
3155   struct GNUNET_GNSRECORD_PlaceData *
3156     rec = GNUNET_malloc (sizeof (*rec) + relay_size);
3157   rec->place_pub_key = preq->place_pub_key;
3158   rec->origin = this_peer;
3159   rec->relay_count = preq->relay_count;
3160   GNUNET_memcpy (&rec[1], relays, relay_size);
3161
3162   rd.data = rec;
3163   rd.data_size = sizeof (*rec) + relay_size;
3164
3165   struct GNUNET_HashCode ego_pub_hash;
3166   GNUNET_CRYPTO_hash (&preq->ego_pub_key, sizeof (preq->ego_pub_key), &ego_pub_hash);
3167   struct Ego *ego = GNUNET_CONTAINER_multihashmap_get (egos, &ego_pub_hash);
3168   if (NULL == ego)
3169   {
3170     client_send_result (client, preq->op_id, GNUNET_SYSERR, NULL, 0);
3171   }
3172   else
3173   {
3174     struct OperationClosure *ocls = GNUNET_malloc (sizeof (*ocls));
3175     ocls->client = client;
3176     ocls->op_id = preq->op_id;
3177     GNUNET_NAMESTORE_records_store (namestore, &ego->key,
3178                                     name, 1, &rd,
3179                                     namestore_recv_records_store_result, ocls);
3180     /** @todo refresh stored records later */
3181   }
3182   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3183 }
3184
3185
3186 /**
3187  * Handle request to add PLACE record to GNS zone.
3188  */
3189 static void
3190 client_recv_zone_add_nym (void *cls, struct GNUNET_SERVER_Client *client,
3191                           const struct GNUNET_MessageHeader *msg)
3192 {
3193   const struct ZoneAddNymRequest *nreq
3194     = (const struct ZoneAddNymRequest *) msg;
3195
3196   uint16_t name_size = ntohs (nreq->header.size) - sizeof (*nreq);
3197   const char *name = NULL;
3198   uint16_t offset = GNUNET_STRINGS_buffer_tokenize ((const char *) &nreq[1],
3199                                                     name_size, 1, &name);
3200   if (0 == offset || offset != name_size)
3201   {
3202     GNUNET_break (0);
3203     client_send_result (client, nreq->op_id, GNUNET_SYSERR, NULL, 0);
3204     GNUNET_SERVER_receive_done (client, GNUNET_OK);
3205     return;
3206   }
3207
3208   struct GNUNET_GNSRECORD_Data rd = { };
3209   rd.record_type = GNUNET_GNSRECORD_TYPE_PKEY;
3210   rd.flags = GNUNET_GNSRECORD_RF_RELATIVE_EXPIRATION;
3211   rd.expiration_time = GNUNET_ntohll (nreq->expiration_time);
3212   rd.data = &nreq->nym_pub_key;
3213   rd.data_size = sizeof (nreq->nym_pub_key);
3214
3215   struct GNUNET_HashCode ego_pub_hash;
3216   GNUNET_CRYPTO_hash (&nreq->ego_pub_key, sizeof (nreq->ego_pub_key), &ego_pub_hash);
3217   struct Ego *ego = GNUNET_CONTAINER_multihashmap_get (egos, &ego_pub_hash);
3218   if (NULL == ego)
3219   {
3220     client_send_result (client, nreq->op_id, GNUNET_SYSERR, NULL, 0);
3221   }
3222   else
3223   {
3224     struct OperationClosure *ocls = GNUNET_malloc (sizeof (*ocls));
3225     ocls->client = client;
3226     ocls->op_id = nreq->op_id;
3227     GNUNET_NAMESTORE_records_store (namestore, &ego->key,
3228                                     name, 1, &rd,
3229                                     namestore_recv_records_store_result, ocls);
3230     /** @todo refresh stored records later */
3231   }
3232   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3233 }
3234
3235
3236 static const struct GNUNET_SERVER_MessageHandler handlers[] = {
3237   { client_recv_host_enter, NULL,
3238     GNUNET_MESSAGE_TYPE_SOCIAL_HOST_ENTER, 0 },
3239
3240   { client_recv_guest_enter, NULL,
3241     GNUNET_MESSAGE_TYPE_SOCIAL_GUEST_ENTER, 0 },
3242
3243   { client_recv_guest_enter_by_name, NULL,
3244     GNUNET_MESSAGE_TYPE_SOCIAL_GUEST_ENTER_BY_NAME, 0 },
3245
3246   { client_recv_join_decision, NULL,
3247     GNUNET_MESSAGE_TYPE_PSYC_JOIN_DECISION, 0 },
3248
3249   { client_recv_psyc_message, NULL,
3250     GNUNET_MESSAGE_TYPE_PSYC_MESSAGE, 0 },
3251
3252   { client_recv_history_replay, NULL,
3253     GNUNET_MESSAGE_TYPE_PSYC_HISTORY_REPLAY, 0 },
3254
3255   { client_recv_state_get, NULL,
3256     GNUNET_MESSAGE_TYPE_PSYC_STATE_GET, 0 },
3257
3258   { client_recv_state_get, NULL,
3259     GNUNET_MESSAGE_TYPE_PSYC_STATE_GET_PREFIX, 0 },
3260
3261   { client_recv_zone_add_place, NULL,
3262     GNUNET_MESSAGE_TYPE_SOCIAL_ZONE_ADD_PLACE, 0 },
3263
3264   { client_recv_zone_add_nym, NULL,
3265     GNUNET_MESSAGE_TYPE_SOCIAL_ZONE_ADD_NYM, 0 },
3266
3267   { client_recv_app_connect, NULL,
3268     GNUNET_MESSAGE_TYPE_SOCIAL_APP_CONNECT, 0 },
3269
3270   { client_recv_app_detach, NULL,
3271     GNUNET_MESSAGE_TYPE_SOCIAL_APP_DETACH, 0 },
3272
3273   { client_recv_place_leave, NULL,
3274     GNUNET_MESSAGE_TYPE_SOCIAL_PLACE_LEAVE, 0 },
3275
3276   { client_recv_msg_proc_set, NULL,
3277     GNUNET_MESSAGE_TYPE_SOCIAL_MSG_PROC_SET, 0 },
3278
3279   { client_recv_msg_proc_clear, NULL,
3280     GNUNET_MESSAGE_TYPE_SOCIAL_MSG_PROC_CLEAR, 0 },
3281
3282   { NULL, NULL, 0, 0 }
3283 };
3284
3285
3286 const char *
3287 path_basename (const char *path)
3288 {
3289   const char *basename = strrchr (path, DIR_SEPARATOR);
3290   if (NULL != basename)
3291     basename++;
3292
3293   if (NULL == basename || '\0' == basename)
3294     return NULL;
3295
3296   return basename;
3297 }
3298
3299
3300 struct PlaceLoadClosure
3301 {
3302   const char *app_id;
3303   const char *ego_pub_str;
3304 };
3305
3306
3307 /** Load a place file */
3308 int
3309 file_place_load (void *cls, const char *place_filename)
3310 {
3311   struct PlaceLoadClosure *plcls = cls;
3312
3313   const char *place_pub_str = path_basename (place_filename);
3314   if (NULL == place_pub_str)
3315   {
3316     GNUNET_break (0);
3317     return GNUNET_OK;
3318   }
3319
3320   char *filename = NULL;
3321   GNUNET_asprintf (&filename, "%s%c" "%s%c" "%s%c" "%s",
3322                    dir_social, DIR_SEPARATOR,
3323                    "places", DIR_SEPARATOR,
3324                    plcls->ego_pub_str, DIR_SEPARATOR,
3325                    place_pub_str);
3326
3327   uint64_t file_size = 0;
3328   if (GNUNET_OK !=
3329       GNUNET_DISK_file_size (filename, &file_size, GNUNET_YES, GNUNET_YES)
3330       || file_size < sizeof (struct PlaceEnterRequest))
3331   {
3332     GNUNET_free (filename);
3333     return GNUNET_OK;
3334   }
3335
3336   struct PlaceEnterRequest *ereq = GNUNET_malloc (file_size);
3337   ssize_t read_size = GNUNET_DISK_fn_read (filename, ereq, file_size);
3338   GNUNET_free (filename);
3339   if (read_size < 0 || read_size < sizeof (*ereq))
3340   {
3341     GNUNET_free (ereq);
3342     return GNUNET_OK;
3343   }
3344
3345   uint16_t ereq_size = ntohs (ereq->header.size);
3346   if (read_size != ereq_size)
3347   {
3348     GNUNET_free (ereq);
3349     return GNUNET_OK;
3350   }
3351
3352   switch (ntohs (ereq->header.type))
3353   {
3354   case GNUNET_MESSAGE_TYPE_SOCIAL_HOST_ENTER:
3355     if (ereq_size < sizeof (struct HostEnterRequest))
3356     {
3357       GNUNET_free (ereq);
3358       return GNUNET_OK;
3359     }
3360     struct HostEnterRequest *hreq = (struct HostEnterRequest *) ereq;
3361     host_enter (hreq, NULL);
3362     break;
3363
3364   case GNUNET_MESSAGE_TYPE_SOCIAL_GUEST_ENTER:
3365     if (ereq_size < sizeof (struct GuestEnterRequest))
3366     {
3367       GNUNET_free (ereq);
3368       return GNUNET_OK;
3369     }
3370     struct GuestEnterRequest *greq = (struct GuestEnterRequest *) ereq;
3371     guest_enter (greq, NULL);
3372     break;
3373
3374   default:
3375     GNUNET_free (ereq);
3376     return GNUNET_OK;
3377   }
3378
3379   app_place_add (plcls->app_id, ereq);
3380   GNUNET_free (ereq);
3381   return GNUNET_OK;
3382 }
3383
3384
3385 /**
3386  * Read @e place_pub_str entries in @a dir_ego
3387  *
3388  * @param dir_ego
3389  *        Data directory of an application ego.
3390  *        $GNUNET_DATA_HOME/social/apps/$app_id/$ego_pub_str/
3391  */
3392 int
3393 scan_app_ego_dir (void *cls, const char *dir_ego)
3394 {
3395   struct PlaceLoadClosure *plcls = cls;
3396   plcls->ego_pub_str = path_basename (dir_ego);
3397
3398   if (NULL != plcls->ego_pub_str)
3399     GNUNET_DISK_directory_scan (dir_ego, file_place_load, plcls);
3400
3401   return GNUNET_OK;
3402 }
3403
3404 /**
3405  * Read @e ego_pub_str entries in @a dir_app
3406  *
3407  * @param dir_app
3408  *        Data directory of an application.
3409  *        $GNUNET_DATA_HOME/social/apps/$app_id/
3410  */
3411 int
3412 scan_app_dir (void *cls, const char *dir_app)
3413 {
3414   if (GNUNET_YES != GNUNET_DISK_directory_test (dir_app, GNUNET_YES))
3415     return GNUNET_OK;
3416
3417   struct PlaceLoadClosure plcls;
3418   plcls.app_id = path_basename (dir_app);
3419
3420   if (NULL != plcls.app_id)
3421     GNUNET_DISK_directory_scan (dir_app, scan_app_ego_dir, &plcls);
3422
3423   return GNUNET_OK;
3424 }
3425
3426
3427 static void
3428 identity_recv_ego (void *cls, struct GNUNET_IDENTITY_Ego *id_ego,
3429                    void **ctx, const char *name)
3430 {
3431   if (NULL == id_ego) // end of initial list of egos
3432     return;
3433
3434   struct GNUNET_CRYPTO_EcdsaPublicKey ego_pub_key;
3435   GNUNET_IDENTITY_ego_get_public_key (id_ego, &ego_pub_key);
3436
3437   struct GNUNET_HashCode ego_pub_hash;
3438   GNUNET_CRYPTO_hash (&ego_pub_key, sizeof (ego_pub_key), &ego_pub_hash);
3439
3440   struct Ego *ego = GNUNET_CONTAINER_multihashmap_get (egos, &ego_pub_hash);
3441   if (NULL != ego)
3442   {
3443     GNUNET_free (ego->name);
3444     if (NULL == name) // deleted
3445     {
3446       GNUNET_CONTAINER_multihashmap_remove (egos, &ego_pub_hash, ego);
3447       GNUNET_free (ego);
3448       ego = NULL;
3449     }
3450   }
3451   else
3452   {
3453     ego = GNUNET_malloc (sizeof (*ego));
3454   }
3455   if (NULL != ego)
3456   {
3457     ego->key = *(GNUNET_IDENTITY_ego_get_private_key (id_ego));
3458     size_t name_size = strlen (name) + 1;
3459     ego->name = GNUNET_malloc (name_size);
3460     GNUNET_memcpy (ego->name, name, name_size);
3461
3462     GNUNET_CONTAINER_multihashmap_put (egos, &ego_pub_hash, ego,
3463                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
3464   }
3465
3466   // FIXME: notify clients about changed ego
3467 }
3468
3469
3470 /**
3471  * Connected to core service.
3472  */
3473 static void
3474 core_connected (void *cls, const struct GNUNET_PeerIdentity *my_identity)
3475 {
3476   this_peer = *my_identity;
3477 }
3478
3479
3480 /**
3481  * Initialize the PSYC service.
3482  *
3483  * @param cls Closure.
3484  * @param server The initialized server.
3485  * @param c Configuration to use.
3486  */
3487 static void
3488 run (void *cls, struct GNUNET_SERVER_Handle *server,
3489      const struct GNUNET_CONFIGURATION_Handle *c)
3490 {
3491   cfg = c;
3492
3493   hosts = GNUNET_CONTAINER_multihashmap_create (1, GNUNET_YES);
3494   guests = GNUNET_CONTAINER_multihashmap_create (1, GNUNET_YES);
3495   place_guests = GNUNET_CONTAINER_multihashmap_create (1, GNUNET_NO);
3496
3497   egos = GNUNET_CONTAINER_multihashmap_create (1, GNUNET_NO);
3498   apps = GNUNET_CONTAINER_multihashmap_create (1, GNUNET_NO);
3499   places = GNUNET_CONTAINER_multihashmap_create(1, GNUNET_NO);
3500   apps_places = GNUNET_CONTAINER_multihashmap_create(1, GNUNET_NO);
3501   places_apps = GNUNET_CONTAINER_multihashmap_create(1, GNUNET_NO);
3502
3503   core = GNUNET_CORE_connect (cfg, NULL, core_connected, NULL, NULL,
3504                               NULL, GNUNET_NO, NULL, GNUNET_NO, NULL);
3505   id = GNUNET_IDENTITY_connect (cfg, &identity_recv_ego, NULL);
3506   gns = GNUNET_GNS_connect (cfg);
3507   namestore = GNUNET_NAMESTORE_connect (cfg);
3508   stats = GNUNET_STATISTICS_create ("social", cfg);
3509
3510   if (GNUNET_OK !=
3511       GNUNET_CONFIGURATION_get_value_filename (cfg, "social", "DATA_HOME",
3512                                                &dir_social))
3513   {
3514     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
3515                                "social", "DATA_HOME");
3516     GNUNET_break (0);
3517     return;
3518   }
3519   GNUNET_asprintf (&dir_places, "%s%c%s",
3520                    dir_social, DIR_SEPARATOR, "places");
3521   GNUNET_asprintf (&dir_apps, "%s%c%s",
3522                    dir_social, DIR_SEPARATOR, "apps");
3523
3524   GNUNET_DISK_directory_scan (dir_apps, scan_app_dir, NULL);
3525
3526   nc = GNUNET_SERVER_notification_context_create (server, 1);
3527   GNUNET_SERVER_add_handlers (server, handlers);
3528   GNUNET_SERVER_disconnect_notify (server, &client_disconnect, NULL);
3529   GNUNET_SCHEDULER_add_shutdown (&shutdown_task, NULL);
3530 }
3531
3532
3533 /**
3534  * The main function for the service.
3535  *
3536  * @param argc number of arguments from the command line
3537  * @param argv command line arguments
3538  * @return 0 ok, 1 on error
3539  */
3540 int
3541 main (int argc, char *const *argv)
3542 {
3543   return (GNUNET_OK ==
3544           GNUNET_SERVICE_run (argc, argv, "social",
3545                               GNUNET_SERVICE_OPTION_NONE,
3546                               &run, NULL)) ? 0 : 1;
3547 }
3548
3549 /* end of gnunet-service-social.c */