vfs: check userland buffers before reading them.
[haiku.git] / src / tests / kits / net / sock / looptcp.c
blob72e1f6416438775c85a50514be956b3c29ac4732
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 /* Copy everything from stdin to "sockfd",
14 * and everything from "sockfd" to stdout. */
16 void loop_tcp(int sockfd)
18 int maxfdp1, nread, ntowrite, stdineof, flags;
19 fd_set rset;
21 if (pauseinit)
22 sleep_us(pauseinit*1000); /* intended for server */
24 flags = 0;
25 stdineof = 0;
26 FD_ZERO(&rset);
27 maxfdp1 = sockfd + 1; /* check descriptors [0..sockfd] */
29 for ( ; ; ) {
30 if (stdineof == 0)
31 FD_SET(STDIN_FILENO, &rset);
32 FD_SET(sockfd, &rset);
34 if (select(maxfdp1, &rset, NULL, NULL, NULL) < 0)
35 err_sys("select error");
37 if (FD_ISSET(STDIN_FILENO, &rset)) {
38 /* data to read on stdin */
39 if ( (nread = read(STDIN_FILENO, rbuf, readlen)) < 0)
40 err_sys("read error from stdin");
41 else if (nread == 0) {
42 /* EOF on stdin */
43 if (halfclose) {
44 if (shutdown(sockfd, SHUT_WR) < 0)
45 err_sys("shutdown() error");
47 FD_CLR(STDIN_FILENO, &rset);
48 stdineof = 1; /* don't read stdin anymore */
49 continue; /* back to select() */
51 break; /* default: stdin EOF -> done */
54 if (crlf) {
55 ntowrite = crlf_add(wbuf, writelen, rbuf, nread);
56 if (dowrite(sockfd, wbuf, ntowrite) != ntowrite)
57 err_sys("write error");
58 } else {
59 if (dowrite(sockfd, rbuf, nread) != nread)
60 err_sys("write error");
64 if (FD_ISSET(sockfd, &rset)) {
65 /* data to read from socket */
66 /* msgpeek = 0 or MSG_PEEK */
67 flags = msgpeek;
68 oncemore:
69 if ( (nread = recv(sockfd, rbuf, readlen, flags)) < 0)
70 err_sys("recv error");
71 else if (nread == 0) {
72 if (verbose)
73 fprintf(stderr, "connection closed by peer\n");
74 break; /* EOF, terminate */
77 if (crlf) {
78 ntowrite = crlf_strip(wbuf, writelen, rbuf, nread);
79 if (writen(STDOUT_FILENO, wbuf, ntowrite) != ntowrite)
80 err_sys("writen error to stdout");
81 } else {
82 if (writen(STDOUT_FILENO, rbuf, nread) != nread)
83 err_sys("writen error to stdout");
86 if (flags != 0) {
87 flags = 0; /* no infinite loop */
88 goto oncemore; /* read the message again */
93 if (pauseclose) {
94 if (verbose)
95 fprintf(stderr, "pausing before close\n");
96 sleep_us(pauseclose*1000);
99 if (close(sockfd) < 0)
100 err_sys("close error"); /* since SO_LINGER may be set */