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