aboutsummaryrefslogtreecommitdiff
path: root/src/util/bio.c
blob: def9b02e12730c161fe937c5f2b9bc2fae121bee (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
/*
     This file is part of GNUnet.
     Copyright (C) 2006, 2009, 2013 GNUnet e.V.

     GNUnet is free software: you can redistribute it and/or modify it
     under the terms of the GNU Affero General Public License as published
     by the Free Software Foundation, either version 3 of the License,
     or (at your option) any later version.

     GNUnet is distributed in the hope that it will be useful, but
     WITHOUT ANY WARRANTY; without even the implied warranty of
     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     Affero General Public License for more details.
    
     You should have received a copy of the GNU Affero General Public License
     along with this program.  If not, see <http://www.gnu.org/licenses/>.

     SPDX-License-Identifier: AGPL3.0-or-later
*/
/**
 * @file util/bio.c
 * @brief functions for buffering IO
 * @author Christian Grothoff
 */
#include "platform.h"
#include "gnunet_util_lib.h"

#define LOG(kind,...) GNUNET_log_from (kind, "util-bio",__VA_ARGS__)

#ifndef PATH_MAX
/**
 * Assumed maximum path length (for source file names).
 */
#define PATH_MAX 4096
#endif


/**
 * Size for I/O buffers.
 */
#define BIO_BUFFER_SIZE 65536

/**
 * Maximum size allowed for meta data written/read from disk.
 * File-sharing limits to 64k, so this should be rather generous.
 */
#define MAX_META_DATA (1024 * 1024)


/**
 * Handle for buffered reading.
 */
struct GNUNET_BIO_ReadHandle
{
  /**
   * Underlying file abstraction.
   */
  struct GNUNET_DISK_FileHandle *fd;

  /**
   * Error message, NULL if there were no errors.
   */
  char *emsg;

  /**
   * I/O buffer.  Allocated at the end of the struct, do not free!
   */
  char *buffer;

  /**
   * Number of bytes available in read @e buffer.
   */
  size_t have;

  /**
   * Total size of @e buffer.
   */
  size_t size;

  /**
   * Current read offset in @e buffer.
   */
  off_t pos;
};


/**
 * Open a file for reading.
 *
 * @param fn file name to be opened
 * @return IO handle on success, NULL on error
 */
struct GNUNET_BIO_ReadHandle *
GNUNET_BIO_read_open (const char *fn)
{
  struct GNUNET_DISK_FileHandle *fd;
  struct GNUNET_BIO_ReadHandle *h;

  fd = GNUNET_DISK_file_open (fn, GNUNET_DISK_OPEN_READ, GNUNET_DISK_PERM_NONE);
  if (NULL == fd)
    return NULL;
  h = GNUNET_malloc (sizeof (struct GNUNET_BIO_ReadHandle) + BIO_BUFFER_SIZE);
  h->buffer = (char *) &h[1];
  h->size = BIO_BUFFER_SIZE;
  h->fd = fd;
  return h;
}


/**
 * Close an open file.  Reports if any errors reading
 * from the file were encountered.
 *
 * @param h file handle
 * @param emsg set to the error message
 * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise
 */
int
GNUNET_BIO_read_close (struct GNUNET_BIO_ReadHandle *h,
                       char **emsg)
{
  int err;

  err = (NULL == h->emsg) ? GNUNET_OK : GNUNET_SYSERR;
  if (emsg != NULL)
    *emsg = h->emsg;
  else
    GNUNET_free_non_null (h->emsg);
  GNUNET_DISK_file_close (h->fd);
  GNUNET_free (h);
  return err;
}


/**
 * Read the contents of a binary file into a buffer.
 *
 * @param h handle to an open file
 * @param what describes what is being read (for error message creation)
 * @param result the buffer to write the result to
 * @param len the number of bytes to read
 * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
 */
int
GNUNET_BIO_read (struct GNUNET_BIO_ReadHandle *h,
                 const char *what,
                 void *result, size_t len)
{
  char *dst = result;
  size_t min;
  size_t pos;
  ssize_t ret;

  if (NULL != h->emsg)
    return GNUNET_SYSERR;
  pos = 0;
  do
  {
    /* first, use buffer */
    min = h->have - h->pos;
    if (min > 0)
    {
      if (min > len - pos)
        min = len - pos;
      GNUNET_memcpy (&dst[pos],
		     &h->buffer[h->pos],
		     min);
      h->pos += min;
      pos += min;
    }
    if (pos == len)
      return GNUNET_OK;         /* done! */
    GNUNET_assert (((off_t) h->have) == h->pos);
    /* fill buffer */
    ret = GNUNET_DISK_file_read (h->fd,
				 h->buffer,
				 h->size);
    if (-1 == ret)
    {
      GNUNET_asprintf (&h->emsg,
		       _("Error reading `%s': %s"),
		       what,
                       STRERROR (errno));
      return GNUNET_SYSERR;
    }
    if (0 == ret)
    {
      GNUNET_asprintf (&h->emsg,
		       _("Error reading `%s': %s"),
		       what,
                       _("End of file"));
      return GNUNET_SYSERR;
    }
    h->pos = 0;
    h->have = ret;
  }
  while (pos < len);            /* should always be true */
  return GNUNET_OK;
}


/**
 * Read the contents of a binary file into a buffer.
 *
 * @param h handle to an open file
 * @param file name of the source file
 * @param line line number in the source file
 * @param result the buffer to write the result to
 * @param len the number of bytes to read
 * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
 */
int
GNUNET_BIO_read_fn (struct GNUNET_BIO_ReadHandle *h,
                    const char *file,
                    int line,
                    void *result,
                    size_t len)
{
  char what[PATH_MAX + 1024];

  GNUNET_snprintf (what, sizeof (what), "%s:%d", file, line);
  return GNUNET_BIO_read (h, what, result, len);
}


/**
 * Read 0-terminated string from a file.
 *
 * @param h handle to an open file
 * @param what describes what is being read (for error message creation)
 * @param result the buffer to store a pointer to the (allocated) string to
 *        (note that *result could be set to NULL as well)
 * @param max_length maximum allowed length for the string
 * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
 */
int
GNUNET_BIO_read_string (struct GNUNET_BIO_ReadHandle *h,
                        const char *what,
                        char **result,
                        size_t max_length)
{
  char *buf;
  uint32_t big;

  if (GNUNET_OK != GNUNET_BIO_read_int32 (h, &big))
  {
    GNUNET_free_non_null (h->emsg);
    GNUNET_asprintf (&h->emsg, _("Error reading length of string `%s'"), what);
    return GNUNET_SYSERR;
  }
  if (0 == big)
  {
    *result = NULL;
    return GNUNET_OK;
  }
  if (big > max_length)
  {
    GNUNET_asprintf (&h->emsg, _("String `%s' longer than allowed (%u > %u)"),
                     what, big, max_length);
    return GNUNET_SYSERR;
  }
  buf = GNUNET_malloc (big);
  *result = buf;
  buf[--big] = '\0';
  if (0 == big)
    return GNUNET_OK;
  if (GNUNET_OK != GNUNET_BIO_read (h, what, buf, big))
  {
    GNUNET_free (buf);
    *result = NULL;
    return GNUNET_SYSERR;
  }
  return GNUNET_OK;
}


/**
 * Read metadata container from a file.
 *
 * @param h handle to an open file
 * @param what describes what is being read (for error message creation)
 * @param result the buffer to store a pointer to the (allocated) metadata
 * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
 */
int
GNUNET_BIO_read_meta_data (struct GNUNET_BIO_ReadHandle *h,
                           const char *what,
                           struct GNUNET_CONTAINER_MetaData **result)
{
  uint32_t size;
  char *buf;
  struct GNUNET_CONTAINER_MetaData *meta;

  if (GNUNET_OK !=
      GNUNET_BIO_read_int32 (h,
			     (int32_t *) & size))
    return GNUNET_SYSERR;
  if (size == 0)
  {
    *result = NULL;
    return GNUNET_OK;
  }
  if (size > MAX_META_DATA)
  {
    GNUNET_asprintf (&h->emsg,
                     _("Serialized metadata `%s' larger than allowed (%u>%u)"),
                     what,
		     size,
		     MAX_META_DATA);
    return GNUNET_SYSERR;
  }
  buf = GNUNET_malloc (size);
  if (GNUNET_OK !=
      GNUNET_BIO_read (h,
		       what,
		       buf,
		       size))
  {
    GNUNET_free (buf);
    return GNUNET_SYSERR;
  }
  meta = GNUNET_CONTAINER_meta_data_deserialize (buf,
						 size);
  if (NULL == meta)
  {
    GNUNET_free (buf);
    GNUNET_asprintf (&h->emsg,
		     _("Metadata `%s' failed to deserialize"),
		     what);
    return GNUNET_SYSERR;
  }
  GNUNET_free (buf);
  *result = meta;
  return GNUNET_OK;
}


/**
 * Read an (u)int32_t.
 *
 * @param h hande to open file
 * @param file name of the source file
 * @param line line number in the source file
 * @param i address of 32-bit integer to read
 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
 */
int
GNUNET_BIO_read_int32__ (struct GNUNET_BIO_ReadHandle *h,
			 const char *file,
                         int line,
			 int32_t * i)
{
  int32_t big;

  if (GNUNET_OK !=
      GNUNET_BIO_read_fn (h,
			  file,
			  line,
			  &big,
			  sizeof (int32_t)))
    return GNUNET_SYSERR;
  *i = ntohl (big);
  return GNUNET_OK;
}


/**
 * Read an (u)int64_t.
 *
 * @param h hande to open file
 * @param file name of the source file
 * @param line line number in the source file
 * @param i address of 64-bit integer to read
 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
 */
int
GNUNET_BIO_read_int64__ (struct GNUNET_BIO_ReadHandle *h,
                         const char *file,
                         int line,
                         int64_t *i)
{
  int64_t big;

  if (GNUNET_OK !=
      GNUNET_BIO_read_fn (h,
			  file,
			  line,
			  &big,
			  sizeof (int64_t)))
    return GNUNET_SYSERR;
  *i = GNUNET_ntohll (big);
  return GNUNET_OK;
}


/**
 * Handle for buffered writing.
 */
struct GNUNET_BIO_WriteHandle
{
  /**
   * Underlying file handle.
   */
  struct GNUNET_DISK_FileHandle *fd;

  /**
   * I/O buffer.  Do not free, allocated at the end of the struct.
   */
  char *buffer;

  /**
   * Number of bytes already in @e buffer.
   */
  size_t have;

  /**
   * Total size of @e buffer.
   */
  size_t size;
};


/**
 * Open a file for writing.
 *
 * @param fn file name to be opened
 * @return IO handle on success, NULL on error
 */
struct GNUNET_BIO_WriteHandle *
GNUNET_BIO_write_open (const char *fn)
{
  struct GNUNET_DISK_FileHandle *fd;
  struct GNUNET_BIO_WriteHandle *h;

  fd = GNUNET_DISK_file_open (fn,
                              GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_TRUNCATE
                              | GNUNET_DISK_OPEN_CREATE,
                              GNUNET_DISK_PERM_USER_READ |
                              GNUNET_DISK_PERM_USER_WRITE);
  if (NULL == fd)
    return NULL;
  h = GNUNET_malloc (sizeof (struct GNUNET_BIO_WriteHandle) + BIO_BUFFER_SIZE);
  h->buffer = (char *) &h[1];
  h->size = BIO_BUFFER_SIZE;
  h->fd = fd;
  return h;
}


/**
 * Close an open file for writing.
 *
 * @param h file handle
 * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise
 */
int
GNUNET_BIO_write_close (struct GNUNET_BIO_WriteHandle *h)
{
  int ret;

  ret = GNUNET_SYSERR;
  if ( (NULL != h->fd) &&
       (GNUNET_OK == (ret = GNUNET_BIO_flush (h))) )
    GNUNET_DISK_file_close (h->fd);
  GNUNET_free (h);
  return ret;
}


/**
 * Force a buffered writer to flush its buffer
 *
 * @param h the writer handle
 * @return #GNUNET_OK upon success.  Upon failure #GNUNET_SYSERR is returned and
 *           the file is closed
 */
int
GNUNET_BIO_flush (struct GNUNET_BIO_WriteHandle *h)
{
  ssize_t ret;

  ret = GNUNET_DISK_file_write (h->fd,
				h->buffer,
				h->have);
  if (ret != (ssize_t) h->have)
  {
    GNUNET_DISK_file_close (h->fd);
    h->fd = NULL;
    return GNUNET_SYSERR;     /* error */
  }
  h->have = 0;
  return GNUNET_OK;
}


/**
 * Write a buffer to a file.
 *
 * @param h handle to open file
 * @param buffer the data to write
 * @param n number of bytes to write
 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
 */
int
GNUNET_BIO_write (struct GNUNET_BIO_WriteHandle *h,
		  const void *buffer,
                  size_t n)
{
  const char *src = buffer;
  size_t min;
  size_t pos;

  if (NULL == h->fd)
    return GNUNET_SYSERR;
  pos = 0;
  do
  {
    /* first, just use buffer */
    min = h->size - h->have;
    if (min > n - pos)
      min = n - pos;
    GNUNET_memcpy (&h->buffer[h->have],
		   &src[pos],
		   min);
    pos += min;
    h->have += min;
    if (pos == n)
      return GNUNET_OK;         /* done */
    GNUNET_assert (h->have == h->size);
    if (GNUNET_OK != GNUNET_BIO_flush (h))
      return GNUNET_SYSERR;     /* error */
  }
  while (pos < n);              /* should always be true */
  GNUNET_break (0);
  return GNUNET_OK;
}


/**
 * Write a string to a file.
 *
 * @param h handle to open file
 * @param s string to write (can be NULL)
 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
 */
int
GNUNET_BIO_write_string (struct GNUNET_BIO_WriteHandle *h,
			 const char *s)
{
  uint32_t slen;

  slen = (uint32_t) ((s == NULL) ? 0 : strlen (s) + 1);
  if (GNUNET_OK != GNUNET_BIO_write_int32 (h, slen))
    return GNUNET_SYSERR;
  if (0 != slen)
    return GNUNET_BIO_write (h, s, slen - 1);
  return GNUNET_OK;
}


/**
 * Write metadata container to a file.
 *
 * @param h handle to open file
 * @param m metadata to write
 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
 */
int
GNUNET_BIO_write_meta_data (struct GNUNET_BIO_WriteHandle *h,
                            const struct GNUNET_CONTAINER_MetaData *m)
{
  ssize_t size;
  char *buf;

  if (m == NULL)
    return GNUNET_BIO_write_int32 (h, 0);
  buf = NULL;
  size =
      GNUNET_CONTAINER_meta_data_serialize (m, &buf, MAX_META_DATA,
                                            GNUNET_CONTAINER_META_DATA_SERIALIZE_PART);
  if (size == -1)
  {
    GNUNET_free (buf);
    return GNUNET_SYSERR;
  }
  if ((GNUNET_OK != GNUNET_BIO_write_int32 (h, (uint32_t) size)) ||
      (GNUNET_OK != GNUNET_BIO_write (h, buf, size)))
  {
    GNUNET_free (buf);
    return GNUNET_SYSERR;
  }
  GNUNET_free (buf);
  return GNUNET_OK;
}


/**
 * Write an (u)int32_t.
 *
 * @param h hande to open file
 * @param i 32-bit integer to write
 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
 */
int
GNUNET_BIO_write_int32 (struct GNUNET_BIO_WriteHandle *h,
                        int32_t i)
{
  int32_t big;

  big = htonl (i);
  return GNUNET_BIO_write (h, &big, sizeof (int32_t));
}


/**
 * Write an (u)int64_t.
 *
 * @param h hande to open file
 * @param i 64-bit integer to write
 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
 */
int
GNUNET_BIO_write_int64 (struct GNUNET_BIO_WriteHandle *h,
                        int64_t i)
{
  int64_t big;

  big = GNUNET_htonll (i);
  return GNUNET_BIO_write (h, &big, sizeof (int64_t));
}


/* end of bio.c */