-fix
[oweals/gnunet.git] / src / util / server_nc.c
1 /*
2      This file is part of GNUnet.
3      (C) 2010 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 2, 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 util/server_nc.c
23  * @brief convenience functions for transmission of
24  *        a notification stream
25  * @author Christian Grothoff
26  */
27
28 #include "platform.h"
29 #include "gnunet_common.h"
30 #include "gnunet_connection_lib.h"
31 #include "gnunet_container_lib.h"
32 #include "gnunet_scheduler_lib.h"
33 #include "gnunet_server_lib.h"
34 #include "gnunet_time_lib.h"
35
36 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
37
38
39 /**
40  * Entry in list of messages pending to be transmitted.
41  */
42 struct PendingMessageList
43 {
44
45   /**
46    * This is a doubly-linked list.
47    */
48   struct PendingMessageList *next;
49
50   /**
51    * This is a doubly-linked list.
52    */
53   struct PendingMessageList *prev;
54
55   /**
56    * Message to transmit (allocated at the end of this
57    * struct, do not free)
58    */
59   const struct GNUNET_MessageHeader *msg;
60
61   /**
62    * Can this message be dropped?
63    */
64   int can_drop;
65
66 };
67
68
69 /**
70  * Lists of clients we manage for notifications.
71  */
72 struct ClientList
73 {
74
75   /**
76    * This is a linked list.
77    */
78   struct ClientList *next;
79
80   /**
81    * Overall context this client belongs to.
82    */
83   struct GNUNET_SERVER_NotificationContext *nc;
84
85   /**
86    * Handle to the client.
87    */
88   struct GNUNET_SERVER_Client *client;
89
90   /**
91    * Handle for pending transmission request to the client (or NULL).
92    */
93   struct GNUNET_SERVER_TransmitHandle *th;
94
95   /**
96    * Head of linked list of requests queued for transmission.
97    */
98   struct PendingMessageList *pending_head;
99
100   /**
101    * Tail of linked list of requests queued for transmission.
102    */
103   struct PendingMessageList *pending_tail;
104
105   /**
106    * Number of messages currently in the list.
107    */
108   unsigned int num_pending;
109
110 };
111
112
113 /**
114  * The notification context is the key datastructure for a convenience
115  * API used for transmission of notifications to the client until the
116  * client disconnects (or the notification context is destroyed, in
117  * which case we disconnect these clients).  Essentially, all
118  * (notification) messages are queued up until the client is able to
119  * read them.
120  */
121 struct GNUNET_SERVER_NotificationContext
122 {
123
124   /**
125    * Server we do notifications for.
126    */
127   struct GNUNET_SERVER_Handle *server;
128
129   /**
130    * List of clients receiving notifications.
131    */
132   struct ClientList *clients;
133
134   /**
135    * Maximum number of optional messages to queue per client.
136    */
137   unsigned int queue_length;
138
139 };
140
141
142 /**
143  * Client has disconnected, clean up.
144  *
145  * @param cls our 'struct GNUNET_SERVER_NotificationContext *'
146  * @param client handle of client that disconnected
147  */
148 static void
149 handle_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
150 {
151   struct GNUNET_SERVER_NotificationContext *nc = cls;
152   struct ClientList *pos;
153   struct ClientList *prev;
154   struct PendingMessageList *pml;
155
156   if (client == NULL)
157   {
158     nc->server = NULL;
159     return;
160   }
161   prev = NULL;
162   pos = nc->clients;
163   while (NULL != pos)
164   {
165     if (pos->client == client)
166       break;
167     prev = pos;
168     pos = pos->next;
169   }
170   if (pos == NULL)
171     return;
172   LOG (GNUNET_ERROR_TYPE_DEBUG,
173        "Client disconnected, cleaning up %u messages in NC queue\n",
174        pos->num_pending);
175   if (prev == NULL)
176     nc->clients = pos->next;
177   else
178     prev->next = pos->next;
179   while (NULL != (pml = pos->pending_head))
180   {
181     GNUNET_CONTAINER_DLL_remove (pos->pending_head, pos->pending_tail, pml);
182     GNUNET_free (pml);
183   }
184   if (pos->th != NULL)
185   {
186     GNUNET_SERVER_notify_transmit_ready_cancel (pos->th);
187     pos->th = NULL;
188   }
189   GNUNET_SERVER_client_drop (client);
190   GNUNET_free (pos);
191 }
192
193
194 /**
195  * Create a new notification context.
196  *
197  * @param server server for which this function creates the context
198  * @param queue_length maximum number of messages to keep in
199  *        the notification queue; optional messages are dropped
200  *        it the queue gets longer than this number of messages
201  * @return handle to the notification context
202  */
203 struct GNUNET_SERVER_NotificationContext *
204 GNUNET_SERVER_notification_context_create (struct GNUNET_SERVER_Handle *server,
205                                            unsigned int queue_length)
206 {
207   struct GNUNET_SERVER_NotificationContext *ret;
208
209   ret = GNUNET_malloc (sizeof (struct GNUNET_SERVER_NotificationContext));
210   ret->server = server;
211   ret->queue_length = queue_length;
212   GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, ret);
213   return ret;
214 }
215
216
217 /**
218  * Destroy the context, force disconnect for all clients.
219  *
220  * @param nc context to destroy.
221  */
222 void
223 GNUNET_SERVER_notification_context_destroy (struct
224                                             GNUNET_SERVER_NotificationContext
225                                             *nc)
226 {
227   struct ClientList *pos;
228   struct PendingMessageList *pml;
229
230   while (NULL != (pos = nc->clients))
231   {
232     nc->clients = pos->next;
233     GNUNET_SERVER_client_drop (pos->client);
234     while (NULL != (pml = pos->pending_head))
235     {
236       GNUNET_CONTAINER_DLL_remove (pos->pending_head, pos->pending_tail, pml);
237       GNUNET_free (pml);
238     }
239     GNUNET_free (pos);
240   }
241   if (nc->server != NULL)
242     GNUNET_SERVER_disconnect_notify_cancel (nc->server,
243                                             &handle_client_disconnect, nc);
244   GNUNET_free (nc);
245 }
246
247
248 /**
249  * Add a client to the notification context.
250  *
251  * @param nc context to modify
252  * @param client client to add
253  */
254 void
255 GNUNET_SERVER_notification_context_add (struct GNUNET_SERVER_NotificationContext
256                                         *nc,
257                                         struct GNUNET_SERVER_Client *client)
258 {
259   struct ClientList *cl;
260
261   for (cl = nc->clients; NULL != cl; cl = cl->next)
262     if (cl->client == client)
263       return; /* already present */    
264   cl = GNUNET_malloc (sizeof (struct ClientList));
265   cl->next = nc->clients;
266   cl->nc = nc;
267   cl->client = client;
268   GNUNET_SERVER_client_keep (client);
269   nc->clients = cl;
270 }
271
272
273 /**
274  * Function called to notify a client about the socket begin ready to
275  * queue more data.  "buf" will be NULL and "size" zero if the socket
276  * was closed for writing in the meantime.
277  *
278  * @param cls the 'struct ClientList *'
279  * @param size number of bytes available in buf
280  * @param buf where the callee should write the message
281  * @return number of bytes written to buf
282  */
283 static size_t
284 transmit_message (void *cls, size_t size, void *buf)
285 {
286   struct ClientList *cl = cls;
287   char *cbuf = buf;
288   struct PendingMessageList *pml;
289   uint16_t msize;
290   size_t ret;
291
292   cl->th = NULL;
293   if (buf == NULL)
294   {
295     /* 'cl' should be freed via disconnect notification shortly */
296     LOG (GNUNET_ERROR_TYPE_DEBUG,
297          "Failed to transmit message from NC queue to client\n");
298     return 0;
299   }
300   ret = 0;
301   while (NULL != (pml = cl->pending_head))
302   {
303     msize = ntohs (pml->msg->size);
304     if (size < msize)
305       break;
306     GNUNET_CONTAINER_DLL_remove (cl->pending_head, cl->pending_tail, pml);
307     LOG (GNUNET_ERROR_TYPE_DEBUG,
308          "Copying message of type %u and size %u from pending queue to transmission buffer\n",
309          ntohs (pml->msg->type), msize);
310     memcpy (&cbuf[ret], pml->msg, msize);
311     ret += msize;
312     size -= msize;
313     GNUNET_free (pml);
314     cl->num_pending--;
315   }
316   if (pml != NULL)
317   {
318     LOG (GNUNET_ERROR_TYPE_DEBUG,
319          "Have %u messages left in NC queue, will try transmission again\n",
320          cl->num_pending);
321     cl->th =
322         GNUNET_SERVER_notify_transmit_ready (cl->client, ntohs (pml->msg->size),
323                                              GNUNET_TIME_UNIT_FOREVER_REL,
324                                              &transmit_message, cl);
325   }
326   else
327     GNUNET_assert (cl->num_pending == 0);
328   return ret;
329 }
330
331
332 /**
333  * Send a message to a particular client.
334  *
335  * @param nc context to modify
336  * @param client client to transmit to
337  * @param msg message to send
338  * @param can_drop can this message be dropped due to queue length limitations
339  */
340 static void
341 do_unicast (struct GNUNET_SERVER_NotificationContext *nc,
342             struct ClientList *client, const struct GNUNET_MessageHeader *msg,
343             int can_drop)
344 {
345   struct PendingMessageList *pml;
346   uint16_t size;
347
348   if ((client->num_pending > nc->queue_length) && (GNUNET_YES == can_drop))
349   {
350     LOG (GNUNET_ERROR_TYPE_INFO,
351          "Dropping message of type %u and size %u due to full queue (%u entries)\n",
352          ntohs (msg->type), ntohs (msg->size), (unsigned int) nc->queue_length);
353     return;                     /* drop! */
354   }
355   if (client->num_pending > nc->queue_length)
356   {
357     /* FIXME: consider checking for other messages in the
358      * queue that are 'droppable' */
359   }
360   client->num_pending++;
361   size = ntohs (msg->size);
362   pml = GNUNET_malloc (sizeof (struct PendingMessageList) + size);
363   pml->msg = (const struct GNUNET_MessageHeader *) &pml[1];
364   pml->can_drop = can_drop;
365   LOG (GNUNET_ERROR_TYPE_DEBUG,
366        "Adding message of type %u and size %u to pending queue (which has %u entries)\n",
367        ntohs (msg->type), ntohs (msg->size), (unsigned int) nc->queue_length);
368   memcpy (&pml[1], msg, size);
369   /* append */
370   GNUNET_CONTAINER_DLL_insert_tail (client->pending_head, client->pending_tail,
371                                     pml);
372   if (client->th == NULL)
373     client->th =
374         GNUNET_SERVER_notify_transmit_ready (client->client,
375                                              ntohs (client->pending_head->
376                                                     msg->size),
377                                              GNUNET_TIME_UNIT_FOREVER_REL,
378                                              &transmit_message, client);
379 }
380
381
382 /**
383  * Send a message to a particular client; must have
384  * already been added to the notification context.
385  *
386  * @param nc context to modify
387  * @param client client to transmit to
388  * @param msg message to send
389  * @param can_drop can this message be dropped due to queue length limitations
390  */
391 void
392 GNUNET_SERVER_notification_context_unicast (struct
393                                             GNUNET_SERVER_NotificationContext
394                                             *nc,
395                                             struct GNUNET_SERVER_Client *client,
396                                             const struct GNUNET_MessageHeader
397                                             *msg, int can_drop)
398 {
399   struct ClientList *pos;
400
401   pos = nc->clients;
402   while (NULL != pos)
403   {
404     if (pos->client == client)
405       break;
406     pos = pos->next;
407   }
408   GNUNET_assert (pos != NULL);
409   do_unicast (nc, pos, msg, can_drop);
410 }
411
412
413 /**
414  * Send a message to all clients of this context.
415  *
416  * @param nc context to modify
417  * @param msg message to send
418  * @param can_drop can this message be dropped due to queue length limitations
419  */
420 void
421 GNUNET_SERVER_notification_context_broadcast (struct
422                                               GNUNET_SERVER_NotificationContext
423                                               *nc,
424                                               const struct GNUNET_MessageHeader
425                                               *msg, int can_drop)
426 {
427   struct ClientList *pos;
428
429   pos = nc->clients;
430   while (NULL != pos)
431   {
432     do_unicast (nc, pos, msg, can_drop);
433     pos = pos->next;
434   }
435 }
436
437
438 /* end of server_nc.c */