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