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