1143e89de82c70577cdb8065ba5ec7e515fe1bd8
[oweals/gnunet.git] / src / util / bio.c
1 /*
2      This file is part of GNUnet.
3      (C) 2006, 2009 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  * @file util/bio.c
22  * @brief functions for buffering IO
23  * @author Christian Grothoff
24  */
25 #include "platform.h"
26 #include "gnunet_bio_lib.h"
27 #include "gnunet_disk_lib.h"
28
29 #define BIO_BUFFER_SIZE 65536
30
31 #define MAX_META_DATA (1024 * 1024)
32
33 /**
34  * Handle for buffered reading.
35  */
36 struct GNUNET_BIO_ReadHandle
37 {
38   struct GNUNET_DISK_FileHandle *fd;
39   char *emsg;
40   char *buffer;
41   size_t have;
42   size_t size;
43   off_t pos;
44 };
45
46
47 /**
48  * Open a file for reading.
49  *
50  * @param fn file name to be opened
51  * @return IO handle on success, NULL on error
52  */
53 struct GNUNET_BIO_ReadHandle *
54 GNUNET_BIO_read_open (const char *fn)
55 {
56   struct GNUNET_DISK_FileHandle *fd;
57   struct GNUNET_BIO_ReadHandle *h;
58
59   fd = GNUNET_DISK_file_open (fn, GNUNET_DISK_OPEN_READ,
60                               GNUNET_DISK_PERM_NONE);
61   if (NULL == fd)
62     return NULL;
63   h = GNUNET_malloc (sizeof (struct GNUNET_BIO_ReadHandle) + BIO_BUFFER_SIZE);
64   h->buffer = (char *) &h[1];
65   h->size = BIO_BUFFER_SIZE;
66   h->fd = fd;
67   return h;
68 }
69
70
71 /**
72  * Close an open file.  Reports if any errors reading
73  * from the file were encountered.
74  *
75  * @param h file handle
76  * @param emsg set to the error message
77  * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
78  */
79 int
80 GNUNET_BIO_read_close (struct GNUNET_BIO_ReadHandle *h, char **emsg)
81 {
82   *emsg = h->emsg;
83   GNUNET_DISK_file_close (h->fd);
84   GNUNET_free (h);
85   return (NULL == *emsg) ? GNUNET_OK : GNUNET_SYSERR;
86 }
87
88
89 /**
90  * Read the contents of a binary file into a buffer.
91  *
92  * @param h handle to an open file
93  * @param what describes what is being read (for error message creation)
94  * @param result the buffer to write the result to
95  * @param len the number of bytes to read
96  * @return GNUNET_OK on success, GNUNET_SYSERR on failure
97  */
98 int
99 GNUNET_BIO_read (struct GNUNET_BIO_ReadHandle *h,
100                  const char *what, void *result, size_t len)
101 {
102   char *dst = result;
103   size_t min;
104   size_t pos;
105   ssize_t ret;
106
107   if (h->emsg != NULL)
108     return GNUNET_SYSERR;
109   pos = 0;
110   do
111     {
112       /* first, use buffer */
113       min = h->have - h->pos;
114       if (min > 0)
115         {
116           if (min > len - pos)
117             min = len - pos;
118           memcpy (&dst[pos], &h->buffer[h->pos], min);
119           h->pos += min;
120           pos += min;
121         }
122       if (pos == len)
123         return GNUNET_OK;       /* done! */
124       GNUNET_assert (h->have == h->pos);
125       /* fill buffer */
126       ret = GNUNET_DISK_file_read (h->fd, h->buffer, h->size);
127       if (ret == -1)
128         {
129           GNUNET_asprintf (&h->emsg,
130                            _("Error reading `%s': %s"),
131                            what, STRERROR (errno));
132           return GNUNET_SYSERR;
133         }
134       if (ret == 0)
135         {
136           GNUNET_asprintf (&h->emsg,
137                            _("Error reading `%s': %s"),
138                            what, _("End of file"));
139           return GNUNET_SYSERR;
140         }
141       h->pos = 0;
142       h->have = ret;
143     }
144   while (pos < len);            /* should always be true */
145   return GNUNET_OK;
146 }
147
148
149 /**
150  * Read 0-terminated string from a file.
151  *
152  * @param h handle to an open file
153  * @param what describes what is being read (for error message creation)
154  * @param result the buffer to store a pointer to the (allocated) string to
155  *        (note that *result could be set to NULL as well)
156  * @param maxLen maximum allowed length for the string
157  * @return GNUNET_OK on success, GNUNET_SYSERR on failure
158  */
159 int
160 GNUNET_BIO_read_string (struct GNUNET_BIO_ReadHandle *h,
161                         const char *what, char **result, size_t maxLen)
162 {
163   char *buf;
164   uint32_t big;
165
166   if (GNUNET_OK != GNUNET_BIO_read_int32 (h, &big))
167     return GNUNET_SYSERR;
168   if (big == 0)
169     {
170       *result = NULL;
171       return GNUNET_OK;
172     }
173   if (big > maxLen)
174     {
175       GNUNET_asprintf (&h->emsg,
176                        _("String `%s' longer than allowed (%u > %u)"),
177                        what, big, maxLen);
178       return GNUNET_SYSERR;
179     }
180   buf = GNUNET_malloc (big);
181   *result = buf;
182   buf[--big] = '\0';
183   if (big == 0)
184     return GNUNET_OK;
185   if (GNUNET_OK != GNUNET_BIO_read (h, what, buf, big))
186     {
187       GNUNET_free (buf);
188       *result = NULL;
189       return GNUNET_SYSERR;
190     }
191   return GNUNET_OK;
192 }
193
194
195 /**
196  * Read metadata container from a file.
197  *
198  * @param h handle to an open file
199  * @param what describes what is being read (for error message creation)
200  * @param result the buffer to store a pointer to the (allocated) metadata
201  * @return GNUNET_OK on success, GNUNET_SYSERR on failure
202  */
203 int
204 GNUNET_BIO_read_meta_data (struct GNUNET_BIO_ReadHandle *h,
205                            const char *what,
206                            struct GNUNET_CONTAINER_MetaData **result)
207 {
208   uint32_t size;
209   char *buf;
210   struct GNUNET_CONTAINER_MetaData *meta;
211
212   if (GNUNET_BIO_read_int32__ (h, what, (int32_t *) & size) != GNUNET_OK)
213     return GNUNET_SYSERR;
214   if (size > MAX_META_DATA)
215     {
216       GNUNET_asprintf (&h->emsg,
217                        _
218                        ("Serialized metadata `%s' larger than allowed (%u > %u)"),
219                        what, size, MAX_META_DATA);
220       return GNUNET_SYSERR;
221     }
222   buf = GNUNET_malloc (size);
223   if (GNUNET_OK != GNUNET_BIO_read (h, what, buf, size))
224     {
225       GNUNET_free (buf);
226       return GNUNET_SYSERR;
227     }
228   meta = GNUNET_CONTAINER_meta_data_deserialize (buf, size);
229   if (meta == NULL)
230     {
231       GNUNET_free (buf);
232       GNUNET_asprintf (&h->emsg,
233                        _("Metadata `%s' failed to deserialize"), what);
234       return GNUNET_SYSERR;
235     }
236   GNUNET_free (buf);
237   *result = meta;
238   return GNUNET_OK;
239 }
240
241
242 /**
243  * Read an (u)int32_t.
244  *
245  * @param h hande to open file
246  * @param what describes what is being read (for error message creation)
247  * @param i address of 32-bit integer to read
248  * @return GNUNET_OK on success, GNUNET_SYSERR on error
249  */
250 int
251 GNUNET_BIO_read_int32__ (struct GNUNET_BIO_ReadHandle *h,
252                          const char *what, int32_t * i)
253 {
254   int32_t big;
255
256   if (GNUNET_OK != GNUNET_BIO_read (h, what, &big, sizeof (int32_t)))
257     return GNUNET_SYSERR;
258   *i = ntohl (big);
259   return GNUNET_OK;
260 }
261
262
263 /**
264  * Read an (u)int64_t.
265  *
266  * @param h hande to open file
267  * @param what describes what is being read (for error message creation)
268  * @param i address of 64-bit integer to read
269  * @return GNUNET_OK on success, GNUNET_SYSERR on error
270  */
271 int
272 GNUNET_BIO_read_int64__ (struct GNUNET_BIO_ReadHandle *h,
273                          const char *what, int64_t * i)
274 {
275   int64_t big;
276
277   if (GNUNET_OK != GNUNET_BIO_read (h, what, &big, sizeof (int64_t)))
278     return GNUNET_SYSERR;
279   *i = GNUNET_ntohll (big);
280   return GNUNET_OK;
281 }
282
283
284 /**
285  * Handle for buffered writing.
286  */
287 struct GNUNET_BIO_WriteHandle
288 {
289   struct GNUNET_DISK_FileHandle *fd;
290   char *buffer;
291   size_t have;
292   size_t size;
293 };
294
295
296 /**
297  * Open a file for writing.
298  *
299  * @param fn file name to be opened
300  * @return IO handle on success, NULL on error
301  */
302 struct GNUNET_BIO_WriteHandle *
303 GNUNET_BIO_write_open (const char *fn)
304 {
305   struct GNUNET_DISK_FileHandle *fd;
306   struct GNUNET_BIO_WriteHandle *h;
307
308   fd = GNUNET_DISK_file_open (fn,
309                               GNUNET_DISK_OPEN_WRITE |
310                               GNUNET_DISK_OPEN_TRUNCATE |
311                               GNUNET_DISK_OPEN_CREATE,
312                               GNUNET_DISK_PERM_USER_READ |
313                               GNUNET_DISK_PERM_USER_WRITE);
314   if (NULL == fd)
315     return NULL;
316   h =
317     GNUNET_malloc (sizeof (struct GNUNET_BIO_WriteHandle) + BIO_BUFFER_SIZE);
318   h->buffer = (char *) &h[1];
319   h->size = BIO_BUFFER_SIZE;
320   h->fd = fd;
321
322   return h;
323 }
324
325
326 /**
327  * Close an open file for writing.
328  *
329  * @param h file handle
330  * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
331  */
332 int
333 GNUNET_BIO_write_close (struct GNUNET_BIO_WriteHandle *h)
334 {
335   ssize_t wrt;
336   int ret;
337
338   if (NULL == h->fd)
339     {
340       ret = GNUNET_SYSERR;
341     }
342   else
343     {
344       wrt = GNUNET_DISK_file_write (h->fd, h->buffer, h->have);
345       if (wrt == h->have)
346         ret = GNUNET_OK;
347       else
348         ret = GNUNET_SYSERR;
349       GNUNET_DISK_file_close (h->fd);
350     }
351   GNUNET_free (h);
352   return ret;
353 }
354
355
356 /**
357  * Write a buffer to a file.
358  *
359  * @param h handle to open file
360  * @param buffer the data to write
361  * @param n number of bytes to write
362  * @return GNUNET_OK on success, GNUNET_SYSERR on error
363  */
364 int
365 GNUNET_BIO_write (struct GNUNET_BIO_WriteHandle *h,
366                   const void *buffer, size_t n)
367 {
368   const char *src = buffer;
369   size_t min;
370   size_t pos;
371   ssize_t ret;
372
373   if (NULL == h->fd)
374     return GNUNET_SYSERR;
375   pos = 0;
376   do
377     {
378       /* first, just use buffer */
379       min = h->size - h->have;
380       if (min > n - pos)
381         min = n - pos;
382       memcpy (&h->buffer[h->have], &src[pos], min);
383       pos += min;
384       h->have += min;
385       if (pos == n)
386         return GNUNET_OK;       /* done */
387       GNUNET_assert (h->have == h->size);
388       ret = GNUNET_DISK_file_write (h->fd, h->buffer, h->size);
389       if (ret != h->size)
390         {
391           GNUNET_DISK_file_close (h->fd);
392           h->fd = NULL;
393           return GNUNET_SYSERR; /* error */
394         }
395       h->have = 0;
396     }
397   while (pos < n);              /* should always be true */
398   GNUNET_break (0);
399   return GNUNET_OK;
400 }
401
402
403 /**
404  * Write a string to a file.
405  *
406  * @param h handle to open file
407  * @param s string to write (can be NULL)
408  * @return GNUNET_OK on success, GNUNET_SYSERR on error
409  */
410 int
411 GNUNET_BIO_write_string (struct GNUNET_BIO_WriteHandle *h, const char *s)
412 {
413   uint32_t slen;
414
415   slen = (uint32_t) ((s == NULL) ? 0 : strlen (s) + 1);
416   if (GNUNET_OK != GNUNET_BIO_write_int32 (h, slen))
417     return GNUNET_SYSERR;
418   if (0 != slen)
419     return GNUNET_BIO_write (h, s, slen - 1);
420   return GNUNET_OK;
421 }
422
423
424 /**
425  * Write metadata container to a file.
426  *
427  * @param h handle to open file
428  * @param m metadata to write
429  * @return GNUNET_OK on success, GNUNET_SYSERR on error
430  */
431 int
432 GNUNET_BIO_write_meta_data (struct GNUNET_BIO_WriteHandle *h,
433                             const struct GNUNET_CONTAINER_MetaData *m)
434 {
435   unsigned int size;
436   char *buf;
437
438   size = GNUNET_CONTAINER_meta_data_get_serialized_size (m,
439                                                          GNUNET_CONTAINER_META_DATA_SERIALIZE_FULL
440                                                          |
441                                                          GNUNET_CONTAINER_META_DATA_SERIALIZE_NO_COMPRESS);
442   if (size > MAX_META_DATA)
443     size = MAX_META_DATA;
444   buf = GNUNET_malloc (size);
445   GNUNET_CONTAINER_meta_data_serialize (m,
446                                         buf,
447                                         size,
448                                         GNUNET_CONTAINER_META_DATA_SERIALIZE_PART
449                                         |
450                                         GNUNET_CONTAINER_META_DATA_SERIALIZE_NO_COMPRESS);
451   if ((GNUNET_OK != GNUNET_BIO_write_int32 (h, size))
452       || (GNUNET_OK != GNUNET_BIO_write (h, buf, size)))
453     {
454       GNUNET_free (buf);
455       return GNUNET_SYSERR;
456     }
457   GNUNET_free (buf);
458   return GNUNET_OK;
459 }
460
461
462 /**
463  * Write an (u)int32_t.
464  *
465  * @param h hande to open file
466  * @param i address of 32-bit integer to write
467  * @return GNUNET_OK on success, GNUNET_SYSERR on error
468  */
469 int
470 GNUNET_BIO_write_int32 (struct GNUNET_BIO_WriteHandle *h, int32_t i)
471 {
472   int32_t big;
473   big = htonl (i);
474   return GNUNET_BIO_write (h, &big, sizeof (int32_t));
475 }
476
477
478 /**
479  * Write an (u)int64_t.
480  *
481  * @param h hande to open file
482  * @param i address of 64-bit integer to write
483  * @return GNUNET_OK on success, GNUNET_SYSERR on error
484  */
485 int
486 GNUNET_BIO_write_int64 (struct GNUNET_BIO_WriteHandle *h, int64_t i)
487 {
488   int64_t big;
489   big = GNUNET_htonll (i);
490   return GNUNET_BIO_write (h, &big, sizeof (int64_t));
491 }
492
493
494 /* end of bio.c */