2 * Client routines for the CUPS scheduler.
4 * Copyright 2007-2015 by Apple Inc.
5 * Copyright 1997-2007 by Easy Software Products, all rights reserved.
7 * This file contains Kerberos support code, copyright 2006 by
10 * These coded instructions, statements, and computer programs are the
11 * property of Apple Inc. and are protected by Federal copyright
12 * law. Distribution and use rights are outlined in the file "LICENSE.txt"
13 * which should have been included with this file. If this file is
14 * file is missing or damaged, see the license at "http://www.cups.org/".
18 * Include necessary headers...
21 #define _CUPS_NO_DEPRECATED
22 #define _HTTP_NO_PRIVATE
27 #endif /* __APPLE__ */
30 #endif /* HAVE_TCPD_H */
37 static int check_if_modified(cupsd_client_t *con,
38 struct stat *filestats);
39 static int compare_clients(cupsd_client_t *a, cupsd_client_t *b,
42 static int cupsd_start_tls(cupsd_client_t *con, http_encryption_t e);
44 static char *get_file(cupsd_client_t *con, struct stat *filestats,
45 char *filename, size_t len);
46 static http_status_t install_cupsd_conf(cupsd_client_t *con);
47 static int is_cgi(cupsd_client_t *con, const char *filename,
48 struct stat *filestats, mime_type_t *type);
49 static int is_path_absolute(const char *path);
50 static int pipe_command(cupsd_client_t *con, int infile, int *outfile,
51 char *command, char *options, int root);
52 static int valid_host(cupsd_client_t *con);
53 static int write_file(cupsd_client_t *con, http_status_t code,
54 char *filename, char *type,
55 struct stat *filestats);
56 static void write_pipe(cupsd_client_t *con);
60 * 'cupsdAcceptClient()' - Accept a new client.
64 cupsdAcceptClient(cupsd_listener_t *lis)/* I - Listener socket */
66 const char *hostname; /* Hostname of client */
67 char name[256]; /* Hostname of client */
68 int count; /* Count of connections on a host */
69 cupsd_client_t *con, /* New client pointer */
70 *tempcon; /* Temporary client pointer */
71 socklen_t addrlen; /* Length of address */
72 http_addr_t temp; /* Temporary address variable */
73 static time_t last_dos = 0; /* Time of last DoS attack */
75 struct request_info wrap_req; /* TCP wrappers request information */
76 #endif /* HAVE_TCPD_H */
79 cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdAcceptClient(lis=%p(%d)) Clients=%d", lis, lis->fd, cupsArrayCount(Clients));
82 * Make sure we don't have a full set of clients already...
85 if (cupsArrayCount(Clients) == MaxClients)
89 * Get a pointer to the next available client...
93 Clients = cupsArrayNew(NULL, NULL);
97 cupsdLogMessage(CUPSD_LOG_ERROR,
98 "Unable to allocate memory for clients array!");
99 cupsdPauseListening();
104 ActiveClients = cupsArrayNew((cups_array_func_t)compare_clients, NULL);
108 cupsdLogMessage(CUPSD_LOG_ERROR,
109 "Unable to allocate memory for active clients array!");
110 cupsdPauseListening();
114 if ((con = calloc(1, sizeof(cupsd_client_t))) == NULL)
116 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to allocate memory for client!");
117 cupsdPauseListening();
122 * Accept the client and get the remote address...
125 con->number = ++ LastClientNumber;
128 if ((con->http = httpAcceptConnection(lis->fd, 0)) == NULL)
130 if (errno == ENFILE || errno == EMFILE)
131 cupsdPauseListening();
133 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to accept client connection - %s.",
141 * Save the connected address and port number...
144 addrlen = sizeof(con->clientaddr);
146 if (getsockname(httpGetFd(con->http), (struct sockaddr *)&con->clientaddr, &addrlen) || addrlen == 0)
147 con->clientaddr = lis->address;
149 cupsdLogClient(con, CUPSD_LOG_DEBUG, "Server address is \"%s\".", httpAddrString(&con->clientaddr, name, sizeof(name)));
152 * Check the number of clients on the same address...
155 for (count = 0, tempcon = (cupsd_client_t *)cupsArrayFirst(Clients);
157 tempcon = (cupsd_client_t *)cupsArrayNext(Clients))
158 if (httpAddrEqual(httpGetAddress(tempcon->http), httpGetAddress(con->http)))
161 if (count >= MaxClientsPerHost)
165 if (count >= MaxClientsPerHost)
167 if ((time(NULL) - last_dos) >= 60)
169 last_dos = time(NULL);
170 cupsdLogMessage(CUPSD_LOG_WARN,
171 "Possible DoS attack - more than %d clients connecting "
174 httpGetHostname(con->http, name, sizeof(name)));
177 httpClose(con->http);
183 * Get the hostname or format the IP address as needed...
187 hostname = httpResolveHostname(con->http, NULL, 0);
189 hostname = httpGetHostname(con->http, NULL, 0);
191 if (hostname == NULL && HostNameLookups == 2)
194 * Can't have an unresolved IP address with double-lookups enabled...
197 httpClose(con->http);
199 cupsdLogClient(con, CUPSD_LOG_WARN,
200 "Name lookup failed - connection from %s closed!",
201 httpGetHostname(con->http, NULL, 0));
207 if (HostNameLookups == 2)
210 * Do double lookups as needed...
213 http_addrlist_t *addrlist, /* List of addresses */
214 *addr; /* Current address */
216 if ((addrlist = httpAddrGetList(hostname, AF_UNSPEC, NULL)) != NULL)
219 * See if the hostname maps to the same IP address...
222 for (addr = addrlist; addr; addr = addr->next)
223 if (httpAddrEqual(httpGetAddress(con->http), &(addr->addr)))
229 httpAddrFreeList(addrlist);
234 * Can't have a hostname that doesn't resolve to the same IP address
235 * with double-lookups enabled...
238 httpClose(con->http);
240 cupsdLogClient(con, CUPSD_LOG_WARN,
241 "IP lookup failed - connection from %s closed!",
242 httpGetHostname(con->http, NULL, 0));
250 * See if the connection is denied by TCP wrappers...
253 request_init(&wrap_req, RQ_DAEMON, "cupsd", RQ_FILE, httpGetFd(con->http),
257 if (!hosts_access(&wrap_req))
259 httpClose(con->http);
261 cupsdLogClient(con, CUPSD_LOG_WARN,
262 "Connection from %s refused by /etc/hosts.allow and "
263 "/etc/hosts.deny rules.", httpGetHostname(con->http, NULL, 0));
267 #endif /* HAVE_TCPD_H */
270 if (httpAddrFamily(httpGetAddress(con->http)) == AF_LOCAL)
273 socklen_t peersize; /* Size of peer credentials */
274 pid_t peerpid; /* Peer process ID */
275 char peername[256]; /* Name of process */
277 peersize = sizeof(peerpid);
278 if (!getsockopt(httpGetFd(con->http), SOL_LOCAL, LOCAL_PEERPID, &peerpid,
281 if (!proc_name((int)peerpid, peername, sizeof(peername)))
282 cupsdLogClient(con, CUPSD_LOG_DEBUG,
283 "Accepted from %s (Domain ???[%d])",
284 httpGetHostname(con->http, NULL, 0), (int)peerpid);
286 cupsdLogClient(con, CUPSD_LOG_DEBUG,
287 "Accepted from %s (Domain %s[%d])",
288 httpGetHostname(con->http, NULL, 0), peername, (int)peerpid);
291 # endif /* __APPLE__ */
293 cupsdLogClient(con, CUPSD_LOG_DEBUG, "Accepted from %s (Domain)",
294 httpGetHostname(con->http, NULL, 0));
297 #endif /* AF_LOCAL */
298 cupsdLogClient(con, CUPSD_LOG_DEBUG, "Accepted from %s:%d (IPv%d)",
299 httpGetHostname(con->http, NULL, 0),
300 httpAddrPort(httpGetAddress(con->http)),
301 httpAddrFamily(httpGetAddress(con->http)) == AF_INET ? 4 : 6);
304 * Get the local address the client connected to...
307 addrlen = sizeof(temp);
308 if (getsockname(httpGetFd(con->http), (struct sockaddr *)&temp, &addrlen))
310 cupsdLogClient(con, CUPSD_LOG_ERROR, "Unable to get local address - %s",
313 strlcpy(con->servername, "localhost", sizeof(con->servername));
314 con->serverport = LocalPort;
317 else if (httpAddrFamily(&temp) == AF_LOCAL)
319 strlcpy(con->servername, "localhost", sizeof(con->servername));
320 con->serverport = LocalPort;
322 #endif /* AF_LOCAL */
325 if (httpAddrLocalhost(&temp))
326 strlcpy(con->servername, "localhost", sizeof(con->servername));
327 else if (HostNameLookups)
328 httpAddrLookup(&temp, con->servername, sizeof(con->servername));
330 httpAddrString(&temp, con->servername, sizeof(con->servername));
332 con->serverport = httpAddrPort(&(lis->address));
336 * Add the connection to the array of active clients...
339 cupsArrayAdd(Clients, con);
342 * Add the socket to the server select.
345 cupsdAddSelect(httpGetFd(con->http), (cupsd_selfunc_t)cupsdReadClient, NULL,
348 cupsdLogClient(con, CUPSD_LOG_DEBUG, "Waiting for request.");
351 * Temporarily suspend accept()'s until we lose a client...
354 if (cupsArrayCount(Clients) == MaxClients)
355 cupsdPauseListening();
359 * See if we are connecting on a secure port...
362 if (lis->encryption == HTTP_ENCRYPTION_ALWAYS)
365 * https connection; go secure...
368 if (cupsd_start_tls(con, HTTP_ENCRYPTION_ALWAYS))
369 cupsdCloseClient(con);
373 #endif /* HAVE_SSL */
378 * 'cupsdCloseAllClients()' - Close all remote clients immediately.
382 cupsdCloseAllClients(void)
384 cupsd_client_t *con; /* Current client */
387 cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdCloseAllClients() Clients=%d", cupsArrayCount(Clients));
389 for (con = (cupsd_client_t *)cupsArrayFirst(Clients);
391 con = (cupsd_client_t *)cupsArrayNext(Clients))
392 if (cupsdCloseClient(con))
393 cupsdCloseClient(con);
398 * 'cupsdCloseClient()' - Close a remote client.
401 int /* O - 1 if partial close, 0 if fully closed */
402 cupsdCloseClient(cupsd_client_t *con) /* I - Client to close */
404 int partial; /* Do partial close for SSL? */
407 cupsdLogClient(con, CUPSD_LOG_DEBUG, "Closing connection.");
410 * Flush pending writes before closing...
413 httpFlushWrite(con->http);
417 if (con->pipe_pid != 0)
420 * Stop any CGI process...
423 cupsdEndProcess(con->pipe_pid, 1);
429 cupsdRemoveSelect(con->file);
436 * Close the socket and clear the file from the input set for select()...
439 if (httpGetFd(con->http) >= 0)
441 cupsArrayRemove(ActiveClients, con);
446 * Shutdown encryption as needed...
449 if (httpIsEncrypted(con->http))
451 #endif /* HAVE_SSL */
456 * Only do a partial close so that the encrypted client gets everything.
459 httpShutdown(con->http);
460 cupsdAddSelect(httpGetFd(con->http), (cupsd_selfunc_t)cupsdReadClient,
463 cupsdLogClient(con, CUPSD_LOG_DEBUG, "Waiting for socket close.");
468 * Shut the socket down fully...
471 cupsdRemoveSelect(httpGetFd(con->http));
472 httpClose(con->http);
483 cupsdRemoveSelect(httpGetFd(con->http));
485 httpClose(con->http);
489 unlink(con->filename);
490 cupsdClearString(&con->filename);
493 cupsdClearString(&con->command);
494 cupsdClearString(&con->options);
495 cupsdClearString(&con->query_string);
499 ippDelete(con->request);
505 ippDelete(con->response);
506 con->response = NULL;
511 cupsLangFree(con->language);
512 con->language = NULL;
515 #ifdef HAVE_AUTHORIZATION_H
518 AuthorizationFree(con->authref, kAuthorizationFlagDefaults);
521 #endif /* HAVE_AUTHORIZATION_H */
524 * Re-enable new client connections if we are going back under the
528 if (cupsArrayCount(Clients) == MaxClients)
529 cupsdResumeListening();
532 * Compact the list of clients as necessary...
535 cupsArrayRemove(Clients, con);
545 * 'cupsdReadClient()' - Read data from a client.
549 cupsdReadClient(cupsd_client_t *con) /* I - Client to read from */
551 char line[32768], /* Line from client... */
552 locale[64], /* Locale */
553 *ptr; /* Pointer into strings */
554 http_status_t status; /* Transfer status */
555 ipp_state_t ipp_state; /* State of IPP transfer */
556 int bytes; /* Number of bytes to POST */
557 char *filename; /* Name of file for GET/HEAD */
558 char buf[1024]; /* Buffer for real filename */
559 struct stat filestats; /* File information */
560 mime_type_t *type; /* MIME type of file */
561 cupsd_printer_t *p; /* Printer */
562 static unsigned request_id = 0; /* Request ID for temp files */
565 status = HTTP_STATUS_CONTINUE;
567 cupsdLogClient(con, CUPSD_LOG_DEBUG2, "cupsdReadClient: error=%d, used=%d, state=%s, data_encoding=HTTP_ENCODING_%s, data_remaining=" CUPS_LLFMT ", request=%p(%s), file=%d", httpError(con->http), (int)httpGetReady(con->http), httpStateString(httpGetState(con->http)), httpIsChunked(con->http) ? "CHUNKED" : "LENGTH", CUPS_LLCAST httpGetRemaining(con->http), con->request, con->request ? ippStateString(ippGetState(con->request)) : "", con->file);
569 if (httpGetState(con->http) == HTTP_STATE_GET_SEND ||
570 httpGetState(con->http) == HTTP_STATE_POST_SEND ||
571 httpGetState(con->http) == HTTP_STATE_STATUS)
574 * If we get called in the wrong state, then something went wrong with the
575 * connection and we need to shut it down...
578 if (!httpGetReady(con->http) && recv(httpGetFd(con->http), buf, 1, MSG_PEEK) < 1)
581 * Connection closed...
584 cupsdLogClient(con, CUPSD_LOG_DEBUG, "Closing on EOF.");
585 cupsdCloseClient(con);
589 cupsdLogClient(con, CUPSD_LOG_DEBUG, "Closing on unexpected HTTP read state %s.", httpStateString(httpGetState(con->http)));
590 cupsdCloseClient(con);
598 * Automatically check for a SSL/TLS handshake...
603 if (recv(httpGetFd(con->http), buf, 1, MSG_PEEK) == 1 &&
604 (!buf[0] || !strchr("DGHOPT", buf[0])))
607 * Encrypt this connection...
610 cupsdLogClient(con, CUPSD_LOG_DEBUG2, "Saw first byte %02X, auto-negotiating SSL/TLS session.", buf[0] & 255);
612 if (cupsd_start_tls(con, HTTP_ENCRYPTION_ALWAYS))
613 cupsdCloseClient(con);
618 #endif /* HAVE_SSL */
620 switch (httpGetState(con->http))
622 case HTTP_STATE_WAITING :
624 * See if we've received a request line...
627 con->operation = httpReadRequest(con->http, con->uri, sizeof(con->uri));
628 if (con->operation == HTTP_STATE_ERROR ||
629 con->operation == HTTP_STATE_UNKNOWN_METHOD ||
630 con->operation == HTTP_STATE_UNKNOWN_VERSION)
632 if (httpError(con->http))
633 cupsdLogClient(con, CUPSD_LOG_DEBUG,
634 "HTTP_STATE_WAITING Closing for error %d (%s)",
635 httpError(con->http), strerror(httpError(con->http)));
637 cupsdLogClient(con, CUPSD_LOG_DEBUG,
638 "HTTP_STATE_WAITING Closing on error: %s",
639 cupsLastErrorString());
641 cupsdCloseClient(con);
646 * Ignore blank request lines...
649 if (con->operation == HTTP_STATE_WAITING)
653 * Clear other state variables...
660 con->username[0] = '\0';
661 con->password[0] = '\0';
663 cupsdClearString(&con->command);
664 cupsdClearString(&con->options);
665 cupsdClearString(&con->query_string);
669 ippDelete(con->request);
675 ippDelete(con->response);
676 con->response = NULL;
681 cupsLangFree(con->language);
682 con->language = NULL;
688 #endif /* HAVE_GSSAPI */
691 * Handle full URLs in the request line...
694 if (strcmp(con->uri, "*"))
696 char scheme[HTTP_MAX_URI], /* Method/scheme */
697 userpass[HTTP_MAX_URI], /* Username:password */
698 hostname[HTTP_MAX_URI], /* Hostname */
699 resource[HTTP_MAX_URI]; /* Resource path */
700 int port; /* Port number */
703 * Separate the URI into its components...
706 if (httpSeparateURI(HTTP_URI_CODING_MOST, con->uri,
707 scheme, sizeof(scheme),
708 userpass, sizeof(userpass),
709 hostname, sizeof(hostname), &port,
710 resource, sizeof(resource)) < HTTP_URI_STATUS_OK)
712 cupsdLogClient(con, CUPSD_LOG_ERROR, "Bad URI \"%s\" in request.",
714 cupsdSendError(con, HTTP_STATUS_METHOD_NOT_ALLOWED, CUPSD_AUTH_NONE);
715 cupsdCloseClient(con);
720 * Only allow URIs with the servername, localhost, or an IP
724 if (strcmp(scheme, "file") &&
725 _cups_strcasecmp(hostname, ServerName) &&
726 _cups_strcasecmp(hostname, "localhost") &&
727 !cupsArrayFind(ServerAlias, hostname) &&
728 !isdigit(hostname[0]) && hostname[0] != '[')
731 * Nope, we don't do proxies...
734 cupsdLogClient(con, CUPSD_LOG_ERROR, "Bad URI \"%s\" in request.",
736 cupsdSendError(con, HTTP_STATUS_METHOD_NOT_ALLOWED, CUPSD_AUTH_NONE);
737 cupsdCloseClient(con);
742 * Copy the resource portion back into the URI; both resource and
743 * con->uri are HTTP_MAX_URI bytes in size...
746 strlcpy(con->uri, resource, sizeof(con->uri));
750 * Process the request...
753 gettimeofday(&(con->start), NULL);
755 cupsdLogClient(con, CUPSD_LOG_DEBUG, "%s %s HTTP/%d.%d",
756 httpStateString(con->operation) + 11, con->uri,
757 httpGetVersion(con->http) / 100,
758 httpGetVersion(con->http) % 100);
760 if (!cupsArrayFind(ActiveClients, con))
762 cupsArrayAdd(ActiveClients, con);
766 case HTTP_STATE_OPTIONS :
767 case HTTP_STATE_DELETE :
768 case HTTP_STATE_GET :
769 case HTTP_STATE_HEAD :
770 case HTTP_STATE_POST :
771 case HTTP_STATE_PUT :
772 case HTTP_STATE_TRACE :
774 * Parse incoming parameters until the status changes...
777 while ((status = httpUpdate(con->http)) == HTTP_STATUS_CONTINUE)
778 if (!httpGetReady(con->http))
781 if (status != HTTP_STATUS_OK && status != HTTP_STATUS_CONTINUE)
783 if (httpError(con->http) && httpError(con->http) != EPIPE)
784 cupsdLogClient(con, CUPSD_LOG_DEBUG,
785 "Closing for error %d (%s) while reading headers.",
786 httpError(con->http), strerror(httpError(con->http)));
788 cupsdLogClient(con, CUPSD_LOG_DEBUG,
789 "Closing on EOF while reading headers.");
791 cupsdSendError(con, HTTP_STATUS_BAD_REQUEST, CUPSD_AUTH_NONE);
792 cupsdCloseClient(con);
798 if (!httpGetReady(con->http) && recv(httpGetFd(con->http), buf, 1, MSG_PEEK) < 1)
801 * Connection closed...
804 cupsdLogClient(con, CUPSD_LOG_DEBUG, "Closing on EOF.");
805 cupsdCloseClient(con);
808 break; /* Anti-compiler-warning-code */
812 * Handle new transfers...
815 cupsdLogClient(con, CUPSD_LOG_DEBUG, "Read: status=%d", status);
817 if (status == HTTP_STATUS_OK)
819 if (httpGetField(con->http, HTTP_FIELD_ACCEPT_LANGUAGE)[0])
822 * Figure out the locale from the Accept-Language and Content-Type
826 if ((ptr = strchr(httpGetField(con->http, HTTP_FIELD_ACCEPT_LANGUAGE),
830 if ((ptr = strchr(httpGetField(con->http, HTTP_FIELD_ACCEPT_LANGUAGE),
834 if ((ptr = strstr(httpGetField(con->http, HTTP_FIELD_CONTENT_TYPE),
835 "charset=")) != NULL)
838 * Combine language and charset, and trim any extra params in the
842 snprintf(locale, sizeof(locale), "%s.%s",
843 httpGetField(con->http, HTTP_FIELD_ACCEPT_LANGUAGE), ptr + 8);
845 if ((ptr = strchr(locale, ',')) != NULL)
849 snprintf(locale, sizeof(locale), "%s.UTF-8",
850 httpGetField(con->http, HTTP_FIELD_ACCEPT_LANGUAGE));
852 con->language = cupsLangGet(locale);
855 con->language = cupsLangGet(DefaultLocale);
859 if (!_cups_strncasecmp(httpGetField(con->http, HTTP_FIELD_CONNECTION),
860 "Keep-Alive", 10) && KeepAlive)
861 httpSetKeepAlive(con->http, HTTP_KEEPALIVE_ON);
862 else if (!_cups_strncasecmp(httpGetField(con->http, HTTP_FIELD_CONNECTION),
864 httpSetKeepAlive(con->http, HTTP_KEEPALIVE_OFF);
866 if (!httpGetField(con->http, HTTP_FIELD_HOST)[0] &&
867 httpGetVersion(con->http) >= HTTP_VERSION_1_1)
870 * HTTP/1.1 and higher require the "Host:" field...
873 if (!cupsdSendError(con, HTTP_STATUS_BAD_REQUEST, CUPSD_AUTH_NONE))
875 cupsdLogClient(con, CUPSD_LOG_ERROR, "Missing Host: field in request.");
876 cupsdCloseClient(con);
880 else if (!valid_host(con))
883 * Access to localhost must use "localhost" or the corresponding IPv4
884 * or IPv6 values in the Host: field.
887 cupsdLogClient(con, CUPSD_LOG_ERROR,
888 "Request from \"%s\" using invalid Host: field \"%s\".",
889 httpGetHostname(con->http, NULL, 0), httpGetField(con->http, HTTP_FIELD_HOST));
891 if (!cupsdSendError(con, HTTP_STATUS_BAD_REQUEST, CUPSD_AUTH_NONE))
893 cupsdCloseClient(con);
897 else if (con->operation == HTTP_STATE_OPTIONS)
900 * Do OPTIONS command...
903 if (con->best && con->best->type != CUPSD_AUTH_NONE)
905 httpClearFields(con->http);
907 if (!cupsdSendHeader(con, HTTP_STATUS_UNAUTHORIZED, NULL, CUPSD_AUTH_NONE))
909 cupsdCloseClient(con);
914 if (!_cups_strcasecmp(httpGetField(con->http, HTTP_FIELD_CONNECTION), "Upgrade") && strstr(httpGetField(con->http, HTTP_FIELD_UPGRADE), "TLS/") != NULL && !httpIsEncrypted(con->http))
918 * Do encryption stuff...
921 httpClearFields(con->http);
923 if (!cupsdSendHeader(con, HTTP_STATUS_SWITCHING_PROTOCOLS, NULL, CUPSD_AUTH_NONE))
925 cupsdCloseClient(con);
929 if (cupsd_start_tls(con, HTTP_ENCRYPTION_REQUIRED))
931 cupsdCloseClient(con);
935 if (!cupsdSendError(con, HTTP_STATUS_NOT_IMPLEMENTED, CUPSD_AUTH_NONE))
937 cupsdCloseClient(con);
940 #endif /* HAVE_SSL */
943 httpClearFields(con->http);
944 httpSetField(con->http, HTTP_FIELD_ALLOW,
945 "GET, HEAD, OPTIONS, POST, PUT");
946 httpSetField(con->http, HTTP_FIELD_CONTENT_LENGTH, "0");
948 if (!cupsdSendHeader(con, HTTP_STATUS_OK, NULL, CUPSD_AUTH_NONE))
950 cupsdCloseClient(con);
954 else if (!is_path_absolute(con->uri))
957 * Protect against malicious users!
960 cupsdLogClient(con, CUPSD_LOG_ERROR,
961 "Request for non-absolute resource \"%s\".", con->uri);
963 if (!cupsdSendError(con, HTTP_STATUS_FORBIDDEN, CUPSD_AUTH_NONE))
965 cupsdCloseClient(con);
971 if (!_cups_strcasecmp(httpGetField(con->http, HTTP_FIELD_CONNECTION),
972 "Upgrade") && !httpIsEncrypted(con->http))
976 * Do encryption stuff...
979 httpClearFields(con->http);
981 if (!cupsdSendHeader(con, HTTP_STATUS_SWITCHING_PROTOCOLS, NULL,
984 cupsdCloseClient(con);
988 if (cupsd_start_tls(con, HTTP_ENCRYPTION_REQUIRED))
990 cupsdCloseClient(con);
994 if (!cupsdSendError(con, HTTP_STATUS_NOT_IMPLEMENTED, CUPSD_AUTH_NONE))
996 cupsdCloseClient(con);
999 #endif /* HAVE_SSL */
1002 if ((status = cupsdIsAuthorized(con, NULL)) != HTTP_STATUS_OK)
1004 cupsdSendError(con, status, CUPSD_AUTH_NONE);
1005 cupsdCloseClient(con);
1009 if (httpGetExpect(con->http) &&
1010 (con->operation == HTTP_STATE_POST || con->operation == HTTP_STATE_PUT))
1012 if (httpGetExpect(con->http) == HTTP_STATUS_CONTINUE)
1015 * Send 100-continue header...
1018 if (httpWriteResponse(con->http, HTTP_STATUS_CONTINUE))
1020 cupsdCloseClient(con);
1027 * Send 417-expectation-failed header...
1030 httpClearFields(con->http);
1031 httpSetField(con->http, HTTP_FIELD_CONTENT_LENGTH, "0");
1033 cupsdSendError(con, HTTP_STATUS_EXPECTATION_FAILED, CUPSD_AUTH_NONE);
1034 cupsdCloseClient(con);
1039 switch (httpGetState(con->http))
1041 case HTTP_STATE_GET_SEND :
1042 cupsdLogClient(con, CUPSD_LOG_DEBUG, "Processing GET %s", con->uri);
1044 if ((!strncmp(con->uri, "/ppd/", 5) ||
1045 !strncmp(con->uri, "/printers/", 10) ||
1046 !strncmp(con->uri, "/classes/", 9)) &&
1047 !strcmp(con->uri + strlen(con->uri) - 4, ".ppd"))
1050 * Send PPD file - get the real printer name since printer
1051 * names are not case sensitive but filenames can be...
1054 con->uri[strlen(con->uri) - 4] = '\0'; /* Drop ".ppd" */
1056 if (!strncmp(con->uri, "/ppd/", 5))
1057 p = cupsdFindPrinter(con->uri + 5);
1058 else if (!strncmp(con->uri, "/printers/", 10))
1059 p = cupsdFindPrinter(con->uri + 10);
1062 p = cupsdFindClass(con->uri + 9);
1066 int i; /* Looping var */
1068 for (i = 0; i < p->num_printers; i ++)
1070 if (!(p->printers[i]->type & CUPS_PRINTER_CLASS))
1072 char ppdname[1024];/* PPD filename */
1074 snprintf(ppdname, sizeof(ppdname), "%s/ppd/%s.ppd",
1075 ServerRoot, p->printers[i]->name);
1076 if (!access(ppdname, 0))
1084 if (i >= p->num_printers)
1091 snprintf(con->uri, sizeof(con->uri), "/ppd/%s.ppd", p->name);
1095 if (!cupsdSendError(con, HTTP_STATUS_NOT_FOUND, CUPSD_AUTH_NONE))
1097 cupsdCloseClient(con);
1104 else if ((!strncmp(con->uri, "/icons/", 7) ||
1105 !strncmp(con->uri, "/printers/", 10) ||
1106 !strncmp(con->uri, "/classes/", 9)) &&
1107 !strcmp(con->uri + strlen(con->uri) - 4, ".png"))
1110 * Send icon file - get the real queue name since queue names are
1111 * not case sensitive but filenames can be...
1114 con->uri[strlen(con->uri) - 4] = '\0'; /* Drop ".png" */
1116 if (!strncmp(con->uri, "/icons/", 7))
1117 p = cupsdFindPrinter(con->uri + 7);
1118 else if (!strncmp(con->uri, "/printers/", 10))
1119 p = cupsdFindPrinter(con->uri + 10);
1122 p = cupsdFindClass(con->uri + 9);
1126 int i; /* Looping var */
1128 for (i = 0; i < p->num_printers; i ++)
1130 if (!(p->printers[i]->type & CUPS_PRINTER_CLASS))
1132 char ppdname[1024];/* PPD filename */
1134 snprintf(ppdname, sizeof(ppdname), "%s/ppd/%s.ppd",
1135 ServerRoot, p->printers[i]->name);
1136 if (!access(ppdname, 0))
1144 if (i >= p->num_printers)
1150 snprintf(con->uri, sizeof(con->uri), "/icons/%s.png", p->name);
1153 if (!cupsdSendError(con, HTTP_STATUS_NOT_FOUND, CUPSD_AUTH_NONE))
1155 cupsdCloseClient(con);
1163 if ((!strncmp(con->uri, "/admin", 6) && strcmp(con->uri, "/admin/conf/cupsd.conf") && strncmp(con->uri, "/admin/log/", 11)) ||
1164 !strncmp(con->uri, "/printers", 9) ||
1165 !strncmp(con->uri, "/classes", 8) ||
1166 !strncmp(con->uri, "/help", 5) ||
1167 !strncmp(con->uri, "/jobs", 5))
1172 * Web interface is disabled. Show an appropriate message...
1175 if (!cupsdSendError(con, HTTP_STATUS_CUPS_WEBIF_DISABLED, CUPSD_AUTH_NONE))
1177 cupsdCloseClient(con);
1185 * Send CGI output...
1188 if (!strncmp(con->uri, "/admin", 6))
1190 cupsdSetStringf(&con->command, "%s/cgi-bin/admin.cgi",
1193 cupsdSetString(&con->options, strchr(con->uri + 6, '?'));
1195 else if (!strncmp(con->uri, "/printers", 9))
1197 cupsdSetStringf(&con->command, "%s/cgi-bin/printers.cgi",
1200 if (con->uri[9] && con->uri[10])
1201 cupsdSetString(&con->options, con->uri + 9);
1203 cupsdSetString(&con->options, NULL);
1205 else if (!strncmp(con->uri, "/classes", 8))
1207 cupsdSetStringf(&con->command, "%s/cgi-bin/classes.cgi",
1210 if (con->uri[8] && con->uri[9])
1211 cupsdSetString(&con->options, con->uri + 8);
1213 cupsdSetString(&con->options, NULL);
1215 else if (!strncmp(con->uri, "/jobs", 5))
1217 cupsdSetStringf(&con->command, "%s/cgi-bin/jobs.cgi",
1220 if (con->uri[5] && con->uri[6])
1221 cupsdSetString(&con->options, con->uri + 5);
1223 cupsdSetString(&con->options, NULL);
1227 cupsdSetStringf(&con->command, "%s/cgi-bin/help.cgi",
1230 if (con->uri[5] && con->uri[6])
1231 cupsdSetString(&con->options, con->uri + 5);
1233 cupsdSetString(&con->options, NULL);
1236 if (!cupsdSendCommand(con, con->command, con->options, 0))
1238 if (!cupsdSendError(con, HTTP_STATUS_NOT_FOUND, CUPSD_AUTH_NONE))
1240 cupsdCloseClient(con);
1245 cupsdLogRequest(con, HTTP_STATUS_OK);
1247 if (httpGetVersion(con->http) <= HTTP_VERSION_1_0)
1248 httpSetKeepAlive(con->http, HTTP_KEEPALIVE_OFF);
1250 else if (!strncmp(con->uri, "/admin/log/", 11) && (strchr(con->uri + 11, '/') || strlen(con->uri) == 11))
1253 * GET can only be done to configuration files directly under
1257 cupsdLogClient(con, CUPSD_LOG_ERROR, "Request for subdirectory \"%s\".", con->uri);
1259 if (!cupsdSendError(con, HTTP_STATUS_FORBIDDEN, CUPSD_AUTH_NONE))
1261 cupsdCloseClient(con);
1273 if ((filename = get_file(con, &filestats, buf,
1274 sizeof(buf))) == NULL)
1276 if (!cupsdSendError(con, HTTP_STATUS_NOT_FOUND, CUPSD_AUTH_NONE))
1278 cupsdCloseClient(con);
1285 type = mimeFileType(MimeDatabase, filename, NULL, NULL);
1287 cupsdLogClient(con, CUPSD_LOG_DEBUG, "filename=\"%s\", type=%s/%s", filename, type ? type->super : "", type ? type->type : "");
1289 if (is_cgi(con, filename, &filestats, type))
1292 * Note: con->command and con->options were set by
1296 if (!cupsdSendCommand(con, con->command, con->options, 0))
1298 if (!cupsdSendError(con, HTTP_STATUS_NOT_FOUND, CUPSD_AUTH_NONE))
1300 cupsdCloseClient(con);
1305 cupsdLogRequest(con, HTTP_STATUS_OK);
1307 if (httpGetVersion(con->http) <= HTTP_VERSION_1_0)
1308 httpSetKeepAlive(con->http, HTTP_KEEPALIVE_OFF);
1312 if (!check_if_modified(con, &filestats))
1314 if (!cupsdSendError(con, HTTP_STATUS_NOT_MODIFIED, CUPSD_AUTH_NONE))
1316 cupsdCloseClient(con);
1323 strlcpy(line, "text/plain", sizeof(line));
1325 snprintf(line, sizeof(line), "%s/%s", type->super, type->type);
1327 if (!write_file(con, HTTP_STATUS_OK, filename, line, &filestats))
1329 cupsdCloseClient(con);
1336 case HTTP_STATE_POST_RECV :
1338 * See if the POST request includes a Content-Length field, and if
1339 * so check the length against any limits that are set...
1342 if (httpGetField(con->http, HTTP_FIELD_CONTENT_LENGTH)[0] &&
1343 MaxRequestSize > 0 &&
1344 httpGetLength2(con->http) > MaxRequestSize)
1347 * Request too large...
1350 if (!cupsdSendError(con, HTTP_STATUS_REQUEST_TOO_LARGE, CUPSD_AUTH_NONE))
1352 cupsdCloseClient(con);
1358 else if (httpGetLength2(con->http) < 0)
1361 * Negative content lengths are invalid!
1364 if (!cupsdSendError(con, HTTP_STATUS_BAD_REQUEST, CUPSD_AUTH_NONE))
1366 cupsdCloseClient(con);
1374 * See what kind of POST request this is; for IPP requests the
1375 * content-type field will be "application/ipp"...
1378 if (!strcmp(httpGetField(con->http, HTTP_FIELD_CONTENT_TYPE),
1380 con->request = ippNew();
1381 else if (!WebInterface)
1384 * Web interface is disabled. Show an appropriate message...
1387 if (!cupsdSendError(con, HTTP_STATUS_CUPS_WEBIF_DISABLED, CUPSD_AUTH_NONE))
1389 cupsdCloseClient(con);
1395 else if ((!strncmp(con->uri, "/admin", 6) && strncmp(con->uri, "/admin/log/", 11)) ||
1396 !strncmp(con->uri, "/printers", 9) ||
1397 !strncmp(con->uri, "/classes", 8) ||
1398 !strncmp(con->uri, "/help", 5) ||
1399 !strncmp(con->uri, "/jobs", 5))
1405 if (!strncmp(con->uri, "/admin", 6))
1407 cupsdSetStringf(&con->command, "%s/cgi-bin/admin.cgi",
1410 cupsdSetString(&con->options, strchr(con->uri + 6, '?'));
1412 else if (!strncmp(con->uri, "/printers", 9))
1414 cupsdSetStringf(&con->command, "%s/cgi-bin/printers.cgi",
1417 if (con->uri[9] && con->uri[10])
1418 cupsdSetString(&con->options, con->uri + 9);
1420 cupsdSetString(&con->options, NULL);
1422 else if (!strncmp(con->uri, "/classes", 8))
1424 cupsdSetStringf(&con->command, "%s/cgi-bin/classes.cgi",
1427 if (con->uri[8] && con->uri[9])
1428 cupsdSetString(&con->options, con->uri + 8);
1430 cupsdSetString(&con->options, NULL);
1432 else if (!strncmp(con->uri, "/jobs", 5))
1434 cupsdSetStringf(&con->command, "%s/cgi-bin/jobs.cgi",
1437 if (con->uri[5] && con->uri[6])
1438 cupsdSetString(&con->options, con->uri + 5);
1440 cupsdSetString(&con->options, NULL);
1444 cupsdSetStringf(&con->command, "%s/cgi-bin/help.cgi",
1447 if (con->uri[5] && con->uri[6])
1448 cupsdSetString(&con->options, con->uri + 5);
1450 cupsdSetString(&con->options, NULL);
1453 if (httpGetVersion(con->http) <= HTTP_VERSION_1_0)
1454 httpSetKeepAlive(con->http, HTTP_KEEPALIVE_OFF);
1462 if ((filename = get_file(con, &filestats, buf,
1463 sizeof(buf))) == NULL)
1465 if (!cupsdSendError(con, HTTP_STATUS_NOT_FOUND, CUPSD_AUTH_NONE))
1467 cupsdCloseClient(con);
1474 type = mimeFileType(MimeDatabase, filename, NULL, NULL);
1476 if (!is_cgi(con, filename, &filestats, type))
1479 * Only POST to CGI's...
1482 if (!cupsdSendError(con, HTTP_STATUS_UNAUTHORIZED, CUPSD_AUTH_NONE))
1484 cupsdCloseClient(con);
1491 case HTTP_STATE_PUT_RECV :
1493 * Validate the resource name...
1496 if (strcmp(con->uri, "/admin/conf/cupsd.conf"))
1499 * PUT can only be done to the cupsd.conf file...
1502 cupsdLogClient(con, CUPSD_LOG_ERROR,
1503 "Disallowed PUT request for \"%s\".", con->uri);
1505 if (!cupsdSendError(con, HTTP_STATUS_FORBIDDEN, CUPSD_AUTH_NONE))
1507 cupsdCloseClient(con);
1515 * See if the PUT request includes a Content-Length field, and if
1516 * so check the length against any limits that are set...
1519 if (httpGetField(con->http, HTTP_FIELD_CONTENT_LENGTH)[0] &&
1520 MaxRequestSize > 0 &&
1521 httpGetLength2(con->http) > MaxRequestSize)
1524 * Request too large...
1527 if (!cupsdSendError(con, HTTP_STATUS_REQUEST_TOO_LARGE, CUPSD_AUTH_NONE))
1529 cupsdCloseClient(con);
1535 else if (httpGetLength2(con->http) < 0)
1538 * Negative content lengths are invalid!
1541 if (!cupsdSendError(con, HTTP_STATUS_BAD_REQUEST, CUPSD_AUTH_NONE))
1543 cupsdCloseClient(con);
1551 * Open a temporary file to hold the request...
1554 cupsdSetStringf(&con->filename, "%s/%08x", RequestRoot,
1556 con->file = open(con->filename, O_WRONLY | O_CREAT | O_TRUNC, 0640);
1560 cupsdLogClient(con, CUPSD_LOG_ERROR,
1561 "Unable to create request file \"%s\": %s",
1562 con->filename, strerror(errno));
1564 if (!cupsdSendError(con, HTTP_STATUS_REQUEST_TOO_LARGE, CUPSD_AUTH_NONE))
1566 cupsdCloseClient(con);
1571 fchmod(con->file, 0640);
1572 fchown(con->file, RunUser, Group);
1573 fcntl(con->file, F_SETFD, fcntl(con->file, F_GETFD) | FD_CLOEXEC);
1576 case HTTP_STATE_DELETE :
1577 case HTTP_STATE_TRACE :
1578 cupsdSendError(con, HTTP_STATUS_NOT_IMPLEMENTED, CUPSD_AUTH_NONE);
1579 cupsdCloseClient(con);
1582 case HTTP_STATE_HEAD :
1583 if (!strncmp(con->uri, "/printers/", 10) &&
1584 !strcmp(con->uri + strlen(con->uri) - 4, ".ppd"))
1587 * Send PPD file - get the real printer name since printer
1588 * names are not case sensitive but filenames can be...
1591 con->uri[strlen(con->uri) - 4] = '\0'; /* Drop ".ppd" */
1593 if ((p = cupsdFindPrinter(con->uri + 10)) != NULL)
1594 snprintf(con->uri, sizeof(con->uri), "/ppd/%s.ppd", p->name);
1597 if (!cupsdSendError(con, HTTP_STATUS_NOT_FOUND, CUPSD_AUTH_NONE))
1599 cupsdCloseClient(con);
1603 cupsdLogRequest(con, HTTP_STATUS_NOT_FOUND);
1607 else if (!strncmp(con->uri, "/printers/", 10) &&
1608 !strcmp(con->uri + strlen(con->uri) - 4, ".png"))
1611 * Send PNG file - get the real printer name since printer
1612 * names are not case sensitive but filenames can be...
1615 con->uri[strlen(con->uri) - 4] = '\0'; /* Drop ".ppd" */
1617 if ((p = cupsdFindPrinter(con->uri + 10)) != NULL)
1618 snprintf(con->uri, sizeof(con->uri), "/icons/%s.png", p->name);
1621 if (!cupsdSendError(con, HTTP_STATUS_NOT_FOUND, CUPSD_AUTH_NONE))
1623 cupsdCloseClient(con);
1627 cupsdLogRequest(con, HTTP_STATUS_NOT_FOUND);
1631 else if (!WebInterface)
1633 httpClearFields(con->http);
1635 if (!cupsdSendHeader(con, HTTP_STATUS_OK, NULL, CUPSD_AUTH_NONE))
1637 cupsdCloseClient(con);
1641 cupsdLogRequest(con, HTTP_STATUS_OK);
1645 if ((!strncmp(con->uri, "/admin", 6) && strcmp(con->uri, "/admin/conf/cupsd.conf") && strncmp(con->uri, "/admin/log/", 11)) ||
1646 !strncmp(con->uri, "/printers", 9) ||
1647 !strncmp(con->uri, "/classes", 8) ||
1648 !strncmp(con->uri, "/help", 5) ||
1649 !strncmp(con->uri, "/jobs", 5))
1655 httpClearFields(con->http);
1657 if (!cupsdSendHeader(con, HTTP_STATUS_OK, "text/html", CUPSD_AUTH_NONE))
1659 cupsdCloseClient(con);
1663 cupsdLogRequest(con, HTTP_STATUS_OK);
1665 else if (!strncmp(con->uri, "/admin/log/", 11) && (strchr(con->uri + 11, '/') || strlen(con->uri) == 11))
1668 * HEAD can only be done to configuration files under
1672 cupsdLogClient(con, CUPSD_LOG_ERROR,
1673 "Request for subdirectory \"%s\".", con->uri);
1675 if (!cupsdSendError(con, HTTP_STATUS_FORBIDDEN, CUPSD_AUTH_NONE))
1677 cupsdCloseClient(con);
1681 cupsdLogRequest(con, HTTP_STATUS_FORBIDDEN);
1684 else if ((filename = get_file(con, &filestats, buf,
1685 sizeof(buf))) == NULL)
1687 httpClearFields(con->http);
1689 if (!cupsdSendHeader(con, HTTP_STATUS_NOT_FOUND, "text/html",
1692 cupsdCloseClient(con);
1696 cupsdLogRequest(con, HTTP_STATUS_NOT_FOUND);
1698 else if (!check_if_modified(con, &filestats))
1700 if (!cupsdSendError(con, HTTP_STATUS_NOT_MODIFIED, CUPSD_AUTH_NONE))
1702 cupsdCloseClient(con);
1706 cupsdLogRequest(con, HTTP_STATUS_NOT_MODIFIED);
1714 type = mimeFileType(MimeDatabase, filename, NULL, NULL);
1716 strlcpy(line, "text/plain", sizeof(line));
1718 snprintf(line, sizeof(line), "%s/%s", type->super, type->type);
1720 httpClearFields(con->http);
1722 httpSetField(con->http, HTTP_FIELD_LAST_MODIFIED,
1723 httpGetDateString(filestats.st_mtime));
1724 httpSetLength(con->http, (size_t)filestats.st_size);
1726 if (!cupsdSendHeader(con, HTTP_STATUS_OK, line, CUPSD_AUTH_NONE))
1728 cupsdCloseClient(con);
1732 cupsdLogRequest(con, HTTP_STATUS_OK);
1737 break; /* Anti-compiler-warning-code */
1743 * Handle any incoming data...
1746 switch (httpGetState(con->http))
1748 case HTTP_STATE_PUT_RECV :
1751 if ((bytes = httpRead2(con->http, line, sizeof(line))) < 0)
1753 if (httpError(con->http) && httpError(con->http) != EPIPE)
1754 cupsdLogClient(con, CUPSD_LOG_DEBUG,
1755 "HTTP_STATE_PUT_RECV Closing for error %d (%s)",
1756 httpError(con->http), strerror(httpError(con->http)));
1758 cupsdLogClient(con, CUPSD_LOG_DEBUG,
1759 "HTTP_STATE_PUT_RECV Closing on EOF.");
1761 cupsdCloseClient(con);
1766 con->bytes += bytes;
1768 if (MaxRequestSize > 0 && con->bytes > MaxRequestSize)
1772 unlink(con->filename);
1773 cupsdClearString(&con->filename);
1775 if (!cupsdSendError(con, HTTP_STATUS_REQUEST_TOO_LARGE, CUPSD_AUTH_NONE))
1777 cupsdCloseClient(con);
1782 if (write(con->file, line, (size_t)bytes) < bytes)
1784 cupsdLogClient(con, CUPSD_LOG_ERROR,
1785 "Unable to write %d bytes to \"%s\": %s", bytes,
1786 con->filename, strerror(errno));
1790 unlink(con->filename);
1791 cupsdClearString(&con->filename);
1793 if (!cupsdSendError(con, HTTP_STATUS_REQUEST_TOO_LARGE, CUPSD_AUTH_NONE))
1795 cupsdCloseClient(con);
1800 else if (httpGetState(con->http) == HTTP_STATE_PUT_RECV)
1802 cupsdCloseClient(con);
1806 while (httpGetState(con->http) == HTTP_STATE_PUT_RECV && httpGetReady(con->http));
1808 if (httpGetState(con->http) == HTTP_STATE_STATUS)
1811 * End of file, see how big it is...
1814 fstat(con->file, &filestats);
1819 if (filestats.st_size > MaxRequestSize &&
1823 * Request is too big; remove it and send an error...
1826 unlink(con->filename);
1827 cupsdClearString(&con->filename);
1829 if (!cupsdSendError(con, HTTP_STATUS_REQUEST_TOO_LARGE, CUPSD_AUTH_NONE))
1831 cupsdCloseClient(con);
1837 * Install the configuration file...
1840 status = install_cupsd_conf(con);
1843 * Return the status to the client...
1846 if (!cupsdSendError(con, status, CUPSD_AUTH_NONE))
1848 cupsdCloseClient(con);
1854 case HTTP_STATE_POST_RECV :
1857 if (con->request && con->file < 0)
1860 * Grab any request data from the connection...
1863 if (!httpWait(con->http, 0))
1866 if ((ipp_state = ippRead(con->http, con->request)) == IPP_STATE_ERROR)
1868 cupsdLogClient(con, CUPSD_LOG_ERROR, "IPP read error: %s",
1869 cupsLastErrorString());
1871 cupsdSendError(con, HTTP_STATUS_BAD_REQUEST, CUPSD_AUTH_NONE);
1872 cupsdCloseClient(con);
1875 else if (ipp_state != IPP_STATE_DATA)
1877 if (httpGetState(con->http) == HTTP_STATE_POST_SEND)
1879 cupsdSendError(con, HTTP_STATUS_BAD_REQUEST, CUPSD_AUTH_NONE);
1880 cupsdCloseClient(con);
1884 if (httpGetReady(con->http))
1890 cupsdLogClient(con, CUPSD_LOG_DEBUG, "%d.%d %s %d",
1891 con->request->request.op.version[0],
1892 con->request->request.op.version[1],
1893 ippOpString(con->request->request.op.operation_id),
1894 con->request->request.op.request_id);
1895 con->bytes += (off_t)ippLength(con->request);
1899 if (con->file < 0 && httpGetState(con->http) != HTTP_STATE_POST_SEND)
1902 * Create a file as needed for the request data...
1905 cupsdSetStringf(&con->filename, "%s/%08x", RequestRoot,
1907 con->file = open(con->filename, O_WRONLY | O_CREAT | O_TRUNC, 0640);
1911 cupsdLogClient(con, CUPSD_LOG_ERROR,
1912 "Unable to create request file \"%s\": %s",
1913 con->filename, strerror(errno));
1915 if (!cupsdSendError(con, HTTP_STATUS_REQUEST_TOO_LARGE, CUPSD_AUTH_NONE))
1917 cupsdCloseClient(con);
1922 fchmod(con->file, 0640);
1923 fchown(con->file, RunUser, Group);
1924 fcntl(con->file, F_SETFD, fcntl(con->file, F_GETFD) | FD_CLOEXEC);
1927 if (httpGetState(con->http) != HTTP_STATE_POST_SEND)
1929 if (!httpWait(con->http, 0))
1931 else if ((bytes = httpRead2(con->http, line, sizeof(line))) < 0)
1933 if (httpError(con->http) && httpError(con->http) != EPIPE)
1934 cupsdLogClient(con, CUPSD_LOG_DEBUG,
1935 "HTTP_STATE_POST_SEND Closing for error %d (%s)",
1936 httpError(con->http), strerror(httpError(con->http)));
1938 cupsdLogClient(con, CUPSD_LOG_DEBUG,
1939 "HTTP_STATE_POST_SEND Closing on EOF.");
1941 cupsdCloseClient(con);
1946 con->bytes += bytes;
1948 if (MaxRequestSize > 0 && con->bytes > MaxRequestSize)
1952 unlink(con->filename);
1953 cupsdClearString(&con->filename);
1955 if (!cupsdSendError(con, HTTP_STATUS_REQUEST_TOO_LARGE, CUPSD_AUTH_NONE))
1957 cupsdCloseClient(con);
1962 if (write(con->file, line, (size_t)bytes) < bytes)
1964 cupsdLogClient(con, CUPSD_LOG_ERROR,
1965 "Unable to write %d bytes to \"%s\": %s",
1966 bytes, con->filename, strerror(errno));
1970 unlink(con->filename);
1971 cupsdClearString(&con->filename);
1973 if (!cupsdSendError(con, HTTP_STATUS_REQUEST_TOO_LARGE,
1976 cupsdCloseClient(con);
1981 else if (httpGetState(con->http) == HTTP_STATE_POST_RECV)
1983 else if (httpGetState(con->http) != HTTP_STATE_POST_SEND)
1985 cupsdLogClient(con, CUPSD_LOG_DEBUG,
1986 "Closing on unexpected state %s.",
1987 httpStateString(httpGetState(con->http)));
1988 cupsdCloseClient(con);
1993 while (httpGetState(con->http) == HTTP_STATE_POST_RECV && httpGetReady(con->http));
1995 if (httpGetState(con->http) == HTTP_STATE_POST_SEND)
1999 fstat(con->file, &filestats);
2004 if (filestats.st_size > MaxRequestSize &&
2008 * Request is too big; remove it and send an error...
2011 unlink(con->filename);
2012 cupsdClearString(&con->filename);
2017 * Delete any IPP request data...
2020 ippDelete(con->request);
2021 con->request = NULL;
2024 if (!cupsdSendError(con, HTTP_STATUS_REQUEST_TOO_LARGE, CUPSD_AUTH_NONE))
2026 cupsdCloseClient(con);
2030 else if (filestats.st_size == 0)
2033 * Don't allow empty file...
2036 unlink(con->filename);
2037 cupsdClearString(&con->filename);
2042 if (!cupsdSendCommand(con, con->command, con->options, 0))
2044 if (!cupsdSendError(con, HTTP_STATUS_NOT_FOUND, CUPSD_AUTH_NONE))
2046 cupsdCloseClient(con);
2051 cupsdLogRequest(con, HTTP_STATUS_OK);
2057 cupsdProcessIPPRequest(con);
2061 unlink(con->filename);
2062 cupsdClearString(&con->filename);
2071 break; /* Anti-compiler-warning-code */
2074 if (httpGetState(con->http) == HTTP_STATE_WAITING)
2076 if (!httpGetKeepAlive(con->http))
2078 cupsdLogClient(con, CUPSD_LOG_DEBUG,
2079 "Closing because Keep-Alive is disabled.");
2080 cupsdCloseClient(con);
2084 cupsArrayRemove(ActiveClients, con);
2085 cupsdSetBusyState();
2092 * 'cupsdSendCommand()' - Send output from a command via HTTP.
2095 int /* O - 1 on success, 0 on failure */
2097 cupsd_client_t *con, /* I - Client connection */
2098 char *command, /* I - Command to run */
2099 char *options, /* I - Command-line options */
2100 int root) /* I - Run as root? */
2102 int fd; /* Standard input file descriptor */
2107 fd = open(con->filename, O_RDONLY);
2111 cupsdLogClient(con, CUPSD_LOG_ERROR,
2112 "Unable to open \"%s\" for reading: %s",
2113 con->filename ? con->filename : "/dev/null",
2118 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC);
2123 con->pipe_pid = pipe_command(con, fd, &(con->file), command, options, root);
2124 con->pipe_status = HTTP_STATUS_OK;
2126 httpClearFields(con->http);
2131 cupsdLogClient(con, CUPSD_LOG_INFO, "Started \"%s\" (pid=%d, file=%d)",
2132 command, con->pipe_pid, con->file);
2134 if (con->pipe_pid == 0)
2137 fcntl(con->file, F_SETFD, fcntl(con->file, F_GETFD) | FD_CLOEXEC);
2139 cupsdAddSelect(con->file, (cupsd_selfunc_t)write_pipe, NULL, con);
2141 cupsdLogClient(con, CUPSD_LOG_DEBUG, "Waiting for CGI data.");
2143 con->sent_header = 0;
2144 con->file_ready = 0;
2145 con->got_fields = 0;
2146 con->header_used = 0;
2153 * 'cupsdSendError()' - Send an error message via HTTP.
2156 int /* O - 1 if successful, 0 otherwise */
2157 cupsdSendError(cupsd_client_t *con, /* I - Connection */
2158 http_status_t code, /* I - Error code */
2159 int auth_type)/* I - Authentication type */
2161 char location[HTTP_MAX_VALUE]; /* Location field */
2164 cupsdLogClient(con, CUPSD_LOG_DEBUG2, "cupsdSendError code=%d, auth_type=%d", code, auth_type);
2168 * Force client to upgrade for authentication if that is how the
2169 * server is configured...
2172 if (code == HTTP_STATUS_UNAUTHORIZED &&
2173 DefaultEncryption == HTTP_ENCRYPTION_REQUIRED &&
2174 _cups_strcasecmp(httpGetHostname(con->http, NULL, 0), "localhost") &&
2175 !httpIsEncrypted(con->http))
2177 code = HTTP_STATUS_UPGRADE_REQUIRED;
2179 #endif /* HAVE_SSL */
2182 * Put the request in the access_log file...
2185 cupsdLogRequest(con, code);
2188 * To work around bugs in some proxies, don't use Keep-Alive for some
2191 * Kerberos authentication doesn't work without Keep-Alive, so
2192 * never disable it in that case.
2195 strlcpy(location, httpGetField(con->http, HTTP_FIELD_LOCATION), sizeof(location));
2197 httpClearFields(con->http);
2199 httpSetField(con->http, HTTP_FIELD_LOCATION, location);
2201 if (code >= HTTP_STATUS_BAD_REQUEST && con->type != CUPSD_AUTH_NEGOTIATE)
2202 httpSetKeepAlive(con->http, HTTP_KEEPALIVE_OFF);
2204 if (httpGetVersion(con->http) >= HTTP_VERSION_1_1 &&
2205 httpGetKeepAlive(con->http) == HTTP_KEEPALIVE_OFF)
2206 httpSetField(con->http, HTTP_FIELD_CONNECTION, "close");
2208 if (code >= HTTP_STATUS_BAD_REQUEST)
2211 * Send a human-readable error message.
2214 char message[4096], /* Message for user */
2215 urltext[1024], /* URL redirection text */
2216 redirect[1024]; /* Redirection link */
2217 const char *text; /* Status-specific text */
2222 if (code == HTTP_STATUS_UNAUTHORIZED)
2223 text = _cupsLangString(con->language,
2224 _("Enter your username and password or the "
2225 "root username and password to access this "
2226 "page. If you are using Kerberos authentication, "
2227 "make sure you have a valid Kerberos ticket."));
2228 else if (code == HTTP_STATUS_UPGRADE_REQUIRED)
2232 snprintf(urltext, sizeof(urltext),
2233 _cupsLangString(con->language,
2234 _("You must access this page using the URL "
2235 "<A HREF=\"https://%s:%d%s\">"
2236 "https://%s:%d%s</A>.")),
2237 con->servername, con->serverport, con->uri,
2238 con->servername, con->serverport, con->uri);
2240 snprintf(redirect, sizeof(redirect),
2241 "<META HTTP-EQUIV=\"Refresh\" "
2242 "CONTENT=\"3;URL=https://%s:%d%s\">\n",
2243 con->servername, con->serverport, con->uri);
2245 else if (code == HTTP_STATUS_CUPS_WEBIF_DISABLED)
2246 text = _cupsLangString(con->language,
2247 _("The web interface is currently disabled. Run "
2248 "\"cupsctl WebInterface=yes\" to enable it."));
2252 snprintf(message, sizeof(message),
2253 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" "
2254 "\"http://www.w3.org/TR/html4/loose.dtd\">\n"
2257 "\t<META HTTP-EQUIV=\"Content-Type\" "
2258 "CONTENT=\"text/html; charset=utf-8\">\n"
2259 "\t<TITLE>%s - " CUPS_SVERSION "</TITLE>\n"
2260 "\t<LINK REL=\"STYLESHEET\" TYPE=\"text/css\" "
2261 "HREF=\"/cups.css\">\n"
2269 _httpStatus(con->language, code), redirect,
2270 _httpStatus(con->language, code), text);
2273 * Send an error message back to the client. If the error code is a
2274 * 400 or 500 series, make sure the message contains some text, too!
2277 size_t length = strlen(message); /* Length of message */
2279 httpSetLength(con->http, length);
2281 if (!cupsdSendHeader(con, code, "text/html", auth_type))
2284 if (httpWrite2(con->http, message, length) < 0)
2287 if (httpFlushWrite(con->http) < 0)
2292 httpSetField(con->http, HTTP_FIELD_CONTENT_LENGTH, "0");
2294 if (!cupsdSendHeader(con, code, NULL, auth_type))
2303 * 'cupsdSendHeader()' - Send an HTTP request.
2306 int /* O - 1 on success, 0 on failure */
2308 cupsd_client_t *con, /* I - Client to send to */
2309 http_status_t code, /* I - HTTP status code */
2310 char *type, /* I - MIME type of document */
2311 int auth_type) /* I - Type of authentication */
2313 char auth_str[1024]; /* Authorization string */
2316 cupsdLogClient(con, CUPSD_LOG_DEBUG, "cupsdSendHeader: code=%d, type=\"%s\", auth_type=%d", code, type, auth_type);
2319 * Send the HTTP status header...
2322 if (code == HTTP_STATUS_CUPS_WEBIF_DISABLED)
2325 * Treat our special "web interface is disabled" status as "200 OK" for web
2329 code = HTTP_STATUS_OK;
2333 httpSetField(con->http, HTTP_FIELD_SERVER, ServerHeader);
2335 if (code == HTTP_STATUS_METHOD_NOT_ALLOWED)
2336 httpSetField(con->http, HTTP_FIELD_ALLOW, "GET, HEAD, OPTIONS, POST, PUT");
2338 if (code == HTTP_STATUS_UNAUTHORIZED)
2340 if (auth_type == CUPSD_AUTH_NONE)
2342 if (!con->best || con->best->type <= CUPSD_AUTH_NONE)
2343 auth_type = cupsdDefaultAuthType();
2345 auth_type = con->best->type;
2350 if (auth_type == CUPSD_AUTH_BASIC)
2351 strlcpy(auth_str, "Basic realm=\"CUPS\"", sizeof(auth_str));
2353 else if (auth_type == CUPSD_AUTH_NEGOTIATE)
2356 if (httpAddrFamily(httpGetAddress(con->http)) == AF_LOCAL)
2357 strlcpy(auth_str, "Basic realm=\"CUPS\"", sizeof(auth_str));
2359 # endif /* AF_LOCAL */
2360 strlcpy(auth_str, "Negotiate", sizeof(auth_str));
2362 #endif /* HAVE_GSSAPI */
2364 if (con->best && auth_type != CUPSD_AUTH_NEGOTIATE &&
2365 !_cups_strcasecmp(httpGetHostname(con->http, NULL, 0), "localhost"))
2368 * Add a "trc" (try root certification) parameter for local non-Kerberos
2369 * requests when the request requires system group membership - then the
2370 * client knows the root certificate can/should be used.
2372 * Also, for macOS we also look for @AUTHKEY and add an "authkey"
2373 * parameter as needed...
2376 char *name, /* Current user name */
2377 *auth_key; /* Auth key buffer */
2378 size_t auth_size; /* Size of remaining buffer */
2380 auth_key = auth_str + strlen(auth_str);
2381 auth_size = sizeof(auth_str) - (size_t)(auth_key - auth_str);
2383 for (name = (char *)cupsArrayFirst(con->best->names);
2385 name = (char *)cupsArrayNext(con->best->names))
2387 #ifdef HAVE_AUTHORIZATION_H
2388 if (!_cups_strncasecmp(name, "@AUTHKEY(", 9))
2390 snprintf(auth_key, auth_size, ", authkey=\"%s\"", name + 9);
2391 /* end parenthesis is stripped in conf.c */
2395 #endif /* HAVE_AUTHORIZATION_H */
2396 if (!_cups_strcasecmp(name, "@SYSTEM"))
2398 #ifdef HAVE_AUTHORIZATION_H
2399 if (SystemGroupAuthKey)
2400 snprintf(auth_key, auth_size,
2402 SystemGroupAuthKey);
2405 strlcpy(auth_key, ", trc=\"y\"", auth_size);
2406 #endif /* HAVE_AUTHORIZATION_H */
2414 cupsdLogClient(con, CUPSD_LOG_DEBUG, "WWW-Authenticate: %s", auth_str);
2416 httpSetField(con->http, HTTP_FIELD_WWW_AUTHENTICATE, auth_str);
2420 if (con->language && strcmp(con->language->language, "C"))
2421 httpSetField(con->http, HTTP_FIELD_CONTENT_LANGUAGE, con->language->language);
2425 if (!strcmp(type, "text/html"))
2426 httpSetField(con->http, HTTP_FIELD_CONTENT_TYPE, "text/html; charset=utf-8");
2428 httpSetField(con->http, HTTP_FIELD_CONTENT_TYPE, type);
2431 return (!httpWriteResponse(con->http, code));
2436 * 'cupsdUpdateCGI()' - Read status messages from CGI scripts and programs.
2440 cupsdUpdateCGI(void)
2442 char *ptr, /* Pointer to end of line in buffer */
2443 message[1024]; /* Pointer to message text */
2444 int loglevel; /* Log level for message */
2447 while ((ptr = cupsdStatBufUpdate(CGIStatusBuffer, &loglevel,
2448 message, sizeof(message))) != NULL)
2450 if (loglevel == CUPSD_LOG_INFO)
2451 cupsdLogMessage(CUPSD_LOG_INFO, "%s", message);
2453 if (!strchr(CGIStatusBuffer->buffer, '\n'))
2457 if (ptr == NULL && !CGIStatusBuffer->bufused)
2460 * Fatal error on pipe - should never happen!
2463 cupsdLogMessage(CUPSD_LOG_CRIT,
2464 "cupsdUpdateCGI: error reading from CGI error pipe - %s",
2471 * 'cupsdWriteClient()' - Write data to a client as needed.
2475 cupsdWriteClient(cupsd_client_t *con) /* I - Client connection */
2477 int bytes, /* Number of bytes written */
2478 field_col; /* Current column */
2479 char *bufptr, /* Pointer into buffer */
2480 *bufend; /* Pointer to end of buffer */
2481 ipp_state_t ipp_state; /* IPP state value */
2484 cupsdLogClient(con, CUPSD_LOG_DEBUG, "con->http=%p", con->http);
2485 cupsdLogClient(con, CUPSD_LOG_DEBUG,
2490 "data_encoding=HTTP_ENCODING_%s, "
2491 "data_remaining=" CUPS_LLFMT ", "
2495 httpError(con->http), (int)httpGetReady(con->http),
2496 httpStateString(httpGetState(con->http)),
2497 httpIsChunked(con->http) ? "CHUNKED" : "LENGTH",
2498 CUPS_LLCAST httpGetLength2(con->http),
2500 con->response ? ippStateString(ippGetState(con->request)) : "",
2501 con->pipe_pid, con->file);
2503 if (httpGetState(con->http) != HTTP_STATE_GET_SEND &&
2504 httpGetState(con->http) != HTTP_STATE_POST_SEND)
2507 * If we get called in the wrong state, then something went wrong with the
2508 * connection and we need to shut it down...
2511 cupsdLogClient(con, CUPSD_LOG_DEBUG, "Closing on unexpected HTTP write state %s.",
2512 httpStateString(httpGetState(con->http)));
2513 cupsdCloseClient(con);
2520 * Make sure we select on the CGI output...
2523 cupsdAddSelect(con->file, (cupsd_selfunc_t)write_pipe, NULL, con);
2525 cupsdLogClient(con, CUPSD_LOG_DEBUG, "Waiting for CGI data.");
2527 if (!con->file_ready)
2530 * Try again later when there is CGI output available...
2533 cupsdRemoveSelect(httpGetFd(con->http));
2537 con->file_ready = 0;
2540 bytes = (ssize_t)(sizeof(con->header) - (size_t)con->header_used);
2542 if (!con->pipe_pid && bytes > (ssize_t)httpGetRemaining(con->http))
2545 * Limit GET bytes to original size of file (STR #3265)...
2548 bytes = (ssize_t)httpGetRemaining(con->http);
2551 if (con->response && con->response->state != IPP_STATE_DATA)
2553 size_t wused = httpGetPending(con->http); /* Previous write buffer use */
2558 * Write a single attribute or the IPP message header...
2561 ipp_state = ippWrite(con->http, con->response);
2564 * If the write buffer has been flushed, stop buffering up attributes...
2567 if (httpGetPending(con->http) <= wused)
2570 while (ipp_state != IPP_STATE_DATA && ipp_state != IPP_STATE_ERROR);
2572 cupsdLogClient(con, CUPSD_LOG_DEBUG,
2573 "Writing IPP response, ipp_state=%s, old "
2574 "wused=" CUPS_LLFMT ", new wused=" CUPS_LLFMT,
2575 ippStateString(ipp_state),
2576 CUPS_LLCAST wused, CUPS_LLCAST httpGetPending(con->http));
2578 if (httpGetPending(con->http) > 0)
2579 httpFlushWrite(con->http);
2581 bytes = ipp_state != IPP_STATE_ERROR &&
2582 (con->file >= 0 || ipp_state != IPP_STATE_DATA);
2584 cupsdLogClient(con, CUPSD_LOG_DEBUG,
2585 "bytes=%d, http_state=%d, data_remaining=" CUPS_LLFMT,
2586 (int)bytes, httpGetState(con->http),
2587 CUPS_LLCAST httpGetLength2(con->http));
2589 else if ((bytes = read(con->file, con->header + con->header_used, (size_t)bytes)) > 0)
2591 con->header_used += bytes;
2593 if (con->pipe_pid && !con->got_fields)
2596 * Inspect the data for Content-Type and other fields.
2599 for (bufptr = con->header, bufend = con->header + con->header_used,
2601 !con->got_fields && bufptr < bufend;
2604 if (*bufptr == '\n')
2607 * Send line to client...
2610 if (bufptr > con->header && bufptr[-1] == '\r')
2614 cupsdLogClient(con, CUPSD_LOG_DEBUG, "Script header: %s", con->header);
2616 if (!con->sent_header)
2619 * Handle redirection and CGI status codes...
2622 http_field_t field; /* HTTP field */
2623 char *value = strchr(con->header, ':');
2624 /* Value of field */
2629 while (isspace(*value & 255))
2633 field = httpFieldValue(con->header);
2635 if (field != HTTP_FIELD_UNKNOWN && value)
2637 httpSetField(con->http, field, value);
2639 if (field == HTTP_FIELD_LOCATION)
2641 con->pipe_status = HTTP_STATUS_SEE_OTHER;
2642 con->sent_header = 2;
2645 con->sent_header = 1;
2647 else if (!_cups_strcasecmp(con->header, "Status") && value)
2649 con->pipe_status = (http_status_t)atoi(value);
2650 con->sent_header = 2;
2652 else if (!_cups_strcasecmp(con->header, "Set-Cookie") && value)
2654 httpSetCookie(con->http, value);
2655 con->sent_header = 1;
2663 con->header_used -= bufptr - con->header;
2665 if (con->header_used > 0)
2666 memmove(con->header, bufptr, (size_t)con->header_used);
2668 bufptr = con->header - 1;
2671 * See if the line was empty...
2676 con->got_fields = 1;
2678 if (httpGetVersion(con->http) == HTTP_VERSION_1_1 &&
2679 !httpGetField(con->http, HTTP_FIELD_CONTENT_LENGTH)[0])
2680 httpSetLength(con->http, 0);
2682 cupsdLogClient(con, CUPSD_LOG_DEBUG, "Sending status %d for CGI.", con->pipe_status);
2684 if (con->pipe_status == HTTP_STATUS_OK)
2686 if (!cupsdSendHeader(con, con->pipe_status, NULL, CUPSD_AUTH_NONE))
2688 cupsdCloseClient(con);
2694 if (!cupsdSendError(con, con->pipe_status, CUPSD_AUTH_NONE))
2696 cupsdCloseClient(con);
2704 else if (*bufptr != '\r')
2708 if (!con->got_fields)
2712 if (con->header_used > 0)
2714 if (httpWrite2(con->http, con->header, (size_t)con->header_used) < 0)
2716 cupsdLogClient(con, CUPSD_LOG_DEBUG, "Closing for error %d (%s)",
2717 httpError(con->http), strerror(httpError(con->http)));
2718 cupsdCloseClient(con);
2722 if (httpIsChunked(con->http))
2723 httpFlushWrite(con->http);
2725 con->bytes += con->header_used;
2727 if (httpGetState(con->http) == HTTP_STATE_WAITING)
2730 bytes = con->header_used;
2732 con->header_used = 0;
2737 (httpGetState(con->http) != HTTP_STATE_GET_SEND &&
2738 httpGetState(con->http) != HTTP_STATE_POST_SEND))
2740 if (!con->sent_header && con->pipe_pid)
2741 cupsdSendError(con, HTTP_STATUS_SERVER_ERROR, CUPSD_AUTH_NONE);
2744 cupsdLogRequest(con, HTTP_STATUS_OK);
2746 if (httpIsChunked(con->http) && (!con->pipe_pid || con->sent_header > 0))
2748 cupsdLogClient(con, CUPSD_LOG_DEBUG, "Sending 0-length chunk.");
2750 if (httpWrite2(con->http, "", 0) < 0)
2752 cupsdLogClient(con, CUPSD_LOG_DEBUG, "Closing for error %d (%s)",
2753 httpError(con->http), strerror(httpError(con->http)));
2754 cupsdCloseClient(con);
2759 cupsdLogClient(con, CUPSD_LOG_DEBUG, "Flushing write buffer.");
2760 httpFlushWrite(con->http);
2761 cupsdLogClient(con, CUPSD_LOG_DEBUG, "New state is %s", httpStateString(httpGetState(con->http)));
2764 cupsdAddSelect(httpGetFd(con->http), (cupsd_selfunc_t)cupsdReadClient, NULL, con);
2766 cupsdLogClient(con, CUPSD_LOG_DEBUG, "Waiting for request.");
2770 cupsdRemoveSelect(con->file);
2773 cupsdEndProcess(con->pipe_pid, 0);
2782 unlink(con->filename);
2783 cupsdClearString(&con->filename);
2788 ippDelete(con->request);
2789 con->request = NULL;
2794 ippDelete(con->response);
2795 con->response = NULL;
2798 cupsdClearString(&con->command);
2799 cupsdClearString(&con->options);
2800 cupsdClearString(&con->query_string);
2802 if (!httpGetKeepAlive(con->http))
2804 cupsdLogClient(con, CUPSD_LOG_DEBUG,
2805 "Closing because Keep-Alive is disabled.");
2806 cupsdCloseClient(con);
2811 cupsArrayRemove(ActiveClients, con);
2812 cupsdSetBusyState();
2819 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
2822 static int /* O - 1 if modified since */
2824 cupsd_client_t *con, /* I - Client connection */
2825 struct stat *filestats) /* I - File information */
2827 const char *ptr; /* Pointer into field */
2828 time_t date; /* Time/date value */
2829 off_t size; /* Size/length value */
2834 ptr = httpGetField(con->http, HTTP_FIELD_IF_MODIFIED_SINCE);
2839 cupsdLogClient(con, CUPSD_LOG_DEBUG2, "check_if_modified: filestats=%p(" CUPS_LLFMT ", %d)) If-Modified-Since=\"%s\"", filestats, CUPS_LLCAST filestats->st_size, (int)filestats->st_mtime, ptr);
2841 while (*ptr != '\0')
2843 while (isspace(*ptr) || *ptr == ';')
2846 if (_cups_strncasecmp(ptr, "length=", 7) == 0)
2849 size = strtoll(ptr, NULL, 10);
2851 while (isdigit(*ptr))
2854 else if (isalpha(*ptr))
2856 date = httpGetDateTime(ptr);
2857 while (*ptr != '\0' && *ptr != ';')
2864 return ((size != filestats->st_size && size != 0) ||
2865 (date < filestats->st_mtime && date != 0) ||
2866 (size == 0 && date == 0));
2871 * 'compare_clients()' - Compare two client connections.
2874 static int /* O - Result of comparison */
2875 compare_clients(cupsd_client_t *a, /* I - First client */
2876 cupsd_client_t *b, /* I - Second client */
2877 void *data) /* I - User data (not used) */
2892 * 'cupsd_start_tls()' - Start encryption on a connection.
2895 static int /* O - 0 on success, -1 on error */
2896 cupsd_start_tls(cupsd_client_t *con, /* I - Client connection */
2897 http_encryption_t e) /* I - Encryption mode */
2899 if (httpEncryption(con->http, e))
2901 cupsdLogClient(con, CUPSD_LOG_ERROR, "Unable to encrypt connection: %s",
2902 cupsLastErrorString());
2906 cupsdLogClient(con, CUPSD_LOG_DEBUG, "Connection now encrypted.");
2909 #endif /* HAVE_SSL */
2913 * 'get_file()' - Get a filename and state info.
2916 static char * /* O - Real filename */
2917 get_file(cupsd_client_t *con, /* I - Client connection */
2918 struct stat *filestats, /* O - File information */
2919 char *filename, /* IO - Filename buffer */
2920 size_t len) /* I - Buffer length */
2922 int status; /* Status of filesystem calls */
2923 char *ptr; /* Pointer info filename */
2924 size_t plen; /* Remaining length after pointer */
2925 char language[7], /* Language subdirectory, if any */
2926 dest[1024]; /* Destination name */
2927 int perm_check = 1; /* Do permissions check? */
2931 * Figure out the real filename...
2936 if (!strncmp(con->uri, "/ppd/", 5) && !strchr(con->uri + 5, '/'))
2938 strlcpy(dest, con->uri + 5, sizeof(dest));
2939 ptr = dest + strlen(dest) - 4;
2941 if (ptr <= dest || strcmp(ptr, ".ppd"))
2943 cupsdLogClient(con, CUPSD_LOG_INFO, "Disallowed path \"%s\".", con->uri);
2948 if (!cupsdFindPrinter(dest))
2950 cupsdLogClient(con, CUPSD_LOG_INFO, "No printer \"%s\" found.", dest);
2954 snprintf(filename, len, "%s%s", ServerRoot, con->uri);
2958 else if (!strncmp(con->uri, "/icons/", 7) && !strchr(con->uri + 7, '/'))
2960 strlcpy(dest, con->uri + 7, sizeof(dest));
2961 ptr = dest + strlen(dest) - 4;
2963 if (ptr <= dest || strcmp(ptr, ".png"))
2965 cupsdLogClient(con, CUPSD_LOG_INFO, "Disallowed path \"%s\".", con->uri);
2970 if (!cupsdFindDest(dest))
2972 cupsdLogClient(con, CUPSD_LOG_INFO, "No printer \"%s\" found.", dest);
2976 snprintf(filename, len, "%s/%s.png", CacheDir, dest);
2977 if (access(filename, F_OK) < 0)
2978 snprintf(filename, len, "%s/images/generic.png", DocumentRoot);
2982 else if (!strncmp(con->uri, "/rss/", 5) && !strchr(con->uri + 5, '/'))
2983 snprintf(filename, len, "%s/rss/%s", CacheDir, con->uri + 5);
2984 else if (!strcmp(con->uri, "/admin/conf/cupsd.conf"))
2986 strlcpy(filename, ConfigurationFile, len);
2990 else if (!strncmp(con->uri, "/admin/log/", 11))
2992 if (!strncmp(con->uri + 11, "access_log", 10) && AccessLog[0] == '/')
2993 strlcpy(filename, AccessLog, len);
2994 else if (!strncmp(con->uri + 11, "error_log", 9) && ErrorLog[0] == '/')
2995 strlcpy(filename, ErrorLog, len);
2996 else if (!strncmp(con->uri + 11, "page_log", 8) && PageLog[0] == '/')
2997 strlcpy(filename, PageLog, len);
3003 else if (con->language)
3005 snprintf(language, sizeof(language), "/%s", con->language->language);
3006 snprintf(filename, len, "%s%s%s", DocumentRoot, language, con->uri);
3009 snprintf(filename, len, "%s%s", DocumentRoot, con->uri);
3011 if ((ptr = strchr(filename, '?')) != NULL)
3015 * Grab the status for this language; if there isn't a language-specific file
3016 * then fallback to the default one...
3019 if ((status = lstat(filename, filestats)) != 0 && language[0] &&
3020 strncmp(con->uri, "/icons/", 7) &&
3021 strncmp(con->uri, "/ppd/", 5) &&
3022 strncmp(con->uri, "/rss/", 5) &&
3023 strncmp(con->uri, "/admin/conf/", 12) &&
3024 strncmp(con->uri, "/admin/log/", 11))
3027 * Drop the country code...
3031 snprintf(filename, len, "%s%s%s", DocumentRoot, language, con->uri);
3033 if ((ptr = strchr(filename, '?')) != NULL)
3036 if ((status = lstat(filename, filestats)) != 0)
3039 * Drop the language prefix and try the root directory...
3043 snprintf(filename, len, "%s%s", DocumentRoot, con->uri);
3045 if ((ptr = strchr(filename, '?')) != NULL)
3048 status = lstat(filename, filestats);
3053 * If we've found a symlink, 404 the sucker to avoid disclosing information.
3056 if (!status && S_ISLNK(filestats->st_mode))
3058 cupsdLogClient(con, CUPSD_LOG_INFO, "Symlinks such as \"%s\" are not allowed.", filename);
3063 * Similarly, if the file/directory does not have world read permissions, do
3064 * not allow access...
3067 if (!status && perm_check && !(filestats->st_mode & S_IROTH))
3069 cupsdLogClient(con, CUPSD_LOG_INFO, "Files/directories such as \"%s\" must be world-readable.", filename);
3074 * If we've found a directory, get the index.html file instead...
3077 if (!status && S_ISDIR(filestats->st_mode))
3080 * Make sure the URI ends with a slash...
3083 if (con->uri[strlen(con->uri) - 1] != '/')
3084 strlcat(con->uri, "/", sizeof(con->uri));
3087 * Find the directory index file, trying every language...
3092 if (status && language[0])
3095 * Try a different language subset...
3099 language[0] = '\0'; /* Strip country code */
3101 language[0] = '\0'; /* Strip language */
3105 * Look for the index file...
3108 snprintf(filename, len, "%s%s%s", DocumentRoot, language, con->uri);
3110 if ((ptr = strchr(filename, '?')) != NULL)
3113 ptr = filename + strlen(filename);
3114 plen = len - (size_t)(ptr - filename);
3116 strlcpy(ptr, "index.html", plen);
3117 status = lstat(filename, filestats);
3122 strlcpy(ptr, "index.class", plen);
3123 status = lstat(filename, filestats);
3125 #endif /* HAVE_JAVA */
3130 strlcpy(ptr, "index.pl", plen);
3131 status = lstat(filename, filestats);
3133 #endif /* HAVE_PERL */
3138 strlcpy(ptr, "index.php", plen);
3139 status = lstat(filename, filestats);
3141 #endif /* HAVE_PHP */
3146 strlcpy(ptr, "index.pyc", plen);
3147 status = lstat(filename, filestats);
3152 strlcpy(ptr, "index.py", plen);
3153 status = lstat(filename, filestats);
3155 #endif /* HAVE_PYTHON */
3158 while (status && language[0]);
3161 * If we've found a symlink, 404 the sucker to avoid disclosing information.
3164 if (!status && S_ISLNK(filestats->st_mode))
3166 cupsdLogClient(con, CUPSD_LOG_INFO, "Symlinks such as \"%s\" are not allowed.", filename);
3171 * Similarly, if the file/directory does not have world read permissions, do
3172 * not allow access...
3175 if (!status && perm_check && !(filestats->st_mode & S_IROTH))
3177 cupsdLogClient(con, CUPSD_LOG_INFO, "Files/directories such as \"%s\" must be world-readable.", filename);
3182 cupsdLogClient(con, CUPSD_LOG_DEBUG2, "get_file: filestats=%p, filename=%p, len=" CUPS_LLFMT ", returning \"%s\".", filestats, filename, CUPS_LLCAST len, status ? "(null)" : filename);
3192 * 'install_cupsd_conf()' - Install a configuration file.
3195 static http_status_t /* O - Status */
3196 install_cupsd_conf(cupsd_client_t *con) /* I - Connection */
3198 char filename[1024]; /* Configuration filename */
3199 cups_file_t *in, /* Input file */
3200 *out; /* Output file */
3201 char buffer[16384]; /* Copy buffer */
3202 ssize_t bytes; /* Number of bytes */
3206 * Open the request file...
3209 if ((in = cupsFileOpen(con->filename, "rb")) == NULL)
3211 cupsdLogClient(con, CUPSD_LOG_ERROR, "Unable to open request file \"%s\": %s",
3212 con->filename, strerror(errno));
3217 * Open the new config file...
3220 if ((out = cupsdCreateConfFile(ConfigurationFile, ConfigFilePerm)) == NULL)
3226 cupsdLogClient(con, CUPSD_LOG_INFO, "Installing config file \"%s\"...",
3230 * Copy from the request to the new config file...
3233 while ((bytes = cupsFileRead(in, buffer, sizeof(buffer))) > 0)
3234 if (cupsFileWrite(out, buffer, (size_t)bytes) < bytes)
3236 cupsdLogClient(con, CUPSD_LOG_ERROR,
3237 "Unable to copy to config file \"%s\": %s",
3238 ConfigurationFile, strerror(errno));
3243 snprintf(filename, sizeof(filename), "%s.N", ConfigurationFile);
3244 cupsdUnlinkOrRemoveFile(filename);
3250 * Close the files...
3255 if (cupsdCloseCreatedConfFile(out, ConfigurationFile))
3259 * Remove the request file...
3262 cupsdUnlinkOrRemoveFile(con->filename);
3263 cupsdClearString(&con->filename);
3266 * Set the NeedReload flag...
3269 NeedReload = RELOAD_CUPSD;
3270 ReloadTime = time(NULL);
3273 * Return that the file was created successfully...
3276 return (HTTP_STATUS_CREATED);
3279 * Common exit for errors...
3284 cupsdUnlinkOrRemoveFile(con->filename);
3285 cupsdClearString(&con->filename);
3287 return (HTTP_STATUS_SERVER_ERROR);
3292 * 'is_cgi()' - Is the resource a CGI script/program?
3295 static int /* O - 1 = CGI, 0 = file */
3296 is_cgi(cupsd_client_t *con, /* I - Client connection */
3297 const char *filename, /* I - Real filename */
3298 struct stat *filestats, /* I - File information */
3299 mime_type_t *type) /* I - MIME type */
3301 const char *options; /* Options on URL */
3305 * Get the options, if any...
3308 if ((options = strchr(con->uri, '?')) != NULL)
3311 cupsdSetStringf(&(con->query_string), "QUERY_STRING=%s", options);
3315 * Check for known types...
3318 if (!type || _cups_strcasecmp(type->super, "application"))
3320 cupsdLogClient(con, CUPSD_LOG_DEBUG2, "is_cgi: filename=\"%s\", filestats=%p, type=%s/%s, returning 0.", filename, filestats, type ? type->super : "unknown", type ? type->type : "unknown");
3324 if (!_cups_strcasecmp(type->type, "x-httpd-cgi") &&
3325 (filestats->st_mode & 0111))
3328 * "application/x-httpd-cgi" is a CGI script.
3331 cupsdSetString(&con->command, filename);
3334 cupsdSetStringf(&con->options, " %s", options);
3336 cupsdLogClient(con, CUPSD_LOG_DEBUG2, "is_cgi: filename=\"%s\", filestats=%p, type=%s/%s, returning 1.", filename, filestats, type->super, type->type);
3340 else if (!_cups_strcasecmp(type->type, "x-httpd-java"))
3343 * "application/x-httpd-java" is a Java servlet.
3346 cupsdSetString(&con->command, CUPS_JAVA);
3349 cupsdSetStringf(&con->options, " %s %s", filename, options);
3351 cupsdSetStringf(&con->options, " %s", filename);
3353 cupsdLogClient(con, CUPSD_LOG_DEBUG2, "is_cgi: filename=\"%s\", filestats=%p, type=%s/%s, returning 1.", filename, filestats, type->super, type->type);
3356 #endif /* HAVE_JAVA */
3358 else if (!_cups_strcasecmp(type->type, "x-httpd-perl"))
3361 * "application/x-httpd-perl" is a Perl page.
3364 cupsdSetString(&con->command, CUPS_PERL);
3367 cupsdSetStringf(&con->options, " %s %s", filename, options);
3369 cupsdSetStringf(&con->options, " %s", filename);
3371 cupsdLogClient(con, CUPSD_LOG_DEBUG2, "is_cgi: filename=\"%s\", filestats=%p, type=%s/%s, returning 1.", filename, filestats, type->super, type->type);
3374 #endif /* HAVE_PERL */
3376 else if (!_cups_strcasecmp(type->type, "x-httpd-php"))
3379 * "application/x-httpd-php" is a PHP page.
3382 cupsdSetString(&con->command, CUPS_PHP);
3385 cupsdSetStringf(&con->options, " %s %s", filename, options);
3387 cupsdSetStringf(&con->options, " %s", filename);
3389 cupsdLogClient(con, CUPSD_LOG_DEBUG2, "is_cgi: filename=\"%s\", filestats=%p, type=%s/%s, returning 1.", filename, filestats, type->super, type->type);
3392 #endif /* HAVE_PHP */
3394 else if (!_cups_strcasecmp(type->type, "x-httpd-python"))
3397 * "application/x-httpd-python" is a Python page.
3400 cupsdSetString(&con->command, CUPS_PYTHON);
3403 cupsdSetStringf(&con->options, " %s %s", filename, options);
3405 cupsdSetStringf(&con->options, " %s", filename);
3407 cupsdLogClient(con, CUPSD_LOG_DEBUG2, "is_cgi: filename=\"%s\", filestats=%p, type=%s/%s, returning 1.", filename, filestats, type->super, type->type);
3410 #endif /* HAVE_PYTHON */
3412 cupsdLogClient(con, CUPSD_LOG_DEBUG2, "is_cgi: filename=\"%s\", filestats=%p, type=%s/%s, returning 0.", filename, filestats, type->super, type->type);
3418 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
3421 static int /* O - 0 if relative, 1 if absolute */
3422 is_path_absolute(const char *path) /* I - Input path */
3425 * Check for a leading slash...
3432 * Check for "<" or quotes in the path and reject since this is probably
3433 * someone trying to inject HTML...
3436 if (strchr(path, '<') != NULL || strchr(path, '\"') != NULL || strchr(path, '\'') != NULL)
3440 * Check for "/.." in the path...
3443 while ((path = strstr(path, "/..")) != NULL)
3445 if (!path[3] || path[3] == '/')
3452 * If we haven't found any relative paths, return 1 indicating an
3461 * 'pipe_command()' - Pipe the output of a command to the remote client.
3464 static int /* O - Process ID */
3465 pipe_command(cupsd_client_t *con, /* I - Client connection */
3466 int infile, /* I - Standard input for command */
3467 int *outfile, /* O - Standard output for command */
3468 char *command, /* I - Command to run */
3469 char *options, /* I - Options for command */
3470 int root) /* I - Run as root? */
3472 int i; /* Looping var */
3473 int pid; /* Process ID */
3474 char *commptr, /* Command string pointer */
3475 commch; /* Command string character */
3476 char *uriptr; /* URI string pointer */
3477 int fds[2]; /* Pipe FDs */
3478 int argc; /* Number of arguments */
3479 int envc; /* Number of environment variables */
3480 char argbuf[10240], /* Argument buffer */
3481 *argv[100], /* Argument strings */
3482 *envp[MAX_ENV + 20]; /* Environment variables */
3483 char auth_type[256], /* AUTH_TYPE environment variable */
3484 content_length[1024], /* CONTENT_LENGTH environment variable */
3485 content_type[1024], /* CONTENT_TYPE environment variable */
3486 http_cookie[32768], /* HTTP_COOKIE environment variable */
3487 http_referer[1024], /* HTTP_REFERER environment variable */
3488 http_user_agent[1024], /* HTTP_USER_AGENT environment variable */
3489 lang[1024], /* LANG environment variable */
3490 path_info[1024], /* PATH_INFO environment variable */
3491 remote_addr[1024], /* REMOTE_ADDR environment variable */
3492 remote_host[1024], /* REMOTE_HOST environment variable */
3493 remote_user[1024], /* REMOTE_USER environment variable */
3494 script_filename[1024], /* SCRIPT_FILENAME environment variable */
3495 script_name[1024], /* SCRIPT_NAME environment variable */
3496 server_name[1024], /* SERVER_NAME environment variable */
3497 server_port[1024]; /* SERVER_PORT environment variable */
3498 ipp_attribute_t *attr; /* attributes-natural-language attribute */
3502 * Parse a copy of the options string, which is of the form:
3504 * argument+argument+argument
3505 * ?argument+argument+argument
3506 * param=value¶m=value
3507 * ?param=value¶m=value
3508 * /name?argument+argument+argument
3509 * /name?param=value¶m=value
3511 * If the string contains an "=" character after the initial name,
3512 * then we treat it as a HTTP GET form request and make a copy of
3513 * the remaining string for the environment variable.
3515 * The string is always parsed out as command-line arguments, to
3516 * be consistent with Apache...
3519 cupsdLogClient(con, CUPSD_LOG_DEBUG2, "pipe_command: infile=%d, outfile=%p, command=\"%s\", options=\"%s\", root=%d", infile, outfile, command, options ? options : "(null)", root);
3524 strlcpy(argbuf, options, sizeof(argbuf));
3528 if (argbuf[0] == '/')
3531 * Found some trailing path information, set PATH_INFO...
3534 if ((commptr = strchr(argbuf, '?')) == NULL)
3535 commptr = argbuf + strlen(argbuf);
3539 snprintf(path_info, sizeof(path_info), "PATH_INFO=%s", argbuf);
3545 path_info[0] = '\0';
3547 if (*commptr == ' ')
3551 if (*commptr == '?' && con->operation == HTTP_STATE_GET && !con->query_string)
3554 cupsdSetStringf(&(con->query_string), "QUERY_STRING=%s", commptr);
3561 argv[argc ++] = commptr;
3563 for (; *commptr && argc < 99; commptr ++)
3566 * Break arguments whenever we see a + or space...
3569 if (*commptr == ' ' || *commptr == '+')
3571 while (*commptr == ' ' || *commptr == '+')
3575 * If we don't have a blank string, save it as another argument...
3580 argv[argc] = commptr;
3586 else if (*commptr == '%' && isxdigit(commptr[1] & 255) &&
3587 isxdigit(commptr[2] & 255))
3590 * Convert the %xx notation to the individual character.
3593 if (commptr[1] >= '0' && commptr[1] <= '9')
3594 *commptr = (char)((commptr[1] - '0') << 4);
3596 *commptr = (char)((tolower(commptr[1]) - 'a' + 10) << 4);
3598 if (commptr[2] >= '0' && commptr[2] <= '9')
3599 *commptr |= commptr[2] - '0';
3601 *commptr |= tolower(commptr[2]) - 'a' + 10;
3603 _cups_strcpy(commptr + 1, commptr + 3);
3606 * Check for a %00 and break if that is the case...
3618 * Setup the environment variables as needed...
3621 if (con->username[0])
3623 snprintf(auth_type, sizeof(auth_type), "AUTH_TYPE=%s",
3624 httpGetField(con->http, HTTP_FIELD_AUTHORIZATION));
3626 if ((uriptr = strchr(auth_type + 10, ' ')) != NULL)
3630 auth_type[0] = '\0';
3633 (attr = ippFindAttribute(con->request, "attributes-natural-language",
3634 IPP_TAG_LANGUAGE)) != NULL)
3636 switch (strlen(attr->values[0].string.text))
3640 * This is an unknown or badly formatted language code; use
3641 * the POSIX locale...
3644 strlcpy(lang, "LANG=C", sizeof(lang));
3649 * Just the language code (ll)...
3652 snprintf(lang, sizeof(lang), "LANG=%s.UTF8",
3653 attr->values[0].string.text);
3658 * Language and country code (ll-cc)...
3661 snprintf(lang, sizeof(lang), "LANG=%c%c_%c%c.UTF8",
3662 attr->values[0].string.text[0],
3663 attr->values[0].string.text[1],
3664 toupper(attr->values[0].string.text[3] & 255),
3665 toupper(attr->values[0].string.text[4] & 255));
3669 else if (con->language)
3670 snprintf(lang, sizeof(lang), "LANG=%s.UTF8", con->language->language);
3672 strlcpy(lang, "LANG=C", sizeof(lang));
3674 strlcpy(remote_addr, "REMOTE_ADDR=", sizeof(remote_addr));
3675 httpAddrString(httpGetAddress(con->http), remote_addr + 12,
3676 sizeof(remote_addr) - 12);
3678 snprintf(remote_host, sizeof(remote_host), "REMOTE_HOST=%s",
3679 httpGetHostname(con->http, NULL, 0));
3681 snprintf(script_name, sizeof(script_name), "SCRIPT_NAME=%s", con->uri);
3682 if ((uriptr = strchr(script_name, '?')) != NULL)
3685 snprintf(script_filename, sizeof(script_filename), "SCRIPT_FILENAME=%s%s",
3686 DocumentRoot, script_name + 12);
3688 snprintf(server_port, sizeof(server_port), "SERVER_PORT=%d", con->serverport);
3690 if (httpGetField(con->http, HTTP_FIELD_HOST)[0])
3692 char *nameptr; /* Pointer to ":port" */
3694 snprintf(server_name, sizeof(server_name), "SERVER_NAME=%s",
3695 httpGetField(con->http, HTTP_FIELD_HOST));
3696 if ((nameptr = strrchr(server_name, ':')) != NULL && !strchr(nameptr, ']'))
3697 *nameptr = '\0'; /* Strip trailing ":port" */
3700 snprintf(server_name, sizeof(server_name), "SERVER_NAME=%s",
3703 envc = cupsdLoadEnv(envp, (int)(sizeof(envp) / sizeof(envp[0])));
3706 envp[envc ++] = auth_type;
3708 envp[envc ++] = lang;
3709 envp[envc ++] = "REDIRECT_STATUS=1";
3710 envp[envc ++] = "GATEWAY_INTERFACE=CGI/1.1";
3711 envp[envc ++] = server_name;
3712 envp[envc ++] = server_port;
3713 envp[envc ++] = remote_addr;
3714 envp[envc ++] = remote_host;
3715 envp[envc ++] = script_name;
3716 envp[envc ++] = script_filename;
3719 envp[envc ++] = path_info;
3721 if (con->username[0])
3723 snprintf(remote_user, sizeof(remote_user), "REMOTE_USER=%s", con->username);
3725 envp[envc ++] = remote_user;
3728 if (httpGetVersion(con->http) == HTTP_VERSION_1_1)
3729 envp[envc ++] = "SERVER_PROTOCOL=HTTP/1.1";
3730 else if (httpGetVersion(con->http) == HTTP_VERSION_1_0)
3731 envp[envc ++] = "SERVER_PROTOCOL=HTTP/1.0";
3733 envp[envc ++] = "SERVER_PROTOCOL=HTTP/0.9";
3735 if (httpGetCookie(con->http))
3737 snprintf(http_cookie, sizeof(http_cookie), "HTTP_COOKIE=%s",
3738 httpGetCookie(con->http));
3739 envp[envc ++] = http_cookie;
3742 if (httpGetField(con->http, HTTP_FIELD_USER_AGENT)[0])
3744 snprintf(http_user_agent, sizeof(http_user_agent), "HTTP_USER_AGENT=%s",
3745 httpGetField(con->http, HTTP_FIELD_USER_AGENT));
3746 envp[envc ++] = http_user_agent;
3749 if (httpGetField(con->http, HTTP_FIELD_REFERER)[0])
3751 snprintf(http_referer, sizeof(http_referer), "HTTP_REFERER=%s",
3752 httpGetField(con->http, HTTP_FIELD_REFERER));
3753 envp[envc ++] = http_referer;
3756 if (con->operation == HTTP_STATE_GET)
3758 envp[envc ++] = "REQUEST_METHOD=GET";
3760 if (con->query_string)
3763 * Add GET form variables after ?...
3766 envp[envc ++] = con->query_string;
3769 envp[envc ++] = "QUERY_STRING=";
3773 sprintf(content_length, "CONTENT_LENGTH=" CUPS_LLFMT,
3774 CUPS_LLCAST con->bytes);
3775 snprintf(content_type, sizeof(content_type), "CONTENT_TYPE=%s",
3776 httpGetField(con->http, HTTP_FIELD_CONTENT_TYPE));
3778 envp[envc ++] = "REQUEST_METHOD=POST";
3779 envp[envc ++] = content_length;
3780 envp[envc ++] = content_type;
3784 * Tell the CGI if we are using encryption...
3787 if (httpIsEncrypted(con->http))
3788 envp[envc ++] = "HTTPS=ON";
3791 * Terminate the environment array...
3796 if (LogLevel >= CUPSD_LOG_DEBUG)
3798 for (i = 0; i < argc; i ++)
3799 cupsdLogMessage(CUPSD_LOG_DEBUG,
3800 "[CGI] argv[%d] = \"%s\"", i, argv[i]);
3801 for (i = 0; i < envc; i ++)
3802 cupsdLogMessage(CUPSD_LOG_DEBUG,
3803 "[CGI] envp[%d] = \"%s\"", i, envp[i]);
3807 * Create a pipe for the output...
3810 if (cupsdOpenPipe(fds))
3812 cupsdLogMessage(CUPSD_LOG_ERROR, "[CGI] Unable to create pipe for %s - %s",
3813 argv[0], strerror(errno));
3818 * Then execute the command...
3821 if (cupsdStartProcess(command, argv, envp, infile, fds[1], CGIPipes[1],
3822 -1, -1, root, DefaultProfile, NULL, &pid) < 0)
3825 * Error - can't fork!
3828 cupsdLogMessage(CUPSD_LOG_ERROR, "[CGI] Unable to start %s - %s", argv[0],
3831 cupsdClosePipe(fds);
3837 * Fork successful - return the PID...
3840 if (con->username[0])
3841 cupsdAddCert(pid, con->username, con->type);
3843 cupsdLogMessage(CUPSD_LOG_DEBUG, "[CGI] Started %s (PID %d)", command, pid);
3854 * 'valid_host()' - Is the Host: field valid?
3857 static int /* O - 1 if valid, 0 if not */
3858 valid_host(cupsd_client_t *con) /* I - Client connection */
3860 cupsd_alias_t *a; /* Current alias */
3861 cupsd_netif_t *netif; /* Current network interface */
3862 const char *end; /* End character */
3863 char *ptr; /* Pointer into host value */
3867 * Copy the Host: header for later use...
3870 strlcpy(con->clientname, httpGetField(con->http, HTTP_FIELD_HOST),
3871 sizeof(con->clientname));
3872 if ((ptr = strrchr(con->clientname, ':')) != NULL && !strchr(ptr, ']'))
3875 con->clientport = atoi(ptr);
3878 con->clientport = con->serverport;
3884 if (httpAddrLocalhost(httpGetAddress(con->http)))
3887 * Only allow "localhost" or the equivalent IPv4 or IPv6 numerical
3888 * addresses when accessing CUPS via the loopback interface...
3891 return (!_cups_strcasecmp(con->clientname, "localhost") ||
3892 !_cups_strcasecmp(con->clientname, "localhost.") ||
3894 !_cups_strcasecmp(con->clientname, "localhost.localdomain") ||
3895 #endif /* __linux */
3896 !strcmp(con->clientname, "127.0.0.1") ||
3897 !strcmp(con->clientname, "[::1]"));
3900 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
3902 * Check if the hostname is something.local (Bonjour); if so, allow it.
3905 if ((end = strrchr(con->clientname, '.')) != NULL && end > con->clientname &&
3909 * "." on end, work back to second-to-last "."...
3912 for (end --; end > con->clientname && *end != '.'; end --);
3915 if (end && (!_cups_strcasecmp(end, ".local") ||
3916 !_cups_strcasecmp(end, ".local.")))
3918 #endif /* HAVE_DNSSD || HAVE_AVAHI */
3921 * Check if the hostname is an IP address...
3924 if (isdigit(con->clientname[0] & 255) || con->clientname[0] == '[')
3927 * Possible IPv4/IPv6 address...
3930 http_addrlist_t *addrlist; /* List of addresses */
3933 if ((addrlist = httpAddrGetList(con->clientname, AF_UNSPEC, NULL)) != NULL)
3936 * Good IPv4/IPv6 address...
3939 httpAddrFreeList(addrlist);
3945 * Check for (alias) name matches...
3948 for (a = (cupsd_alias_t *)cupsArrayFirst(ServerAlias);
3950 a = (cupsd_alias_t *)cupsArrayNext(ServerAlias))
3953 * "ServerAlias *" allows all host values through...
3956 if (!strcmp(a->name, "*"))
3959 if (!_cups_strncasecmp(con->clientname, a->name, a->namelen))
3962 * Prefix matches; check the character at the end - it must be "." or nul.
3965 end = con->clientname + a->namelen;
3967 if (!*end || (*end == '.' && !end[1]))
3972 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
3973 for (a = (cupsd_alias_t *)cupsArrayFirst(DNSSDAlias);
3975 a = (cupsd_alias_t *)cupsArrayNext(DNSSDAlias))
3978 * "ServerAlias *" allows all host values through...
3981 if (!strcmp(a->name, "*"))
3984 if (!_cups_strncasecmp(con->clientname, a->name, a->namelen))
3987 * Prefix matches; check the character at the end - it must be "." or nul.
3990 end = con->clientname + a->namelen;
3992 if (!*end || (*end == '.' && !end[1]))
3996 #endif /* HAVE_DNSSD || HAVE_AVAHI */
3999 * Check for interface hostname matches...
4002 for (netif = (cupsd_netif_t *)cupsArrayFirst(NetIFList);
4004 netif = (cupsd_netif_t *)cupsArrayNext(NetIFList))
4006 if (!_cups_strncasecmp(con->clientname, netif->hostname, netif->hostlen))
4009 * Prefix matches; check the character at the end - it must be "." or nul.
4012 end = con->clientname + netif->hostlen;
4014 if (!*end || (*end == '.' && !end[1]))
4024 * 'write_file()' - Send a file via HTTP.
4027 static int /* O - 0 on failure, 1 on success */
4028 write_file(cupsd_client_t *con, /* I - Client connection */
4029 http_status_t code, /* I - HTTP status */
4030 char *filename, /* I - Filename */
4031 char *type, /* I - File type */
4032 struct stat *filestats) /* O - File information */
4034 con->file = open(filename, O_RDONLY);
4036 cupsdLogClient(con, CUPSD_LOG_DEBUG2, "write_file: code=%d, filename=\"%s\" (%d), type=\"%s\", filestats=%p.", code, filename, con->file, type ? type : "(null)", filestats);
4041 fcntl(con->file, F_SETFD, fcntl(con->file, F_GETFD) | FD_CLOEXEC);
4044 con->sent_header = 1;
4046 httpClearFields(con->http);
4048 httpSetLength(con->http, (size_t)filestats->st_size);
4050 httpSetField(con->http, HTTP_FIELD_LAST_MODIFIED,
4051 httpGetDateString(filestats->st_mtime));
4053 if (!cupsdSendHeader(con, code, type, CUPSD_AUTH_NONE))
4056 cupsdAddSelect(httpGetFd(con->http), NULL, (cupsd_selfunc_t)cupsdWriteClient, con);
4058 cupsdLogClient(con, CUPSD_LOG_DEBUG, "Sending file.");
4065 * 'write_pipe()' - Flag that data is available on the CGI pipe.
4069 write_pipe(cupsd_client_t *con) /* I - Client connection */
4071 cupsdLogClient(con, CUPSD_LOG_DEBUG2, "write_pipe: CGI output on fd %d.", con->file);
4073 con->file_ready = 1;
4075 cupsdRemoveSelect(con->file);
4076 cupsdAddSelect(httpGetFd(con->http), NULL, (cupsd_selfunc_t)cupsdWriteClient, con);
4078 cupsdLogClient(con, CUPSD_LOG_DEBUG, "CGI data ready to be sent.");