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