2 * httpd.c - a simple HTTP server
6 * Copyright (C) 2002 RealVNC Ltd.
7 * Copyright (C) 1999 AT&T Laboratories Cambridge. All Rights Reserved.
9 * This is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This software is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License
20 * along with this software; if not, write to the Free Software
21 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
28 #ifdef LIBVNCSERVER_HAVE_UNISTD_H
31 #ifdef LIBVNCSERVER_HAVE_SYS_TYPES_H
32 #include <sys/types.h>
34 #ifdef LIBVNCSERVER_HAVE_FCNTL_H
41 #define close closesocket
43 #ifdef LIBVNCSERVER_HAVE_SYS_TIME_H
46 #ifdef LIBVNCSERVER_HAVE_SYS_SOCKET_H
47 #include <sys/socket.h>
49 #ifdef LIBVNCSERVER_HAVE_NETINET_IN_H
50 #include <netinet/in.h>
51 #include <netinet/tcp.h>
53 #include <arpa/inet.h>
62 #define connection_close
63 #ifndef connection_close
65 #define NOT_FOUND_STR "HTTP/1.0 404 Not found\r\n\r\n" \
66 "<HEAD><TITLE>File Not Found</TITLE></HEAD>\n" \
67 "<BODY><H1>File Not Found</H1></BODY>\n"
69 #define INVALID_REQUEST_STR "HTTP/1.0 400 Invalid Request\r\n\r\n" \
70 "<HEAD><TITLE>Invalid Request</TITLE></HEAD>\n" \
71 "<BODY><H1>Invalid request</H1></BODY>\n"
73 #define OK_STR "HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n\r\n"
77 #define NOT_FOUND_STR "HTTP/1.0 404 Not found\r\nConnection: close\r\n\r\n" \
78 "<HEAD><TITLE>File Not Found</TITLE></HEAD>\n" \
79 "<BODY><H1>File Not Found</H1></BODY>\n"
81 #define INVALID_REQUEST_STR "HTTP/1.0 400 Invalid Request\r\nConnection: close\r\n\r\n" \
82 "<HEAD><TITLE>Invalid Request</TITLE></HEAD>\n" \
83 "<BODY><H1>Invalid request</H1></BODY>\n"
85 #define OK_STR "HTTP/1.0 200 OK\r\nConnection: close\r\nContent-Type: text/html\r\n\r\n"
89 static void httpProcessInput(rfbScreenInfoPtr screen);
90 static rfbBool compareAndSkip(char **ptr, const char *str);
91 static rfbBool parseParams(const char *request, char *result, int max_bytes);
92 static rfbBool validateString(char *str);
94 #define BUF_SIZE 32768
96 static char buf[BUF_SIZE];
97 static size_t buf_filled=0;
100 * httpInitSockets sets up the TCP socket to listen for HTTP connections.
104 rfbHttpInitSockets(rfbScreenInfoPtr rfbScreen)
106 if (rfbScreen->httpInitDone)
109 rfbScreen->httpInitDone = TRUE;
111 if (!rfbScreen->httpDir)
114 if (rfbScreen->httpPort == 0) {
115 rfbScreen->httpPort = rfbScreen->port-100;
118 rfbLog("Listening for HTTP connections on TCP port %d\n", rfbScreen->httpPort);
120 rfbLog(" URL http://%s:%d\n",rfbScreen->thisHost,rfbScreen->httpPort);
122 if ((rfbScreen->httpListenSock =
123 rfbListenOnTCPPort(rfbScreen->httpPort, rfbScreen->listenInterface)) < 0) {
124 rfbLogPerror("ListenOnTCPPort");
128 /*AddEnabledDevice(httpListenSock);*/
131 void rfbHttpShutdownSockets(rfbScreenInfoPtr rfbScreen) {
132 if(rfbScreen->httpSock>-1) {
133 close(rfbScreen->httpSock);
134 FD_CLR(rfbScreen->httpSock,&rfbScreen->allFds);
135 rfbScreen->httpSock=-1;
140 * httpCheckFds is called from ProcessInputEvents to check for input on the
141 * HTTP socket(s). If there is input to process, httpProcessInput is called.
145 rfbHttpCheckFds(rfbScreenInfoPtr rfbScreen)
150 struct sockaddr_in addr;
151 socklen_t addrlen = sizeof(addr);
153 if (!rfbScreen->httpDir)
156 if (rfbScreen->httpListenSock < 0)
160 FD_SET(rfbScreen->httpListenSock, &fds);
161 if (rfbScreen->httpSock >= 0) {
162 FD_SET(rfbScreen->httpSock, &fds);
166 nfds = select(max(rfbScreen->httpSock,rfbScreen->httpListenSock) + 1, &fds, NULL, NULL, &tv);
172 errno = WSAGetLastError();
175 rfbLogPerror("httpCheckFds: select");
179 if ((rfbScreen->httpSock >= 0) && FD_ISSET(rfbScreen->httpSock, &fds)) {
180 httpProcessInput(rfbScreen);
183 if (FD_ISSET(rfbScreen->httpListenSock, &fds)) {
185 if (rfbScreen->httpSock >= 0) close(rfbScreen->httpSock);
187 if ((rfbScreen->httpSock = accept(rfbScreen->httpListenSock,
188 (struct sockaddr *)&addr, &addrlen)) < 0) {
189 rfbLogPerror("httpCheckFds: accept");
193 rfbErr("O_NONBLOCK on MinGW32 NOT IMPLEMENTED");
196 if(!hosts_ctl("vnc",STRING_UNKNOWN,inet_ntoa(addr.sin_addr),
198 rfbLog("Rejected HTTP connection from client %s\n",
199 inet_ntoa(addr.sin_addr));
201 flags = fcntl(rfbScreen->httpSock, F_GETFL);
203 if (flags < 0 || fcntl(rfbScreen->httpSock, F_SETFL, flags | O_NONBLOCK) == -1) {
204 rfbLogPerror("httpCheckFds: fcntl");
206 close(rfbScreen->httpSock);
207 rfbScreen->httpSock = -1;
211 flags=fcntl(rfbScreen->httpSock,F_GETFL);
213 fcntl(rfbScreen->httpSock,F_SETFL,flags|O_NONBLOCK)==-1) {
214 rfbLogPerror("httpCheckFds: fcntl");
215 close(rfbScreen->httpSock);
216 rfbScreen->httpSock=-1;
221 /*AddEnabledDevice(httpSock);*/
227 httpCloseSock(rfbScreenInfoPtr rfbScreen)
229 close(rfbScreen->httpSock);
230 rfbScreen->httpSock = -1;
234 static rfbClientRec cl;
237 * httpProcessInput is called when input is received on the HTTP socket.
241 httpProcessInput(rfbScreenInfoPtr rfbScreen)
243 struct sockaddr_in addr;
244 socklen_t addrlen = sizeof(addr);
249 unsigned int maxFnameLen;
251 rfbBool performSubstitutions = FALSE;
254 char* user=getenv("USER");
257 cl.sock=rfbScreen->httpSock;
259 if (strlen(rfbScreen->httpDir) > 255) {
260 rfbErr("-httpd directory too long\n");
261 httpCloseSock(rfbScreen);
264 strcpy(fullFname, rfbScreen->httpDir);
265 fname = &fullFname[strlen(fullFname)];
266 maxFnameLen = 511 - strlen(fullFname);
270 /* Read data from the HTTP client until we get a complete request. */
274 if (buf_filled > sizeof (buf)) {
275 rfbErr("httpProcessInput: HTTP request is too long\n");
276 httpCloseSock(rfbScreen);
280 got = read (rfbScreen->httpSock, buf + buf_filled,
281 sizeof (buf) - buf_filled - 1);
285 rfbErr("httpd: premature connection close\n");
287 if (errno == EAGAIN) {
290 rfbLogPerror("httpProcessInput: read");
292 httpCloseSock(rfbScreen);
297 buf[buf_filled] = '\0';
299 /* Is it complete yet (is there a blank line)? */
300 if (strstr (buf, "\r\r") || strstr (buf, "\n\n") ||
301 strstr (buf, "\r\n\r\n") || strstr (buf, "\n\r\n\r"))
306 /* Process the request. */
307 if(rfbScreen->httpEnableProxyConnect) {
308 const static char* PROXY_OK_STR = "HTTP/1.0 200 OK\r\nContent-Type: octet-stream\r\nPragma: no-cache\r\n\r\n";
309 if(!strncmp(buf, "CONNECT ", 8)) {
310 if(atoi(strchr(buf, ':')+1)!=rfbScreen->port) {
311 rfbErr("httpd: CONNECT format invalid.\n");
312 rfbWriteExact(&cl,INVALID_REQUEST_STR, strlen(INVALID_REQUEST_STR));
313 httpCloseSock(rfbScreen);
316 /* proxy connection */
317 rfbLog("httpd: client asked for CONNECT\n");
318 rfbWriteExact(&cl,PROXY_OK_STR,strlen(PROXY_OK_STR));
319 rfbNewClientConnection(rfbScreen,rfbScreen->httpSock);
320 rfbScreen->httpSock = -1;
323 if (!strncmp(buf, "GET ",4) && !strncmp(strchr(buf,'/'),"/proxied.connection HTTP/1.", 27)) {
324 /* proxy connection */
325 rfbLog("httpd: client asked for /proxied.connection\n");
326 rfbWriteExact(&cl,PROXY_OK_STR,strlen(PROXY_OK_STR));
327 rfbNewClientConnection(rfbScreen,rfbScreen->httpSock);
328 rfbScreen->httpSock = -1;
333 if (strncmp(buf, "GET ", 4)) {
334 rfbErr("httpd: no GET line\n");
335 httpCloseSock(rfbScreen);
338 /* Only use the first line. */
339 buf[strcspn(buf, "\n\r")] = '\0';
342 if (strlen(buf) > maxFnameLen) {
343 rfbErr("httpd: GET line too long\n");
344 httpCloseSock(rfbScreen);
348 if (sscanf(buf, "GET %s HTTP/1.", fname) != 1) {
349 rfbErr("httpd: couldn't parse GET line\n");
350 httpCloseSock(rfbScreen);
354 if (fname[0] != '/') {
355 rfbErr("httpd: filename didn't begin with '/'\n");
356 rfbWriteExact(&cl, NOT_FOUND_STR, strlen(NOT_FOUND_STR));
357 httpCloseSock(rfbScreen);
361 if (strchr(fname+1, '/') != NULL) {
362 rfbErr("httpd: asking for file in other directory\n");
363 rfbWriteExact(&cl, NOT_FOUND_STR, strlen(NOT_FOUND_STR));
364 httpCloseSock(rfbScreen);
368 getpeername(rfbScreen->httpSock, (struct sockaddr *)&addr, &addrlen);
369 rfbLog("httpd: get '%s' for %s\n", fname+1,
370 inet_ntoa(addr.sin_addr));
372 /* Extract parameters from the URL string if necessary */
375 ptr = strchr(fname, '?');
378 if (!parseParams(&ptr[1], params, 1024)) {
380 rfbErr("httpd: bad parameters in the URL\n");
385 /* If we were asked for '/', actually read the file index.vnc */
387 if (strcmp(fname, "/") == 0) {
388 strcpy(fname, "/index.vnc");
389 rfbLog("httpd: defaulting to '%s'\n", fname+1);
392 /* Substitutions are performed on files ending .vnc */
394 if (strlen(fname) >= 4 && strcmp(&fname[strlen(fname)-4], ".vnc") == 0) {
395 performSubstitutions = TRUE;
400 if ((fd = fopen(fullFname, "r")) == 0) {
401 rfbLogPerror("httpProcessInput: open");
402 rfbWriteExact(&cl, NOT_FOUND_STR, strlen(NOT_FOUND_STR));
403 httpCloseSock(rfbScreen);
407 rfbWriteExact(&cl, OK_STR, strlen(OK_STR));
410 int n = fread(buf, 1, BUF_SIZE-1, fd);
412 rfbLogPerror("httpProcessInput: read");
414 httpCloseSock(rfbScreen);
421 if (performSubstitutions) {
423 /* Substitute $WIDTH, $HEIGHT, etc with the appropriate values.
424 This won't quite work properly if the .vnc file is longer than
425 BUF_SIZE, but it's reasonable to assume that .vnc files will
430 buf[n] = 0; /* make sure it's null-terminated */
432 while ((dollar = strchr(ptr, '$'))!=NULL) {
433 rfbWriteExact(&cl, ptr, (dollar - ptr));
437 if (compareAndSkip(&ptr, "$WIDTH")) {
439 sprintf(str, "%d", rfbScreen->width);
440 rfbWriteExact(&cl, str, strlen(str));
442 } else if (compareAndSkip(&ptr, "$HEIGHT")) {
444 sprintf(str, "%d", rfbScreen->height);
445 rfbWriteExact(&cl, str, strlen(str));
447 } else if (compareAndSkip(&ptr, "$APPLETWIDTH")) {
449 sprintf(str, "%d", rfbScreen->width);
450 rfbWriteExact(&cl, str, strlen(str));
452 } else if (compareAndSkip(&ptr, "$APPLETHEIGHT")) {
454 sprintf(str, "%d", rfbScreen->height + 32);
455 rfbWriteExact(&cl, str, strlen(str));
457 } else if (compareAndSkip(&ptr, "$PORT")) {
459 sprintf(str, "%d", rfbScreen->port);
460 rfbWriteExact(&cl, str, strlen(str));
462 } else if (compareAndSkip(&ptr, "$DESKTOP")) {
464 rfbWriteExact(&cl, rfbScreen->desktopName, strlen(rfbScreen->desktopName));
466 } else if (compareAndSkip(&ptr, "$DISPLAY")) {
468 sprintf(str, "%s:%d", rfbScreen->thisHost, rfbScreen->port-5900);
469 rfbWriteExact(&cl, str, strlen(str));
471 } else if (compareAndSkip(&ptr, "$USER")) {
474 rfbWriteExact(&cl, user,
478 rfbWriteExact(&cl, "?", 1);
479 } else if (compareAndSkip(&ptr, "$PARAMS")) {
480 if (params[0] != '\0')
481 rfbWriteExact(&cl, params, strlen(params));
483 if (!compareAndSkip(&ptr, "$$"))
486 if (rfbWriteExact(&cl, "$", 1) < 0) {
488 httpCloseSock(rfbScreen);
493 if (rfbWriteExact(&cl, ptr, (&buf[n] - ptr)) < 0)
498 /* For files not ending .vnc, just write out the buffer */
500 if (rfbWriteExact(&cl, buf, n) < 0)
506 httpCloseSock(rfbScreen);
511 compareAndSkip(char **ptr, const char *str)
513 if (strncmp(*ptr, str, strlen(str)) == 0) {
522 * Parse the request tail after the '?' character, and format a sequence
523 * of <param> tags for inclusion into an HTML page with embedded applet.
527 parseParams(const char *request, char *result, int max_bytes)
529 char param_request[128];
530 char param_formatted[196];
541 /* Copy individual "name=value" string into a buffer */
542 delim_ptr = strchr((char *)tail, '&');
543 if (delim_ptr == NULL) {
544 if (strlen(tail) >= sizeof(param_request)) {
547 strcpy(param_request, tail);
549 len = delim_ptr - tail;
550 if (len >= sizeof(param_request)) {
553 memcpy(param_request, tail, len);
554 param_request[len] = '\0';
557 /* Split the request into parameter name and value */
558 value_str = strchr(¶m_request[1], '=');
559 if (value_str == NULL) {
563 if (strlen(value_str) == 0) {
567 /* Validate both parameter name and value */
568 if (!validateString(param_request) || !validateString(value_str)) {
572 /* Prepare HTML-formatted representation of the name=value pair */
573 len = sprintf(param_formatted,
574 "<PARAM NAME=\"%s\" VALUE=\"%s\">\n",
575 param_request, value_str);
576 if (cur_bytes + len + 1 > max_bytes) {
579 strcat(result, param_formatted);
582 /* Go to the next parameter */
583 if (delim_ptr == NULL) {
586 tail = delim_ptr + 1;
592 * Check if the string consists only of alphanumeric characters, '+'
593 * signs, underscores, and dots. Replace all '+' signs with spaces.
597 validateString(char *str)
601 for (ptr = str; *ptr != '\0'; ptr++) {
602 if (!isalnum(*ptr) && *ptr != '_' && *ptr != '.') {