run indent twice, it alternates between two 'canonical' forms, also run whitespace...
[oweals/gnunet.git] / src / chat / gnunet-service-chat.c
1 /*
2      This file is part of GNUnet.
3      (C) 2009, 2011 Christian Grothoff (and other contributing authors)
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., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file chat/gnunet-service-chat.c
23  * @brief service providing chat functionality
24  * @author Christian Grothoff
25  * @author Vitaly Minko
26  */
27
28 #include "platform.h"
29 #include "gnunet_core_service.h"
30 #include "gnunet_crypto_lib.h"
31 #include "gnunet_protocols.h"
32 #include "gnunet_service_lib.h"
33 #include "gnunet_signatures.h"
34 #include "chat.h"
35
36 #define DEBUG_CHAT_SERVICE GNUNET_NO
37 #define MAX_TRANSMIT_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 60)
38 #define EXPECTED_NEIGHBOUR_COUNT 16
39 #define QUEUE_SIZE 16
40 #define MAX_ANONYMOUS_MSG_LIST_LENGTH 16
41
42
43 /**
44  * Linked list of our current clients.
45  */
46 struct ChatClient
47 {
48   struct ChatClient *next;
49
50   /**
51    * Handle for a chat client (NULL for external clients).
52    */
53   struct GNUNET_SERVER_Client *client;
54
55   /**
56    * Public key of the client.
57    */
58   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded public_key;
59
60   /**
61    * Name of the room which the client is in.
62    */
63   char *room;
64
65   /**
66    * Serialized metadata of the client.
67    */
68   char *member_info;
69
70   /**
71    * Hash of the public key (for convenience).
72    */
73   GNUNET_HashCode id;
74
75   /**
76    * Options which the client is willing to receive.
77    */
78   uint32_t msg_options;
79
80   /**
81    * Length of serialized metadata in member_info.
82    */
83   uint16_t meta_len;
84
85   /**
86    * Sequence number of the last message sent by the client.
87    */
88   uint32_t msg_sequence_number;
89
90   /**
91    * Sequence number of the last receipt sent by the client.
92    * Used to discard already processed receipts.
93    */
94   uint32_t rcpt_sequence_number;
95
96 };
97
98 /**
99  * Information about a peer that we are connected to.
100  * We track data that is useful for determining which
101  * peers should receive our requests.
102  */
103 struct ConnectedPeer
104 {
105   /**
106    * The peer's identity.
107    */
108   GNUNET_PEER_Id pid;
109 };
110
111 /**
112  * Linked list of recent anonymous messages.
113  */
114 struct AnonymousMessage
115 {
116   struct AnonymousMessage *next;
117
118   /**
119    * Hash of the message.
120    */
121   GNUNET_HashCode hash;
122
123 };
124
125
126 /**
127  * Handle to the core service (NULL until we've connected to it).
128  */
129 static struct GNUNET_CORE_Handle *core;
130
131 /**
132  * Our configuration.
133  */
134 static const struct GNUNET_CONFIGURATION_Handle *cfg;
135
136 /**
137  * The identity of this host.
138  */
139 static const struct GNUNET_PeerIdentity *me;
140
141 /**
142  * Head of the list of current clients.
143  */
144 static struct ChatClient *client_list_head = NULL;
145
146 /**
147  * Notification context containing all connected clients.
148  */
149 struct GNUNET_SERVER_NotificationContext *nc = NULL;
150
151 /**
152  * Head of the list of recent anonymous messages.
153  */
154 static struct AnonymousMessage *anonymous_list_head = NULL;
155
156 /**
157  * Map of peer identifiers to "struct ConnectedPeer" (for that peer).
158  */
159 static struct GNUNET_CONTAINER_MultiHashMap *connected_peers;
160
161
162 static void
163 remember_anonymous_message (const struct P2PReceiveNotificationMessage
164                             *p2p_rnmsg)
165 {
166   static GNUNET_HashCode hash;
167   struct AnonymousMessage *anon_msg;
168   struct AnonymousMessage *prev;
169   int anon_list_len;
170
171   GNUNET_CRYPTO_hash (p2p_rnmsg, ntohs (p2p_rnmsg->header.size), &hash);
172   anon_msg = GNUNET_malloc (sizeof (struct AnonymousMessage));
173   anon_msg->hash = hash;
174   anon_msg->next = anonymous_list_head;
175   anonymous_list_head = anon_msg;
176   anon_list_len = 1;
177   prev = NULL;
178   while ((NULL != anon_msg->next))
179   {
180     prev = anon_msg;
181     anon_msg = anon_msg->next;
182     anon_list_len++;
183   }
184   if (anon_list_len == MAX_ANONYMOUS_MSG_LIST_LENGTH)
185   {
186     GNUNET_free (anon_msg);
187     if (NULL != prev)
188       prev->next = NULL;
189   }
190 }
191
192
193 static int
194 lookup_anonymous_message (const struct P2PReceiveNotificationMessage *p2p_rnmsg)
195 {
196   static GNUNET_HashCode hash;
197   struct AnonymousMessage *anon_msg;
198
199   GNUNET_CRYPTO_hash (p2p_rnmsg, ntohs (p2p_rnmsg->header.size), &hash);
200   anon_msg = anonymous_list_head;
201   while ((NULL != anon_msg) &&
202          (0 != memcmp (&anon_msg->hash, &hash, sizeof (GNUNET_HashCode))))
203     anon_msg = anon_msg->next;
204   return (NULL != anon_msg);
205 }
206
207
208 /**
209  * Transmit a message notification to the peer.
210  *
211  * @param cls closure, pointer to the 'struct P2PReceiveNotificationMessage'
212  * @param size number of bytes available in buf
213  * @param buf where the callee should write the message
214  * @return number of bytes written to buf
215  */
216 static size_t
217 transmit_message_notification_to_peer (void *cls, size_t size, void *buf)
218 {
219   struct P2PReceiveNotificationMessage *my_msg = cls;
220   struct P2PReceiveNotificationMessage *m = buf;
221   size_t msg_size;
222
223 #if DEBUG_CHAT_SERVICE
224   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
225               "Transmitting P2P message notification\n");
226 #endif
227   if (buf == NULL)
228   {
229     /* client disconnected */
230 #if DEBUG_CHAT_SERVICE
231     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
232                 "Buffer is NULL, dropping the message\n");
233 #endif
234     return 0;
235   }
236   msg_size = ntohs (my_msg->header.size);
237   GNUNET_assert (size >= msg_size);
238   memcpy (m, my_msg, msg_size);
239   GNUNET_free (my_msg);
240   return msg_size;
241 }
242
243
244 /**
245  * Ask to send a message notification to the peer.
246  */
247 static int
248 send_message_noficiation (void *cls, const GNUNET_HashCode * key, void *value)
249 {
250   struct P2PReceiveNotificationMessage *msg = cls;
251   struct ConnectedPeer *cp = value;
252   struct GNUNET_PeerIdentity pid;
253   struct P2PReceiveNotificationMessage *my_msg;
254
255   GNUNET_PEER_resolve (cp->pid, &pid);
256 #if DEBUG_CHAT_SERVICE
257   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending message notification to `%s'\n",
258               GNUNET_i2s (&pid));
259 #endif
260   my_msg = GNUNET_memdup (msg, ntohs (msg->header.size));
261   if (NULL ==
262       GNUNET_CORE_notify_transmit_ready (core, GNUNET_NO, 1, MAX_TRANSMIT_DELAY,
263                                          &pid, ntohs (msg->header.size),
264                                          &transmit_message_notification_to_peer,
265                                          my_msg))
266     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
267                 _("Failed to queue a message notification\n"));
268   return GNUNET_YES;
269 }
270
271
272 /**
273  * A client sent a chat message.  Encrypt the message text if the message is
274  * private.  Send the message to local room members and to all connected peers.
275  *
276  * @param cls closure, NULL
277  * @param client identification of the client
278  * @param message the actual message
279  */
280 static void
281 handle_transmit_request (void *cls, struct GNUNET_SERVER_Client *client,
282                          const struct GNUNET_MessageHeader *message)
283 {
284   static GNUNET_HashCode all_zeros;
285   const struct TransmitRequestMessage *trmsg;
286   struct ReceiveNotificationMessage *rnmsg;
287   struct P2PReceiveNotificationMessage *p2p_rnmsg;
288   struct ChatClient *pos;
289   struct ChatClient *target;
290   struct GNUNET_CRYPTO_AesSessionKey key;
291   char encrypted_msg[MAX_MESSAGE_LENGTH];
292   const char *room;
293   size_t room_len;
294   int msg_len;
295   int is_priv;
296   int is_anon;
297
298   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Client sent a chat message\n");
299   if (ntohs (message->size) <= sizeof (struct TransmitRequestMessage))
300   {
301     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Malformed message: wrong size\n");
302     GNUNET_break (0);
303     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
304     return;
305   }
306   trmsg = (const struct TransmitRequestMessage *) message;
307   msg_len = ntohs (trmsg->header.size) - sizeof (struct TransmitRequestMessage);
308   is_priv = (0 != (ntohl (trmsg->msg_options) & GNUNET_CHAT_MSG_PRIVATE));
309   if (is_priv)
310   {
311 #if DEBUG_CHAT_SERVICE
312     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Encrypting the message text\n");
313 #endif
314     GNUNET_CRYPTO_aes_create_session_key (&key);
315     msg_len =
316         GNUNET_CRYPTO_aes_encrypt (&trmsg[1], msg_len, &key,
317                                    (const struct
318                                     GNUNET_CRYPTO_AesInitializationVector *)
319                                    INITVALUE, encrypted_msg);
320     if (-1 == msg_len)
321     {
322       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
323                   "Could not encrypt the message text\n");
324       GNUNET_break (0);
325       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
326       return;
327     }
328   }
329   rnmsg = GNUNET_malloc (sizeof (struct ReceiveNotificationMessage) + msg_len);
330   rnmsg->header.size =
331       htons (sizeof (struct ReceiveNotificationMessage) + msg_len);
332   rnmsg->header.type = htons (GNUNET_MESSAGE_TYPE_CHAT_MESSAGE_NOTIFICATION);
333   rnmsg->msg_options = trmsg->msg_options;
334   rnmsg->timestamp = trmsg->timestamp;
335   pos = client_list_head;
336   while ((NULL != pos) && (pos->client != client))
337     pos = pos->next;
338   if (NULL == pos)
339   {
340     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
341                 "The client is not a member of a chat room. Client has to "
342                 "join a chat room first\n");
343     GNUNET_break (0);
344     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
345     GNUNET_free (rnmsg);
346     return;
347   }
348   room = pos->room;
349   pos->msg_sequence_number = ntohl (trmsg->sequence_number);
350   is_anon = (0 != (ntohl (trmsg->msg_options) & GNUNET_CHAT_MSG_ANONYMOUS));
351   if (is_anon)
352   {
353     memset (&rnmsg->sender, 0, sizeof (GNUNET_HashCode));
354     rnmsg->sequence_number = 0;
355   }
356   else
357   {
358     rnmsg->sender = pos->id;
359     rnmsg->sequence_number = trmsg->sequence_number;
360   }
361   if (is_priv)
362   {
363 #if DEBUG_CHAT_SERVICE
364     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
365                 "Encrypting the session key using the public key of '%s'\n",
366                 GNUNET_h2s (&trmsg->target));
367 #endif
368     if (0 == memcmp (&all_zeros, &trmsg->target, sizeof (GNUNET_HashCode)))
369     {
370       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
371                   "Malformed message: private, but no target\n");
372       GNUNET_break (0);
373       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
374       GNUNET_free (rnmsg);
375       return;
376     }
377     memcpy (&rnmsg[1], encrypted_msg, msg_len);
378     target = client_list_head;
379     while ((NULL != target) &&
380            (0 !=
381             memcmp (&target->id, &trmsg->target, sizeof (GNUNET_HashCode))))
382       target = target->next;
383     if (NULL == target)
384     {
385       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
386                   "Unknown target of the private message\n");
387       GNUNET_break (0);
388       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
389       GNUNET_free (rnmsg);
390       return;
391     }
392     if (GNUNET_SYSERR ==
393         GNUNET_CRYPTO_rsa_encrypt (&key,
394                                    sizeof (struct GNUNET_CRYPTO_AesSessionKey),
395                                    &target->public_key, &rnmsg->encrypted_key))
396     {
397       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
398                   "Could not encrypt the session key\n");
399       GNUNET_break (0);
400       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
401       GNUNET_free (rnmsg);
402       return;
403     }
404   }
405   else
406   {
407     memcpy (&rnmsg[1], &trmsg[1], msg_len);
408   }
409   pos = client_list_head;
410 #if DEBUG_CHAT_SERVICE
411   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
412               "Sending message to local room members\n");
413 #endif
414   while (NULL != pos)
415   {
416     if ((0 == strcmp (room, pos->room)) && (NULL != pos->client) &&
417         (pos->client != client))
418     {
419       if (((!is_priv) ||
420            (0 == memcmp (&trmsg->target, &pos->id, sizeof (GNUNET_HashCode))))
421           && (0 == (ntohl (trmsg->msg_options) & (~pos->msg_options))))
422       {
423         GNUNET_SERVER_notification_context_unicast (nc, pos->client,
424                                                     &rnmsg->header, GNUNET_NO);
425       }
426     }
427     pos = pos->next;
428   }
429 #if DEBUG_CHAT_SERVICE
430   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
431               "Broadcasting message to neighbour peers\n");
432 #endif
433   if (is_anon)
434   {
435     room_len = strlen (room);
436     p2p_rnmsg =
437         GNUNET_malloc (sizeof (struct P2PReceiveNotificationMessage) + msg_len +
438                        room_len);
439     p2p_rnmsg->header.size =
440         htons (sizeof (struct P2PReceiveNotificationMessage) + msg_len +
441                room_len);
442     p2p_rnmsg->room_name_len = htons (room_len);
443     memcpy ((char *) &p2p_rnmsg[1], room, room_len);
444     memcpy ((char *) &p2p_rnmsg[1] + room_len, &trmsg[1], msg_len);
445   }
446   else
447   {
448     p2p_rnmsg =
449         GNUNET_malloc (sizeof (struct P2PReceiveNotificationMessage) + msg_len);
450     p2p_rnmsg->header.size =
451         htons (sizeof (struct P2PReceiveNotificationMessage) + msg_len);
452     if (is_priv)
453     {
454       memcpy (&p2p_rnmsg[1], encrypted_msg, msg_len);
455       memcpy (&p2p_rnmsg->encrypted_key, &rnmsg->encrypted_key,
456               sizeof (struct GNUNET_CRYPTO_RsaEncryptedData));
457     }
458     else
459       memcpy (&p2p_rnmsg[1], &trmsg[1], msg_len);
460   }
461   p2p_rnmsg->header.type =
462       htons (GNUNET_MESSAGE_TYPE_CHAT_P2P_MESSAGE_NOTIFICATION);
463   p2p_rnmsg->msg_options = trmsg->msg_options;
464   p2p_rnmsg->sequence_number = trmsg->sequence_number;
465   p2p_rnmsg->timestamp = trmsg->timestamp;
466   p2p_rnmsg->reserved = htons (0);
467   p2p_rnmsg->sender = rnmsg->sender;
468   p2p_rnmsg->target = trmsg->target;
469   if (is_anon)
470     remember_anonymous_message (p2p_rnmsg);
471   GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
472                                          &send_message_noficiation, p2p_rnmsg);
473   GNUNET_free (p2p_rnmsg);
474   GNUNET_SERVER_receive_done (client, GNUNET_OK);
475   GNUNET_free (rnmsg);
476 }
477
478
479 /**
480  * Transmit a join notification to the peer.
481  *
482  * @param cls closure, pointer to the 'struct ChatClient'
483  * @param size number of bytes available in buf
484  * @param buf where the callee should write the message
485  * @return number of bytes written to buf
486  */
487 static size_t
488 transmit_join_notification_to_peer (void *cls, size_t size, void *buf)
489 {
490   struct ChatClient *entry = cls;
491   struct P2PJoinNotificationMessage *m = buf;
492   size_t room_len;
493   size_t meta_len;
494   size_t msg_size;
495   char *roomptr;
496
497 #if DEBUG_CHAT_SERVICE
498   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Transmitting P2P join notification\n");
499 #endif
500   room_len = strlen (entry->room);
501   meta_len = entry->meta_len;
502   msg_size = sizeof (struct P2PJoinNotificationMessage) + meta_len + room_len;
503   GNUNET_assert (size >= msg_size);
504   GNUNET_assert (NULL != buf);
505   m = buf;
506   m->header.type = htons (GNUNET_MESSAGE_TYPE_CHAT_P2P_JOIN_NOTIFICATION);
507   m->header.size = htons (msg_size);
508   m->msg_options = htonl (entry->msg_options);
509   m->room_name_len = htons (room_len);
510   m->reserved = htons (0);
511   m->reserved2 = htonl (0);
512   m->public_key = entry->public_key;
513   roomptr = (char *) &m[1];
514   memcpy (roomptr, entry->room, room_len);
515   if (meta_len > 0)
516     memcpy (&roomptr[room_len], entry->member_info, meta_len);
517   return msg_size;
518 }
519
520
521 /**
522  * Ask to send a join notification to the peer.
523  */
524 static int
525 send_join_noficiation (void *cls, const GNUNET_HashCode * key, void *value)
526 {
527   struct ChatClient *entry = cls;
528   struct ConnectedPeer *cp = value;
529   struct GNUNET_PeerIdentity pid;
530   size_t msg_size;
531
532   GNUNET_PEER_resolve (cp->pid, &pid);
533 #if DEBUG_CHAT_SERVICE
534   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending join notification to `%s'\n",
535               GNUNET_i2s (&pid));
536 #endif
537   msg_size =
538       sizeof (struct P2PJoinNotificationMessage) + strlen (entry->room) +
539       entry->meta_len;
540   if (NULL ==
541       GNUNET_CORE_notify_transmit_ready (core, GNUNET_NO, 1, MAX_TRANSMIT_DELAY,
542                                          &pid, msg_size,
543                                          &transmit_join_notification_to_peer,
544                                          entry))
545     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
546                 _("Failed to queue a join notification\n"));
547   return GNUNET_YES;
548 }
549
550
551 /**
552  * A client asked for entering a chat room.  Add the new member to the list of
553  * clients and notify remaining room members.
554  *
555  * @param cls closure, NULL
556  * @param client identification of the client
557  * @param message the actual message
558  */
559 static void
560 handle_join_request (void *cls, struct GNUNET_SERVER_Client *client,
561                      const struct GNUNET_MessageHeader *message)
562 {
563   const struct JoinRequestMessage *jrmsg;
564   char *room_name;
565   const char *roomptr;
566   uint16_t header_size;
567   uint16_t meta_len;
568   uint16_t room_name_len;
569   struct ChatClient *new_entry;
570   struct ChatClient *entry;
571   struct JoinNotificationMessage *jnmsg;
572   struct JoinNotificationMessage *entry_jnmsg;
573
574   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Client sent a join request\n");
575   if (ntohs (message->size) <= sizeof (struct JoinRequestMessage))
576   {
577     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Malformed message: wrong size\n");
578     GNUNET_break (0);
579     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
580     return;
581   }
582   jrmsg = (const struct JoinRequestMessage *) message;
583   header_size = ntohs (jrmsg->header.size);
584   room_name_len = ntohs (jrmsg->room_name_len);
585   if (header_size - sizeof (struct JoinRequestMessage) <= room_name_len)
586   {
587     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
588                 "Malformed message: wrong length of the room name\n");
589     GNUNET_break (0);
590     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
591     return;
592   }
593   meta_len = header_size - sizeof (struct JoinRequestMessage) - room_name_len;
594   roomptr = (const char *) &jrmsg[1];
595   room_name = GNUNET_malloc (room_name_len + 1);
596   memcpy (room_name, roomptr, room_name_len);
597   room_name[room_name_len] = '\0';
598   new_entry = GNUNET_malloc (sizeof (struct ChatClient));
599   memset (new_entry, 0, sizeof (struct ChatClient));
600   new_entry->client = client;
601   new_entry->room = room_name;
602   new_entry->public_key = jrmsg->public_key;
603   new_entry->meta_len = meta_len;
604   if (meta_len > 0)
605   {
606     new_entry->member_info = GNUNET_malloc (meta_len);
607     memcpy (new_entry->member_info, &roomptr[room_name_len], meta_len);
608   }
609   else
610     new_entry->member_info = NULL;
611   GNUNET_CRYPTO_hash (&new_entry->public_key,
612                       sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
613                       &new_entry->id);
614   new_entry->msg_options = ntohl (jrmsg->msg_options);
615   new_entry->next = client_list_head;
616   client_list_head = new_entry;
617 #if DEBUG_CHAT_SERVICE
618   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
619               "Synchronizing room members between local clients\n");
620 #endif
621   jnmsg = GNUNET_malloc (sizeof (struct JoinNotificationMessage) + meta_len);
622   jnmsg->header.type = htons (GNUNET_MESSAGE_TYPE_CHAT_JOIN_NOTIFICATION);
623   jnmsg->header.size =
624       htons (sizeof (struct JoinNotificationMessage) + meta_len);
625   jnmsg->msg_options = jrmsg->msg_options;
626   jnmsg->public_key = new_entry->public_key;
627   memcpy (&jnmsg[1], &roomptr[room_name_len], meta_len);
628   GNUNET_SERVER_notification_context_add (nc, client);
629   entry = client_list_head;
630   while (NULL != entry)
631   {
632     if (0 == strcmp (room_name, entry->room))
633     {
634       if (NULL != entry->client)
635         GNUNET_SERVER_notification_context_unicast (nc, entry->client,
636                                                     &jnmsg->header, GNUNET_NO);
637       if (entry->client != client)
638       {
639         entry_jnmsg =
640             GNUNET_malloc (sizeof (struct JoinNotificationMessage) +
641                            entry->meta_len);
642         entry_jnmsg->header.type =
643             htons (GNUNET_MESSAGE_TYPE_CHAT_JOIN_NOTIFICATION);
644         entry_jnmsg->header.size =
645             htons (sizeof (struct JoinNotificationMessage) + entry->meta_len);
646         entry_jnmsg->msg_options = entry->msg_options;
647         entry_jnmsg->public_key = entry->public_key;
648         memcpy (&entry_jnmsg[1], entry->member_info, entry->meta_len);
649         GNUNET_SERVER_notification_context_unicast (nc, client,
650                                                     &entry_jnmsg->header,
651                                                     GNUNET_NO);
652         GNUNET_free (entry_jnmsg);
653       }
654     }
655     entry = entry->next;
656   }
657 #if DEBUG_CHAT_SERVICE
658   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
659               "Broadcasting join notification to neighbour peers\n");
660 #endif
661   GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
662                                          &send_join_noficiation, new_entry);
663   GNUNET_SERVER_receive_done (client, GNUNET_OK);
664   GNUNET_free (jnmsg);
665 }
666
667 /**
668  * Transmit a confirmation receipt to the peer.
669  *
670  * @param cls closure, pointer to the 'struct P2PConfirmationReceiptMessage'
671  * @param size number of bytes available in buf
672  * @param buf where the callee should write the message
673  * @return number of bytes written to buf
674  */
675 static size_t
676 transmit_confirmation_receipt_to_peer (void *cls, size_t size, void *buf)
677 {
678   struct P2PConfirmationReceiptMessage *receipt = cls;
679   size_t msg_size;
680
681 #if DEBUG_CHAT_SERVICE
682   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
683               "Transmitting P2P confirmation receipt to '%s'\n",
684               GNUNET_h2s (&receipt->target));
685 #endif
686   if (buf == NULL)
687   {
688     /* client disconnected */
689 #if DEBUG_CHAT_SERVICE
690     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
691                 "Buffer is NULL, dropping the message\n");
692 #endif
693     return 0;
694   }
695   msg_size = sizeof (struct P2PConfirmationReceiptMessage);
696   GNUNET_assert (size >= msg_size);
697   memcpy (buf, receipt, msg_size);
698   GNUNET_free (receipt);
699   return msg_size;
700 }
701
702
703 /**
704  * Ask to send a confirmation receipt to the peer.
705  */
706 static int
707 send_confirmation_receipt (void *cls, const GNUNET_HashCode * key, void *value)
708 {
709   struct P2PConfirmationReceiptMessage *receipt = cls;
710   struct ConnectedPeer *cp = value;
711   struct GNUNET_PeerIdentity pid;
712   struct P2PConfirmationReceiptMessage *my_receipt;
713   size_t msg_size;
714
715   GNUNET_PEER_resolve (cp->pid, &pid);
716 #if DEBUG_CHAT_SERVICE
717   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending confirmation receipt to `%s'\n",
718               GNUNET_i2s (&pid));
719 #endif
720   msg_size = sizeof (struct P2PConfirmationReceiptMessage);
721   my_receipt =
722       GNUNET_memdup (receipt, sizeof (struct P2PConfirmationReceiptMessage));
723   if (NULL ==
724       GNUNET_CORE_notify_transmit_ready (core, GNUNET_YES, 1,
725                                          MAX_TRANSMIT_DELAY, &pid, msg_size,
726                                          &transmit_confirmation_receipt_to_peer,
727                                          my_receipt))
728     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
729                 _("Failed to queue a confirmation receipt\n"));
730   return GNUNET_YES;
731 }
732
733
734 /**
735  * A client sent a confirmation receipt.  Broadcast the receipt to all connected
736  * peers if the author of the original message is a local client.  Otherwise
737  * check the signature and notify the user if the signature is valid.
738  *
739  * @param cls closure, NULL
740  * @param client identification of the client
741  * @param message the actual message
742  */
743 static void
744 handle_acknowledge_request (void *cls, struct GNUNET_SERVER_Client *client,
745                             const struct GNUNET_MessageHeader *message)
746 {
747   const struct ConfirmationReceiptMessage *receipt;
748   struct ConfirmationReceiptMessage *crmsg;
749   struct P2PConfirmationReceiptMessage *p2p_crmsg;
750   struct ChatClient *target;
751   struct ChatClient *author;
752
753   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Client sent a confirmation receipt\n");
754   receipt = (const struct ConfirmationReceiptMessage *) message;
755   author = client_list_head;
756   while ((NULL != author) &&
757          (0 !=
758           memcmp (&receipt->author, &author->id, sizeof (GNUNET_HashCode))))
759     author = author->next;
760   if (NULL == author)
761   {
762     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
763                 "Unknown author of the original message\n");
764     GNUNET_break (0);
765     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
766     return;
767   }
768   target = client_list_head;
769   while ((NULL != target) &&
770          (0 !=
771           memcmp (&receipt->target, &target->id, sizeof (GNUNET_HashCode))))
772     target = target->next;
773   if (NULL == target)
774   {
775     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
776                 "Unknown target of the confirmation receipt\n");
777     GNUNET_break (0);
778     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
779     return;
780   }
781   if (NULL == author->client)
782   {
783     target->rcpt_sequence_number++;
784 #if DEBUG_CHAT_SERVICE
785     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
786                 "Broadcasting %s's receipt #%u to neighbour peers\n",
787                 GNUNET_h2s (&target->id), target->rcpt_sequence_number);
788 #endif
789     p2p_crmsg = GNUNET_malloc (sizeof (struct P2PConfirmationReceiptMessage));
790     p2p_crmsg->header.size =
791         htons (sizeof (struct P2PConfirmationReceiptMessage));
792     p2p_crmsg->header.type =
793         htons (GNUNET_MESSAGE_TYPE_CHAT_P2P_CONFIRMATION_RECEIPT);
794     p2p_crmsg->reserved = htonl (0);
795     p2p_crmsg->signature = receipt->signature;
796     p2p_crmsg->purpose = receipt->purpose;
797     p2p_crmsg->msg_sequence_number = receipt->sequence_number;
798     p2p_crmsg->timestamp = receipt->timestamp;
799     p2p_crmsg->target = receipt->target;
800     p2p_crmsg->author = receipt->author;
801     p2p_crmsg->content = receipt->content;
802     p2p_crmsg->sequence_number = htonl (target->rcpt_sequence_number);
803     GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
804                                            &send_confirmation_receipt,
805                                            p2p_crmsg);
806     GNUNET_free (p2p_crmsg);
807   }
808   else
809   {
810 #if DEBUG_CHAT_SERVICE
811     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
812                 "Verifying signature of the receipt\n");
813 #endif
814     if (GNUNET_OK !=
815         GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_CHAT_RECEIPT,
816                                   &receipt->purpose, &receipt->signature,
817                                   &target->public_key))
818     {
819       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
820                   "Invalid signature of the receipt\n");
821       GNUNET_break (0);
822       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
823       return;
824     }
825 #if DEBUG_CHAT_SERVICE
826     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
827                 "Sending receipt to the client which sent the original message\n");
828 #endif
829     crmsg = GNUNET_memdup (receipt, sizeof (struct ConfirmationReceiptMessage));
830     crmsg->header.type =
831         htons (GNUNET_MESSAGE_TYPE_CHAT_CONFIRMATION_NOTIFICATION);
832     GNUNET_SERVER_notification_context_unicast (nc, author->client,
833                                                 &crmsg->header, GNUNET_NO);
834     GNUNET_free (crmsg);
835   }
836   GNUNET_SERVER_receive_done (client, GNUNET_OK);
837 }
838
839
840 /**
841  * Transmit a leave notification to the peer.
842  *
843  * @param cls closure, pointer to the
844  *        'struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded'
845  * @param size number of bytes available in buf
846  * @param buf where the callee should write the message
847  * @return number of bytes written to buf
848  */
849 static size_t
850 transmit_leave_notification_to_peer (void *cls, size_t size, void *buf)
851 {
852   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *public_key = cls;
853   struct P2PLeaveNotificationMessage *m = buf;
854   size_t msg_size;
855
856 #if DEBUG_CHAT_SERVICE
857   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Transmitting P2P leave notification\n");
858 #endif
859   if (buf == NULL)
860   {
861     /* client disconnected */
862 #if DEBUG_CHAT_SERVICE
863     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
864                 "Buffer is NULL, dropping the message\n");
865 #endif
866     return 0;
867   }
868   msg_size = sizeof (struct P2PLeaveNotificationMessage);
869   GNUNET_assert (size >= msg_size);
870   m = buf;
871   m->header.type = htons (GNUNET_MESSAGE_TYPE_CHAT_P2P_LEAVE_NOTIFICATION);
872   m->header.size = htons (msg_size);
873   m->reserved = htonl (0);
874   m->user = *public_key;
875   GNUNET_free (public_key);
876   return msg_size;
877 }
878
879
880 /**
881  * Ask to send a leave notification to the peer.
882  */
883 static int
884 send_leave_noficiation (void *cls, const GNUNET_HashCode * key, void *value)
885 {
886   struct ChatClient *entry = cls;
887   struct ConnectedPeer *cp = value;
888   struct GNUNET_PeerIdentity pid;
889   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *public_key;
890   size_t msg_size;
891
892   GNUNET_PEER_resolve (cp->pid, &pid);
893 #if DEBUG_CHAT_SERVICE
894   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending leave notification to `%s'\n",
895               GNUNET_i2s (&pid));
896 #endif
897   msg_size = sizeof (struct P2PLeaveNotificationMessage);
898   public_key =
899       GNUNET_memdup (&entry->public_key,
900                      sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
901   if (NULL ==
902       GNUNET_CORE_notify_transmit_ready (core, GNUNET_YES, 1,
903                                          MAX_TRANSMIT_DELAY, &pid, msg_size,
904                                          &transmit_leave_notification_to_peer,
905                                          public_key))
906     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
907                 _("Failed to queue a leave notification\n"));
908   return GNUNET_YES;
909 }
910
911
912 /**
913  * A client disconnected.  Remove all of its data structure entries and notify
914  * remaining room members.
915  *
916  * @param cls closure, NULL
917  * @param client identification of the client
918  */
919 static void
920 handle_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
921 {
922   struct ChatClient *entry;
923   struct ChatClient *pos;
924   struct ChatClient *prev;
925   struct LeaveNotificationMessage lnmsg;
926
927   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Client disconnected\n");
928   pos = client_list_head;
929   prev = NULL;
930   while ((NULL != pos) && (pos->client != client))
931   {
932     prev = pos;
933     pos = pos->next;
934   }
935   if (NULL == pos)
936   {
937 #if DEBUG_CHAT_SERVICE
938     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
939                 "No such client. There is nothing to do\n");
940 #endif
941     return;
942   }
943   if (NULL == prev)
944     client_list_head = pos->next;
945   else
946     prev->next = pos->next;
947   entry = client_list_head;
948 #if DEBUG_CHAT_SERVICE
949   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
950               "Notifying local room members that the client has disconnected\n");
951 #endif
952   lnmsg.header.size = htons (sizeof (struct LeaveNotificationMessage));
953   lnmsg.header.type = htons (GNUNET_MESSAGE_TYPE_CHAT_LEAVE_NOTIFICATION);
954   lnmsg.reserved = htonl (0);
955   lnmsg.user = pos->public_key;
956   while (NULL != entry)
957   {
958     if ((0 == strcmp (pos->room, entry->room)) && (NULL != entry->client))
959     {
960       GNUNET_SERVER_notification_context_unicast (nc, entry->client,
961                                                   &lnmsg.header, GNUNET_NO);
962     }
963     entry = entry->next;
964   }
965 #if DEBUG_CHAT_SERVICE
966   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
967               "Broadcasting leave notification to neighbour peers\n");
968 #endif
969   GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
970                                          &send_leave_noficiation, pos);
971   GNUNET_free (pos->room);
972   GNUNET_free_non_null (pos->member_info);
973   GNUNET_free (pos);
974 }
975
976
977 /**
978  * Handle P2P join notification.
979  *
980  * @param cls closure, always NULL
981  * @param other the other peer involved
982  * @param message the actual message
983  * @param atsi performance information
984  * @return GNUNET_OK to keep the connection open,
985  *         GNUNET_SYSERR to close it (signal serious error)
986  */
987 static int
988 handle_p2p_join_notification (void *cls,
989                               const struct GNUNET_PeerIdentity *other,
990                               const struct GNUNET_MessageHeader *message,
991                               const struct GNUNET_TRANSPORT_ATS_Information
992                               *atsi)
993 {
994   const struct P2PJoinNotificationMessage *p2p_jnmsg;
995   char *room_name;
996   const char *roomptr;
997   uint16_t header_size;
998   uint16_t meta_len;
999   uint16_t room_name_len;
1000   struct ChatClient *new_entry;
1001   struct ChatClient *entry;
1002   struct JoinNotificationMessage *jnmsg;
1003   GNUNET_HashCode id;
1004
1005   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Got P2P join notification\n");
1006   if (ntohs (message->size) <= sizeof (struct P2PJoinNotificationMessage))
1007   {
1008     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Malformed message: wrong size\n");
1009     GNUNET_break_op (0);
1010     return GNUNET_SYSERR;
1011   }
1012   p2p_jnmsg = (const struct P2PJoinNotificationMessage *) message;
1013   header_size = ntohs (p2p_jnmsg->header.size);
1014   room_name_len = ntohs (p2p_jnmsg->room_name_len);
1015   if (header_size - sizeof (struct P2PJoinNotificationMessage) <= room_name_len)
1016   {
1017     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1018                 "Malformed message: wrong length of the room name\n");
1019     GNUNET_break_op (0);
1020     return GNUNET_SYSERR;
1021   }
1022   GNUNET_CRYPTO_hash (&p2p_jnmsg->public_key,
1023                       sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1024                       &id);
1025   entry = client_list_head;
1026   while (NULL != entry)
1027   {
1028     if (0 == memcmp (&entry->id, &id, sizeof (GNUNET_HashCode)))
1029     {
1030 #if DEBUG_CHAT_SERVICE
1031       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1032                   "The client has already joined. There is nothing to do\n");
1033 #endif
1034       return GNUNET_OK;
1035     }
1036     entry = entry->next;
1037   }
1038   meta_len =
1039       header_size - sizeof (struct P2PJoinNotificationMessage) - room_name_len;
1040   roomptr = (const char *) &p2p_jnmsg[1];
1041   room_name = GNUNET_malloc (room_name_len + 1);
1042   memcpy (room_name, roomptr, room_name_len);
1043   room_name[room_name_len] = '\0';
1044   new_entry = GNUNET_malloc (sizeof (struct ChatClient));
1045   memset (new_entry, 0, sizeof (struct ChatClient));
1046   new_entry->id = id;
1047   new_entry->client = NULL;
1048   new_entry->room = room_name;
1049   new_entry->public_key = p2p_jnmsg->public_key;
1050   new_entry->meta_len = meta_len;
1051   if (meta_len > 0)
1052   {
1053     new_entry->member_info = GNUNET_malloc (meta_len);
1054     memcpy (new_entry->member_info, &roomptr[room_name_len], meta_len);
1055   }
1056   else
1057     new_entry->member_info = NULL;
1058   new_entry->msg_options = ntohl (p2p_jnmsg->msg_options);
1059   new_entry->next = client_list_head;
1060   client_list_head = new_entry;
1061 #if DEBUG_CHAT_SERVICE
1062   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1063               "Notifying local room members that we have a new client\n");
1064 #endif
1065   jnmsg = GNUNET_malloc (sizeof (struct JoinNotificationMessage) + meta_len);
1066   jnmsg->header.type = htons (GNUNET_MESSAGE_TYPE_CHAT_JOIN_NOTIFICATION);
1067   jnmsg->header.size =
1068       htons (sizeof (struct JoinNotificationMessage) + meta_len);
1069   jnmsg->msg_options = p2p_jnmsg->msg_options;
1070   jnmsg->public_key = new_entry->public_key;
1071   memcpy (&jnmsg[1], &roomptr[room_name_len], meta_len);
1072   entry = client_list_head;
1073   while (NULL != entry)
1074   {
1075     if ((0 == strcmp (room_name, entry->room)) && (NULL != entry->client))
1076     {
1077       GNUNET_SERVER_notification_context_unicast (nc, entry->client,
1078                                                   &jnmsg->header, GNUNET_NO);
1079     }
1080     entry = entry->next;
1081   }
1082 #if DEBUG_CHAT_SERVICE
1083   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1084               "Broadcasting join notification to neighbour peers\n");
1085 #endif
1086   GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1087                                          &send_join_noficiation, new_entry);
1088   GNUNET_free (jnmsg);
1089   return GNUNET_OK;
1090 }
1091
1092
1093 /**
1094  * Handle P2P leave notification.
1095  *
1096  * @param cls closure, always NULL
1097  * @param other the other peer involved
1098  * @param message the actual message
1099  * @param atsi performance information
1100  * @return GNUNET_OK to keep the connection open,
1101  *         GNUNET_SYSERR to close it (signal serious error)
1102  */
1103 static int
1104 handle_p2p_leave_notification (void *cls,
1105                                const struct GNUNET_PeerIdentity *other,
1106                                const struct GNUNET_MessageHeader *message,
1107                                const struct GNUNET_TRANSPORT_ATS_Information
1108                                *atsi)
1109 {
1110   const struct P2PLeaveNotificationMessage *p2p_lnmsg;
1111   GNUNET_HashCode id;
1112   struct ChatClient *pos;
1113   struct ChatClient *prev;
1114   struct ChatClient *entry;
1115   struct LeaveNotificationMessage lnmsg;
1116
1117   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Got P2P leave notification\n");
1118   p2p_lnmsg = (const struct P2PLeaveNotificationMessage *) message;
1119   GNUNET_CRYPTO_hash (&p2p_lnmsg->user,
1120                       sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1121                       &id);
1122   pos = client_list_head;
1123   prev = NULL;
1124   while (NULL != pos)
1125   {
1126     if (0 == memcmp (&pos->id, &id, sizeof (GNUNET_HashCode)))
1127       break;
1128     prev = pos;
1129     pos = pos->next;
1130   }
1131   if (NULL == pos)
1132   {
1133 #if DEBUG_CHAT_SERVICE
1134     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1135                 "No such client. There is nothing to do\n");
1136 #endif
1137     return GNUNET_OK;
1138   }
1139   if (NULL == prev)
1140     client_list_head = pos->next;
1141   else
1142     prev->next = pos->next;
1143 #if DEBUG_CHAT_SERVICE
1144   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1145               "Notifying local room members that the client has gone away\n");
1146 #endif
1147   lnmsg.header.size = htons (sizeof (struct LeaveNotificationMessage));
1148   lnmsg.header.type = htons (GNUNET_MESSAGE_TYPE_CHAT_LEAVE_NOTIFICATION);
1149   lnmsg.reserved = htonl (0);
1150   lnmsg.user = pos->public_key;
1151   entry = client_list_head;
1152   while (NULL != entry)
1153   {
1154     if (0 == strcmp (pos->room, entry->room) && (NULL != entry->client))
1155     {
1156       GNUNET_SERVER_notification_context_unicast (nc, entry->client,
1157                                                   &lnmsg.header, GNUNET_NO);
1158     }
1159     entry = entry->next;
1160   }
1161 #if DEBUG_CHAT_SERVICE
1162   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1163               "Broadcasting leave notification to neighbour peers\n");
1164 #endif
1165   GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1166                                          &send_leave_noficiation, pos);
1167   GNUNET_free (pos->room);
1168   GNUNET_free_non_null (pos->member_info);
1169   GNUNET_free (pos);
1170   return GNUNET_OK;
1171 }
1172
1173
1174 /**
1175  * Handle P2P message notification.
1176  *
1177  * @param cls closure, always NULL
1178  * @param other the other peer involved
1179  * @param message the actual message
1180  * @param atsi performance information
1181  * @return GNUNET_OK to keep the connection open,
1182  *         GNUNET_SYSERR to close it (signal serious error)
1183  */
1184 static int
1185 handle_p2p_message_notification (void *cls,
1186                                  const struct GNUNET_PeerIdentity *other,
1187                                  const struct GNUNET_MessageHeader *message,
1188                                  const struct GNUNET_TRANSPORT_ATS_Information
1189                                  *atsi)
1190 {
1191   const struct P2PReceiveNotificationMessage *p2p_rnmsg;
1192   struct P2PReceiveNotificationMessage *my_p2p_rnmsg;
1193   struct ReceiveNotificationMessage *rnmsg;
1194   struct ChatClient *sender;
1195   struct ChatClient *pos;
1196   static GNUNET_HashCode all_zeros;
1197   int is_priv;
1198   int is_anon;
1199   uint16_t msg_len;
1200   uint16_t room_name_len;
1201   char *room_name = NULL;
1202   char *text;
1203
1204   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Got P2P message notification\n");
1205   if (ntohs (message->size) <= sizeof (struct P2PReceiveNotificationMessage))
1206   {
1207     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Malformed message: wrong size\n");
1208     GNUNET_break_op (0);
1209     return GNUNET_SYSERR;
1210   }
1211   p2p_rnmsg = (const struct P2PReceiveNotificationMessage *) message;
1212   msg_len =
1213       ntohs (p2p_rnmsg->header.size) -
1214       sizeof (struct P2PReceiveNotificationMessage);
1215
1216   is_anon = (0 != (ntohl (p2p_rnmsg->msg_options) & GNUNET_CHAT_MSG_ANONYMOUS));
1217   if (is_anon)
1218   {
1219     room_name_len = ntohs (p2p_rnmsg->room_name_len);
1220     if (msg_len <= room_name_len)
1221     {
1222       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1223                   "Malformed message: wrong length of the room name\n");
1224       GNUNET_break_op (0);
1225       return GNUNET_SYSERR;
1226     }
1227     msg_len -= room_name_len;
1228     if (lookup_anonymous_message (p2p_rnmsg))
1229     {
1230 #if DEBUG_CHAT_SERVICE
1231       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1232                   "This anonymous message has already been handled.");
1233 #endif
1234       return GNUNET_OK;
1235     }
1236     remember_anonymous_message (p2p_rnmsg);
1237     room_name = GNUNET_malloc (room_name_len + 1);
1238     memcpy (room_name, (char *) &p2p_rnmsg[1], room_name_len);
1239     room_name[room_name_len] = '\0';
1240     text = (char *) &p2p_rnmsg[1] + room_name_len;
1241   }
1242   else
1243   {
1244     sender = client_list_head;
1245     while ((NULL != sender) &&
1246            (0 !=
1247             memcmp (&sender->id, &p2p_rnmsg->sender, sizeof (GNUNET_HashCode))))
1248       sender = sender->next;
1249     if (NULL == sender)
1250     {
1251       /* not an error since the sender may have left before we got the
1252        * message */
1253 #if DEBUG_CHAT_SERVICE
1254       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1255                   "Unknown source. Rejecting the message\n");
1256 #endif
1257       return GNUNET_OK;
1258     }
1259     if (sender->msg_sequence_number >= ntohl (p2p_rnmsg->sequence_number))
1260     {
1261 #if DEBUG_CHAT_SERVICE
1262       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1263                   "This message has already been handled."
1264                   " Sequence numbers (msg/sender): %u/%u\n",
1265                   ntohl (p2p_rnmsg->sequence_number),
1266                   sender->msg_sequence_number);
1267 #endif
1268       return GNUNET_OK;
1269     }
1270     sender->msg_sequence_number = ntohl (p2p_rnmsg->sequence_number);
1271     room_name = sender->room;
1272     text = (char *) &p2p_rnmsg[1];
1273   }
1274
1275 #if DEBUG_CHAT_SERVICE
1276   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1277               "Sending message to local room members\n");
1278 #endif
1279   rnmsg = GNUNET_malloc (sizeof (struct ReceiveNotificationMessage) + msg_len);
1280   rnmsg->header.size =
1281       htons (sizeof (struct ReceiveNotificationMessage) + msg_len);
1282   rnmsg->header.type = htons (GNUNET_MESSAGE_TYPE_CHAT_MESSAGE_NOTIFICATION);
1283   rnmsg->msg_options = p2p_rnmsg->msg_options;
1284   rnmsg->sequence_number = p2p_rnmsg->sequence_number;
1285   rnmsg->reserved = htonl (0);
1286   rnmsg->timestamp = p2p_rnmsg->timestamp;
1287   is_priv =
1288       (0 != memcmp (&all_zeros, &p2p_rnmsg->target, sizeof (GNUNET_HashCode)));
1289   if (is_priv)
1290     memcpy (&rnmsg->encrypted_key, &p2p_rnmsg->encrypted_key,
1291             sizeof (struct GNUNET_CRYPTO_RsaEncryptedData));
1292   rnmsg->sender = p2p_rnmsg->sender;
1293   memcpy (&rnmsg[1], text, msg_len);
1294   pos = client_list_head;
1295   while (NULL != pos)
1296   {
1297     if ((0 == strcmp (room_name, pos->room)) && (NULL != pos->client))
1298     {
1299       if (((!is_priv) ||
1300            (0 ==
1301             memcmp (&p2p_rnmsg->target, &pos->id, sizeof (GNUNET_HashCode)))) &&
1302           (0 == (ntohl (p2p_rnmsg->msg_options) & (~pos->msg_options))))
1303       {
1304         GNUNET_SERVER_notification_context_unicast (nc, pos->client,
1305                                                     &rnmsg->header, GNUNET_NO);
1306       }
1307     }
1308     pos = pos->next;
1309   }
1310   if (is_anon)
1311     GNUNET_free (room_name);
1312 #if DEBUG_CHAT_SERVICE
1313   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1314               "Broadcasting message notification to neighbour peers\n");
1315 #endif
1316   my_p2p_rnmsg = GNUNET_memdup (p2p_rnmsg, ntohs (p2p_rnmsg->header.size));
1317   GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1318                                          &send_message_noficiation,
1319                                          my_p2p_rnmsg);
1320   GNUNET_free (rnmsg);
1321   return GNUNET_OK;
1322 }
1323
1324
1325 /**
1326  * Handle P2P sync request.
1327  *
1328  * @param cls closure, always NULL
1329  * @param other the other peer involved
1330  * @param message the actual message
1331  * @param atsi performance information
1332  * @return GNUNET_OK to keep the connection open,
1333  *         GNUNET_SYSERR to close it (signal serious error)
1334  */
1335 static int
1336 handle_p2p_sync_request (void *cls, const struct GNUNET_PeerIdentity *other,
1337                          const struct GNUNET_MessageHeader *message,
1338                          const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1339 {
1340   struct ChatClient *entry;
1341   struct GNUNET_CORE_TransmitHandle *th;
1342   size_t msg_size;
1343
1344   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Got P2P sync request\n");
1345 #if DEBUG_CHAT_SERVICE
1346   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1347               "Notifying the requester of all known clients\n");
1348 #endif
1349   entry = client_list_head;
1350   while (NULL != entry)
1351   {
1352     msg_size =
1353         sizeof (struct P2PJoinNotificationMessage) + strlen (entry->room) +
1354         entry->meta_len;
1355     th = GNUNET_CORE_notify_transmit_ready (core, GNUNET_NO, 1,
1356                                             MAX_TRANSMIT_DELAY, other, msg_size,
1357                                             &transmit_join_notification_to_peer,
1358                                             entry);
1359     GNUNET_assert (NULL != th);
1360     entry = entry->next;
1361   }
1362   return GNUNET_OK;
1363 }
1364
1365
1366 /**
1367  * Handle P2P confirmation receipt.
1368  *
1369  * @param cls closure, always NULL
1370  * @param other the other peer involved
1371  * @param message the actual message
1372  * @param atsi performance information
1373  * @return GNUNET_OK to keep the connection open,
1374  *         GNUNET_SYSERR to close it (signal serious error)
1375  */
1376 static int
1377 handle_p2p_confirmation_receipt (void *cls,
1378                                  const struct GNUNET_PeerIdentity *other,
1379                                  const struct GNUNET_MessageHeader *message,
1380                                  const struct GNUNET_TRANSPORT_ATS_Information
1381                                  *atsi)
1382 {
1383   const struct P2PConfirmationReceiptMessage *p2p_crmsg;
1384   struct P2PConfirmationReceiptMessage *my_p2p_crmsg;
1385   struct ConfirmationReceiptMessage *crmsg;
1386   struct ChatClient *target;
1387   struct ChatClient *author;
1388
1389   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Got P2P confirmation receipt\n");
1390   p2p_crmsg = (const struct P2PConfirmationReceiptMessage *) message;
1391   target = client_list_head;
1392   while ((NULL != target) &&
1393          (0 !=
1394           memcmp (&target->id, &p2p_crmsg->target, sizeof (GNUNET_HashCode))))
1395     target = target->next;
1396   if (NULL == target)
1397   {
1398     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1399                 "Unknown source of the receipt. Rejecting the message\n");
1400     GNUNET_break_op (0);
1401     return GNUNET_SYSERR;
1402   }
1403   if (target->rcpt_sequence_number >= ntohl (p2p_crmsg->sequence_number))
1404   {
1405 #if DEBUG_CHAT_SERVICE
1406     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1407                 "This receipt has already been handled."
1408                 " Sequence numbers (msg/sender): %u/%u\n",
1409                 ntohl (p2p_crmsg->sequence_number),
1410                 target->rcpt_sequence_number);
1411 #endif
1412     return GNUNET_OK;
1413   }
1414   target->rcpt_sequence_number = ntohl (p2p_crmsg->sequence_number);
1415   author = client_list_head;
1416   while ((NULL != author) &&
1417          (0 !=
1418           memcmp (&author->id, &p2p_crmsg->author, sizeof (GNUNET_HashCode))))
1419     author = author->next;
1420   if (NULL == author)
1421   {
1422     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1423                 "Unknown addressee. Rejecting the receipt\n");
1424     GNUNET_break_op (0);
1425     return GNUNET_SYSERR;
1426   }
1427
1428   if (NULL == author->client)
1429   {
1430 #if DEBUG_CHAT_SERVICE
1431     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1432                 "The author of the original message is not a local client."
1433                 " Broadcasting receipt to neighbour peers\n");
1434 #endif
1435     my_p2p_crmsg =
1436         GNUNET_memdup (p2p_crmsg,
1437                        sizeof (struct P2PConfirmationReceiptMessage));
1438     GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1439                                            &send_confirmation_receipt,
1440                                            my_p2p_crmsg);
1441     GNUNET_free (my_p2p_crmsg);
1442   }
1443   else
1444   {
1445 #if DEBUG_CHAT_SERVICE
1446     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1447                 "The author of the original message is a local client."
1448                 " Verifying signature of the receipt\n");
1449 #endif
1450     crmsg = GNUNET_malloc (sizeof (struct ConfirmationReceiptMessage));
1451     crmsg->header.size = htons (sizeof (struct ConfirmationReceiptMessage));
1452     crmsg->header.type =
1453         htons (GNUNET_MESSAGE_TYPE_CHAT_CONFIRMATION_NOTIFICATION);
1454     crmsg->signature = p2p_crmsg->signature;
1455     crmsg->purpose = p2p_crmsg->purpose;
1456     crmsg->sequence_number = p2p_crmsg->msg_sequence_number;
1457     crmsg->reserved2 = 0;
1458     crmsg->timestamp = p2p_crmsg->timestamp;
1459     crmsg->target = p2p_crmsg->target;
1460     crmsg->author = p2p_crmsg->author;
1461     crmsg->content = p2p_crmsg->content;
1462     if (GNUNET_OK !=
1463         GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_CHAT_RECEIPT,
1464                                   &crmsg->purpose, &crmsg->signature,
1465                                   &target->public_key))
1466     {
1467       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1468                   "Invalid signature of the receipt\n");
1469       GNUNET_break_op (0);
1470       return GNUNET_SYSERR;
1471     }
1472 #if DEBUG_CHAT_SERVICE
1473     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1474                 "The author of the original message is a local client."
1475                 " Sending receipt to the client\n");
1476 #endif
1477     GNUNET_SERVER_notification_context_unicast (nc, author->client,
1478                                                 &crmsg->header, GNUNET_NO);
1479     GNUNET_free (crmsg);
1480   }
1481   return GNUNET_OK;
1482 }
1483
1484
1485 /**
1486  * Transmit a sync request to the peer.
1487  *
1488  * @param cls closure, NULL
1489  * @param size number of bytes available in buf
1490  * @param buf where the callee should write the message
1491  * @return number of bytes written to buf
1492  */
1493 static size_t
1494 transmit_sync_request_to_peer (void *cls, size_t size, void *buf)
1495 {
1496   struct GNUNET_MessageHeader *m = buf;
1497   size_t msg_size;
1498
1499 #if DEBUG_CHAT_SERVICE
1500   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Transmitting P2P sync request\n");
1501 #endif
1502   msg_size = sizeof (struct GNUNET_MessageHeader);
1503   GNUNET_assert (size >= msg_size);
1504   GNUNET_assert (NULL != buf);
1505   m = buf;
1506   m->type = htons (GNUNET_MESSAGE_TYPE_CHAT_P2P_SYNC_REQUEST);
1507   m->size = htons (msg_size);
1508   return msg_size;
1509 }
1510
1511
1512 /**
1513  * Method called whenever a peer connects.
1514  *
1515  * @param cls closure
1516  * @param peer peer identity this notification is about
1517  * @param atsi performance data
1518  */
1519 static void
1520 peer_connect_handler (void *cls, const struct GNUNET_PeerIdentity *peer,
1521                       const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1522 {
1523   struct ConnectedPeer *cp;
1524   struct GNUNET_CORE_TransmitHandle *th;
1525
1526   if (0 == memcmp (peer, me, sizeof (struct GNUNET_PeerIdentity)))
1527     return;
1528   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Peer connected: %s\n",
1529               GNUNET_i2s (peer));
1530   th = GNUNET_CORE_notify_transmit_ready (core, GNUNET_YES, 1,
1531                                           MAX_TRANSMIT_DELAY, peer,
1532                                           sizeof (struct GNUNET_MessageHeader),
1533                                           &transmit_sync_request_to_peer, NULL);
1534   GNUNET_assert (NULL != th);
1535   cp = GNUNET_CONTAINER_multihashmap_get (connected_peers, &peer->hashPubKey);
1536   if (NULL != cp)
1537   {
1538     GNUNET_break (0);
1539     return;
1540   }
1541   cp = GNUNET_malloc (sizeof (struct ConnectedPeer));
1542   cp->pid = GNUNET_PEER_intern (peer);
1543   GNUNET_break (GNUNET_OK ==
1544                 GNUNET_CONTAINER_multihashmap_put (connected_peers,
1545                                                    &peer->hashPubKey, cp,
1546                                                    GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1547 }
1548
1549
1550 /**
1551  * Iterator to free peer entries.
1552  *
1553  * @param cls closure, unused
1554  * @param key current key code
1555  * @param value value in the hash map (peer entry)
1556  * @return GNUNET_YES (we should continue to iterate)
1557  */
1558 static int
1559 clean_peer (void *cls, const GNUNET_HashCode * key, void *value)
1560 {
1561   struct ConnectedPeer *cp;
1562   const struct GNUNET_PeerIdentity *peer =
1563       (const struct GNUNET_PeerIdentity *) key;
1564
1565   cp = GNUNET_CONTAINER_multihashmap_get (connected_peers, &peer->hashPubKey);
1566   if (cp == NULL)
1567     return GNUNET_YES;
1568   GNUNET_break (GNUNET_YES ==
1569                 GNUNET_CONTAINER_multihashmap_remove (connected_peers,
1570                                                       &peer->hashPubKey, cp));
1571   GNUNET_PEER_change_rc (cp->pid, -1);
1572   GNUNET_free (cp);
1573   return GNUNET_YES;
1574 }
1575
1576
1577 /**
1578  * Method called whenever a peer disconnects.
1579  *
1580  * @param cls closure, not used
1581  * @param peer peer identity this notification is about
1582  */
1583 static void
1584 peer_disconnect_handler (void *cls, const struct GNUNET_PeerIdentity *peer)
1585 {
1586
1587   if (0 == memcmp (peer, me, sizeof (struct GNUNET_PeerIdentity)))
1588     return;
1589   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Peer disconnected: %s\n",
1590               GNUNET_i2s (peer));
1591   clean_peer (NULL, (const GNUNET_HashCode *) peer, NULL);
1592 }
1593
1594
1595 /**
1596  * Task run during shutdown.
1597  *
1598  * @param cls unused
1599  * @param tc unused
1600  */
1601 static void
1602 cleanup_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1603 {
1604   struct AnonymousMessage *next_msg;
1605   struct ChatClient *next_client;
1606
1607   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Cleaning up\n");
1608   if (NULL != core)
1609   {
1610     GNUNET_CORE_disconnect (core);
1611     core = NULL;
1612   }
1613   if (NULL != nc)
1614   {
1615     GNUNET_SERVER_notification_context_destroy (nc);
1616     nc = NULL;
1617   }
1618   while (NULL != client_list_head)
1619   {
1620     next_client = client_list_head->next;
1621     GNUNET_free (client_list_head->room);
1622     GNUNET_free_non_null (client_list_head->member_info);
1623     GNUNET_free (client_list_head);
1624     client_list_head = next_client;
1625   }
1626   while (NULL != anonymous_list_head)
1627   {
1628     next_msg = anonymous_list_head->next;
1629     GNUNET_free (anonymous_list_head);
1630     anonymous_list_head = next_msg;
1631   }
1632   GNUNET_CONTAINER_multihashmap_iterate (connected_peers, &clean_peer, NULL);
1633   GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
1634   connected_peers = NULL;
1635 }
1636
1637
1638 /**
1639  * To be called on core init/fail.
1640  *
1641  * @param cls closure, NULL
1642  * @param server handle to the server for this service
1643  * @param my_identity the public identity of this peer
1644  * @param publicKey the public key of this peer
1645  */
1646 static void
1647 core_init (void *cls, struct GNUNET_CORE_Handle *server,
1648            const struct GNUNET_PeerIdentity *my_identity,
1649            const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
1650 {
1651   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Core initialized\n");
1652   me = my_identity;
1653 }
1654
1655
1656 /**
1657  * Process chat requests.
1658  *
1659  * @param cls closure, NULL
1660  * @param server the initialized server
1661  * @param c configuration to use
1662  */
1663 static void
1664 run (void *cls, struct GNUNET_SERVER_Handle *server,
1665      const struct GNUNET_CONFIGURATION_Handle *c)
1666 {
1667   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
1668     {&handle_join_request, NULL,
1669      GNUNET_MESSAGE_TYPE_CHAT_JOIN_REQUEST, 0},
1670     {&handle_transmit_request, NULL,
1671      GNUNET_MESSAGE_TYPE_CHAT_TRANSMIT_REQUEST, 0},
1672     {&handle_acknowledge_request, NULL,
1673      GNUNET_MESSAGE_TYPE_CHAT_CONFIRMATION_RECEIPT,
1674      sizeof (struct ConfirmationReceiptMessage)},
1675     {NULL, NULL, 0, 0}
1676   };
1677   static const struct GNUNET_CORE_MessageHandler p2p_handlers[] = {
1678     {&handle_p2p_join_notification,
1679      GNUNET_MESSAGE_TYPE_CHAT_P2P_JOIN_NOTIFICATION, 0},
1680     {&handle_p2p_leave_notification,
1681      GNUNET_MESSAGE_TYPE_CHAT_P2P_LEAVE_NOTIFICATION,
1682      sizeof (struct P2PLeaveNotificationMessage)},
1683     {&handle_p2p_message_notification,
1684      GNUNET_MESSAGE_TYPE_CHAT_P2P_MESSAGE_NOTIFICATION, 0},
1685     {&handle_p2p_sync_request,
1686      GNUNET_MESSAGE_TYPE_CHAT_P2P_SYNC_REQUEST,
1687      sizeof (struct GNUNET_MessageHeader)},
1688     {&handle_p2p_confirmation_receipt,
1689      GNUNET_MESSAGE_TYPE_CHAT_P2P_CONFIRMATION_RECEIPT,
1690      sizeof (struct P2PConfirmationReceiptMessage)},
1691     {NULL, 0, 0}
1692   };
1693
1694   GNUNET_log_setup ("gnunet-service-chat",
1695 #if DEBUG_CHAT_SERVICE
1696                     "DEBUG",
1697 #else
1698                     "WARNING",
1699 #endif
1700                     NULL);
1701   cfg = c;
1702   nc = GNUNET_SERVER_notification_context_create (server, 16);
1703   connected_peers =
1704       GNUNET_CONTAINER_multihashmap_create (EXPECTED_NEIGHBOUR_COUNT);
1705   GNUNET_SERVER_add_handlers (server, handlers);
1706   core =
1707       GNUNET_CORE_connect (cfg, QUEUE_SIZE, NULL, &core_init,
1708                            &peer_connect_handler, &peer_disconnect_handler,
1709                            NULL, NULL, GNUNET_NO, NULL, GNUNET_NO,
1710                            p2p_handlers);
1711   GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
1712   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &cleanup_task,
1713                                 NULL);
1714 }
1715
1716
1717 /**
1718  * The main function for the chat service.
1719  *
1720  * @param argc number of arguments from the command line
1721  * @param argv command line arguments
1722  * @return 0 ok, 1 on error
1723  */
1724 int
1725 main (int argc, char *const *argv)
1726 {
1727   return (GNUNET_OK ==
1728           GNUNET_SERVICE_run (argc, argv, "chat", GNUNET_SERVICE_OPTION_NONE,
1729                               &run, NULL)) ? 0 : 1;
1730 }
1731
1732 /* end of gnunet-service-chat.c */