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