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.
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
;
22 sleep_us(pauseinit
*1000); /* intended for server */
27 maxfdp1
= sockfd
+ 1; /* check descriptors [0..sockfd] */
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) {
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 */
55 ntowrite
= crlf_add(wbuf
, writelen
, rbuf
, nread
);
56 if (dowrite(sockfd
, wbuf
, ntowrite
) != ntowrite
)
57 err_sys("write error");
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 */
69 if ( (nread
= recv(sockfd
, rbuf
, readlen
, flags
)) < 0)
70 err_sys("recv error");
71 else if (nread
== 0) {
73 fprintf(stderr
, "connection closed by peer\n");
74 break; /* EOF, terminate */
78 ntowrite
= crlf_strip(wbuf
, writelen
, rbuf
, nread
);
79 if (writen(STDOUT_FILENO
, wbuf
, ntowrite
) != ntowrite
)
80 err_sys("writen error to stdout");
82 if (writen(STDOUT_FILENO
, rbuf
, nread
) != nread
)
83 err_sys("writen error to stdout");
87 flags
= 0; /* no infinite loop */
88 goto oncemore
; /* read the message again */
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 */