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