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