4 * Client routines for the CUPS scheduler.
6 * Copyright 2007-2013 by Apple Inc.
7 * Copyright 1997-2007 by Easy Software Products, all rights reserved.
9 * This file contains Kerberos support code, copyright 2006 by
12 * These coded instructions, statements, and computer programs are the
13 * property of Apple Inc. and are protected by Federal copyright
14 * law. Distribution and use rights are outlined in the file "LICENSE.txt"
15 * which should have been included with this file. If this file is
16 * file is missing or damaged, see the license at "http://www.cups.org/".
20 * Include necessary headers...
23 #define _CUPS_NO_DEPRECATED
24 //#define _HTTP_NO_PRIVATE
29 #endif /* __APPLE__ */
32 #endif /* HAVE_TCPD_H */
39 static const char * const ipp_states
[] =
40 { /* IPP state strings */
52 static int check_if_modified(cupsd_client_t
*con
,
53 struct stat
*filestats
);
54 static int compare_clients(cupsd_client_t
*a
, cupsd_client_t
*b
,
56 static char *get_file(cupsd_client_t
*con
, struct stat
*filestats
,
57 char *filename
, int len
);
58 static http_status_t
install_cupsd_conf(cupsd_client_t
*con
);
59 static int is_cgi(cupsd_client_t
*con
, const char *filename
,
60 struct stat
*filestats
, mime_type_t
*type
);
61 static int is_path_absolute(const char *path
);
62 static int pipe_command(cupsd_client_t
*con
, int infile
, int *outfile
,
63 char *command
, char *options
, int root
);
64 static int valid_host(cupsd_client_t
*con
);
65 static int write_file(cupsd_client_t
*con
, http_status_t code
,
66 char *filename
, char *type
,
67 struct stat
*filestats
);
68 static void write_pipe(cupsd_client_t
*con
);
72 * 'cupsdAcceptClient()' - Accept a new client.
76 cupsdAcceptClient(cupsd_listener_t
*lis
)/* I - Listener socket */
78 char name
[256]; /* Hostname of client */
79 int count
; /* Count of connections on a host */
80 // int val; /* Parameter value */
81 cupsd_client_t
*con
, /* New client pointer */
82 *tempcon
; /* Temporary client pointer */
83 // http_addrlist_t *addrlist, /* List of adddresses for host */
84 // *addr; /* Current address */
85 socklen_t addrlen
; /* Length of address */
86 // char *hostname; /* Hostname for address */
87 http_addr_t temp
; /* Temporary address variable */
88 static time_t last_dos
= 0; /* Time of last DoS attack */
90 struct request_info wrap_req
; /* TCP wrappers request information */
91 #endif /* HAVE_TCPD_H */
94 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
95 "cupsdAcceptClient(lis=%p(%d)) Clients=%d",
96 lis
, lis
->fd
, cupsArrayCount(Clients
));
99 * Make sure we don't have a full set of clients already...
102 if (cupsArrayCount(Clients
) == MaxClients
)
106 * Get a pointer to the next available client...
110 Clients
= cupsArrayNew(NULL
, NULL
);
114 cupsdLogMessage(CUPSD_LOG_ERROR
,
115 "Unable to allocate memory for clients array!");
116 cupsdPauseListening();
121 ActiveClients
= cupsArrayNew((cups_array_func_t
)compare_clients
, NULL
);
125 cupsdLogMessage(CUPSD_LOG_ERROR
,
126 "Unable to allocate memory for active clients array!");
127 cupsdPauseListening();
131 if ((con
= calloc(1, sizeof(cupsd_client_t
))) == NULL
)
133 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to allocate memory for client!");
134 cupsdPauseListening();
139 * Accept the client and get the remote address...
142 con
->number
= ++ LastClientNumber
;
144 // con->http->activity = time(NULL);
145 // httpGetAddress(con->http) = &(con->clientaddr);
146 // con->http->wait_value = 10000;
147 // con->http->mode = _HTTP_MODE_SERVER;
149 if ((con
->http
= httpAcceptConnection(lis
->fd
, 0)) == NULL
)
151 if (errno
== ENFILE
|| errno
== EMFILE
)
152 cupsdPauseListening();
154 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to accept client connection - %s.",
162 * Save the connected address and port number...
165 con
->clientaddr
= lis
->address
;
167 #if 0 /* ifdef AF_INET6 */
168 /* FIXME: I don't believe this is recommended any longer, and we specifically
169 * disable IPv4-over-IPv6 when we listen...
172 * Convert IPv4 over IPv6 addresses (::ffff:n.n.n.n) to IPv4 forms we
173 * can more easily use...
176 if (lis
->address
.addr
.sa_family
== AF_INET6
&&
177 httpGetAddress(con
->http
)->ipv6
.sin6_addr
.s6_addr32
[0] == 0 &&
178 httpGetAddress(con
->http
)->ipv6
.sin6_addr
.s6_addr32
[1] == 0 &&
179 ntohl(httpGetAddress(con
->http
)->ipv6
.sin6_addr
.s6_addr32
[2]) == 0xffff)
180 httpGetAddress(con
->http
)->ipv6
.sin6_addr
.s6_addr32
[2] = 0;
181 #endif /* AF_INET6 */
184 * Check the number of clients on the same address...
187 for (count
= 0, tempcon
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
189 tempcon
= (cupsd_client_t
*)cupsArrayNext(Clients
))
190 if (httpAddrEqual(httpGetAddress(tempcon
->http
), httpGetAddress(con
->http
)))
193 if (count
>= MaxClientsPerHost
)
197 if (count
>= MaxClientsPerHost
)
199 if ((time(NULL
) - last_dos
) >= 60)
201 last_dos
= time(NULL
);
202 cupsdLogMessage(CUPSD_LOG_WARN
,
203 "Possible DoS attack - more than %d clients connecting "
206 httpGetHostname(con
->http
, name
, sizeof(name
)));
209 httpClose(con
->http
);
214 #if 0 /* Decide if we keep this, and where to store the name */
216 * Get the hostname or format the IP address as needed...
219 if (httpAddrLocalhost(httpGetAddress(con
->http
)))
222 * Map accesses from the loopback interface to "localhost"...
225 strlcpy(httpGetHostname(con
->http
, NULL
, 0), "localhost", sizeof(httpGetHostname(con
->http
, NULL
, 0)));
226 hostname
= httpGetHostname(con
->http
, NULL
, 0);
231 * Map accesses from the same host to the server name.
235 hostname
= httpAddrLookup(httpGetAddress(con
->http
), httpGetHostname(con
->http
, NULL
, 0),
236 sizeof(httpGetHostname(con
->http
, NULL
, 0)));
240 httpAddrString(httpGetAddress(con
->http
), httpGetHostname(con
->http
, NULL
, 0),
241 sizeof(httpGetHostname(con
->http
, NULL
, 0)));
245 if (hostname
== NULL
&& HostNameLookups
== 2)
248 * Can't have an unresolved IP address with double-lookups enabled...
251 httpClose(con
->http
);
253 cupsdLogClient(con
, CUPSD_LOG_WARN
,
254 "Name lookup failed - connection from %s closed!",
255 httpGetHostname(con
->http
, NULL
, 0));
261 if (HostNameLookups
== 2)
264 * Do double lookups as needed...
267 if ((addrlist
= httpAddrGetList(httpGetHostname(con
->http
, NULL
, 0), AF_UNSPEC
, NULL
))
271 * See if the hostname maps to the same IP address...
274 for (addr
= addrlist
; addr
; addr
= addr
->next
)
275 if (httpAddrEqual(httpGetAddress(con
->http
), &(addr
->addr
)))
281 httpAddrFreeList(addrlist
);
286 * Can't have a hostname that doesn't resolve to the same IP address
287 * with double-lookups enabled...
290 httpClose(con
->http
);
292 cupsdLogClient(con
, CUPSD_LOG_WARN
,
293 "IP lookup failed - connection from %s closed!",
294 httpGetHostname(con
->http
, NULL
, 0));
303 * See if the connection is denied by TCP wrappers...
306 request_init(&wrap_req
, RQ_DAEMON
, "cupsd", RQ_FILE
, httpGetFd(con
->http
),
310 if (!hosts_access(&wrap_req
))
312 httpClose(con
->http
);
314 cupsdLogClient(con
, CUPSD_LOG_WARN
,
315 "Connection from %s refused by /etc/hosts.allow and "
316 "/etc/hosts.deny rules.", httpGetHostname(con
->http
, NULL
, 0));
320 #endif /* HAVE_TCPD_H */
323 if (httpAddrFamily(httpGetAddress(con
->http
)) == AF_LOCAL
)
326 socklen_t peersize
; /* Size of peer credentials */
327 pid_t peerpid
; /* Peer process ID */
328 char peername
[256]; /* Name of process */
330 peersize
= sizeof(peerpid
);
331 if (!getsockopt(con
->number
, SOL_LOCAL
, LOCAL_PEERPID
, &peerpid
,
334 if (!proc_name(peerpid
, peername
, sizeof(peername
)))
335 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
336 "Accepted from %s (Domain ???[%d])",
337 httpGetHostname(con
->http
, NULL
, 0), (int)peerpid
);
339 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
340 "Accepted from %s (Domain %s[%d])",
341 httpGetHostname(con
->http
, NULL
, 0), name
, (int)peerpid
);
344 # endif /* __APPLE__ */
346 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Accepted from %s (Domain)",
347 httpGetHostname(con
->http
, NULL
, 0));
350 #endif /* AF_LOCAL */
351 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Accepted from %s:%d (IPv%d)",
352 httpGetHostname(con
->http
, NULL
, 0),
353 httpAddrPort(httpGetAddress(con
->http
)),
354 httpAddrFamily(httpGetAddress(con
->http
)) == AF_INET
? 4 : 6);
357 * Get the local address the client connected to...
360 addrlen
= sizeof(temp
);
361 if (getsockname(httpGetFd(con
->http
), (struct sockaddr
*)&temp
, &addrlen
))
363 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Unable to get local address - %s",
366 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
367 con
->serverport
= LocalPort
;
370 else if (httpAddrFamily(&temp
) == AF_LOCAL
)
372 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
373 con
->serverport
= LocalPort
;
375 #endif /* AF_LOCAL */
378 if (httpAddrLocalhost(&temp
))
379 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
380 else if (HostNameLookups
)
381 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
383 httpAddrString(&temp
, con
->servername
, sizeof(con
->servername
));
385 con
->serverport
= httpAddrPort(&(lis
->address
));
389 * Add the connection to the array of active clients...
392 cupsArrayAdd(Clients
, con
);
395 * Add the socket to the server select.
398 cupsdAddSelect(httpGetFd(con
->http
), (cupsd_selfunc_t
)cupsdReadClient
, NULL
,
401 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for request.");
404 * Temporarily suspend accept()'s until we lose a client...
407 if (cupsArrayCount(Clients
) == MaxClients
)
408 cupsdPauseListening();
412 * See if we are connecting on a secure port...
415 if (lis
->encryption
== HTTP_ENCRYPTION_ALWAYS
)
418 * https connection; go secure...
421 if (!cupsdStartTLS(con
))
422 cupsdCloseClient(con
);
426 #endif /* HAVE_SSL */
431 * 'cupsdCloseAllClients()' - Close all remote clients immediately.
435 cupsdCloseAllClients(void)
437 cupsd_client_t
*con
; /* Current client */
440 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdCloseAllClients() Clients=%d",
441 cupsArrayCount(Clients
));
443 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
445 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
446 if (cupsdCloseClient(con
))
447 cupsdCloseClient(con
);
452 * 'cupsdCloseClient()' - Close a remote client.
455 int /* O - 1 if partial close, 0 if fully closed */
456 cupsdCloseClient(cupsd_client_t
*con
) /* I - Client to close */
458 int partial
; /* Do partial close for SSL? */
460 #elif defined(HAVE_GNUTLS)
461 # elif defined(HAVE_CDSASSL)
462 #endif /* HAVE_LIBSSL */
465 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing connection.");
468 * Flush pending writes before closing...
471 httpFlushWrite(con
->http
);
475 if (con
->pipe_pid
!= 0)
478 * Stop any CGI process...
481 cupsdEndProcess(con
->pipe_pid
, 1);
487 cupsdRemoveSelect(con
->file
);
494 * Close the socket and clear the file from the input set for select()...
497 if (httpGetFd(con
->http
) >= 0)
499 cupsArrayRemove(ActiveClients
, con
);
504 * Shutdown encryption as needed...
507 if (httpIsEncrypted(con
->http
))
509 #endif /* HAVE_SSL */
514 * Only do a partial close so that the encrypted client gets everything.
517 httpShutdown(con
->http
);
518 cupsdAddSelect(httpGetFd(con
->http
), (cupsd_selfunc_t
)cupsdReadClient
,
521 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for socket close.");
526 * Shut the socket down fully...
529 cupsdRemoveSelect(httpGetFd(con
->http
));
530 httpClose(con
->http
);
541 cupsdRemoveSelect(httpGetFd(con
->http
));
543 httpClose(con
->http
);
545 cupsdClearString(&con
->filename
);
546 cupsdClearString(&con
->command
);
547 cupsdClearString(&con
->options
);
548 cupsdClearString(&con
->query_string
);
552 ippDelete(con
->request
);
558 ippDelete(con
->response
);
559 con
->response
= NULL
;
564 cupsLangFree(con
->language
);
565 con
->language
= NULL
;
568 #ifdef HAVE_AUTHORIZATION_H
571 AuthorizationFree(con
->authref
, kAuthorizationFlagDefaults
);
574 #endif /* HAVE_AUTHORIZATION_H */
577 * Re-enable new client connections if we are going back under the
581 if (cupsArrayCount(Clients
) == MaxClients
)
582 cupsdResumeListening();
585 * Compact the list of clients as necessary...
588 cupsArrayRemove(Clients
, con
);
598 * 'cupsdFlushHeader()' - Flush the header fields to the client.
601 int /* I - Bytes written or -1 on error */
602 cupsdFlushHeader(cupsd_client_t
*con
) /* I - Client to flush to */
604 int bytes
= httpFlushWrite(con
->http
);
606 // TODO: Need to use httpSendResponse
607 con
->http
->data_encoding
= HTTP_ENCODING_LENGTH
;
614 * 'cupsdReadClient()' - Read data from a client.
618 cupsdReadClient(cupsd_client_t
*con
) /* I - Client to read from */
620 char line
[32768], /* Line from client... */
621 operation
[64], /* Operation code from socket */
622 version
[64], /* HTTP version number string */
623 locale
[64], /* Locale */
624 *ptr
; /* Pointer into strings */
625 int major
, minor
; /* HTTP version numbers */
626 http_status_t status
; /* Transfer status */
627 ipp_state_t ipp_state
; /* State of IPP transfer */
628 int bytes
; /* Number of bytes to POST */
629 char *filename
; /* Name of file for GET/HEAD */
630 char buf
[1024]; /* Buffer for real filename */
631 struct stat filestats
; /* File information */
632 mime_type_t
*type
; /* MIME type of file */
633 cupsd_printer_t
*p
; /* Printer */
634 static unsigned request_id
= 0; /* Request ID for temp files */
637 status
= HTTP_STATUS_CONTINUE
;
639 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
644 "data_encoding=HTTP_ENCODING_%s, "
645 "data_remaining=" CUPS_LLFMT
", "
648 httpError(con
->http
), (int)httpGetReady(con
->http
),
649 httpStateString(httpGetState(con
->http
)),
650 httpIsChunked(con
->http
) ? "CHUNKED" : "LENGTH",
651 CUPS_LLCAST
httpGetRemaining(con
->http
),
653 con
->request
? ipp_states
[con
->request
->state
] : "",
660 * Automatically check for a SSL/TLS handshake...
665 if (recv(httpGetFd(con
->http
), buf
, 1, MSG_PEEK
) == 1 &&
666 (!buf
[0] || !strchr("DGHOPT", buf
[0])))
669 * Encrypt this connection...
672 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
673 "Saw first byte %02X, auto-negotiating "
674 "SSL/TLS session.", buf
[0] & 255);
676 if (!cupsdStartTLS(con
))
677 cupsdCloseClient(con
);
682 #endif /* HAVE_SSL */
684 switch (httpGetState(con
->http
))
686 case HTTP_STATE_WAITING
:
688 * See if we've received a request line...
691 if (httpGets(line
, sizeof(line
) - 1, con
->http
) == NULL
)
693 if (httpError(con
->http
) && httpError(con
->http
) != EPIPE
)
694 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
695 "HTTP_STATE_WAITING Closing for error %d (%s)",
696 httpError(con
->http
), strerror(httpError(con
->http
)));
698 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
699 "HTTP_STATE_WAITING Closing on EOF.");
701 cupsdCloseClient(con
);
706 * Ignore blank request lines...
713 * Clear other state variables...
716 httpClearFields(con
->http
);
718 con
->http
->activity
= time(NULL
);
719 con
->http
->version
= HTTP_VERSION_1_0
;
720 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
721 con
->http
->data_encoding
= HTTP_ENCODING_LENGTH
;
722 con
->http
->data_remaining
= 0;
723 con
->http
->_data_remaining
= 0;
724 con
->operation
= HTTP_STATE_WAITING
;
729 con
->username
[0] = '\0';
730 con
->password
[0] = '\0';
733 cupsdClearString(&con
->command
);
734 cupsdClearString(&con
->options
);
735 cupsdClearString(&con
->query_string
);
739 ippDelete(con
->request
);
745 ippDelete(con
->response
);
746 con
->response
= NULL
;
751 cupsLangFree(con
->language
);
752 con
->language
= NULL
;
758 #endif /* HAVE_GSSAPI */
761 * Grab the request line...
764 switch (sscanf(line
, "%63s%1023s%63s", operation
, con
->uri
, version
))
769 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
770 "Bad request line \"%s\" from %s.",
771 _httpEncodeURI(buf
, line
, sizeof(buf
)),
772 httpGetHostname(con
->http
, NULL
, 0));
773 cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
);
774 cupsdCloseClient(con
);
778 con
->http
->version
= HTTP_VERSION_0_9
;
781 if (sscanf(version
, "HTTP/%d.%d", &major
, &minor
) != 2)
783 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
784 "Bad request line \"%s\" from %s.",
785 _httpEncodeURI(buf
, line
, sizeof(buf
)),
786 httpGetHostname(con
->http
, NULL
, 0));
787 cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
);
788 cupsdCloseClient(con
);
794 con
->http
->version
= (http_version_t
)(major
* 100 + minor
);
795 if (con
->http
->version
== HTTP_VERSION_1_1
&& KeepAlive
)
796 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_ON
);
798 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
802 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
803 "Unsupported request line \"%s\" from %s.",
804 _httpEncodeURI(buf
, line
, sizeof(buf
)),
805 httpGetHostname(con
->http
, NULL
, 0));
806 cupsdSendError(con
, HTTP_STATUS_NOT_SUPPORTED
, CUPSD_AUTH_NONE
);
807 cupsdCloseClient(con
);
814 * Handle full URLs in the request line...
817 if (strcmp(con
->uri
, "*"))
819 char scheme
[HTTP_MAX_URI
], /* Method/scheme */
820 userpass
[HTTP_MAX_URI
], /* Username:password */
821 hostname
[HTTP_MAX_URI
], /* Hostname */
822 resource
[HTTP_MAX_URI
]; /* Resource path */
823 int port
; /* Port number */
827 * Separate the URI into its components...
830 httpSeparateURI(HTTP_URI_CODING_MOST
, con
->uri
,
831 scheme
, sizeof(scheme
),
832 userpass
, sizeof(userpass
),
833 hostname
, sizeof(hostname
), &port
,
834 resource
, sizeof(resource
));
837 * Only allow URIs with the servername, localhost, or an IP
841 if (strcmp(scheme
, "file") &&
842 _cups_strcasecmp(hostname
, ServerName
) &&
843 _cups_strcasecmp(hostname
, "localhost") &&
844 !isdigit(hostname
[0]) && hostname
[0] != '[')
847 * Nope, we don't do proxies...
850 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Bad URI \"%s\" in request.",
852 cupsdSendError(con
, HTTP_STATUS_METHOD_NOT_ALLOWED
, CUPSD_AUTH_NONE
);
853 cupsdCloseClient(con
);
858 * Copy the resource portion back into the URI; both resource and
859 * con->uri are HTTP_MAX_URI bytes in size...
862 strlcpy(con
->uri
, resource
, sizeof(con
->uri
));
866 * Process the request...
869 if (!strcmp(operation
, "GET"))
870 con
->http
->state
= HTTP_STATE_GET
;
871 else if (!strcmp(operation
, "PUT"))
872 con
->http
->state
= HTTP_STATE_PUT
;
873 else if (!strcmp(operation
, "POST"))
874 con
->http
->state
= HTTP_STATE_POST
;
875 else if (!strcmp(operation
, "DELETE"))
876 con
->http
->state
= HTTP_STATE_DELETE
;
877 else if (!strcmp(operation
, "TRACE"))
878 con
->http
->state
= HTTP_STATE_TRACE
;
879 else if (!strcmp(operation
, "OPTIONS"))
880 con
->http
->state
= HTTP_STATE_OPTIONS
;
881 else if (!strcmp(operation
, "HEAD"))
882 con
->http
->state
= HTTP_STATE_HEAD
;
885 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Bad operation \"%s\".",
887 cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
);
888 cupsdCloseClient(con
);
892 gettimeofday(&(con
->start
), NULL
);
893 con
->operation
= httpGetState(con
->http
);
895 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "%s %s HTTP/%d.%d",
896 operation
, con
->uri
, con
->http
->version
/ 100,
897 con
->http
->version
% 100);
899 con
->http
->status
= HTTP_STATUS_OK
;
901 if (!cupsArrayFind(ActiveClients
, con
))
903 cupsArrayAdd(ActiveClients
, con
);
907 case HTTP_STATE_OPTIONS
:
908 case HTTP_STATE_DELETE
:
909 case HTTP_STATE_GET
:
910 case HTTP_STATE_HEAD
:
911 case HTTP_STATE_POST
:
912 case HTTP_STATE_PUT
:
913 case HTTP_STATE_TRACE
:
915 * Parse incoming parameters until the status changes...
918 while ((status
= httpUpdate(con
->http
)) == HTTP_STATUS_CONTINUE
)
919 if (!httpGetReady(con
->http
))
922 if (status
!= HTTP_STATUS_OK
&& status
!= HTTP_STATUS_CONTINUE
)
924 if (httpError(con
->http
) && httpError(con
->http
) != EPIPE
)
925 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
926 "Closing for error %d (%s) while reading headers.",
927 httpError(con
->http
), strerror(httpError(con
->http
)));
929 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
930 "Closing on EOF while reading headers.");
932 cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
);
933 cupsdCloseClient(con
);
939 if (!httpGetReady(con
->http
) && recv(httpGetFd(con
->http
), buf
, 1, MSG_PEEK
) < 1)
942 * Connection closed...
945 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing on EOF.");
946 cupsdCloseClient(con
);
949 break; /* Anti-compiler-warning-code */
953 * Handle new transfers...
956 if (status
== HTTP_STATUS_OK
)
958 if (httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
)[0])
961 * Figure out the locale from the Accept-Language and Content-Type
965 if ((ptr
= strchr(httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
),
969 if ((ptr
= strchr(httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
),
973 if ((ptr
= strstr(httpGetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
),
974 "charset=")) != NULL
)
977 * Combine language and charset, and trim any extra params in the
981 snprintf(locale
, sizeof(locale
), "%s.%s",
982 httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
), ptr
+ 8);
984 if ((ptr
= strchr(locale
, ',')) != NULL
)
988 snprintf(locale
, sizeof(locale
), "%s.UTF-8",
989 httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
));
991 con
->language
= cupsLangGet(locale
);
994 con
->language
= cupsLangGet(DefaultLocale
);
998 if (!_cups_strncasecmp(httpGetField(con
->http
, HTTP_FIELD_CONNECTION
),
999 "Keep-Alive", 10) && KeepAlive
)
1000 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_ON
);
1001 else if (!_cups_strncasecmp(httpGetField(con
->http
, HTTP_FIELD_CONNECTION
),
1003 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
1005 if (!httpGetField(con
->http
, HTTP_FIELD_HOST
)[0] &&
1006 httpGetVersion(con
->http
) >= HTTP_VERSION_1_1
)
1009 * HTTP/1.1 and higher require the "Host:" field...
1012 if (!cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1014 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Missing Host: field in request.");
1015 cupsdCloseClient(con
);
1019 else if (!valid_host(con
))
1022 * Access to localhost must use "localhost" or the corresponding IPv4
1023 * or IPv6 values in the Host: field.
1026 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1027 "Request from \"%s\" using invalid Host: field \"%s\".",
1028 httpGetHostname(con
->http
, NULL
, 0), httpGetField(con
->http
, HTTP_FIELD_HOST
));
1030 if (!cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1032 cupsdCloseClient(con
);
1036 else if (con
->operation
== HTTP_STATE_OPTIONS
)
1039 * Do OPTIONS command...
1042 if (con
->best
&& con
->best
->type
!= CUPSD_AUTH_NONE
)
1044 if (!cupsdSendHeader(con
, HTTP_STATUS_UNAUTHORIZED
, NULL
, CUPSD_AUTH_NONE
))
1046 cupsdCloseClient(con
);
1051 if (!_cups_strcasecmp(httpGetField(con
->http
, HTTP_FIELD_CONNECTION
), "Upgrade") &&
1052 !httpIsEncrypted(con
->http
))
1056 * Do encryption stuff...
1059 if (!cupsdSendHeader(con
, HTTP_STATUS_SWITCHING_PROTOCOLS
, NULL
, CUPSD_AUTH_NONE
))
1061 cupsdCloseClient(con
);
1065 httpPrintf(con
->http
, "Connection: Upgrade\r\n");
1066 httpPrintf(con
->http
, "Upgrade: TLS/1.2,TLS/1.1,TLS/1.0\r\n");
1067 httpPrintf(con
->http
, "Content-Length: 0\r\n");
1068 httpPrintf(con
->http
, "\r\n");
1070 if (cupsdFlushHeader(con
) < 0)
1072 cupsdCloseClient(con
);
1076 if (!cupsdStartTLS(con
))
1078 cupsdCloseClient(con
);
1082 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
1084 cupsdCloseClient(con
);
1087 #endif /* HAVE_SSL */
1090 if (!cupsdSendHeader(con
, HTTP_STATUS_OK
, NULL
, CUPSD_AUTH_NONE
))
1092 cupsdCloseClient(con
);
1096 httpPrintf(con
->http
, "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n");
1097 httpPrintf(con
->http
, "Content-Length: 0\r\n");
1098 httpPrintf(con
->http
, "\r\n");
1100 if (cupsdFlushHeader(con
) < 0)
1102 cupsdCloseClient(con
);
1106 else if (!is_path_absolute(con
->uri
))
1109 * Protect against malicious users!
1112 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1113 "Request for non-absolute resource \"%s\".", con
->uri
);
1115 if (!cupsdSendError(con
, HTTP_STATUS_FORBIDDEN
, CUPSD_AUTH_NONE
))
1117 cupsdCloseClient(con
);
1123 if (!_cups_strcasecmp(httpGetField(con
->http
, HTTP_FIELD_CONNECTION
),
1124 "Upgrade") && con
->http
->tls
== NULL
)
1128 * Do encryption stuff...
1131 if (!cupsdSendHeader(con
, HTTP_STATUS_SWITCHING_PROTOCOLS
, NULL
,
1134 cupsdCloseClient(con
);
1138 httpPrintf(con
->http
, "Connection: Upgrade\r\n");
1139 httpPrintf(con
->http
, "Upgrade: TLS/1.2,TLS/1.1,TLS/1.0\r\n");
1140 httpPrintf(con
->http
, "Content-Length: 0\r\n");
1141 httpPrintf(con
->http
, "\r\n");
1143 if (cupsdFlushHeader(con
) < 0)
1145 cupsdCloseClient(con
);
1149 if (!cupsdStartTLS(con
))
1151 cupsdCloseClient(con
);
1155 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
1157 cupsdCloseClient(con
);
1160 #endif /* HAVE_SSL */
1163 if ((status
= cupsdIsAuthorized(con
, NULL
)) != HTTP_STATUS_OK
)
1165 cupsdSendError(con
, status
, CUPSD_AUTH_NONE
);
1166 cupsdCloseClient(con
);
1170 if (con
->http
->expect
&&
1171 (con
->operation
== HTTP_STATE_POST
|| con
->operation
== HTTP_STATE_PUT
))
1173 if (con
->http
->expect
== HTTP_STATUS_CONTINUE
)
1176 * Send 100-continue header...
1179 if (!cupsdSendHeader(con
, HTTP_STATUS_CONTINUE
, NULL
, CUPSD_AUTH_NONE
))
1181 cupsdCloseClient(con
);
1188 * Send 417-expectation-failed header...
1191 if (!cupsdSendHeader(con
, HTTP_STATUS_EXPECTATION_FAILED
, NULL
,
1194 cupsdCloseClient(con
);
1198 httpPrintf(con
->http
, "Content-Length: 0\r\n");
1199 httpPrintf(con
->http
, "\r\n");
1201 if (cupsdFlushHeader(con
) < 0)
1203 cupsdCloseClient(con
);
1209 switch (httpGetState(con
->http
))
1211 case HTTP_STATE_GET_SEND
:
1212 if ((!strncmp(con
->uri
, "/ppd/", 5) ||
1213 !strncmp(con
->uri
, "/printers/", 10) ||
1214 !strncmp(con
->uri
, "/classes/", 9)) &&
1215 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1218 * Send PPD file - get the real printer name since printer
1219 * names are not case sensitive but filenames can be...
1222 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1224 if (!strncmp(con
->uri
, "/ppd/", 5))
1225 p
= cupsdFindPrinter(con
->uri
+ 5);
1226 else if (!strncmp(con
->uri
, "/printers/", 10))
1227 p
= cupsdFindPrinter(con
->uri
+ 10);
1230 p
= cupsdFindClass(con
->uri
+ 9);
1234 int i
; /* Looping var */
1236 for (i
= 0; i
< p
->num_printers
; i
++)
1238 if (!(p
->printers
[i
]->type
& CUPS_PRINTER_CLASS
))
1240 char ppdname
[1024];/* PPD filename */
1242 snprintf(ppdname
, sizeof(ppdname
), "%s/ppd/%s.ppd",
1243 ServerRoot
, p
->printers
[i
]->name
);
1244 if (!access(ppdname
, 0))
1252 if (i
>= p
->num_printers
)
1259 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1263 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1265 cupsdCloseClient(con
);
1272 else if ((!strncmp(con
->uri
, "/icons/", 7) ||
1273 !strncmp(con
->uri
, "/printers/", 10) ||
1274 !strncmp(con
->uri
, "/classes/", 9)) &&
1275 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".png"))
1278 * Send icon file - get the real queue name since queue names are
1279 * not case sensitive but filenames can be...
1282 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".png" */
1284 if (!strncmp(con
->uri
, "/icons/", 7))
1285 p
= cupsdFindPrinter(con
->uri
+ 7);
1286 else if (!strncmp(con
->uri
, "/printers/", 10))
1287 p
= cupsdFindPrinter(con
->uri
+ 10);
1290 p
= cupsdFindClass(con
->uri
+ 9);
1294 int i
; /* Looping var */
1296 for (i
= 0; i
< p
->num_printers
; i
++)
1298 if (!(p
->printers
[i
]->type
& CUPS_PRINTER_CLASS
))
1300 char ppdname
[1024];/* PPD filename */
1302 snprintf(ppdname
, sizeof(ppdname
), "%s/ppd/%s.ppd",
1303 ServerRoot
, p
->printers
[i
]->name
);
1304 if (!access(ppdname
, 0))
1312 if (i
>= p
->num_printers
)
1318 snprintf(con
->uri
, sizeof(con
->uri
), "/icons/%s.png", p
->name
);
1321 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1323 cupsdCloseClient(con
);
1330 else if (!WebInterface
)
1333 * Web interface is disabled. Show an appropriate message...
1336 if (!cupsdSendError(con
, HTTP_STATUS_CUPS_WEBIF_DISABLED
, CUPSD_AUTH_NONE
))
1338 cupsdCloseClient(con
);
1345 if ((!strncmp(con
->uri
, "/admin", 6) &&
1346 strncmp(con
->uri
, "/admin/conf/", 12) &&
1347 strncmp(con
->uri
, "/admin/log/", 11)) ||
1348 !strncmp(con
->uri
, "/printers", 9) ||
1349 !strncmp(con
->uri
, "/classes", 8) ||
1350 !strncmp(con
->uri
, "/help", 5) ||
1351 !strncmp(con
->uri
, "/jobs", 5))
1354 * Send CGI output...
1357 if (!strncmp(con
->uri
, "/admin", 6))
1359 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1362 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1364 else if (!strncmp(con
->uri
, "/printers", 9))
1366 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1369 if (con
->uri
[9] && con
->uri
[10])
1370 cupsdSetString(&con
->options
, con
->uri
+ 9);
1372 cupsdSetString(&con
->options
, NULL
);
1374 else if (!strncmp(con
->uri
, "/classes", 8))
1376 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1379 if (con
->uri
[8] && con
->uri
[9])
1380 cupsdSetString(&con
->options
, con
->uri
+ 8);
1382 cupsdSetString(&con
->options
, NULL
);
1384 else if (!strncmp(con
->uri
, "/jobs", 5))
1386 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1389 if (con
->uri
[5] && con
->uri
[6])
1390 cupsdSetString(&con
->options
, con
->uri
+ 5);
1392 cupsdSetString(&con
->options
, NULL
);
1396 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1399 if (con
->uri
[5] && con
->uri
[6])
1400 cupsdSetString(&con
->options
, con
->uri
+ 5);
1402 cupsdSetString(&con
->options
, NULL
);
1405 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1407 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1409 cupsdCloseClient(con
);
1414 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1416 if (con
->http
->version
<= HTTP_VERSION_1_0
)
1417 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
1419 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1420 (strchr(con
->uri
+ 12, '/') ||
1421 strlen(con
->uri
) == 12)) ||
1422 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1423 (strchr(con
->uri
+ 11, '/') ||
1424 strlen(con
->uri
) == 11)))
1427 * GET can only be done to configuration files directly under
1431 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1432 "Request for subdirectory \"%s\"!", con
->uri
);
1434 if (!cupsdSendError(con
, HTTP_STATUS_FORBIDDEN
, CUPSD_AUTH_NONE
))
1436 cupsdCloseClient(con
);
1448 if ((filename
= get_file(con
, &filestats
, buf
,
1449 sizeof(buf
))) == NULL
)
1451 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1453 cupsdCloseClient(con
);
1460 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1462 if (is_cgi(con
, filename
, &filestats
, type
))
1465 * Note: con->command and con->options were set by
1469 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1471 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1473 cupsdCloseClient(con
);
1478 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1480 if (con
->http
->version
<= HTTP_VERSION_1_0
)
1481 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
1485 if (!check_if_modified(con
, &filestats
))
1487 if (!cupsdSendError(con
, HTTP_STATUS_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1489 cupsdCloseClient(con
);
1496 strlcpy(line
, "text/plain", sizeof(line
));
1498 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1500 if (!write_file(con
, HTTP_STATUS_OK
, filename
, line
, &filestats
))
1502 cupsdCloseClient(con
);
1509 case HTTP_STATE_POST_RECV
:
1511 * See if the POST request includes a Content-Length field, and if
1512 * so check the length against any limits that are set...
1515 if (httpGetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
)[0] &&
1516 MaxRequestSize
> 0 &&
1517 con
->http
->data_remaining
> MaxRequestSize
)
1520 * Request too large...
1523 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1525 cupsdCloseClient(con
);
1531 else if (con
->http
->data_remaining
< 0 ||
1532 (!httpGetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
)[0] &&
1533 con
->http
->data_encoding
== HTTP_ENCODING_LENGTH
))
1536 * Negative content lengths are invalid!
1539 if (!cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1541 cupsdCloseClient(con
);
1549 * See what kind of POST request this is; for IPP requests the
1550 * content-type field will be "application/ipp"...
1553 if (!strcmp(httpGetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
),
1555 con
->request
= ippNew();
1556 else if (!WebInterface
)
1559 * Web interface is disabled. Show an appropriate message...
1562 if (!cupsdSendError(con
, HTTP_STATUS_CUPS_WEBIF_DISABLED
, CUPSD_AUTH_NONE
))
1564 cupsdCloseClient(con
);
1570 else if ((!strncmp(con
->uri
, "/admin", 6) &&
1571 strncmp(con
->uri
, "/admin/conf/", 12) &&
1572 strncmp(con
->uri
, "/admin/log/", 11)) ||
1573 !strncmp(con
->uri
, "/printers", 9) ||
1574 !strncmp(con
->uri
, "/classes", 8) ||
1575 !strncmp(con
->uri
, "/help", 5) ||
1576 !strncmp(con
->uri
, "/jobs", 5))
1582 if (!strncmp(con
->uri
, "/admin", 6))
1584 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1587 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1589 else if (!strncmp(con
->uri
, "/printers", 9))
1591 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1594 if (con
->uri
[9] && con
->uri
[10])
1595 cupsdSetString(&con
->options
, con
->uri
+ 9);
1597 cupsdSetString(&con
->options
, NULL
);
1599 else if (!strncmp(con
->uri
, "/classes", 8))
1601 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1604 if (con
->uri
[8] && con
->uri
[9])
1605 cupsdSetString(&con
->options
, con
->uri
+ 8);
1607 cupsdSetString(&con
->options
, NULL
);
1609 else if (!strncmp(con
->uri
, "/jobs", 5))
1611 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1614 if (con
->uri
[5] && con
->uri
[6])
1615 cupsdSetString(&con
->options
, con
->uri
+ 5);
1617 cupsdSetString(&con
->options
, NULL
);
1621 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1624 if (con
->uri
[5] && con
->uri
[6])
1625 cupsdSetString(&con
->options
, con
->uri
+ 5);
1627 cupsdSetString(&con
->options
, NULL
);
1630 if (con
->http
->version
<= HTTP_VERSION_1_0
)
1631 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
1639 if ((filename
= get_file(con
, &filestats
, buf
,
1640 sizeof(buf
))) == NULL
)
1642 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1644 cupsdCloseClient(con
);
1651 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1653 if (!is_cgi(con
, filename
, &filestats
, type
))
1656 * Only POST to CGI's...
1659 if (!cupsdSendError(con
, HTTP_STATUS_UNAUTHORIZED
, CUPSD_AUTH_NONE
))
1661 cupsdCloseClient(con
);
1668 case HTTP_STATE_PUT_RECV
:
1670 * Validate the resource name...
1673 if (strcmp(con
->uri
, "/admin/conf/cupsd.conf"))
1676 * PUT can only be done to the cupsd.conf file...
1679 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1680 "Disallowed PUT request for \"%s\".", con
->uri
);
1682 if (!cupsdSendError(con
, HTTP_STATUS_FORBIDDEN
, CUPSD_AUTH_NONE
))
1684 cupsdCloseClient(con
);
1692 * See if the PUT request includes a Content-Length field, and if
1693 * so check the length against any limits that are set...
1696 if (httpGetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
)[0] &&
1697 MaxRequestSize
> 0 &&
1698 con
->http
->data_remaining
> MaxRequestSize
)
1701 * Request too large...
1704 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1706 cupsdCloseClient(con
);
1712 else if (con
->http
->data_remaining
< 0)
1715 * Negative content lengths are invalid!
1718 if (!cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1720 cupsdCloseClient(con
);
1728 * Open a temporary file to hold the request...
1731 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
1733 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1737 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1738 "Unable to create request file \"%s\": %s",
1739 con
->filename
, strerror(errno
));
1741 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1743 cupsdCloseClient(con
);
1748 fchmod(con
->file
, 0640);
1749 fchown(con
->file
, RunUser
, Group
);
1750 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1753 case HTTP_STATE_DELETE
:
1754 case HTTP_STATE_TRACE
:
1755 cupsdSendError(con
, HTTP_STATUS_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
);
1756 cupsdCloseClient(con
);
1759 case HTTP_STATE_HEAD
:
1760 if (!strncmp(con
->uri
, "/printers/", 10) &&
1761 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1764 * Send PPD file - get the real printer name since printer
1765 * names are not case sensitive but filenames can be...
1768 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1770 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1771 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1774 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1776 cupsdCloseClient(con
);
1783 else if (!strncmp(con
->uri
, "/printers/", 10) &&
1784 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".png"))
1787 * Send PNG file - get the real printer name since printer
1788 * names are not case sensitive but filenames can be...
1791 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1793 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1794 snprintf(con
->uri
, sizeof(con
->uri
), "/icons/%s.png", p
->name
);
1797 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1799 cupsdCloseClient(con
);
1806 else if (!WebInterface
)
1808 if (!cupsdSendHeader(con
, HTTP_STATUS_OK
, NULL
, CUPSD_AUTH_NONE
))
1810 cupsdCloseClient(con
);
1814 if (httpPrintf(con
->http
, "\r\n") < 0)
1816 cupsdCloseClient(con
);
1820 if (cupsdFlushHeader(con
) < 0)
1822 cupsdCloseClient(con
);
1826 con
->http
->state
= HTTP_STATE_WAITING
;
1827 DEBUG_puts("cupsdReadClient: Set state to HTTP_STATE_WAITING "
1832 if ((!strncmp(con
->uri
, "/admin", 6) &&
1833 strncmp(con
->uri
, "/admin/conf/", 12) &&
1834 strncmp(con
->uri
, "/admin/log/", 11)) ||
1835 !strncmp(con
->uri
, "/printers", 9) ||
1836 !strncmp(con
->uri
, "/classes", 8) ||
1837 !strncmp(con
->uri
, "/help", 5) ||
1838 !strncmp(con
->uri
, "/jobs", 5))
1844 if (!cupsdSendHeader(con
, HTTP_STATUS_OK
, "text/html", CUPSD_AUTH_NONE
))
1846 cupsdCloseClient(con
);
1850 if (httpPrintf(con
->http
, "\r\n") < 0)
1852 cupsdCloseClient(con
);
1856 if (cupsdFlushHeader(con
) < 0)
1858 cupsdCloseClient(con
);
1862 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1864 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1865 (strchr(con
->uri
+ 12, '/') ||
1866 strlen(con
->uri
) == 12)) ||
1867 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1868 (strchr(con
->uri
+ 11, '/') ||
1869 strlen(con
->uri
) == 11)))
1872 * HEAD can only be done to configuration files under
1876 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1877 "Request for subdirectory \"%s\".", con
->uri
);
1879 if (!cupsdSendError(con
, HTTP_STATUS_FORBIDDEN
, CUPSD_AUTH_NONE
))
1881 cupsdCloseClient(con
);
1887 else if ((filename
= get_file(con
, &filestats
, buf
,
1888 sizeof(buf
))) == NULL
)
1890 if (!cupsdSendHeader(con
, HTTP_STATUS_NOT_FOUND
, "text/html",
1893 cupsdCloseClient(con
);
1897 cupsdLogRequest(con
, HTTP_STATUS_NOT_FOUND
);
1899 else if (!check_if_modified(con
, &filestats
))
1901 if (!cupsdSendError(con
, HTTP_STATUS_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1903 cupsdCloseClient(con
);
1907 cupsdLogRequest(con
, HTTP_STATUS_NOT_MODIFIED
);
1915 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1917 strlcpy(line
, "text/plain", sizeof(line
));
1919 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1921 if (!cupsdSendHeader(con
, HTTP_STATUS_OK
, line
, CUPSD_AUTH_NONE
))
1923 cupsdCloseClient(con
);
1927 if (httpPrintf(con
->http
, "Last-Modified: %s\r\n",
1928 httpGetDateString(filestats
.st_mtime
)) < 0)
1930 cupsdCloseClient(con
);
1934 if (httpPrintf(con
->http
, "Content-Length: %lu\r\n",
1935 (unsigned long)filestats
.st_size
) < 0)
1937 cupsdCloseClient(con
);
1941 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1944 if (httpPrintf(con
->http
, "\r\n") < 0)
1946 cupsdCloseClient(con
);
1950 if (cupsdFlushHeader(con
) < 0)
1952 cupsdCloseClient(con
);
1956 con
->http
->state
= HTTP_STATE_WAITING
;
1957 DEBUG_puts("cupsdReadClient: Set state to HTTP_STATE_WAITING "
1962 break; /* Anti-compiler-warning-code */
1968 * Handle any incoming data...
1971 switch (httpGetState(con
->http
))
1973 case HTTP_STATE_PUT_RECV
:
1976 if ((bytes
= httpRead2(con
->http
, line
, sizeof(line
))) < 0)
1978 if (httpError(con
->http
) && httpError(con
->http
) != EPIPE
)
1979 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1980 "HTTP_STATE_PUT_RECV Closing for error %d (%s)",
1981 httpError(con
->http
), strerror(httpError(con
->http
)));
1983 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1984 "HTTP_STATE_PUT_RECV Closing on EOF.");
1986 cupsdCloseClient(con
);
1991 con
->bytes
+= bytes
;
1993 if (write(con
->file
, line
, bytes
) < bytes
)
1995 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1996 "Unable to write %d bytes to \"%s\": %s", bytes
,
1997 con
->filename
, strerror(errno
));
2001 unlink(con
->filename
);
2002 cupsdClearString(&con
->filename
);
2004 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2006 cupsdCloseClient(con
);
2012 while (httpGetState(con
->http
) == HTTP_STATE_PUT_RECV
&& httpGetReady(con
->http
));
2014 if (httpGetState(con
->http
) == HTTP_STATE_STATUS
)
2017 * End of file, see how big it is...
2020 fstat(con
->file
, &filestats
);
2025 if (filestats
.st_size
> MaxRequestSize
&&
2029 * Request is too big; remove it and send an error...
2032 unlink(con
->filename
);
2033 cupsdClearString(&con
->filename
);
2035 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2037 cupsdCloseClient(con
);
2043 * Install the configuration file...
2046 status
= install_cupsd_conf(con
);
2049 * Return the status to the client...
2052 if (!cupsdSendError(con
, status
, CUPSD_AUTH_NONE
))
2054 cupsdCloseClient(con
);
2060 case HTTP_STATE_POST_RECV
:
2063 if (con
->request
&& con
->file
< 0)
2066 * Grab any request data from the connection...
2069 if ((ipp_state
= ippRead(con
->http
, con
->request
)) == IPP_STATE_ERROR
)
2071 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "IPP read error: %s",
2072 cupsLastErrorString());
2074 cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
);
2075 cupsdCloseClient(con
);
2078 else if (ipp_state
!= IPP_STATE_DATA
)
2080 if (httpGetState(con
->http
) == HTTP_STATE_POST_SEND
)
2082 cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
);
2083 cupsdCloseClient(con
);
2087 if (httpGetReady(con
->http
))
2093 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "%d.%d %s %d",
2094 con
->request
->request
.op
.version
[0],
2095 con
->request
->request
.op
.version
[1],
2096 ippOpString(con
->request
->request
.op
.operation_id
),
2097 con
->request
->request
.op
.request_id
);
2098 con
->bytes
+= ippLength(con
->request
);
2102 if (con
->file
< 0 && httpGetState(con
->http
) != HTTP_STATE_POST_SEND
)
2105 * Create a file as needed for the request data...
2108 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
2110 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
2114 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
2115 "Unable to create request file \"%s\": %s",
2116 con
->filename
, strerror(errno
));
2118 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2120 cupsdCloseClient(con
);
2125 fchmod(con
->file
, 0640);
2126 fchown(con
->file
, RunUser
, Group
);
2127 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2130 if (httpGetState(con
->http
) != HTTP_STATE_POST_SEND
)
2132 if (!httpWait(con
->http
, 0))
2134 else if ((bytes
= httpRead2(con
->http
, line
, sizeof(line
))) < 0)
2136 if (httpError(con
->http
) && httpError(con
->http
) != EPIPE
)
2137 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2138 "HTTP_STATE_POST_SEND Closing for error %d (%s)",
2139 httpError(con
->http
), strerror(httpError(con
->http
)));
2141 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2142 "HTTP_STATE_POST_SEND Closing on EOF.");
2144 cupsdCloseClient(con
);
2149 con
->bytes
+= bytes
;
2151 if (write(con
->file
, line
, bytes
) < bytes
)
2153 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
2154 "Unable to write %d bytes to \"%s\": %s",
2155 bytes
, con
->filename
, strerror(errno
));
2159 unlink(con
->filename
);
2160 cupsdClearString(&con
->filename
);
2162 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
,
2165 cupsdCloseClient(con
);
2170 else if (httpGetState(con
->http
) == HTTP_STATE_POST_RECV
)
2172 else if (httpGetState(con
->http
) != HTTP_STATE_POST_SEND
)
2174 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2175 "Closing on unexpected state %s.",
2176 httpStateString(httpGetState(con
->http
)));
2177 cupsdCloseClient(con
);
2182 while (httpGetState(con
->http
) == HTTP_STATE_POST_RECV
&& httpGetReady(con
->http
));
2184 if (httpGetState(con
->http
) == HTTP_STATE_POST_SEND
)
2188 fstat(con
->file
, &filestats
);
2193 if (filestats
.st_size
> MaxRequestSize
&&
2197 * Request is too big; remove it and send an error...
2200 unlink(con
->filename
);
2201 cupsdClearString(&con
->filename
);
2206 * Delete any IPP request data...
2209 ippDelete(con
->request
);
2210 con
->request
= NULL
;
2213 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2215 cupsdCloseClient(con
);
2219 else if (filestats
.st_size
== 0)
2222 * Don't allow empty file...
2225 unlink(con
->filename
);
2226 cupsdClearString(&con
->filename
);
2231 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
2233 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
2235 cupsdCloseClient(con
);
2240 cupsdLogRequest(con
, HTTP_STATUS_OK
);
2246 cupsdProcessIPPRequest(con
);
2250 unlink(con
->filename
);
2251 cupsdClearString(&con
->filename
);
2260 break; /* Anti-compiler-warning-code */
2263 if (httpGetState(con
->http
) == HTTP_STATE_WAITING
)
2265 if (!httpGetKeepAlive(con
->http
))
2267 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2268 "Closing because Keep-Alive is disabled.");
2269 cupsdCloseClient(con
);
2273 cupsArrayRemove(ActiveClients
, con
);
2274 cupsdSetBusyState();
2281 * 'cupsdSendCommand()' - Send output from a command via HTTP.
2284 int /* O - 1 on success, 0 on failure */
2286 cupsd_client_t
*con
, /* I - Client connection */
2287 char *command
, /* I - Command to run */
2288 char *options
, /* I - Command-line options */
2289 int root
) /* I - Run as root? */
2291 int fd
; /* Standard input file descriptor */
2296 fd
= open(con
->filename
, O_RDONLY
);
2300 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
2301 "Unable to open \"%s\" for reading: %s",
2302 con
->filename
? con
->filename
: "/dev/null",
2307 fcntl(fd
, F_SETFD
, fcntl(fd
, F_GETFD
) | FD_CLOEXEC
);
2312 con
->pipe_pid
= pipe_command(con
, fd
, &(con
->file
), command
, options
, root
);
2317 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Started \"%s\" (pid=%d, file=%d)",
2318 command
, con
->pipe_pid
, con
->file
);
2320 if (con
->pipe_pid
== 0)
2323 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2325 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2327 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for CGI data.");
2329 con
->sent_header
= 0;
2330 con
->file_ready
= 0;
2331 con
->got_fields
= 0;
2332 con
->header_used
= 0;
2339 * 'cupsdSendError()' - Send an error message via HTTP.
2342 int /* O - 1 if successful, 0 otherwise */
2343 cupsdSendError(cupsd_client_t
*con
, /* I - Connection */
2344 http_status_t code
, /* I - Error code */
2345 int auth_type
)/* I - Authentication type */
2347 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "cupsdSendError code=%d, auth_type=%d",
2352 * Force client to upgrade for authentication if that is how the
2353 * server is configured...
2356 if (code
== HTTP_STATUS_UNAUTHORIZED
&&
2357 DefaultEncryption
== HTTP_ENCRYPTION_REQUIRED
&&
2358 _cups_strcasecmp(httpGetHostname(con
->http
, NULL
, 0), "localhost") &&
2359 !httpIsEncrypted(con
->http
))
2361 code
= HTTP_STATUS_UPGRADE_REQUIRED
;
2363 #endif /* HAVE_SSL */
2366 * Put the request in the access_log file...
2369 cupsdLogRequest(con
, code
);
2372 * To work around bugs in some proxies, don't use Keep-Alive for some
2375 * Kerberos authentication doesn't work without Keep-Alive, so
2376 * never disable it in that case.
2379 if (code
>= HTTP_STATUS_BAD_REQUEST
&& con
->type
!= CUPSD_AUTH_NEGOTIATE
)
2380 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
2383 * Send an error message back to the client. If the error code is a
2384 * 400 or 500 series, make sure the message contains some text, too!
2387 if (!cupsdSendHeader(con
, code
, NULL
, auth_type
))
2391 if (code
== HTTP_STATUS_UPGRADE_REQUIRED
)
2392 if (httpPrintf(con
->http
, "Connection: Upgrade\r\n") < 0)
2395 if (httpPrintf(con
->http
, "Upgrade: TLS/1.2,TLS/1.1,TLS/1.0\r\n") < 0)
2397 #endif /* HAVE_SSL */
2399 if (con
->http
->version
>= HTTP_VERSION_1_1
&&
2400 httpGetKeepAlive(con
->http
) == HTTP_KEEPALIVE_OFF
)
2402 if (httpPrintf(con
->http
, "Connection: close\r\n") < 0)
2406 if (code
>= HTTP_STATUS_BAD_REQUEST
)
2409 * Send a human-readable error message.
2412 char message
[4096], /* Message for user */
2413 urltext
[1024], /* URL redirection text */
2414 redirect
[1024]; /* Redirection link */
2415 const char *text
; /* Status-specific text */
2420 if (code
== HTTP_STATUS_UNAUTHORIZED
)
2421 text
= _cupsLangString(con
->language
,
2422 _("Enter your username and password or the "
2423 "root username and password to access this "
2424 "page. If you are using Kerberos authentication, "
2425 "make sure you have a valid Kerberos ticket."));
2426 else if (code
== HTTP_STATUS_UPGRADE_REQUIRED
)
2430 snprintf(urltext
, sizeof(urltext
),
2431 _cupsLangString(con
->language
,
2432 _("You must access this page using the URL "
2433 "<A HREF=\"https://%s:%d%s\">"
2434 "https://%s:%d%s</A>.")),
2435 con
->servername
, con
->serverport
, con
->uri
,
2436 con
->servername
, con
->serverport
, con
->uri
);
2438 snprintf(redirect
, sizeof(redirect
),
2439 "<META HTTP-EQUIV=\"Refresh\" "
2440 "CONTENT=\"3;URL=https://%s:%d%s\">\n",
2441 con
->servername
, con
->serverport
, con
->uri
);
2443 else if (code
== HTTP_STATUS_CUPS_WEBIF_DISABLED
)
2444 text
= _cupsLangString(con
->language
,
2445 _("The web interface is currently disabled. Run "
2446 "\"cupsctl WebInterface=yes\" to enable it."));
2450 snprintf(message
, sizeof(message
),
2451 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" "
2452 "\"http://www.w3.org/TR/html4/loose.dtd\">\n"
2455 "\t<META HTTP-EQUIV=\"Content-Type\" "
2456 "CONTENT=\"text/html; charset=utf-8\">\n"
2457 "\t<TITLE>%s - " CUPS_SVERSION
"</TITLE>\n"
2458 "\t<LINK REL=\"STYLESHEET\" TYPE=\"text/css\" "
2459 "HREF=\"/cups.css\">\n"
2467 _httpStatus(con
->language
, code
), redirect
,
2468 _httpStatus(con
->language
, code
), text
);
2470 if (httpPrintf(con
->http
, "Content-Type: text/html; charset=utf-8\r\n") < 0)
2472 if (httpPrintf(con
->http
, "Content-Length: %d\r\n",
2473 (int)strlen(message
)) < 0)
2475 if (httpPrintf(con
->http
, "\r\n") < 0)
2477 if (httpPrintf(con
->http
, "%s", message
) < 0)
2480 else if (httpPrintf(con
->http
, "\r\n") < 0)
2483 if (cupsdFlushHeader(con
) < 0)
2486 con
->http
->state
= HTTP_STATE_WAITING
;
2488 DEBUG_puts("cupsdSendError: Set state to HTTP_STATE_WAITING.");
2495 * 'cupsdSendHeader()' - Send an HTTP request.
2498 int /* O - 1 on success, 0 on failure */
2500 cupsd_client_t
*con
, /* I - Client to send to */
2501 http_status_t code
, /* I - HTTP status code */
2502 char *type
, /* I - MIME type of document */
2503 int auth_type
) /* I - Type of authentication */
2505 char auth_str
[1024]; /* Authorization string */
2509 * Send the HTTP status header...
2512 if (code
== HTTP_STATUS_CONTINUE
)
2515 * 100-continue doesn't send any headers...
2518 return (httpPrintf(con
->http
, "HTTP/%d.%d 100 Continue\r\n\r\n",
2519 con
->http
->version
/ 100, con
->http
->version
% 100) > 0);
2521 else if (code
== HTTP_STATUS_CUPS_WEBIF_DISABLED
)
2524 * Treat our special "web interface is disabled" status as "200 OK" for web
2528 code
= HTTP_STATUS_OK
;
2531 httpFlushWrite(con
->http
);
2533 con
->http
->data_encoding
= HTTP_ENCODING_FIELDS
;
2535 if (httpPrintf(con
->http
, "HTTP/%d.%d %d %s\r\n", con
->http
->version
/ 100,
2536 con
->http
->version
% 100, code
, httpStatus(code
)) < 0)
2538 if (httpPrintf(con
->http
, "Date: %s\r\n", httpGetDateString(time(NULL
))) < 0)
2541 if (httpPrintf(con
->http
, "Server: %s\r\n", ServerHeader
) < 0)
2543 if (httpGetKeepAlive(con
->http
) && con
->http
->version
>= HTTP_VERSION_1_0
)
2545 if (httpPrintf(con
->http
, "Connection: Keep-Alive\r\n") < 0)
2547 if (httpPrintf(con
->http
, "Keep-Alive: timeout=%d\r\n",
2548 KeepAliveTimeout
) < 0)
2551 else if (httpPrintf(con
->http
, "Connection: close\r\n") < 0)
2554 if (code
== HTTP_STATUS_METHOD_NOT_ALLOWED
)
2555 if (httpPrintf(con
->http
, "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n") < 0)
2558 if (code
== HTTP_STATUS_UNAUTHORIZED
)
2560 if (auth_type
== CUPSD_AUTH_NONE
)
2562 if (!con
->best
|| con
->best
->type
<= CUPSD_AUTH_NONE
)
2563 auth_type
= cupsdDefaultAuthType();
2565 auth_type
= con
->best
->type
;
2570 if (auth_type
== CUPSD_AUTH_BASIC
|| auth_type
== CUPSD_AUTH_BASICDIGEST
)
2571 strlcpy(auth_str
, "Basic realm=\"CUPS\"", sizeof(auth_str
));
2572 else if (auth_type
== CUPSD_AUTH_DIGEST
)
2573 snprintf(auth_str
, sizeof(auth_str
), "Digest realm=\"CUPS\", nonce=\"%s\"",
2574 httpGetHostname(con
->http
, NULL
, 0));
2576 else if (auth_type
== CUPSD_AUTH_NEGOTIATE
)
2579 if (httpAddrFamily(httpGetAddress(con
->http
)) == AF_LOCAL
)
2580 strlcpy(auth_str
, "Basic realm=\"CUPS\"", sizeof(auth_str
));
2582 # endif /* AF_LOCAL */
2583 strlcpy(auth_str
, "Negotiate", sizeof(auth_str
));
2585 #endif /* HAVE_GSSAPI */
2587 if (con
->best
&& auth_type
!= CUPSD_AUTH_NEGOTIATE
&&
2588 !_cups_strcasecmp(httpGetHostname(con
->http
, NULL
, 0), "localhost"))
2591 * Add a "trc" (try root certification) parameter for local non-Kerberos
2592 * requests when the request requires system group membership - then the
2593 * client knows the root certificate can/should be used.
2595 * Also, for OS X we also look for @AUTHKEY and add an "authkey"
2596 * parameter as needed...
2599 char *name
, /* Current user name */
2600 *auth_key
; /* Auth key buffer */
2601 size_t auth_size
; /* Size of remaining buffer */
2603 auth_key
= auth_str
+ strlen(auth_str
);
2604 auth_size
= sizeof(auth_str
) - (auth_key
- auth_str
);
2606 for (name
= (char *)cupsArrayFirst(con
->best
->names
);
2608 name
= (char *)cupsArrayNext(con
->best
->names
))
2610 #ifdef HAVE_AUTHORIZATION_H
2611 if (!_cups_strncasecmp(name
, "@AUTHKEY(", 9))
2613 snprintf(auth_key
, auth_size
, ", authkey=\"%s\"", name
+ 9);
2614 /* end parenthesis is stripped in conf.c */
2618 #endif /* HAVE_AUTHORIZATION_H */
2619 if (!_cups_strcasecmp(name
, "@SYSTEM"))
2621 #ifdef HAVE_AUTHORIZATION_H
2622 if (SystemGroupAuthKey
)
2623 snprintf(auth_key
, auth_size
,
2625 SystemGroupAuthKey
);
2628 strlcpy(auth_key
, ", trc=\"y\"", auth_size
);
2629 #endif /* HAVE_AUTHORIZATION_H */
2637 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "WWW-Authenticate: %s", auth_str
);
2639 if (httpPrintf(con
->http
, "WWW-Authenticate: %s\r\n", auth_str
) < 0)
2644 if (con
->language
&& strcmp(con
->language
->language
, "C"))
2646 if (httpPrintf(con
->http
, "Content-Language: %s\r\n",
2647 con
->language
->language
) < 0)
2653 if (!strcmp(type
, "text/html"))
2655 if (httpPrintf(con
->http
,
2656 "Content-Type: text/html; charset=utf-8\r\n") < 0)
2659 else if (httpPrintf(con
->http
, "Content-Type: %s\r\n", type
) < 0)
2668 * 'cupsdUpdateCGI()' - Read status messages from CGI scripts and programs.
2672 cupsdUpdateCGI(void)
2674 char *ptr
, /* Pointer to end of line in buffer */
2675 message
[1024]; /* Pointer to message text */
2676 int loglevel
; /* Log level for message */
2679 while ((ptr
= cupsdStatBufUpdate(CGIStatusBuffer
, &loglevel
,
2680 message
, sizeof(message
))) != NULL
)
2682 if (loglevel
== CUPSD_LOG_INFO
)
2683 cupsdLogMessage(CUPSD_LOG_INFO
, "%s", message
);
2685 if (!strchr(CGIStatusBuffer
->buffer
, '\n'))
2689 if (ptr
== NULL
&& !CGIStatusBuffer
->bufused
)
2692 * Fatal error on pipe - should never happen!
2695 cupsdLogMessage(CUPSD_LOG_CRIT
,
2696 "cupsdUpdateCGI: error reading from CGI error pipe - %s",
2703 * 'cupsdWriteClient()' - Write data to a client as needed.
2707 cupsdWriteClient(cupsd_client_t
*con
) /* I - Client connection */
2709 int bytes
, /* Number of bytes written */
2710 field_col
; /* Current column */
2711 char *bufptr
, /* Pointer into buffer */
2712 *bufend
; /* Pointer to end of buffer */
2713 ipp_state_t ipp_state
; /* IPP state value */
2716 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "con->http=%p", con
->http
);
2717 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2722 "data_encoding=HTTP_ENCODING_%s, "
2723 "data_remaining=" CUPS_LLFMT
", "
2727 httpError(con
->http
), (int)httpGetReady(con
->http
),
2728 httpStateString(httpGetState(con
->http
)),
2729 con
->http
->data_encoding
== HTTP_ENCODING_CHUNKED
?
2730 "CHUNKED" : "LENGTH",
2731 CUPS_LLCAST con
->http
->data_remaining
,
2733 con
->response
? ipp_states
[con
->response
->state
] : "",
2734 con
->pipe_pid
, con
->file
);
2736 if (httpGetState(con
->http
) != HTTP_STATE_GET_SEND
&&
2737 httpGetState(con
->http
) != HTTP_STATE_POST_SEND
)
2740 * If we get called in the wrong state, then something went wrong with the
2741 * connection and we need to shut it down...
2744 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing on unexpected HTTP state %s.",
2745 httpStateString(httpGetState(con
->http
)));
2746 cupsdCloseClient(con
);
2753 * Make sure we select on the CGI output...
2756 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2758 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for CGI data.");
2760 if (!con
->file_ready
)
2763 * Try again later when there is CGI output available...
2766 cupsdRemoveSelect(httpGetFd(con
->http
));
2770 con
->file_ready
= 0;
2773 if (con
->response
&& con
->response
->state
!= IPP_STATE_DATA
)
2775 int wused
= con
->http
->wused
; /* Previous write buffer use */
2780 * Write a single attribute or the IPP message header...
2783 ipp_state
= ippWrite(con
->http
, con
->response
);
2786 * If the write buffer has been flushed, stop buffering up attributes...
2789 if (con
->http
->wused
<= wused
)
2792 while (ipp_state
!= IPP_STATE_DATA
&& ipp_state
!= IPP_STATE_ERROR
);
2794 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2795 "Writing IPP response, ipp_state=%s, old "
2796 "wused=%d, new wused=%d",
2797 ipp_state
== IPP_STATE_ERROR
? "ERROR" :
2798 ipp_state
== IPP_STATE_IDLE
? "IDLE" :
2799 ipp_state
== IPP_STATE_HEADER
? "HEADER" :
2800 ipp_state
== IPP_STATE_ATTRIBUTE
? "ATTRIBUTE" : "DATA",
2801 wused
, con
->http
->wused
);
2803 if (con
->http
->wused
> 0)
2804 httpFlushWrite(con
->http
);
2806 bytes
= ipp_state
!= IPP_STATE_ERROR
&&
2807 (con
->file
>= 0 || ipp_state
!= IPP_STATE_DATA
);
2809 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2810 "bytes=%d, http_state=%d, data_remaining=" CUPS_LLFMT
,
2811 (int)bytes
, httpGetState(con
->http
),
2812 CUPS_LLCAST con
->http
->data_remaining
);
2814 else if ((bytes
= read(con
->file
, con
->header
+ con
->header_used
,
2815 sizeof(con
->header
) - con
->header_used
)) > 0)
2817 con
->header_used
+= bytes
;
2819 if (con
->pipe_pid
&& !con
->got_fields
)
2822 * Inspect the data for Content-Type and other fields.
2825 for (bufptr
= con
->header
, bufend
= con
->header
+ con
->header_used
,
2827 !con
->got_fields
&& bufptr
< bufend
;
2830 if (*bufptr
== '\n')
2833 * Send line to client...
2836 if (bufptr
> con
->header
&& bufptr
[-1] == '\r')
2840 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Script header: %s", con
->header
);
2842 if (!con
->sent_header
)
2845 * Handle redirection and CGI status codes...
2848 if (!_cups_strncasecmp(con
->header
, "Location:", 9))
2850 if (!cupsdSendHeader(con
, HTTP_STATUS_SEE_OTHER
, NULL
, CUPSD_AUTH_NONE
))
2852 cupsdCloseClient(con
);
2856 con
->sent_header
= 2;
2858 if (httpPrintf(con
->http
, "Content-Length: 0\r\n") < 0)
2861 else if (!_cups_strncasecmp(con
->header
, "Status:", 7))
2863 cupsdSendError(con
, (http_status_t
)atoi(con
->header
+ 7),
2865 con
->sent_header
= 2;
2869 if (!cupsdSendHeader(con
, HTTP_STATUS_OK
, NULL
, CUPSD_AUTH_NONE
))
2871 cupsdCloseClient(con
);
2875 con
->sent_header
= 1;
2877 if (con
->http
->version
== HTTP_VERSION_1_1
)
2879 if (httpPrintf(con
->http
, "Transfer-Encoding: chunked\r\n") < 0)
2885 if (_cups_strncasecmp(con
->header
, "Status:", 7))
2886 httpPrintf(con
->http
, "%s\r\n", con
->header
);
2892 con
->header_used
-= bufptr
- con
->header
;
2894 if (con
->header_used
> 0)
2895 memmove(con
->header
, bufptr
, con
->header_used
);
2897 bufptr
= con
->header
- 1;
2900 * See if the line was empty...
2905 con
->got_fields
= 1;
2907 if (cupsdFlushHeader(con
) < 0)
2909 cupsdCloseClient(con
);
2913 if (con
->http
->version
== HTTP_VERSION_1_1
)
2914 con
->http
->data_encoding
= HTTP_ENCODING_CHUNKED
;
2919 else if (*bufptr
!= '\r')
2923 if (!con
->got_fields
)
2925 con
->http
->activity
= time(NULL
);
2930 if (con
->header_used
> 0)
2932 if (httpWrite2(con
->http
, con
->header
, con
->header_used
) < 0)
2934 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing for error %d (%s)",
2935 httpError(con
->http
), strerror(httpError(con
->http
)));
2936 cupsdCloseClient(con
);
2940 if (con
->http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
2941 httpFlushWrite(con
->http
);
2943 con
->bytes
+= con
->header_used
;
2945 if (httpGetState(con
->http
) == HTTP_STATE_WAITING
)
2948 bytes
= con
->header_used
;
2950 con
->header_used
= 0;
2955 (httpGetState(con
->http
) != HTTP_STATE_GET_SEND
&&
2956 httpGetState(con
->http
) != HTTP_STATE_POST_SEND
))
2958 if (!con
->sent_header
&& con
->pipe_pid
)
2959 cupsdSendError(con
, HTTP_STATUS_SERVER_ERROR
, CUPSD_AUTH_NONE
);
2962 cupsdLogRequest(con
, HTTP_STATUS_OK
);
2964 httpFlushWrite(con
->http
);
2966 if (con
->http
->data_encoding
== HTTP_ENCODING_CHUNKED
&&
2967 con
->sent_header
== 1)
2969 if (httpWrite2(con
->http
, "", 0) < 0)
2971 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing for error %d (%s)",
2972 httpError(con
->http
), strerror(httpError(con
->http
)));
2973 cupsdCloseClient(con
);
2979 con
->http
->state
= HTTP_STATE_WAITING
;
2981 cupsdAddSelect(httpGetFd(con
->http
), (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
2983 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for request.");
2987 cupsdRemoveSelect(con
->file
);
2990 cupsdEndProcess(con
->pipe_pid
, 0);
2999 unlink(con
->filename
);
3000 cupsdClearString(&con
->filename
);
3005 ippDelete(con
->request
);
3006 con
->request
= NULL
;
3011 ippDelete(con
->response
);
3012 con
->response
= NULL
;
3015 cupsdClearString(&con
->command
);
3016 cupsdClearString(&con
->options
);
3017 cupsdClearString(&con
->query_string
);
3019 if (!httpGetKeepAlive(con
->http
))
3021 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
3022 "Closing because Keep-Alive is disabled.");
3023 cupsdCloseClient(con
);
3028 cupsArrayRemove(ActiveClients
, con
);
3029 cupsdSetBusyState();
3033 con
->http
->activity
= time(NULL
);
3038 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
3041 static int /* O - 1 if modified since */
3043 cupsd_client_t
*con
, /* I - Client connection */
3044 struct stat
*filestats
) /* I - File information */
3046 const char *ptr
; /* Pointer into field */
3047 time_t date
; /* Time/date value */
3048 off_t size
; /* Size/length value */
3053 ptr
= httpGetField(con
->http
, HTTP_FIELD_IF_MODIFIED_SINCE
);
3058 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3059 "check_if_modified "
3060 "filestats=%p(" CUPS_LLFMT
", %d)) If-Modified-Since=\"%s\"",
3061 filestats
, CUPS_LLCAST filestats
->st_size
,
3062 (int)filestats
->st_mtime
, ptr
);
3064 while (*ptr
!= '\0')
3066 while (isspace(*ptr
) || *ptr
== ';')
3069 if (_cups_strncasecmp(ptr
, "length=", 7) == 0)
3072 size
= strtoll(ptr
, NULL
, 10);
3074 while (isdigit(*ptr
))
3077 else if (isalpha(*ptr
))
3079 date
= httpGetDateTime(ptr
);
3080 while (*ptr
!= '\0' && *ptr
!= ';')
3087 return ((size
!= filestats
->st_size
&& size
!= 0) ||
3088 (date
< filestats
->st_mtime
&& date
!= 0) ||
3089 (size
== 0 && date
== 0));
3094 * 'compare_clients()' - Compare two client connections.
3097 static int /* O - Result of comparison */
3098 compare_clients(cupsd_client_t
*a
, /* I - First client */
3099 cupsd_client_t
*b
, /* I - Second client */
3100 void *data
) /* I - User data (not used) */
3114 * 'get_file()' - Get a filename and state info.
3117 static char * /* O - Real filename */
3118 get_file(cupsd_client_t
*con
, /* I - Client connection */
3119 struct stat
*filestats
, /* O - File information */
3120 char *filename
, /* IO - Filename buffer */
3121 int len
) /* I - Buffer length */
3123 int status
; /* Status of filesystem calls */
3124 char *ptr
; /* Pointer info filename */
3125 int plen
; /* Remaining length after pointer */
3126 char language
[7]; /* Language subdirectory, if any */
3130 * Figure out the real filename...
3135 if (!strncmp(con
->uri
, "/ppd/", 5) && !strchr(con
->uri
+ 5, '/'))
3136 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
);
3137 else if (!strncmp(con
->uri
, "/icons/", 7) && !strchr(con
->uri
+ 7, '/'))
3139 snprintf(filename
, len
, "%s/%s", CacheDir
, con
->uri
+ 7);
3140 if (access(filename
, F_OK
) < 0)
3141 snprintf(filename
, len
, "%s/images/generic.png", DocumentRoot
);
3143 else if (!strncmp(con
->uri
, "/rss/", 5) && !strchr(con
->uri
+ 5, '/'))
3144 snprintf(filename
, len
, "%s/rss/%s", CacheDir
, con
->uri
+ 5);
3145 else if (!strncmp(con
->uri
, "/admin/conf/", 12))
3146 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
+ 11);
3147 else if (!strncmp(con
->uri
, "/admin/log/", 11))
3149 if (!strncmp(con
->uri
+ 11, "access_log", 10) && AccessLog
[0] == '/')
3150 strlcpy(filename
, AccessLog
, len
);
3151 else if (!strncmp(con
->uri
+ 11, "error_log", 9) && ErrorLog
[0] == '/')
3152 strlcpy(filename
, ErrorLog
, len
);
3153 else if (!strncmp(con
->uri
+ 11, "page_log", 8) && PageLog
[0] == '/')
3154 strlcpy(filename
, PageLog
, len
);
3158 else if (con
->language
)
3160 snprintf(language
, sizeof(language
), "/%s", con
->language
->language
);
3161 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3164 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3166 if ((ptr
= strchr(filename
, '?')) != NULL
)
3170 * Grab the status for this language; if there isn't a language-specific file
3171 * then fallback to the default one...
3174 if ((status
= stat(filename
, filestats
)) != 0 && language
[0] &&
3175 strncmp(con
->uri
, "/icons/", 7) &&
3176 strncmp(con
->uri
, "/ppd/", 5) &&
3177 strncmp(con
->uri
, "/rss/", 5) &&
3178 strncmp(con
->uri
, "/admin/conf/", 12) &&
3179 strncmp(con
->uri
, "/admin/log/", 11))
3182 * Drop the country code...
3186 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3188 if ((ptr
= strchr(filename
, '?')) != NULL
)
3191 if ((status
= stat(filename
, filestats
)) != 0)
3194 * Drop the language prefix and try the root directory...
3198 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3200 if ((ptr
= strchr(filename
, '?')) != NULL
)
3203 status
= stat(filename
, filestats
);
3208 * If we're found a directory, get the index.html file instead...
3211 if (!status
&& S_ISDIR(filestats
->st_mode
))
3214 * Make sure the URI ends with a slash...
3217 if (con
->uri
[strlen(con
->uri
) - 1] != '/')
3218 strlcat(con
->uri
, "/", sizeof(con
->uri
));
3221 * Find the directory index file, trying every language...
3226 if (status
&& language
[0])
3229 * Try a different language subset...
3233 language
[0] = '\0'; /* Strip country code */
3235 language
[0] = '\0'; /* Strip language */
3239 * Look for the index file...
3242 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3244 if ((ptr
= strchr(filename
, '?')) != NULL
)
3247 ptr
= filename
+ strlen(filename
);
3248 plen
= len
- (ptr
- filename
);
3250 strlcpy(ptr
, "index.html", plen
);
3251 status
= stat(filename
, filestats
);
3256 strlcpy(ptr
, "index.class", plen
);
3257 status
= stat(filename
, filestats
);
3259 #endif /* HAVE_JAVA */
3264 strlcpy(ptr
, "index.pl", plen
);
3265 status
= stat(filename
, filestats
);
3267 #endif /* HAVE_PERL */
3272 strlcpy(ptr
, "index.php", plen
);
3273 status
= stat(filename
, filestats
);
3275 #endif /* HAVE_PHP */
3280 strlcpy(ptr
, "index.pyc", plen
);
3281 status
= stat(filename
, filestats
);
3286 strlcpy(ptr
, "index.py", plen
);
3287 status
= stat(filename
, filestats
);
3289 #endif /* HAVE_PYTHON */
3292 while (status
&& language
[0]);
3295 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3296 "get_file filestats=%p, filename=%p, len=%d, "
3297 "returning \"%s\".", filestats
, filename
, len
,
3298 status
? "(null)" : filename
);
3308 * 'install_cupsd_conf()' - Install a configuration file.
3311 static http_status_t
/* O - Status */
3312 install_cupsd_conf(cupsd_client_t
*con
) /* I - Connection */
3314 char filename
[1024]; /* Configuration filename */
3315 cups_file_t
*in
, /* Input file */
3316 *out
; /* Output file */
3317 char buffer
[16384]; /* Copy buffer */
3318 ssize_t bytes
; /* Number of bytes */
3322 * Open the request file...
3325 if ((in
= cupsFileOpen(con
->filename
, "rb")) == NULL
)
3327 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Unable to open request file \"%s\": %s",
3328 con
->filename
, strerror(errno
));
3329 return (HTTP_STATUS_SERVER_ERROR
);
3333 * Open the new config file...
3336 if ((out
= cupsdCreateConfFile(ConfigurationFile
, ConfigFilePerm
)) == NULL
)
3339 return (HTTP_STATUS_SERVER_ERROR
);
3342 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Installing config file \"%s\"...",
3346 * Copy from the request to the new config file...
3349 while ((bytes
= cupsFileRead(in
, buffer
, sizeof(buffer
))) > 0)
3350 if (cupsFileWrite(out
, buffer
, bytes
) < bytes
)
3352 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
3353 "Unable to copy to config file \"%s\": %s",
3354 ConfigurationFile
, strerror(errno
));
3359 snprintf(filename
, sizeof(filename
), "%s.N", ConfigurationFile
);
3360 cupsdUnlinkOrRemoveFile(filename
);
3362 return (HTTP_STATUS_SERVER_ERROR
);
3366 * Close the files...
3371 if (cupsdCloseCreatedConfFile(out
, ConfigurationFile
))
3372 return (HTTP_STATUS_SERVER_ERROR
);
3375 * Remove the request file...
3378 cupsdUnlinkOrRemoveFile(con
->filename
);
3379 cupsdClearString(&con
->filename
);
3382 * Set the NeedReload flag...
3385 NeedReload
= RELOAD_CUPSD
;
3386 ReloadTime
= time(NULL
);
3389 * Return that the file was created successfully...
3392 return (HTTP_STATUS_CREATED
);
3397 * 'is_cgi()' - Is the resource a CGI script/program?
3400 static int /* O - 1 = CGI, 0 = file */
3401 is_cgi(cupsd_client_t
*con
, /* I - Client connection */
3402 const char *filename
, /* I - Real filename */
3403 struct stat
*filestats
, /* I - File information */
3404 mime_type_t
*type
) /* I - MIME type */
3406 const char *options
; /* Options on URL */
3410 * Get the options, if any...
3413 if ((options
= strchr(con
->uri
, '?')) != NULL
)
3416 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", options
);
3420 * Check for known types...
3423 if (!type
|| _cups_strcasecmp(type
->super
, "application"))
3425 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3426 "is_cgi filename=\"%s\", filestats=%p, "
3427 "type=%s/%s, returning 0", filename
,
3428 filestats
, type
? type
->super
: "unknown",
3429 type
? type
->type
: "unknown");
3433 if (!_cups_strcasecmp(type
->type
, "x-httpd-cgi") &&
3434 (filestats
->st_mode
& 0111))
3437 * "application/x-httpd-cgi" is a CGI script.
3440 cupsdSetString(&con
->command
, filename
);
3443 cupsdSetStringf(&con
->options
, " %s", options
);
3445 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3446 "is_cgi filename=\"%s\", filestats=%p, "
3447 "type=%s/%s, returning 1", filename
,
3448 filestats
, type
->super
, type
->type
);
3452 else if (!_cups_strcasecmp(type
->type
, "x-httpd-java"))
3455 * "application/x-httpd-java" is a Java servlet.
3458 cupsdSetString(&con
->command
, CUPS_JAVA
);
3461 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3463 cupsdSetStringf(&con
->options
, " %s", filename
);
3465 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3466 "is_cgi filename=\"%s\", filestats=%p, "
3467 "type=%s/%s, returning 1", filename
,
3468 filestats
, type
->super
, type
->type
);
3471 #endif /* HAVE_JAVA */
3473 else if (!_cups_strcasecmp(type
->type
, "x-httpd-perl"))
3476 * "application/x-httpd-perl" is a Perl page.
3479 cupsdSetString(&con
->command
, CUPS_PERL
);
3482 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3484 cupsdSetStringf(&con
->options
, " %s", filename
);
3486 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3487 "is_cgi filename=\"%s\", filestats=%p, "
3488 "type=%s/%s, returning 1", filename
,
3489 filestats
, type
->super
, type
->type
);
3492 #endif /* HAVE_PERL */
3494 else if (!_cups_strcasecmp(type
->type
, "x-httpd-php"))
3497 * "application/x-httpd-php" is a PHP page.
3500 cupsdSetString(&con
->command
, CUPS_PHP
);
3503 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3505 cupsdSetStringf(&con
->options
, " %s", filename
);
3507 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3508 "is_cgi filename=\"%s\", filestats=%p, "
3509 "type=%s/%s, returning 1", filename
,
3510 filestats
, type
->super
, type
->type
);
3513 #endif /* HAVE_PHP */
3515 else if (!_cups_strcasecmp(type
->type
, "x-httpd-python"))
3518 * "application/x-httpd-python" is a Python page.
3521 cupsdSetString(&con
->command
, CUPS_PYTHON
);
3524 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3526 cupsdSetStringf(&con
->options
, " %s", filename
);
3528 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3529 "is_cgi filename=\"%s\", filestats=%p, "
3530 "type=%s/%s, returning 1", filename
,
3531 filestats
, type
->super
, type
->type
);
3534 #endif /* HAVE_PYTHON */
3536 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3537 "is_cgi filename=\"%s\", filestats=%p, "
3538 "type=%s/%s, returning 0", filename
,
3539 filestats
, type
->super
, type
->type
);
3545 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
3548 static int /* O - 0 if relative, 1 if absolute */
3549 is_path_absolute(const char *path
) /* I - Input path */
3552 * Check for a leading slash...
3559 * Check for "/.." in the path...
3562 while ((path
= strstr(path
, "/..")) != NULL
)
3564 if (!path
[3] || path
[3] == '/')
3571 * If we haven't found any relative paths, return 1 indicating an
3580 * 'pipe_command()' - Pipe the output of a command to the remote client.
3583 static int /* O - Process ID */
3584 pipe_command(cupsd_client_t
*con
, /* I - Client connection */
3585 int infile
, /* I - Standard input for command */
3586 int *outfile
, /* O - Standard output for command */
3587 char *command
, /* I - Command to run */
3588 char *options
, /* I - Options for command */
3589 int root
) /* I - Run as root? */
3591 int i
; /* Looping var */
3592 int pid
; /* Process ID */
3593 char *commptr
, /* Command string pointer */
3594 commch
; /* Command string character */
3595 char *uriptr
; /* URI string pointer */
3596 int fds
[2]; /* Pipe FDs */
3597 int argc
; /* Number of arguments */
3598 int envc
; /* Number of environment variables */
3599 char argbuf
[10240], /* Argument buffer */
3600 *argv
[100], /* Argument strings */
3601 *envp
[MAX_ENV
+ 20]; /* Environment variables */
3602 char auth_type
[256], /* AUTH_TYPE environment variable */
3603 content_length
[1024], /* CONTENT_LENGTH environment variable */
3604 content_type
[1024], /* CONTENT_TYPE environment variable */
3605 http_cookie
[32768], /* HTTP_COOKIE environment variable */
3606 http_referer
[1024], /* HTTP_REFERER environment variable */
3607 http_user_agent
[1024], /* HTTP_USER_AGENT environment variable */
3608 lang
[1024], /* LANG environment variable */
3609 path_info
[1024], /* PATH_INFO environment variable */
3610 remote_addr
[1024], /* REMOTE_ADDR environment variable */
3611 remote_host
[1024], /* REMOTE_HOST environment variable */
3612 remote_user
[1024], /* REMOTE_USER environment variable */
3613 script_filename
[1024], /* SCRIPT_FILENAME environment variable */
3614 script_name
[1024], /* SCRIPT_NAME environment variable */
3615 server_name
[1024], /* SERVER_NAME environment variable */
3616 server_port
[1024]; /* SERVER_PORT environment variable */
3617 ipp_attribute_t
*attr
; /* attributes-natural-language attribute */
3621 * Parse a copy of the options string, which is of the form:
3623 * argument+argument+argument
3624 * ?argument+argument+argument
3625 * param=value¶m=value
3626 * ?param=value¶m=value
3627 * /name?argument+argument+argument
3628 * /name?param=value¶m=value
3630 * If the string contains an "=" character after the initial name,
3631 * then we treat it as a HTTP GET form request and make a copy of
3632 * the remaining string for the environment variable.
3634 * The string is always parsed out as command-line arguments, to
3635 * be consistent with Apache...
3638 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3639 "pipe_command infile=%d, outfile=%p, "
3640 "command=\"%s\", options=\"%s\", root=%d",
3641 infile
, outfile
, command
,
3642 options
? options
: "(null)", root
);
3649 if (*commptr
== ' ')
3651 strlcpy(argbuf
, commptr
, sizeof(argbuf
));
3656 if (argbuf
[0] == '/')
3659 * Found some trailing path information, set PATH_INFO...
3662 if ((commptr
= strchr(argbuf
, '?')) == NULL
)
3663 commptr
= argbuf
+ strlen(argbuf
);
3667 snprintf(path_info
, sizeof(path_info
), "PATH_INFO=%s", argbuf
);
3673 path_info
[0] = '\0';
3675 if (*commptr
== ' ')
3679 if (*commptr
== '?' && con
->operation
== HTTP_STATE_GET
&& !con
->query_string
)
3682 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", commptr
);
3689 argv
[argc
++] = commptr
;
3691 for (; *commptr
&& argc
< 99; commptr
++)
3694 * Break arguments whenever we see a + or space...
3697 if (*commptr
== ' ' || *commptr
== '+')
3699 while (*commptr
== ' ' || *commptr
== '+')
3703 * If we don't have a blank string, save it as another argument...
3708 argv
[argc
] = commptr
;
3714 else if (*commptr
== '%' && isxdigit(commptr
[1] & 255) &&
3715 isxdigit(commptr
[2] & 255))
3718 * Convert the %xx notation to the individual character.
3721 if (commptr
[1] >= '0' && commptr
[1] <= '9')
3722 *commptr
= (commptr
[1] - '0') << 4;
3724 *commptr
= (tolower(commptr
[1]) - 'a' + 10) << 4;
3726 if (commptr
[2] >= '0' && commptr
[2] <= '9')
3727 *commptr
|= commptr
[2] - '0';
3729 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
3731 _cups_strcpy(commptr
+ 1, commptr
+ 3);
3734 * Check for a %00 and break if that is the case...
3746 * Setup the environment variables as needed...
3749 if (con
->username
[0])
3751 snprintf(auth_type
, sizeof(auth_type
), "AUTH_TYPE=%s",
3752 httpGetField(con
->http
, HTTP_FIELD_AUTHORIZATION
));
3754 if ((uriptr
= strchr(auth_type
+ 10, ' ')) != NULL
)
3758 auth_type
[0] = '\0';
3761 (attr
= ippFindAttribute(con
->request
, "attributes-natural-language",
3762 IPP_TAG_LANGUAGE
)) != NULL
)
3764 switch (strlen(attr
->values
[0].string
.text
))
3768 * This is an unknown or badly formatted language code; use
3769 * the POSIX locale...
3772 strlcpy(lang
, "LANG=C", sizeof(lang
));
3777 * Just the language code (ll)...
3780 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8",
3781 attr
->values
[0].string
.text
);
3786 * Language and country code (ll-cc)...
3789 snprintf(lang
, sizeof(lang
), "LANG=%c%c_%c%c.UTF8",
3790 attr
->values
[0].string
.text
[0],
3791 attr
->values
[0].string
.text
[1],
3792 toupper(attr
->values
[0].string
.text
[3] & 255),
3793 toupper(attr
->values
[0].string
.text
[4] & 255));
3797 else if (con
->language
)
3798 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8", con
->language
->language
);
3800 strlcpy(lang
, "LANG=C", sizeof(lang
));
3802 strlcpy(remote_addr
, "REMOTE_ADDR=", sizeof(remote_addr
));
3803 httpAddrString(httpGetAddress(con
->http
), remote_addr
+ 12,
3804 sizeof(remote_addr
) - 12);
3806 snprintf(remote_host
, sizeof(remote_host
), "REMOTE_HOST=%s",
3807 httpGetHostname(con
->http
, NULL
, 0));
3809 snprintf(script_name
, sizeof(script_name
), "SCRIPT_NAME=%s", con
->uri
);
3810 if ((uriptr
= strchr(script_name
, '?')) != NULL
)
3813 snprintf(script_filename
, sizeof(script_filename
), "SCRIPT_FILENAME=%s%s",
3814 DocumentRoot
, script_name
+ 12);
3816 sprintf(server_port
, "SERVER_PORT=%d", con
->serverport
);
3818 if (httpGetField(con
->http
, HTTP_FIELD_HOST
)[0])
3820 char *nameptr
; /* Pointer to ":port" */
3822 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
3823 httpGetField(con
->http
, HTTP_FIELD_HOST
));
3824 if ((nameptr
= strrchr(server_name
, ':')) != NULL
&& !strchr(nameptr
, ']'))
3825 *nameptr
= '\0'; /* Strip trailing ":port" */
3828 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
3831 envc
= cupsdLoadEnv(envp
, (int)(sizeof(envp
) / sizeof(envp
[0])));
3834 envp
[envc
++] = auth_type
;
3836 envp
[envc
++] = lang
;
3837 envp
[envc
++] = "REDIRECT_STATUS=1";
3838 envp
[envc
++] = "GATEWAY_INTERFACE=CGI/1.1";
3839 envp
[envc
++] = server_name
;
3840 envp
[envc
++] = server_port
;
3841 envp
[envc
++] = remote_addr
;
3842 envp
[envc
++] = remote_host
;
3843 envp
[envc
++] = script_name
;
3844 envp
[envc
++] = script_filename
;
3847 envp
[envc
++] = path_info
;
3849 if (con
->username
[0])
3851 snprintf(remote_user
, sizeof(remote_user
), "REMOTE_USER=%s", con
->username
);
3853 envp
[envc
++] = remote_user
;
3856 if (con
->http
->version
== HTTP_VERSION_1_1
)
3857 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.1";
3858 else if (con
->http
->version
== HTTP_VERSION_1_0
)
3859 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.0";
3861 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/0.9";
3863 if (con
->http
->cookie
)
3865 snprintf(http_cookie
, sizeof(http_cookie
), "HTTP_COOKIE=%s",
3867 envp
[envc
++] = http_cookie
;
3870 if (httpGetField(con
->http
, HTTP_FIELD_USER_AGENT
)[0])
3872 snprintf(http_user_agent
, sizeof(http_user_agent
), "HTTP_USER_AGENT=%s",
3873 httpGetField(con
->http
, HTTP_FIELD_USER_AGENT
));
3874 envp
[envc
++] = http_user_agent
;
3877 if (httpGetField(con
->http
, HTTP_FIELD_REFERER
)[0])
3879 snprintf(http_referer
, sizeof(http_referer
), "HTTP_REFERER=%s",
3880 httpGetField(con
->http
, HTTP_FIELD_REFERER
));
3881 envp
[envc
++] = http_referer
;
3884 if (con
->operation
== HTTP_STATE_GET
)
3886 envp
[envc
++] = "REQUEST_METHOD=GET";
3888 if (con
->query_string
)
3891 * Add GET form variables after ?...
3894 envp
[envc
++] = con
->query_string
;
3897 envp
[envc
++] = "QUERY_STRING=";
3901 sprintf(content_length
, "CONTENT_LENGTH=" CUPS_LLFMT
,
3902 CUPS_LLCAST con
->bytes
);
3903 snprintf(content_type
, sizeof(content_type
), "CONTENT_TYPE=%s",
3904 httpGetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
));
3906 envp
[envc
++] = "REQUEST_METHOD=POST";
3907 envp
[envc
++] = content_length
;
3908 envp
[envc
++] = content_type
;
3912 * Tell the CGI if we are using encryption...
3916 envp
[envc
++] = "HTTPS=ON";
3919 * Terminate the environment array...
3924 if (LogLevel
>= CUPSD_LOG_DEBUG
)
3926 for (i
= 0; i
< argc
; i
++)
3927 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3928 "[CGI] argv[%d] = \"%s\"", i
, argv
[i
]);
3929 for (i
= 0; i
< envc
; i
++)
3930 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3931 "[CGI] envp[%d] = \"%s\"", i
, envp
[i
]);
3935 * Create a pipe for the output...
3938 if (cupsdOpenPipe(fds
))
3940 cupsdLogMessage(CUPSD_LOG_ERROR
, "[CGI] Unable to create pipe for %s - %s",
3941 argv
[0], strerror(errno
));
3946 * Then execute the command...
3949 if (cupsdStartProcess(command
, argv
, envp
, infile
, fds
[1], CGIPipes
[1],
3950 -1, -1, root
, DefaultProfile
, NULL
, &pid
) < 0)
3953 * Error - can't fork!
3956 cupsdLogMessage(CUPSD_LOG_ERROR
, "[CGI] Unable to start %s - %s", argv
[0],
3959 cupsdClosePipe(fds
);
3965 * Fork successful - return the PID...
3968 if (con
->username
[0])
3969 cupsdAddCert(pid
, con
->username
, con
->type
);
3971 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[CGI] Started %s (PID %d)", command
, pid
);
3982 * 'valid_host()' - Is the Host: field valid?
3985 static int /* O - 1 if valid, 0 if not */
3986 valid_host(cupsd_client_t
*con
) /* I - Client connection */
3988 cupsd_alias_t
*a
; /* Current alias */
3989 cupsd_netif_t
*netif
; /* Current network interface */
3990 const char *end
; /* End character */
3991 char *ptr
; /* Pointer into host value */
3995 * Copy the Host: header for later use...
3998 strlcpy(con
->clientname
, httpGetField(con
->http
, HTTP_FIELD_HOST
),
3999 sizeof(con
->clientname
));
4000 if ((ptr
= strrchr(con
->clientname
, ':')) != NULL
&& !strchr(ptr
, ']'))
4003 con
->clientport
= atoi(ptr
);
4006 con
->clientport
= con
->serverport
;
4012 if (httpAddrLocalhost(httpGetAddress(con
->http
)))
4015 * Only allow "localhost" or the equivalent IPv4 or IPv6 numerical
4016 * addresses when accessing CUPS via the loopback interface...
4019 return (!_cups_strcasecmp(con
->clientname
, "localhost") ||
4020 !_cups_strcasecmp(con
->clientname
, "localhost.") ||
4022 !_cups_strcasecmp(con
->clientname
, "localhost.localdomain") ||
4023 #endif /* __linux */
4024 !strcmp(con
->clientname
, "127.0.0.1") ||
4025 !strcmp(con
->clientname
, "[::1]"));
4028 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
4030 * Check if the hostname is something.local (Bonjour); if so, allow it.
4033 if ((end
= strrchr(con
->clientname
, '.')) != NULL
&& end
> con
->clientname
&&
4037 * "." on end, work back to second-to-last "."...
4040 for (end
--; end
> con
->clientname
&& *end
!= '.'; end
--);
4043 if (end
&& (!_cups_strcasecmp(end
, ".local") ||
4044 !_cups_strcasecmp(end
, ".local.")))
4046 #endif /* HAVE_DNSSD || HAVE_AVAHI */
4049 * Check if the hostname is an IP address...
4052 if (isdigit(con
->clientname
[0] & 255) || con
->clientname
[0] == '[')
4055 * Possible IPv4/IPv6 address...
4058 http_addrlist_t
*addrlist
; /* List of addresses */
4061 if ((addrlist
= httpAddrGetList(con
->clientname
, AF_UNSPEC
, NULL
)) != NULL
)
4064 * Good IPv4/IPv6 address...
4067 httpAddrFreeList(addrlist
);
4073 * Check for (alias) name matches...
4076 for (a
= (cupsd_alias_t
*)cupsArrayFirst(ServerAlias
);
4078 a
= (cupsd_alias_t
*)cupsArrayNext(ServerAlias
))
4081 * "ServerAlias *" allows all host values through...
4084 if (!strcmp(a
->name
, "*"))
4087 if (!_cups_strncasecmp(con
->clientname
, a
->name
, a
->namelen
))
4090 * Prefix matches; check the character at the end - it must be "." or nul.
4093 end
= con
->clientname
+ a
->namelen
;
4095 if (!*end
|| (*end
== '.' && !end
[1]))
4100 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
4101 for (a
= (cupsd_alias_t
*)cupsArrayFirst(DNSSDAlias
);
4103 a
= (cupsd_alias_t
*)cupsArrayNext(DNSSDAlias
))
4106 * "ServerAlias *" allows all host values through...
4109 if (!strcmp(a
->name
, "*"))
4112 if (!_cups_strncasecmp(con
->clientname
, a
->name
, a
->namelen
))
4115 * Prefix matches; check the character at the end - it must be "." or nul.
4118 end
= con
->clientname
+ a
->namelen
;
4120 if (!*end
|| (*end
== '.' && !end
[1]))
4124 #endif /* HAVE_DNSSD || HAVE_AVAHI */
4127 * Check for interface hostname matches...
4130 for (netif
= (cupsd_netif_t
*)cupsArrayFirst(NetIFList
);
4132 netif
= (cupsd_netif_t
*)cupsArrayNext(NetIFList
))
4134 if (!_cups_strncasecmp(con
->clientname
, netif
->hostname
, netif
->hostlen
))
4137 * Prefix matches; check the character at the end - it must be "." or nul.
4140 end
= con
->clientname
+ netif
->hostlen
;
4142 if (!*end
|| (*end
== '.' && !end
[1]))
4152 * 'write_file()' - Send a file via HTTP.
4155 static int /* O - 0 on failure, 1 on success */
4156 write_file(cupsd_client_t
*con
, /* I - Client connection */
4157 http_status_t code
, /* I - HTTP status */
4158 char *filename
, /* I - Filename */
4159 char *type
, /* I - File type */
4160 struct stat
*filestats
) /* O - File information */
4162 con
->file
= open(filename
, O_RDONLY
);
4164 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
4165 "write_file code=%d, filename=\"%s\" (%d), "
4166 "type=\"%s\", filestats=%p",
4167 code
, filename
, con
->file
, type
? type
: "(null)", filestats
);
4172 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
4176 if (!cupsdSendHeader(con
, code
, type
, CUPSD_AUTH_NONE
))
4179 if (httpPrintf(con
->http
, "Last-Modified: %s\r\n",
4180 httpGetDateString(filestats
->st_mtime
)) < 0)
4182 if (httpPrintf(con
->http
, "Content-Length: " CUPS_LLFMT
"\r\n",
4183 CUPS_LLCAST filestats
->st_size
) < 0)
4185 if (httpPrintf(con
->http
, "\r\n") < 0)
4188 if (cupsdFlushHeader(con
) < 0)
4191 con
->http
->data_encoding
= HTTP_ENCODING_LENGTH
;
4192 con
->http
->data_remaining
= filestats
->st_size
;
4194 if (con
->http
->data_remaining
<= INT_MAX
)
4195 con
->http
->_data_remaining
= con
->http
->data_remaining
;
4197 con
->http
->_data_remaining
= INT_MAX
;
4199 cupsdAddSelect(httpGetFd(con
->http
), (cupsd_selfunc_t
)cupsdReadClient
,
4200 (cupsd_selfunc_t
)cupsdWriteClient
, con
);
4202 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Sending file.");
4209 * 'write_pipe()' - Flag that data is available on the CGI pipe.
4213 write_pipe(cupsd_client_t
*con
) /* I - Client connection */
4215 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "write_pipe CGI output on fd %d",
4218 con
->file_ready
= 1;
4220 cupsdRemoveSelect(con
->file
);
4221 cupsdAddSelect(httpGetFd(con
->http
), NULL
, (cupsd_selfunc_t
)cupsdWriteClient
, con
);
4223 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "CGI data ready to be sent.");