]>
diplodocus.org Git - nmh/blob - test/fakehttp.c
2 * fakehttp - A fake HTTP server used by the nmh test suite
4 * This code is Copyright (c) 2014, by the authors of nmh. See the
5 * COPYRIGHT file in the root directory of the nmh distribution for
6 * complete copyright information.
11 #include <sys/types.h>
19 #define PIDFN "/tmp/fakehttp.pid"
21 int serve(const char *, const char *);
22 void putcrlf(int, char *);
25 strip_cr(char *buf
, ssize_t
*len
)
28 for (src
= dst
= 0; src
< *len
; src
++) {
30 if (buf
[src
] != '\r') {
38 save_req(int conn
, FILE *req
)
42 int e
; /* used to save errno */
43 int started
= 0; /* whether the request has started coming in */
45 if (fcntl(conn
, F_SETFL
, O_NONBLOCK
) < 0) {
46 fprintf(stderr
, "Unable to make socket non-blocking: %s\n",
52 r
= read(conn
, buf
, sizeof buf
);
54 /* First keep trying until some data is ready; for testing, don't
55 * bother with using select to wait for input. */
58 if (e
== EAGAIN
|| e
== EWOULDBLOCK
) {
59 continue; /* keep waiting */
62 fprintf(stderr
, "Unable to read socket: %s\n", strerror(e
));
65 /* Request is here. Fall through to the fwrite below and keep
71 putc('\n', req
); /* req body usually has no newline */
73 if (e
!= EAGAIN
&& e
!= EWOULDBLOCK
) {
74 fprintf(stderr
, "Unable to read socket: %s\n", strerror(e
));
77 /* For testing, we can get away without understand the HTTP request
78 * and just treating the would-block case as meaning the request is
83 fwrite(buf
, 1, r
, req
);
88 send_res(int conn
, FILE *res
)
92 char *res_line
= NULL
;
94 while ((len
= getline(&res_line
, &size
, res
)) > 0) {
95 res_line
[len
- 1] = '\0';
96 putcrlf(conn
, res_line
);
100 fprintf(stderr
, "read response failed: %s\n", strerror(errno
));
106 main(int argc
, char *argv
[])
113 fprintf(stderr
, "Usage: %s output-filename port response\n",
118 if (!(req
= fopen(argv
[1], "w"))) {
119 fprintf(stderr
, "Unable to open output file \"%s\": %s\n",
120 argv
[1], strerror(errno
));
124 if (!(res
= fopen(argv
[3], "r"))) {
125 fprintf(stderr
, "Unable to open response \"%s\": %s\n",
126 argv
[3], strerror(errno
));
130 conn
= serve(PIDFN
, argv
[2]);