]>
diplodocus.org Git - nmh/blob - test/fakehttp.c
1 /* fakehttp - A fake HTTP server used by the nmh test suite
3 * This code is Copyright (c) 2014, by the authors of nmh. See the
4 * COPYRIGHT file in the root directory of the nmh distribution for
5 * complete copyright information.
10 #include <sys/types.h>
17 #define PIDFN "/tmp/fakehttp.pid"
19 int serve(const char *, const char *);
20 void putcrlf(int, char *);
23 strip_cr(char *buf
, ssize_t
*len
)
26 for (src
= dst
= 0; src
< *len
; src
++) {
28 if (buf
[src
] != '\r') {
36 save_req(int conn
, FILE *req
)
40 int e
; /* used to save errno */
41 int started
= 0; /* whether the request has started coming in */
43 if (fcntl(conn
, F_SETFL
, O_NONBLOCK
) < 0) {
44 fprintf(stderr
, "Unable to make socket non-blocking: %s\n",
50 r
= read(conn
, buf
, sizeof buf
);
52 /* First keep trying until some data is ready; for testing, don't
53 * bother with using select to wait for input. */
56 if (e
== EAGAIN
|| e
== EWOULDBLOCK
) {
57 continue; /* keep waiting */
60 fprintf(stderr
, "Unable to read socket: %s\n", strerror(e
));
63 /* Request is here. Fall through to the fwrite below and keep
69 putc('\n', req
); /* req body usually has no newline */
71 if (e
!= EAGAIN
&& e
!= EWOULDBLOCK
) {
72 fprintf(stderr
, "Unable to read socket: %s\n", strerror(e
));
75 /* For testing, we can get away without understand the HTTP request
76 * and just treating the would-block case as meaning the request is
81 fwrite(buf
, 1, r
, req
);
86 send_res(int conn
, FILE *res
)
90 char *res_line
= NULL
;
92 while ((len
= getline(&res_line
, &size
, res
)) > 0) {
93 res_line
[len
- 1] = '\0';
94 putcrlf(conn
, res_line
);
98 fprintf(stderr
, "read response failed: %s\n", strerror(errno
));
104 main(int argc
, char *argv
[])
111 fprintf(stderr
, "Usage: %s output-filename port response\n",
116 if (!(req
= fopen(argv
[1], "w"))) {
117 fprintf(stderr
, "Unable to open output file \"%s\": %s\n",
118 argv
[1], strerror(errno
));
122 if (!(res
= fopen(argv
[3], "r"))) {
123 fprintf(stderr
, "Unable to open response \"%s\": %s\n",
124 argv
[3], strerror(errno
));
128 conn
= serve(PIDFN
, argv
[2]);