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