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