vfs: check userland buffers before reading them.
[haiku.git] / src / tests / kits / net / sock / write.c
blobb48192e3c501f06d7e0136a9829220b0fafbf6f4
1 /* -*- c-basic-offset: 8; -*-
3 * Copyright (c) 1993 W. Richard Stevens. All rights reserved.
4 * Permission to use or modify this software and its documentation only for
5 * educational purposes and without fee is hereby granted, provided that
6 * the above copyright notice appear in all copies. The author makes no
7 * representations about the suitability of this software for any purpose.
8 * It is provided "as is" without express or implied warranty.
9 */
11 #include "sock.h"
13 #ifndef UIO_MAXIOV
14 #define UIO_MAXIOV 16 /* we assume this; may not be true? */
15 #endif
17 ssize_t
18 dowrite(int fd, const void *vptr, size_t nbytes)
20 struct iovec iov[UIO_MAXIOV];
21 const char *ptr;
22 int chunksize, i, n, nleft, nwritten, ntotal;
24 if (chunkwrite == 0 && usewritev == 0)
25 return(write(fd, vptr, nbytes)); /* common case */
28 * Figure out what sized chunks to write.
29 * Try to use UIO_MAXIOV chunks.
32 chunksize = nbytes / UIO_MAXIOV;
33 if (chunksize <= 0)
34 chunksize = 1;
35 else if ((nbytes % UIO_MAXIOV) != 0)
36 chunksize++;
38 ptr = vptr;
39 nleft = nbytes;
40 for (i = 0; i < UIO_MAXIOV; i++)
42 iov[i].iov_base = (void *) ptr;
43 n = (nleft >= chunksize) ? chunksize : nleft;
44 iov[i].iov_len = n;
45 if (verbose)
46 fprintf(stderr, "iov[%2d].iov_base = %x, iov[%2d].iov_len = %d\n",
47 i, (u_int32_t) iov[i].iov_base, i, (int) iov[i].iov_len);
48 ptr += n;
49 if ((nleft -= n) == 0)
50 break;
52 if (i == UIO_MAXIOV)
53 err_quit("i == UIO_MAXIOV");
55 if (usewritev)
56 return(writev(fd, iov, i+1));
57 else {
58 ntotal = 0;
59 for (n = 0; n <= i; n++) {
60 nwritten = write(fd, iov[n].iov_base, iov[n].iov_len);
61 if (nwritten != (int) iov[n].iov_len)
62 return(-1);
63 ntotal += nwritten;
65 return(ntotal);