d7a109f3b91b135e1ae59c5a538c9fc9ce143bc7
[oweals/gnunet.git] / src / util / server_mst.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_mst.c
23  * @brief convenience functions for handling inbound message buffers
24  * @author Christian Grothoff
25  */
26
27 #include "platform.h"
28 #include "gnunet_common.h"
29 #include "gnunet_connection_lib.h"
30 #include "gnunet_scheduler_lib.h"
31 #include "gnunet_server_lib.h"
32 #include "gnunet_time_lib.h"
33
34 #define DEBUG_SERVER_MST GNUNET_NO
35
36 #if HAVE_UNALIGNED_64_ACCESS
37 #define ALIGN_FACTOR 4
38 #else
39 #define ALIGN_FACTOR 8
40 #endif
41
42
43 /**
44  * Handle to a message stream tokenizer.
45  */
46 struct GNUNET_SERVER_MessageStreamTokenizer
47 {
48
49   /**
50    * Function to call on completed messages.
51    */
52   GNUNET_SERVER_MessageTokenizerCallback cb;
53   
54   /**
55    * Closure for cb.
56    */
57   void *cb_cls;
58
59   /**
60    * Size of the buffer (starting at 'hdr').
61    */
62   size_t curr_buf;
63
64   /**
65    * Maximum size of the buffer.
66    */
67   size_t maxbuf;
68
69   /**
70    * How many bytes in buffer have we already processed?
71    */
72   size_t off;
73
74   /**
75    * How many bytes in buffer are valid right now?
76    */
77   size_t pos;
78
79   /**
80    * Beginning of the buffer.  Typed like this to force alignment.
81    */
82   struct GNUNET_MessageHeader *hdr;
83
84 };
85
86
87
88 /**
89  * Create a message stream tokenizer.
90  *
91  * @param maxbuf maximum message size to support (typically
92  *    GNUNET_SERVER_MAX_MESSAGE_SIZE - 1)
93  * @param cb function to call on completed messages
94  * @param cb_cls closure for cb
95  * @return handle to tokenizer
96  */
97 struct GNUNET_SERVER_MessageStreamTokenizer *
98 GNUNET_SERVER_mst_create (size_t maxbuf,
99                           GNUNET_SERVER_MessageTokenizerCallback cb,
100                           void *cb_cls)
101 {
102   struct GNUNET_SERVER_MessageStreamTokenizer *ret;
103
104   ret = GNUNET_malloc (sizeof (struct GNUNET_SERVER_MessageStreamTokenizer));
105   ret->hdr = GNUNET_malloc(GNUNET_SERVER_MIN_BUFFER_SIZE);
106   ret->curr_buf = GNUNET_SERVER_MIN_BUFFER_SIZE;
107   ret->maxbuf = maxbuf;
108   ret->cb = cb;
109   ret->cb_cls = cb_cls;
110   return ret;
111 }
112
113
114 /**
115  * Add incoming data to the receive buffer and call the
116  * callback for all complete messages.
117  *
118  * @param mst tokenizer to use
119  * @param client_identity ID of client for which this is a buffer
120  * @param buf input data to add
121  * @param size number of bytes in buf
122  * @param purge should any excess bytes in the buffer be discarded 
123  *       (i.e. for packet-based services like UDP)
124  * @param one_shot only call callback once, keep rest of message in buffer
125  * @return GNUNET_OK if we are done processing (need more data)
126  *         GNUNET_NO if one_shot was set and we have another message ready
127  *         GNUNET_SYSERR if the data stream is corrupt
128  */
129 int
130 GNUNET_SERVER_mst_receive (struct GNUNET_SERVER_MessageStreamTokenizer *mst,
131                            void *client_identity,
132                            const char *buf,
133                            size_t size,
134                            int purge,
135                            int one_shot)
136 {
137   const struct GNUNET_MessageHeader *hdr;
138   size_t delta;
139   uint16_t want;
140   char *ibuf;
141   int need_align;
142   unsigned long offset;
143   int ret;
144   size_t newsize;
145
146 #if DEBUG_SERVER_MST
147   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
148               "Server-mst receives %u bytes with %u bytes already in private buffer\n",
149               (unsigned int) size,
150               (unsigned int) (mst->pos - mst->off));
151 #endif
152   if ((size > mst->curr_buf) && (size < mst->maxbuf)) /* Received bigger message than we can currently handle! */
153     {
154       newsize = mst->curr_buf + size; /* How much space do we need? */
155       if (newsize > mst->maxbuf)
156         newsize = mst->maxbuf; /* Check it's not bigger than maxbuf */
157
158       mst->hdr = GNUNET_realloc(mst->hdr, newsize);
159       mst->curr_buf = newsize;
160     }
161
162   ret = GNUNET_OK;
163   ibuf = (char*)mst->hdr;
164   while (mst->pos > 0)
165     {
166     do_align:
167       if ( (mst->curr_buf - mst->off < sizeof (struct GNUNET_MessageHeader)) ||
168            (0 != (mst->off % ALIGN_FACTOR)) )
169         {
170           /* need to align or need more space */
171           mst->pos -= mst->off;
172           memmove (ibuf,
173                    &ibuf[mst->off],
174                    mst->pos);
175           mst->off = 0;
176         }
177       if (mst->pos - mst->off < sizeof (struct GNUNET_MessageHeader))
178         {
179           delta = GNUNET_MIN (sizeof (struct GNUNET_MessageHeader) - (mst->pos - mst->off),
180                               size);
181           memcpy (&ibuf[mst->pos],
182                   buf,
183                   delta);
184           mst->pos += delta;
185           buf += delta;
186           size -= delta;
187         }
188       if (mst->pos - mst->off < sizeof (struct GNUNET_MessageHeader))
189         {
190           if (purge)
191             {
192               mst->off = 0;    
193               mst->pos = 0;
194             }
195           return GNUNET_OK;
196         }
197       hdr = (const struct GNUNET_MessageHeader*) &ibuf[mst->off];
198       want = ntohs (hdr->size);
199       if (want < sizeof (struct GNUNET_MessageHeader))
200         {
201           GNUNET_break_op (0);
202           return GNUNET_SYSERR;
203         }
204       if (mst->curr_buf - mst->off < want)
205         {
206           /* need more space */
207           mst->pos -= mst->off;
208           memmove (ibuf,
209                    &ibuf[mst->off],
210                    mst->pos);
211           mst->off = 0;
212         }
213       if (mst->pos - mst->off < want)
214         {
215           delta = GNUNET_MIN (want - (mst->pos - mst->off),
216                               size);
217           memcpy (&ibuf[mst->pos],
218                   buf,
219                   delta);
220           mst->pos += delta;
221           buf += delta;
222           size -= delta;
223         }
224       if (mst->pos - mst->off < want)
225         {
226           if (purge)
227             {
228               mst->off = 0;    
229               mst->pos = 0;
230             }
231           return GNUNET_OK;
232         }
233       if (one_shot == GNUNET_SYSERR)
234         {
235           /* cannot call callback again, but return value saying that
236              we have another full message in the buffer */
237           ret = GNUNET_NO;
238           goto copy;
239         }
240       if (one_shot == GNUNET_YES)
241         one_shot = GNUNET_SYSERR;
242       mst->cb (mst->cb_cls, client_identity, hdr);
243       mst->off += want;
244       if (mst->off == mst->pos)
245         {
246           /* reset to beginning of buffer, it's free right now! */
247           mst->off = 0;
248           mst->pos = 0;
249         }
250     }
251   while (size > 0)
252     {
253 #if DEBUG_SERVER_MST
254       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
255                   "Server-mst has %u bytes left in inbound buffer\n",
256                   (unsigned int) size);
257 #endif
258       if (size < sizeof (struct GNUNET_MessageHeader))
259         break;
260       offset = (unsigned long) buf;
261       need_align = (0 != offset % ALIGN_FACTOR) ? GNUNET_YES : GNUNET_NO;
262       if (GNUNET_NO == need_align)
263         {
264           /* can try to do zero-copy and process directly from original buffer */
265           hdr = (const struct GNUNET_MessageHeader *) buf;
266           want = ntohs (hdr->size);
267           if (size < want)
268             break; /* or not, buffer incomplete, so copy to private buffer... */
269           if (one_shot == GNUNET_SYSERR)
270             {
271               /* cannot call callback again, but return value saying that
272                  we have another full message in the buffer */
273               ret = GNUNET_NO;
274               goto copy;
275             }
276           if (one_shot == GNUNET_YES)
277             one_shot = GNUNET_SYSERR;
278           mst->cb (mst->cb_cls, client_identity, hdr);
279           buf += want;
280           size -= want;
281         }
282       else
283         {
284           /* need to copy to private buffer to align;
285              yes, we go a bit more spagetti than usual here */
286           goto do_align;
287         }
288     }
289  copy:
290   if ( (size > 0) && (! purge) )
291     {
292       GNUNET_assert (mst->pos + size <= mst->curr_buf);
293       memcpy (&ibuf[mst->pos], buf, size);
294       mst->pos += size;
295     }
296   if (purge)
297     mst->off = 0;    
298 #if DEBUG_SERVER_MST
299   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
300               "Server-mst leaves %u bytes in private buffer\n",
301               (unsigned int) (mst->pos - mst->off));
302 #endif
303   return ret;
304 }
305
306
307 /**
308  * Destroys a tokenizer.
309  *
310  * @param mst tokenizer to destroy
311  */
312 void
313 GNUNET_SERVER_mst_destroy (struct GNUNET_SERVER_MessageStreamTokenizer *mst)
314 {
315   GNUNET_free (mst);
316 }
317
318
319
320 /* end of server_mst.c */