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