1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
10 * This software is licensed as described in the file COPYING, which
11 * you should have received as part of this distribution. The terms
12 * are also available at https://curl.haxx.se/docs/copyright.html.
14 * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15 * copies of the Software, and permit persons to whom the Software is
16 * furnished to do so, under the terms of the COPYING file.
18 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19 * KIND, either express or implied.
21 ***************************************************************************/
22 #include "server_setup.h"
25 * curl's test suite Real Time Streaming Protocol (RTSP) server.
27 * This source file was started based on curl's HTTP test suite server.
33 #ifdef HAVE_NETINET_IN_H
34 #include <netinet/in.h>
36 #ifdef HAVE_NETINET_IN6_H
37 #include <netinet/in6.h>
39 #ifdef HAVE_ARPA_INET_H
40 #include <arpa/inet.h>
45 #ifdef HAVE_NETINET_TCP_H
46 #include <netinet/tcp.h> /* for TCP_NODELAY */
49 #define ENABLE_CURLX_PRINTF
50 /* make the curlx header define all printf() functions to use the curlx_*
52 #include "curlx.h" /* from the private lib dir */
55 #include "server_sockaddr.h"
57 /* include memdebug.h last */
62 #define EINTR 4 /* errno.h value */
64 #define ERANGE 34 /* errno.h value */
68 static bool use_ipv6 = FALSE;
70 static const char *ipv_inuse = "IPv4";
71 static int serverlogslocked = 0;
73 #define REQBUFSIZ 150000
74 #define REQBUFSIZ_TXT "149999"
76 static long prevtestno = -1; /* previous test number we served */
77 static long prevpartno = -1; /* previous part number we served */
78 static bool prevbounce = FALSE; /* instructs the server to increase the part
79 number for a test in case the identical
80 testno+partno request shows up again */
82 #define RCMD_NORMALREQ 0 /* default request, use the tests file normally */
83 #define RCMD_IDLE 1 /* told to sit idle */
84 #define RCMD_STREAM 2 /* told to stream */
92 #define SET_RTP_PKT_CHN(p,c) ((p)[1] = (unsigned char)((c) & 0xFF))
94 #define SET_RTP_PKT_LEN(p,l) (((p)[2] = (unsigned char)(((l) >> 8) & 0xFF)), \
95 ((p)[3] = (unsigned char)((l) & 0xFF)))
98 char reqbuf[REQBUFSIZ]; /* buffer area for the incoming request */
99 size_t checkindex; /* where to start checking of the request */
100 size_t offset; /* size of the incoming request */
101 long testno; /* test number found in the request */
102 long partno; /* part number found in the request */
103 bool open; /* keep connection open info, as found in the request */
104 bool auth_req; /* authentication required, don't wait for body unless
105 there's an Authorization header */
106 bool auth; /* Authorization header present in the incoming request */
107 size_t cl; /* Content-Length of the incoming request */
108 bool digest; /* Authorization digest header found */
109 bool ntlm; /* Authorization ntlm header found */
110 int pipe; /* if non-zero, expect this many requests to do a "piped"
112 int skip; /* if non-zero, the server is instructed to not read this
113 many bytes from a PUT/POST request. Ie the client sends N
114 bytes said in Content-Length, but the server only reads N
116 int rcmd; /* doing a special command, see defines above */
117 reqprot_t protocol; /* request protocol, HTTP or RTSP */
118 int prot_version; /* HTTP or RTSP version (major*10 + minor) */
119 bool pipelining; /* true if request is pipelined */
121 size_t rtp_buffersize;
124 static int ProcessRequest(struct httprequest *req);
125 static void storerequest(char *reqbuf, size_t totalsize);
127 #define DEFAULT_PORT 8999
129 #ifndef DEFAULT_LOGFILE
130 #define DEFAULT_LOGFILE "log/rtspd.log"
133 const char *serverlogfile = DEFAULT_LOGFILE;
135 #define RTSPDVERSION "curl test suite RTSP server/0.1"
137 #define REQUEST_DUMP "log/server.input"
138 #define RESPONSE_DUMP "log/server.response"
140 /* very-big-path support */
141 #define MAXDOCNAMELEN 140000
142 #define MAXDOCNAMELEN_TXT "139999"
144 #define REQUEST_KEYWORD_SIZE 256
145 #define REQUEST_KEYWORD_SIZE_TXT "255"
147 #define CMD_AUTH_REQUIRED "auth_required"
149 /* 'idle' means that it will accept the request fine but never respond
150 any data. Just keep the connection alive. */
151 #define CMD_IDLE "idle"
153 /* 'stream' means to send a never-ending stream of data */
154 #define CMD_STREAM "stream"
156 #define END_OF_HEADERS "\r\n\r\n"
159 DOCNUMBER_NOTHING = -7,
161 DOCNUMBER_BADCONNECT = -5,
162 DOCNUMBER_INTERNAL = -4,
163 DOCNUMBER_CONNECT = -3,
164 DOCNUMBER_WERULEZ = -2,
169 /* sent as reply to a QUIT */
170 static const char *docquit =
171 "HTTP/1.1 200 Goodbye" END_OF_HEADERS;
173 /* sent as reply to a CONNECT */
174 static const char *docconnect =
175 "HTTP/1.1 200 Mighty fine indeed" END_OF_HEADERS;
177 /* sent as reply to a "bad" CONNECT */
178 static const char *docbadconnect =
179 "HTTP/1.1 501 Forbidden you fool" END_OF_HEADERS;
181 /* send back this on HTTP 404 file not found */
182 static const char *doc404_HTTP = "HTTP/1.1 404 Not Found\r\n"
183 "Server: " RTSPDVERSION "\r\n"
184 "Connection: close\r\n"
185 "Content-Type: text/html"
187 "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n"
189 "<TITLE>404 Not Found</TITLE>\n"
191 "<H1>Not Found</H1>\n"
192 "The requested URL was not found on this server.\n"
193 "<P><HR><ADDRESS>" RTSPDVERSION "</ADDRESS>\n" "</BODY></HTML>\n";
195 /* send back this on RTSP 404 file not found */
196 static const char *doc404_RTSP = "RTSP/1.0 404 Not Found\r\n"
197 "Server: " RTSPDVERSION
200 /* Default size to send away fake RTP data */
201 #define RTP_DATA_SIZE 12
202 static const char *RTP_DATA = "$_1234\n\0asdf";
204 /* do-nothing macro replacement for systems which lack siginterrupt() */
206 #ifndef HAVE_SIGINTERRUPT
207 #define siginterrupt(x,y) do {} while(0)
210 /* vars used to keep around previous signal handlers */
212 typedef RETSIGTYPE (*SIGHANDLER_T)(int);
215 static SIGHANDLER_T old_sighup_handler = SIG_ERR;
219 static SIGHANDLER_T old_sigpipe_handler = SIG_ERR;
223 static SIGHANDLER_T old_sigalrm_handler = SIG_ERR;
227 static SIGHANDLER_T old_sigint_handler = SIG_ERR;
231 static SIGHANDLER_T old_sigterm_handler = SIG_ERR;
234 #if defined(SIGBREAK) && defined(WIN32)
235 static SIGHANDLER_T old_sigbreak_handler = SIG_ERR;
238 /* var which if set indicates that the program should finish execution */
240 SIG_ATOMIC_T got_exit_signal = 0;
242 /* if next is set indicates the first signal handled in exit_signal_handler */
244 static volatile int exit_signal = 0;
246 /* signal handler that will be triggered to indicate that the program
247 should finish its execution in a controlled manner as soon as possible.
248 The first time this is called it will set got_exit_signal to one and
249 store in exit_signal the signal that triggered its execution. */
251 static RETSIGTYPE exit_signal_handler(int signum)
253 int old_errno = errno;
254 if(got_exit_signal == 0) {
256 exit_signal = signum;
258 (void)signal(signum, exit_signal_handler);
262 static void install_signal_handlers(void)
265 /* ignore SIGHUP signal */
266 old_sighup_handler = signal(SIGHUP, SIG_IGN);
267 if(old_sighup_handler == SIG_ERR)
268 logmsg("cannot install SIGHUP handler: %s", strerror(errno));
271 /* ignore SIGPIPE signal */
272 old_sigpipe_handler = signal(SIGPIPE, SIG_IGN);
273 if(old_sigpipe_handler == SIG_ERR)
274 logmsg("cannot install SIGPIPE handler: %s", strerror(errno));
277 /* ignore SIGALRM signal */
278 old_sigalrm_handler = signal(SIGALRM, SIG_IGN);
279 if(old_sigalrm_handler == SIG_ERR)
280 logmsg("cannot install SIGALRM handler: %s", strerror(errno));
283 /* handle SIGINT signal with our exit_signal_handler */
284 old_sigint_handler = signal(SIGINT, exit_signal_handler);
285 if(old_sigint_handler == SIG_ERR)
286 logmsg("cannot install SIGINT handler: %s", strerror(errno));
288 siginterrupt(SIGINT, 1);
291 /* handle SIGTERM signal with our exit_signal_handler */
292 old_sigterm_handler = signal(SIGTERM, exit_signal_handler);
293 if(old_sigterm_handler == SIG_ERR)
294 logmsg("cannot install SIGTERM handler: %s", strerror(errno));
296 siginterrupt(SIGTERM, 1);
298 #if defined(SIGBREAK) && defined(WIN32)
299 /* handle SIGBREAK signal with our exit_signal_handler */
300 old_sigbreak_handler = signal(SIGBREAK, exit_signal_handler);
301 if(old_sigbreak_handler == SIG_ERR)
302 logmsg("cannot install SIGBREAK handler: %s", strerror(errno));
304 siginterrupt(SIGBREAK, 1);
308 static void restore_signal_handlers(void)
311 if(SIG_ERR != old_sighup_handler)
312 (void)signal(SIGHUP, old_sighup_handler);
315 if(SIG_ERR != old_sigpipe_handler)
316 (void)signal(SIGPIPE, old_sigpipe_handler);
319 if(SIG_ERR != old_sigalrm_handler)
320 (void)signal(SIGALRM, old_sigalrm_handler);
323 if(SIG_ERR != old_sigint_handler)
324 (void)signal(SIGINT, old_sigint_handler);
327 if(SIG_ERR != old_sigterm_handler)
328 (void)signal(SIGTERM, old_sigterm_handler);
330 #if defined(SIGBREAK) && defined(WIN32)
331 if(SIG_ERR != old_sigbreak_handler)
332 (void)signal(SIGBREAK, old_sigbreak_handler);
336 static int ProcessRequest(struct httprequest *req)
338 char *line = &req->reqbuf[req->checkindex];
339 bool chunked = FALSE;
340 static char request[REQUEST_KEYWORD_SIZE];
341 static char doc[MAXDOCNAMELEN];
342 static char prot_str[5];
344 int prot_major, prot_minor;
347 end = strstr(line, END_OF_HEADERS);
349 logmsg("ProcessRequest() called with testno %ld and line [%s]",
352 /* try to figure out the request characteristics as soon as possible, but
354 if((req->testno == DOCNUMBER_NOTHING) &&
356 "%" REQUEST_KEYWORD_SIZE_TXT"s %" MAXDOCNAMELEN_TXT "s %4s/%d.%d",
364 if(!strcmp(prot_str, "HTTP")) {
365 req->protocol = RPROT_HTTP;
367 else if(!strcmp(prot_str, "RTSP")) {
368 req->protocol = RPROT_RTSP;
371 req->protocol = RPROT_NONE;
372 logmsg("got unknown protocol %s", prot_str);
376 req->prot_version = prot_major*10 + prot_minor;
378 /* find the last slash */
379 ptr = strrchr(doc, '/');
381 /* get the number after it */
386 if((strlen(doc) + strlen(request)) < 200)
387 snprintf(logbuf, sizeof(logbuf), "Got request: %s %s %s/%d.%d",
388 request, doc, prot_str, prot_major, prot_minor);
390 snprintf(logbuf, sizeof(logbuf), "Got a *HUGE* request %s/%d.%d",
391 prot_str, prot_major, prot_minor);
392 logmsg("%s", logbuf);
394 if(!strncmp("/verifiedserver", ptr, 15)) {
395 logmsg("Are-we-friendly question received");
396 req->testno = DOCNUMBER_WERULEZ;
400 if(!strncmp("/quit", ptr, 5)) {
401 logmsg("Request-to-quit received");
402 req->testno = DOCNUMBER_QUIT;
406 ptr++; /* skip the slash */
408 /* skip all non-numericals following the slash */
409 while(*ptr && !ISDIGIT(*ptr))
412 req->testno = strtol(ptr, &ptr, 10);
414 if(req->testno > 10000) {
415 req->partno = req->testno % 10000;
416 req->testno /= 10000;
421 snprintf(logbuf, sizeof(logbuf), "Requested test number %ld part %ld",
422 req->testno, req->partno);
423 logmsg("%s", logbuf);
425 filename = test2file(req->testno);
427 stream = fopen(filename, "rb");
430 logmsg("fopen() failed with error: %d %s", error, strerror(error));
431 logmsg("Error opening file: %s", filename);
432 logmsg("Couldn't open test file %ld", req->testno);
433 req->open = FALSE; /* closes connection */
445 char *rtp_scratch = NULL;
447 /* get the custom server control "commands" */
448 error = getpart(&cmd, &cmdsize, "reply", "servercmd", stream);
451 logmsg("getpart() failed with error: %d", error);
452 req->open = FALSE; /* closes connection */
458 logmsg("Found a reply-servercmd section!");
460 if(!strncmp(CMD_AUTH_REQUIRED, ptr, strlen(CMD_AUTH_REQUIRED))) {
461 logmsg("instructed to require authorization header");
462 req->auth_req = TRUE;
464 else if(!strncmp(CMD_IDLE, ptr, strlen(CMD_IDLE))) {
465 logmsg("instructed to idle");
466 req->rcmd = RCMD_IDLE;
469 else if(!strncmp(CMD_STREAM, ptr, strlen(CMD_STREAM))) {
470 logmsg("instructed to stream");
471 req->rcmd = RCMD_STREAM;
473 else if(1 == sscanf(ptr, "pipe: %d", &num)) {
474 logmsg("instructed to allow a pipe size of %d", num);
476 logmsg("negative pipe size ignored");
478 req->pipe = num-1; /* decrease by one since we don't count the
479 first request in this number */
481 else if(1 == sscanf(ptr, "skip: %d", &num)) {
482 logmsg("instructed to skip this number of bytes %d", num);
485 else if(3 == sscanf(ptr, "rtp: part %d channel %d size %d",
486 &rtp_partno, &rtp_channel, &rtp_size)) {
488 if(rtp_partno == req->partno) {
489 logmsg("RTP: part %d channel %d size %d",
490 rtp_partno, rtp_channel, rtp_size);
492 /* Make our scratch buffer enough to fit all the
493 * desired data and one for padding */
494 rtp_scratch = malloc(rtp_size + 4 + RTP_DATA_SIZE);
496 /* RTP is signalled with a $ */
497 rtp_scratch[0] = '$';
499 /* The channel follows and is one byte */
500 SET_RTP_PKT_CHN(rtp_scratch, rtp_channel);
502 /* Length follows and is a two byte short in network order */
503 SET_RTP_PKT_LEN(rtp_scratch, rtp_size);
505 /* Fill it with junk data */
506 for(i = 0; i < rtp_size; i += RTP_DATA_SIZE) {
507 memcpy(rtp_scratch + 4 + i, RTP_DATA, RTP_DATA_SIZE);
510 if(req->rtp_buffer == NULL) {
511 req->rtp_buffer = rtp_scratch;
512 req->rtp_buffersize = rtp_size + 4;
515 req->rtp_buffer = realloc(req->rtp_buffer,
516 req->rtp_buffersize +
518 memcpy(req->rtp_buffer + req->rtp_buffersize, rtp_scratch,
520 req->rtp_buffersize += rtp_size + 4;
523 logmsg("rtp_buffersize is %zu, rtp_size is %d.",
524 req->rtp_buffersize, rtp_size);
528 logmsg("funny instruction found: %s", ptr);
531 ptr = strchr(ptr, '\n');
536 } while(ptr && *ptr);
537 logmsg("Done parsing server commands");
543 if(sscanf(req->reqbuf, "CONNECT %" MAXDOCNAMELEN_TXT "s HTTP/%d.%d",
544 doc, &prot_major, &prot_minor) == 3) {
545 snprintf(logbuf, sizeof(logbuf),
546 "Received a CONNECT %s HTTP/%d.%d request",
547 doc, prot_major, prot_minor);
548 logmsg("%s", logbuf);
550 if(req->prot_version == 10)
551 req->open = FALSE; /* HTTP 1.0 closes connection by default */
553 if(!strncmp(doc, "bad", 3))
554 /* if the host name starts with bad, we fake an error here */
555 req->testno = DOCNUMBER_BADCONNECT;
556 else if(!strncmp(doc, "test", 4)) {
557 /* if the host name starts with test, the port number used in the
558 CONNECT line will be used as test number! */
559 char *portp = strchr(doc, ':');
560 if(portp && (*(portp + 1) != '\0') && ISDIGIT(*(portp + 1)))
561 req->testno = strtol(portp + 1, NULL, 10);
563 req->testno = DOCNUMBER_CONNECT;
566 req->testno = DOCNUMBER_CONNECT;
569 logmsg("Did not find test number in PATH");
570 req->testno = DOCNUMBER_404;
576 /* we don't have a complete request yet! */
577 logmsg("ProcessRequest returned without a complete request");
578 return 0; /* not complete yet */
580 logmsg("ProcessRequest found a complete request");
583 /* we do have a full set, advance the checkindex to after the end of the
584 headers, for the pipelining case mostly */
585 req->checkindex += (end - line) + strlen(END_OF_HEADERS);
587 /* **** Persistence ****
589 * If the request is a HTTP/1.0 one, we close the connection unconditionally
592 * If the request is a HTTP/1.1 one, we MUST check for a "Connection:"
593 * header that might say "close". If it does, we close a connection when
594 * this request is processed. Otherwise, we keep the connection alive for X
602 if((req->cl == 0) && strncasecompare("Content-Length:", line, 15)) {
603 /* If we don't ignore content-length, we read it and we read the whole
604 request including the body before we return. If we've been told to
605 ignore the content-length, we will return as soon as all headers
606 have been received */
608 char *ptr = line + 15;
609 unsigned long clen = 0;
610 while(*ptr && ISSPACE(*ptr))
614 clen = strtoul(ptr, &endptr, 10);
615 if((ptr == endptr) || !ISSPACE(*endptr) || (ERANGE == errno)) {
616 /* this assumes that a zero Content-Length is valid */
617 logmsg("Found invalid Content-Length: (%s) in the request", ptr);
618 req->open = FALSE; /* closes connection */
621 req->cl = clen - req->skip;
623 logmsg("Found Content-Length: %lu in the request", clen);
625 logmsg("... but will abort after %zu bytes", req->cl);
628 else if(strncasecompare("Transfer-Encoding: chunked", line,
629 strlen("Transfer-Encoding: chunked"))) {
630 /* chunked data coming in */
635 if(strstr(req->reqbuf, "\r\n0\r\n\r\n"))
636 /* end of chunks reached */
639 return 0; /* not done */
642 line = strchr(line, '\n');
648 if(!req->auth && strstr(req->reqbuf, "Authorization:")) {
649 req->auth = TRUE; /* Authorization: header present! */
651 logmsg("Authorization header found, as required");
654 if(!req->digest && strstr(req->reqbuf, "Authorization: Digest")) {
655 /* If the client is passing this Digest-header, we set the part number
656 to 1000. Not only to spice up the complexity of this, but to make
657 Digest stuff to work in the test suite. */
659 req->digest = TRUE; /* header found */
660 logmsg("Received Digest request, sending back data %ld", req->partno);
662 else if(!req->ntlm &&
663 strstr(req->reqbuf, "Authorization: NTLM TlRMTVNTUAAD")) {
664 /* If the client is passing this type-3 NTLM header */
666 req->ntlm = TRUE; /* NTLM found */
667 logmsg("Received NTLM type-3, sending back data %ld", req->partno);
669 logmsg(" Expecting %zu POSTed bytes", req->cl);
672 else if(!req->ntlm &&
673 strstr(req->reqbuf, "Authorization: NTLM TlRMTVNTUAAB")) {
674 /* If the client is passing this type-1 NTLM header */
676 req->ntlm = TRUE; /* NTLM found */
677 logmsg("Received NTLM type-1, sending back data %ld", req->partno);
679 else if((req->partno >= 1000) &&
680 strstr(req->reqbuf, "Authorization: Basic")) {
681 /* If the client is passing this Basic-header and the part number is
682 already >=1000, we add 1 to the part number. This allows simple Basic
683 authentication negotiation to work in the test suite. */
685 logmsg("Received Basic request, sending back data %ld", req->partno);
687 if(strstr(req->reqbuf, "Connection: close"))
688 req->open = FALSE; /* close connection after this request */
692 req->prot_version >= 11 &&
694 req->reqbuf + req->offset > end + strlen(END_OF_HEADERS) &&
695 (!strncmp(req->reqbuf, "GET", strlen("GET")) ||
696 !strncmp(req->reqbuf, "HEAD", strlen("HEAD")))) {
697 /* If we have a persistent connection, HTTP version >= 1.1
698 and GET/HEAD request, enable pipelining. */
699 req->checkindex = (end - req->reqbuf) + strlen(END_OF_HEADERS);
700 req->pipelining = TRUE;
706 /* scan for more header ends within this chunk */
707 line = &req->reqbuf[req->checkindex];
708 end = strstr(line, END_OF_HEADERS);
711 req->checkindex += (end - line) + strlen(END_OF_HEADERS);
715 /* If authentication is required and no auth was provided, end now. This
716 makes the server NOT wait for PUT/POST data and you can then make the
717 test case send a rejection before any such data has been sent. Test case
719 if(req->auth_req && !req->auth)
723 if(req->cl <= req->offset - (end - req->reqbuf) - strlen(END_OF_HEADERS))
726 return 0; /* not complete yet */
732 /* store the entire request in a file */
733 static void storerequest(char *reqbuf, size_t totalsize)
747 dump = fopen(REQUEST_DUMP, "ab");
748 } while((dump == NULL) && ((error = errno) == EINTR));
750 logmsg("Error opening file %s error: %d %s",
751 REQUEST_DUMP, error, strerror(error));
752 logmsg("Failed to write request input to " REQUEST_DUMP);
756 writeleft = totalsize;
758 written = fwrite(&reqbuf[totalsize-writeleft],
761 goto storerequest_cleanup;
763 writeleft -= written;
764 } while((writeleft > 0) && ((error = errno) == EINTR));
767 logmsg("Wrote request (%zu bytes) input to " REQUEST_DUMP, totalsize);
768 else if(writeleft > 0) {
769 logmsg("Error writing file %s error: %d %s",
770 REQUEST_DUMP, error, strerror(error));
771 logmsg("Wrote only (%zu bytes) of (%zu bytes) request input to %s",
772 totalsize-writeleft, totalsize, REQUEST_DUMP);
775 storerequest_cleanup:
779 } while(res && ((error = errno) == EINTR));
781 logmsg("Error closing file %s error: %d %s",
782 REQUEST_DUMP, error, strerror(error));
785 /* return 0 on success, non-zero on failure */
786 static int get_request(curl_socket_t sock, struct httprequest *req)
790 int done_processing = 0;
791 char *reqbuf = req->reqbuf;
794 char *pipereq = NULL;
795 size_t pipereq_length = 0;
797 if(req->pipelining) {
798 pipereq = reqbuf + req->checkindex;
799 pipereq_length = req->offset - req->checkindex;
802 /*** Init the httprequest structure properly for the upcoming request ***/
806 req->testno = DOCNUMBER_NOTHING;
809 req->auth_req = FALSE;
816 req->rcmd = RCMD_NORMALREQ;
817 req->protocol = RPROT_NONE;
818 req->prot_version = 0;
819 req->pipelining = FALSE;
820 req->rtp_buffer = NULL;
821 req->rtp_buffersize = 0;
823 /*** end of httprequest init ***/
825 while(!done_processing && (req->offset < REQBUFSIZ-1)) {
826 if(pipereq_length && pipereq) {
827 memmove(reqbuf, pipereq, pipereq_length);
828 got = curlx_uztosz(pipereq_length);
833 /* we are instructed to not read the entire thing, so we make sure to
834 only read what we're supposed to and NOT read the enire thing the
835 client wants to send! */
836 got = sread(sock, reqbuf + req->offset, req->cl);
838 got = sread(sock, reqbuf + req->offset, REQBUFSIZ-1 - req->offset);
843 logmsg("Connection closed by client");
848 logmsg("recv() returned error: (%d) %s", error, strerror(error));
852 /* dump the request received so far to the external file */
853 reqbuf[req->offset] = '\0';
854 storerequest(reqbuf, req->offset);
858 logmsg("Read %zd bytes", got);
860 req->offset += (size_t)got;
861 reqbuf[req->offset] = '\0';
863 done_processing = ProcessRequest(req);
866 if(done_processing && req->pipe) {
867 logmsg("Waiting for another piped request");
873 if((req->offset == REQBUFSIZ-1) && (got > 0)) {
874 logmsg("Request would overflow buffer, closing connection");
875 /* dump request received so far to external file anyway */
876 reqbuf[REQBUFSIZ-1] = '\0';
879 else if(req->offset > REQBUFSIZ-1) {
880 logmsg("Request buffer overflow, closing connection");
881 /* dump request received so far to external file anyway */
882 reqbuf[REQBUFSIZ-1] = '\0';
886 reqbuf[req->offset] = '\0';
888 /* dump the request to an external file */
889 storerequest(reqbuf, req->pipelining ? req->checkindex : req->offset);
893 return fail; /* return 0 on success */
896 /* returns -1 on failure */
897 static int send_doc(curl_socket_t sock, struct httprequest *req)
907 bool persistant = TRUE;
908 bool sendfailure = FALSE;
913 static char weare[256];
915 char partbuf[80]="data";
917 logmsg("Send response number %ld part %ld", req->testno, req->partno);
922 break; /* continue with business as usual */
924 #define STREAMTHIS "a string to stream 01234567890\n"
925 count = strlen(STREAMTHIS);
927 written = swrite(sock, STREAMTHIS, count);
930 if(written != (ssize_t)count) {
931 logmsg("Stopped streaming");
937 /* Do nothing. Sit idle. Pretend it rains. */
943 if(req->testno < 0) {
947 switch(req->testno) {
949 logmsg("Replying to QUIT");
952 case DOCNUMBER_WERULEZ:
953 /* we got a "friends?" question, reply back that we sure are */
954 logmsg("Identifying ourselves as friends");
955 snprintf(msgbuf, sizeof(msgbuf), "RTSP_SERVER WE ROOLZ: %ld\r\n",
957 msglen = strlen(msgbuf);
958 snprintf(weare, sizeof(weare),
959 "HTTP/1.1 200 OK\r\nContent-Length: %zu\r\n\r\n%s",
963 case DOCNUMBER_INTERNAL:
964 logmsg("Bailing out due to internal error");
966 case DOCNUMBER_CONNECT:
967 logmsg("Replying to CONNECT");
970 case DOCNUMBER_BADCONNECT:
971 logmsg("Replying to a bad CONNECT");
972 buffer = docbadconnect;
976 logmsg("Replying to with a 404");
977 if(req->protocol == RPROT_HTTP) {
978 buffer = doc404_HTTP;
981 buffer = doc404_RTSP;
986 count = strlen(buffer);
989 char *filename = test2file(req->testno);
992 snprintf(partbuf, sizeof(partbuf), "data%ld", req->partno);
994 stream = fopen(filename, "rb");
997 logmsg("fopen() failed with error: %d %s", error, strerror(error));
998 logmsg("Error opening file: %s", filename);
999 logmsg("Couldn't open test file");
1003 error = getpart(&ptr, &count, "reply", partbuf, stream);
1006 logmsg("getpart() failed with error: %d", error);
1012 if(got_exit_signal) {
1017 /* re-open the same file again */
1018 stream = fopen(filename, "rb");
1021 logmsg("fopen() failed with error: %d %s", error, strerror(error));
1022 logmsg("Error opening file: %s", filename);
1023 logmsg("Couldn't open test file");
1028 /* get the custom server control "commands" */
1029 error = getpart(&cmd, &cmdsize, "reply", "postcmd", stream);
1032 logmsg("getpart() failed with error: %d", error);
1039 if(got_exit_signal) {
1045 /* If the word 'swsclose' is present anywhere in the reply chunk, the
1046 connection will be closed after the data has been sent to the requesting
1048 if(strstr(buffer, "swsclose") || !count) {
1050 logmsg("connection close instruction \"swsclose\" found in response");
1052 if(strstr(buffer, "swsbounce")) {
1054 logmsg("enable \"swsbounce\" in the next request");
1059 dump = fopen(RESPONSE_DUMP, "ab");
1062 logmsg("fopen() failed with error: %d %s", error, strerror(error));
1063 logmsg("Error opening file: %s", RESPONSE_DUMP);
1064 logmsg("couldn't create logfile: " RESPONSE_DUMP);
1070 responsesize = count;
1072 /* Ok, we send no more than 200 bytes at a time, just to make sure that
1073 larger chunks are split up so that the client will need to do multiple
1074 recv() calls to get it and thus we exercise that code better */
1078 written = swrite(sock, buffer, num);
1084 logmsg("Sent off %zd bytes", written);
1086 /* write to file as well */
1087 fwrite(buffer, 1, (size_t)written, dump);
1095 /* Send out any RTP data */
1096 if(req->rtp_buffer) {
1097 logmsg("About to write %zu RTP bytes", req->rtp_buffersize);
1098 count = req->rtp_buffersize;
1103 written = swrite(sock, req->rtp_buffer + (req->rtp_buffersize - count),
1112 free(req->rtp_buffer);
1113 req->rtp_buffersize = 0;
1118 } while(res && ((error = errno) == EINTR));
1120 logmsg("Error closing file %s error: %d %s",
1121 RESPONSE_DUMP, error, strerror(error));
1123 if(got_exit_signal) {
1130 logmsg("Sending response failed. Only (%zu bytes) of "
1131 "(%zu bytes) were sent",
1132 responsesize-count, responsesize);
1138 logmsg("Response sent (%zu bytes) and written to " RESPONSE_DUMP,
1148 if(2 == sscanf(ptr, "%31s %d", command, &num)) {
1149 if(!strcmp("wait", command)) {
1150 logmsg("Told to sleep for %d seconds", num);
1152 while(quarters > 0) {
1158 /* should not happen */
1160 logmsg("wait_ms() failed with error: (%d) %s",
1161 error, strerror(error));
1166 logmsg("Continuing after sleeping %d seconds", num);
1169 logmsg("Unknown command in reply command section");
1171 ptr = strchr(ptr, '\n');
1176 } while(ptr && *ptr);
1179 req->open = persistant;
1181 prevtestno = req->testno;
1182 prevpartno = req->partno;
1188 int main(int argc, char *argv[])
1190 srvr_sockaddr_union_t me;
1191 curl_socket_t sock = CURL_SOCKET_BAD;
1192 curl_socket_t msgsock = CURL_SOCKET_BAD;
1193 int wrotepidfile = 0;
1195 unsigned short port = DEFAULT_PORT;
1196 const char *pidname = ".rtsp.pid";
1197 struct httprequest req;
1203 memset(&req, 0, sizeof(req));
1206 if(!strcmp("--version", argv[arg])) {
1207 printf("rtspd IPv4%s"
1218 else if(!strcmp("--pidfile", argv[arg])) {
1221 pidname = argv[arg++];
1223 else if(!strcmp("--logfile", argv[arg])) {
1226 serverlogfile = argv[arg++];
1228 else if(!strcmp("--ipv4", argv[arg])) {
1235 else if(!strcmp("--ipv6", argv[arg])) {
1242 else if(!strcmp("--port", argv[arg])) {
1246 unsigned long ulnum = strtoul(argv[arg], &endptr, 10);
1247 if((endptr != argv[arg] + strlen(argv[arg])) ||
1248 (ulnum < 1025UL) || (ulnum > 65535UL)) {
1249 fprintf(stderr, "rtspd: invalid --port argument (%s)\n",
1253 port = curlx_ultous(ulnum);
1257 else if(!strcmp("--srcdir", argv[arg])) {
1265 puts("Usage: rtspd [option]\n"
1267 " --logfile [file]\n"
1268 " --pidfile [file]\n"
1272 " --srcdir [path]");
1279 atexit(win32_cleanup);
1282 install_signal_handlers();
1284 pid = (long)getpid();
1289 sock = socket(AF_INET, SOCK_STREAM, 0);
1292 sock = socket(AF_INET6, SOCK_STREAM, 0);
1295 if(CURL_SOCKET_BAD == sock) {
1297 logmsg("Error creating socket: (%d) %s",
1298 error, strerror(error));
1299 goto server_cleanup;
1303 if(0 != setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
1304 (void *)&flag, sizeof(flag))) {
1306 logmsg("setsockopt(SO_REUSEADDR) failed with error: (%d) %s",
1307 error, strerror(error));
1308 goto server_cleanup;
1314 memset(&me.sa4, 0, sizeof(me.sa4));
1315 me.sa4.sin_family = AF_INET;
1316 me.sa4.sin_addr.s_addr = INADDR_ANY;
1317 me.sa4.sin_port = htons(port);
1318 rc = bind(sock, &me.sa, sizeof(me.sa4));
1322 memset(&me.sa6, 0, sizeof(me.sa6));
1323 me.sa6.sin6_family = AF_INET6;
1324 me.sa6.sin6_addr = in6addr_any;
1325 me.sa6.sin6_port = htons(port);
1326 rc = bind(sock, &me.sa, sizeof(me.sa6));
1328 #endif /* ENABLE_IPV6 */
1331 logmsg("Error binding socket on port %hu: (%d) %s",
1332 port, error, strerror(error));
1333 goto server_cleanup;
1336 logmsg("Running %s version on port %d", ipv_inuse, (int)port);
1338 /* start accepting connections */
1339 rc = listen(sock, 5);
1342 logmsg("listen() failed with error: (%d) %s",
1343 error, strerror(error));
1344 goto server_cleanup;
1348 ** As soon as this server writes its pid file the test harness will
1349 ** attempt to connect to this server and initiate its verification.
1352 wrotepidfile = write_pidfile(pidname);
1354 goto server_cleanup;
1357 msgsock = accept(sock, NULL, NULL);
1361 if(CURL_SOCKET_BAD == msgsock) {
1363 logmsg("MAJOR ERROR: accept() failed with error: (%d) %s",
1364 error, strerror(error));
1369 ** As soon as this server acepts a connection from the test harness it
1370 ** must set the server logs advisor read lock to indicate that server
1371 ** logs should not be read until this lock is removed by this server.
1374 set_advisor_read_lock(SERVERLOGS_LOCK);
1375 serverlogslocked = 1;
1377 logmsg("====> Client connect");
1381 * Disable the Nagle algorithm to make it easier to send out a large
1382 * response in many small segments to torture the clients more.
1385 if(setsockopt(msgsock, IPPROTO_TCP, TCP_NODELAY,
1386 (void *)&flag, sizeof(flag)) == -1) {
1387 logmsg("====> TCP_NODELAY failed");
1391 /* initialization of httprequest struct is done in get_request(), but due
1392 to pipelining treatment the pipelining struct field must be initialized
1393 previously to FALSE every time a new connection arrives. */
1395 req.pipelining = FALSE;
1401 if(get_request(msgsock, &req))
1402 /* non-zero means error, break out of loop */
1406 /* bounce treatment requested */
1407 if((req.testno == prevtestno) &&
1408 (req.partno == prevpartno)) {
1410 logmsg("BOUNCE part number to %ld", req.partno);
1419 send_doc(msgsock, &req);
1423 if((req.testno < 0) && (req.testno != DOCNUMBER_CONNECT)) {
1424 logmsg("special request received, no persistency");
1428 logmsg("instructed to close connection after server-reply");
1433 logmsg("=> persistant connection request ended, awaits new request");
1434 /* if we got a CONNECT, loop and get another request as well! */
1435 } while(req.open || (req.testno == DOCNUMBER_CONNECT));
1440 logmsg("====> Client disconnect");
1442 msgsock = CURL_SOCKET_BAD;
1444 if(serverlogslocked) {
1445 serverlogslocked = 0;
1446 clear_advisor_read_lock(SERVERLOGS_LOCK);
1449 if(req.testno == DOCNUMBER_QUIT)
1455 if((msgsock != sock) && (msgsock != CURL_SOCKET_BAD))
1458 if(sock != CURL_SOCKET_BAD)
1462 logmsg("signalled to die");
1467 if(serverlogslocked) {
1468 serverlogslocked = 0;
1469 clear_advisor_read_lock(SERVERLOGS_LOCK);
1472 restore_signal_handlers();
1474 if(got_exit_signal) {
1475 logmsg("========> %s rtspd (port: %d pid: %ld) exits with signal (%d)",
1476 ipv_inuse, (int)port, pid, exit_signal);
1478 * To properly set the return status of the process we
1479 * must raise the same signal SIGINT or SIGTERM that we
1480 * caught and let the old handler take care of it.
1485 logmsg("========> rtspd quits");