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 const char *hostname
; /* Hostname of client */
79 char name
[256]; /* Hostname of client */
80 int count
; /* Count of connections on a host */
81 cupsd_client_t
*con
, /* New client pointer */
82 *tempcon
; /* Temporary client pointer */
83 socklen_t addrlen
; /* Length of address */
84 http_addr_t temp
; /* Temporary address variable */
85 static time_t last_dos
= 0; /* Time of last DoS attack */
87 struct request_info wrap_req
; /* TCP wrappers request information */
88 #endif /* HAVE_TCPD_H */
91 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
92 "cupsdAcceptClient(lis=%p(%d)) Clients=%d",
93 lis
, lis
->fd
, cupsArrayCount(Clients
));
96 * Make sure we don't have a full set of clients already...
99 if (cupsArrayCount(Clients
) == MaxClients
)
103 * Get a pointer to the next available client...
107 Clients
= cupsArrayNew(NULL
, NULL
);
111 cupsdLogMessage(CUPSD_LOG_ERROR
,
112 "Unable to allocate memory for clients array!");
113 cupsdPauseListening();
118 ActiveClients
= cupsArrayNew((cups_array_func_t
)compare_clients
, NULL
);
122 cupsdLogMessage(CUPSD_LOG_ERROR
,
123 "Unable to allocate memory for active clients array!");
124 cupsdPauseListening();
128 if ((con
= calloc(1, sizeof(cupsd_client_t
))) == NULL
)
130 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to allocate memory for client!");
131 cupsdPauseListening();
136 * Accept the client and get the remote address...
139 con
->number
= ++ LastClientNumber
;
142 if ((con
->http
= httpAcceptConnection(lis
->fd
, 0)) == NULL
)
144 if (errno
== ENFILE
|| errno
== EMFILE
)
145 cupsdPauseListening();
147 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to accept client connection - %s.",
155 * Save the connected address and port number...
158 con
->clientaddr
= lis
->address
;
160 #if 0 /* ifdef AF_INET6 */
161 /* FIXME: I don't believe this is recommended any longer, and we specifically
162 * disable IPv4-over-IPv6 when we listen...
165 * Convert IPv4 over IPv6 addresses (::ffff:n.n.n.n) to IPv4 forms we
166 * can more easily use...
169 if (lis
->address
.addr
.sa_family
== AF_INET6
&&
170 httpGetAddress(con
->http
)->ipv6
.sin6_addr
.s6_addr32
[0] == 0 &&
171 httpGetAddress(con
->http
)->ipv6
.sin6_addr
.s6_addr32
[1] == 0 &&
172 ntohl(httpGetAddress(con
->http
)->ipv6
.sin6_addr
.s6_addr32
[2]) == 0xffff)
173 httpGetAddress(con
->http
)->ipv6
.sin6_addr
.s6_addr32
[2] = 0;
174 #endif /* AF_INET6 */
177 * Check the number of clients on the same address...
180 for (count
= 0, tempcon
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
182 tempcon
= (cupsd_client_t
*)cupsArrayNext(Clients
))
183 if (httpAddrEqual(httpGetAddress(tempcon
->http
), httpGetAddress(con
->http
)))
186 if (count
>= MaxClientsPerHost
)
190 if (count
>= MaxClientsPerHost
)
192 if ((time(NULL
) - last_dos
) >= 60)
194 last_dos
= time(NULL
);
195 cupsdLogMessage(CUPSD_LOG_WARN
,
196 "Possible DoS attack - more than %d clients connecting "
199 httpGetHostname(con
->http
, name
, sizeof(name
)));
202 httpClose(con
->http
);
208 * Get the hostname or format the IP address as needed...
212 hostname
= httpResolveHostname(con
->http
, NULL
, 0);
214 hostname
= httpGetHostname(con
->http
, NULL
, 0);
216 if (hostname
== NULL
&& HostNameLookups
== 2)
219 * Can't have an unresolved IP address with double-lookups enabled...
222 httpClose(con
->http
);
224 cupsdLogClient(con
, CUPSD_LOG_WARN
,
225 "Name lookup failed - connection from %s closed!",
226 httpGetHostname(con
->http
, NULL
, 0));
232 if (HostNameLookups
== 2)
235 * Do double lookups as needed...
238 http_addrlist_t
*addrlist
, /* List of addresses */
239 *addr
; /* Current address */
241 if ((addrlist
= httpAddrGetList(hostname
, AF_UNSPEC
, NULL
)) != NULL
)
244 * See if the hostname maps to the same IP address...
247 for (addr
= addrlist
; addr
; addr
= addr
->next
)
248 if (httpAddrEqual(httpGetAddress(con
->http
), &(addr
->addr
)))
254 httpAddrFreeList(addrlist
);
259 * Can't have a hostname that doesn't resolve to the same IP address
260 * with double-lookups enabled...
263 httpClose(con
->http
);
265 cupsdLogClient(con
, CUPSD_LOG_WARN
,
266 "IP lookup failed - connection from %s closed!",
267 httpGetHostname(con
->http
, NULL
, 0));
275 * See if the connection is denied by TCP wrappers...
278 request_init(&wrap_req
, RQ_DAEMON
, "cupsd", RQ_FILE
, httpGetFd(con
->http
),
282 if (!hosts_access(&wrap_req
))
284 httpClose(con
->http
);
286 cupsdLogClient(con
, CUPSD_LOG_WARN
,
287 "Connection from %s refused by /etc/hosts.allow and "
288 "/etc/hosts.deny rules.", httpGetHostname(con
->http
, NULL
, 0));
292 #endif /* HAVE_TCPD_H */
295 if (httpAddrFamily(httpGetAddress(con
->http
)) == AF_LOCAL
)
298 socklen_t peersize
; /* Size of peer credentials */
299 pid_t peerpid
; /* Peer process ID */
300 char peername
[256]; /* Name of process */
302 peersize
= sizeof(peerpid
);
303 if (!getsockopt(con
->number
, SOL_LOCAL
, LOCAL_PEERPID
, &peerpid
,
306 if (!proc_name(peerpid
, peername
, sizeof(peername
)))
307 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
308 "Accepted from %s (Domain ???[%d])",
309 httpGetHostname(con
->http
, NULL
, 0), (int)peerpid
);
311 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
312 "Accepted from %s (Domain %s[%d])",
313 httpGetHostname(con
->http
, NULL
, 0), name
, (int)peerpid
);
316 # endif /* __APPLE__ */
318 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Accepted from %s (Domain)",
319 httpGetHostname(con
->http
, NULL
, 0));
322 #endif /* AF_LOCAL */
323 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Accepted from %s:%d (IPv%d)",
324 httpGetHostname(con
->http
, NULL
, 0),
325 httpAddrPort(httpGetAddress(con
->http
)),
326 httpAddrFamily(httpGetAddress(con
->http
)) == AF_INET
? 4 : 6);
329 * Get the local address the client connected to...
332 addrlen
= sizeof(temp
);
333 if (getsockname(httpGetFd(con
->http
), (struct sockaddr
*)&temp
, &addrlen
))
335 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Unable to get local address - %s",
338 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
339 con
->serverport
= LocalPort
;
342 else if (httpAddrFamily(&temp
) == AF_LOCAL
)
344 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
345 con
->serverport
= LocalPort
;
347 #endif /* AF_LOCAL */
350 if (httpAddrLocalhost(&temp
))
351 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
352 else if (HostNameLookups
)
353 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
355 httpAddrString(&temp
, con
->servername
, sizeof(con
->servername
));
357 con
->serverport
= httpAddrPort(&(lis
->address
));
361 * Add the connection to the array of active clients...
364 cupsArrayAdd(Clients
, con
);
367 * Add the socket to the server select.
370 cupsdAddSelect(httpGetFd(con
->http
), (cupsd_selfunc_t
)cupsdReadClient
, NULL
,
373 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for request.");
376 * Temporarily suspend accept()'s until we lose a client...
379 if (cupsArrayCount(Clients
) == MaxClients
)
380 cupsdPauseListening();
384 * See if we are connecting on a secure port...
387 if (lis
->encryption
== HTTP_ENCRYPTION_ALWAYS
)
390 * https connection; go secure...
393 if (!cupsdStartTLS(con
))
394 cupsdCloseClient(con
);
398 #endif /* HAVE_SSL */
403 * 'cupsdCloseAllClients()' - Close all remote clients immediately.
407 cupsdCloseAllClients(void)
409 cupsd_client_t
*con
; /* Current client */
412 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdCloseAllClients() Clients=%d",
413 cupsArrayCount(Clients
));
415 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
417 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
418 if (cupsdCloseClient(con
))
419 cupsdCloseClient(con
);
424 * 'cupsdCloseClient()' - Close a remote client.
427 int /* O - 1 if partial close, 0 if fully closed */
428 cupsdCloseClient(cupsd_client_t
*con
) /* I - Client to close */
430 int partial
; /* Do partial close for SSL? */
432 #elif defined(HAVE_GNUTLS)
433 # elif defined(HAVE_CDSASSL)
434 #endif /* HAVE_LIBSSL */
437 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing connection.");
440 * Flush pending writes before closing...
443 httpFlushWrite(con
->http
);
447 if (con
->pipe_pid
!= 0)
450 * Stop any CGI process...
453 cupsdEndProcess(con
->pipe_pid
, 1);
459 cupsdRemoveSelect(con
->file
);
466 * Close the socket and clear the file from the input set for select()...
469 if (httpGetFd(con
->http
) >= 0)
471 cupsArrayRemove(ActiveClients
, con
);
476 * Shutdown encryption as needed...
479 if (httpIsEncrypted(con
->http
))
481 #endif /* HAVE_SSL */
486 * Only do a partial close so that the encrypted client gets everything.
489 httpShutdown(con
->http
);
490 cupsdAddSelect(httpGetFd(con
->http
), (cupsd_selfunc_t
)cupsdReadClient
,
493 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for socket close.");
498 * Shut the socket down fully...
501 cupsdRemoveSelect(httpGetFd(con
->http
));
502 httpClose(con
->http
);
513 cupsdRemoveSelect(httpGetFd(con
->http
));
515 httpClose(con
->http
);
517 cupsdClearString(&con
->filename
);
518 cupsdClearString(&con
->command
);
519 cupsdClearString(&con
->options
);
520 cupsdClearString(&con
->query_string
);
524 ippDelete(con
->request
);
530 ippDelete(con
->response
);
531 con
->response
= NULL
;
536 cupsLangFree(con
->language
);
537 con
->language
= NULL
;
540 #ifdef HAVE_AUTHORIZATION_H
543 AuthorizationFree(con
->authref
, kAuthorizationFlagDefaults
);
546 #endif /* HAVE_AUTHORIZATION_H */
549 * Re-enable new client connections if we are going back under the
553 if (cupsArrayCount(Clients
) == MaxClients
)
554 cupsdResumeListening();
557 * Compact the list of clients as necessary...
560 cupsArrayRemove(Clients
, con
);
570 * 'cupsdFlushHeader()' - Flush the header fields to the client.
573 int /* I - Bytes written or -1 on error */
574 cupsdFlushHeader(cupsd_client_t
*con
) /* I - Client to flush to */
576 int bytes
= httpFlushWrite(con
->http
);
578 // TODO: Need to use httpSendResponse
579 con
->http
->data_encoding
= HTTP_ENCODING_LENGTH
;
586 * 'cupsdReadClient()' - Read data from a client.
590 cupsdReadClient(cupsd_client_t
*con
) /* I - Client to read from */
592 char line
[32768], /* Line from client... */
593 operation
[64], /* Operation code from socket */
594 version
[64], /* HTTP version number string */
595 locale
[64], /* Locale */
596 *ptr
; /* Pointer into strings */
597 int major
, minor
; /* HTTP version numbers */
598 http_status_t status
; /* Transfer status */
599 ipp_state_t ipp_state
; /* State of IPP transfer */
600 int bytes
; /* Number of bytes to POST */
601 char *filename
; /* Name of file for GET/HEAD */
602 char buf
[1024]; /* Buffer for real filename */
603 struct stat filestats
; /* File information */
604 mime_type_t
*type
; /* MIME type of file */
605 cupsd_printer_t
*p
; /* Printer */
606 static unsigned request_id
= 0; /* Request ID for temp files */
609 status
= HTTP_STATUS_CONTINUE
;
611 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
616 "data_encoding=HTTP_ENCODING_%s, "
617 "data_remaining=" CUPS_LLFMT
", "
620 httpError(con
->http
), (int)httpGetReady(con
->http
),
621 httpStateString(httpGetState(con
->http
)),
622 httpIsChunked(con
->http
) ? "CHUNKED" : "LENGTH",
623 CUPS_LLCAST
httpGetRemaining(con
->http
),
625 con
->request
? ipp_states
[con
->request
->state
] : "",
632 * Automatically check for a SSL/TLS handshake...
637 if (recv(httpGetFd(con
->http
), buf
, 1, MSG_PEEK
) == 1 &&
638 (!buf
[0] || !strchr("DGHOPT", buf
[0])))
641 * Encrypt this connection...
644 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
645 "Saw first byte %02X, auto-negotiating "
646 "SSL/TLS session.", buf
[0] & 255);
648 if (!cupsdStartTLS(con
))
649 cupsdCloseClient(con
);
654 #endif /* HAVE_SSL */
656 switch (httpGetState(con
->http
))
658 case HTTP_STATE_WAITING
:
660 * See if we've received a request line...
663 if (httpGets(line
, sizeof(line
) - 1, con
->http
) == NULL
)
665 if (httpError(con
->http
) && httpError(con
->http
) != EPIPE
)
666 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
667 "HTTP_STATE_WAITING Closing for error %d (%s)",
668 httpError(con
->http
), strerror(httpError(con
->http
)));
670 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
671 "HTTP_STATE_WAITING Closing on EOF.");
673 cupsdCloseClient(con
);
678 * Ignore blank request lines...
685 * Clear other state variables...
688 httpClearFields(con
->http
);
690 con
->http
->activity
= time(NULL
);
691 con
->http
->version
= HTTP_VERSION_1_0
;
692 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
693 con
->http
->data_encoding
= HTTP_ENCODING_LENGTH
;
694 con
->http
->data_remaining
= 0;
695 con
->http
->_data_remaining
= 0;
696 con
->operation
= HTTP_STATE_WAITING
;
701 con
->username
[0] = '\0';
702 con
->password
[0] = '\0';
705 cupsdClearString(&con
->command
);
706 cupsdClearString(&con
->options
);
707 cupsdClearString(&con
->query_string
);
711 ippDelete(con
->request
);
717 ippDelete(con
->response
);
718 con
->response
= NULL
;
723 cupsLangFree(con
->language
);
724 con
->language
= NULL
;
730 #endif /* HAVE_GSSAPI */
733 * Grab the request line...
736 switch (sscanf(line
, "%63s%1023s%63s", operation
, con
->uri
, version
))
741 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
742 "Bad request line \"%s\" from %s.",
743 _httpEncodeURI(buf
, line
, sizeof(buf
)),
744 httpGetHostname(con
->http
, NULL
, 0));
745 cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
);
746 cupsdCloseClient(con
);
750 con
->http
->version
= HTTP_VERSION_0_9
;
753 if (sscanf(version
, "HTTP/%d.%d", &major
, &minor
) != 2)
755 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
756 "Bad request line \"%s\" from %s.",
757 _httpEncodeURI(buf
, line
, sizeof(buf
)),
758 httpGetHostname(con
->http
, NULL
, 0));
759 cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
);
760 cupsdCloseClient(con
);
766 con
->http
->version
= (http_version_t
)(major
* 100 + minor
);
767 if (con
->http
->version
== HTTP_VERSION_1_1
&& KeepAlive
)
768 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_ON
);
770 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
774 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
775 "Unsupported request line \"%s\" from %s.",
776 _httpEncodeURI(buf
, line
, sizeof(buf
)),
777 httpGetHostname(con
->http
, NULL
, 0));
778 cupsdSendError(con
, HTTP_STATUS_NOT_SUPPORTED
, CUPSD_AUTH_NONE
);
779 cupsdCloseClient(con
);
786 * Handle full URLs in the request line...
789 if (strcmp(con
->uri
, "*"))
791 char scheme
[HTTP_MAX_URI
], /* Method/scheme */
792 userpass
[HTTP_MAX_URI
], /* Username:password */
793 hostname
[HTTP_MAX_URI
], /* Hostname */
794 resource
[HTTP_MAX_URI
]; /* Resource path */
795 int port
; /* Port number */
799 * Separate the URI into its components...
802 httpSeparateURI(HTTP_URI_CODING_MOST
, con
->uri
,
803 scheme
, sizeof(scheme
),
804 userpass
, sizeof(userpass
),
805 hostname
, sizeof(hostname
), &port
,
806 resource
, sizeof(resource
));
809 * Only allow URIs with the servername, localhost, or an IP
813 if (strcmp(scheme
, "file") &&
814 _cups_strcasecmp(hostname
, ServerName
) &&
815 _cups_strcasecmp(hostname
, "localhost") &&
816 !isdigit(hostname
[0]) && hostname
[0] != '[')
819 * Nope, we don't do proxies...
822 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Bad URI \"%s\" in request.",
824 cupsdSendError(con
, HTTP_STATUS_METHOD_NOT_ALLOWED
, CUPSD_AUTH_NONE
);
825 cupsdCloseClient(con
);
830 * Copy the resource portion back into the URI; both resource and
831 * con->uri are HTTP_MAX_URI bytes in size...
834 strlcpy(con
->uri
, resource
, sizeof(con
->uri
));
838 * Process the request...
841 if (!strcmp(operation
, "GET"))
842 con
->http
->state
= HTTP_STATE_GET
;
843 else if (!strcmp(operation
, "PUT"))
844 con
->http
->state
= HTTP_STATE_PUT
;
845 else if (!strcmp(operation
, "POST"))
846 con
->http
->state
= HTTP_STATE_POST
;
847 else if (!strcmp(operation
, "DELETE"))
848 con
->http
->state
= HTTP_STATE_DELETE
;
849 else if (!strcmp(operation
, "TRACE"))
850 con
->http
->state
= HTTP_STATE_TRACE
;
851 else if (!strcmp(operation
, "OPTIONS"))
852 con
->http
->state
= HTTP_STATE_OPTIONS
;
853 else if (!strcmp(operation
, "HEAD"))
854 con
->http
->state
= HTTP_STATE_HEAD
;
857 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Bad operation \"%s\".",
859 cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
);
860 cupsdCloseClient(con
);
864 gettimeofday(&(con
->start
), NULL
);
865 con
->operation
= httpGetState(con
->http
);
867 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "%s %s HTTP/%d.%d",
868 operation
, con
->uri
, con
->http
->version
/ 100,
869 con
->http
->version
% 100);
871 con
->http
->status
= HTTP_STATUS_OK
;
873 if (!cupsArrayFind(ActiveClients
, con
))
875 cupsArrayAdd(ActiveClients
, con
);
879 case HTTP_STATE_OPTIONS
:
880 case HTTP_STATE_DELETE
:
881 case HTTP_STATE_GET
:
882 case HTTP_STATE_HEAD
:
883 case HTTP_STATE_POST
:
884 case HTTP_STATE_PUT
:
885 case HTTP_STATE_TRACE
:
887 * Parse incoming parameters until the status changes...
890 while ((status
= httpUpdate(con
->http
)) == HTTP_STATUS_CONTINUE
)
891 if (!httpGetReady(con
->http
))
894 if (status
!= HTTP_STATUS_OK
&& status
!= HTTP_STATUS_CONTINUE
)
896 if (httpError(con
->http
) && httpError(con
->http
) != EPIPE
)
897 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
898 "Closing for error %d (%s) while reading headers.",
899 httpError(con
->http
), strerror(httpError(con
->http
)));
901 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
902 "Closing on EOF while reading headers.");
904 cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
);
905 cupsdCloseClient(con
);
911 if (!httpGetReady(con
->http
) && recv(httpGetFd(con
->http
), buf
, 1, MSG_PEEK
) < 1)
914 * Connection closed...
917 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing on EOF.");
918 cupsdCloseClient(con
);
921 break; /* Anti-compiler-warning-code */
925 * Handle new transfers...
928 if (status
== HTTP_STATUS_OK
)
930 if (httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
)[0])
933 * Figure out the locale from the Accept-Language and Content-Type
937 if ((ptr
= strchr(httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
),
941 if ((ptr
= strchr(httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
),
945 if ((ptr
= strstr(httpGetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
),
946 "charset=")) != NULL
)
949 * Combine language and charset, and trim any extra params in the
953 snprintf(locale
, sizeof(locale
), "%s.%s",
954 httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
), ptr
+ 8);
956 if ((ptr
= strchr(locale
, ',')) != NULL
)
960 snprintf(locale
, sizeof(locale
), "%s.UTF-8",
961 httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
));
963 con
->language
= cupsLangGet(locale
);
966 con
->language
= cupsLangGet(DefaultLocale
);
970 if (!_cups_strncasecmp(httpGetField(con
->http
, HTTP_FIELD_CONNECTION
),
971 "Keep-Alive", 10) && KeepAlive
)
972 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_ON
);
973 else if (!_cups_strncasecmp(httpGetField(con
->http
, HTTP_FIELD_CONNECTION
),
975 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
977 if (!httpGetField(con
->http
, HTTP_FIELD_HOST
)[0] &&
978 httpGetVersion(con
->http
) >= HTTP_VERSION_1_1
)
981 * HTTP/1.1 and higher require the "Host:" field...
984 if (!cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
))
986 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Missing Host: field in request.");
987 cupsdCloseClient(con
);
991 else if (!valid_host(con
))
994 * Access to localhost must use "localhost" or the corresponding IPv4
995 * or IPv6 values in the Host: field.
998 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
999 "Request from \"%s\" using invalid Host: field \"%s\".",
1000 httpGetHostname(con
->http
, NULL
, 0), httpGetField(con
->http
, HTTP_FIELD_HOST
));
1002 if (!cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1004 cupsdCloseClient(con
);
1008 else if (con
->operation
== HTTP_STATE_OPTIONS
)
1011 * Do OPTIONS command...
1014 if (con
->best
&& con
->best
->type
!= CUPSD_AUTH_NONE
)
1016 if (!cupsdSendHeader(con
, HTTP_STATUS_UNAUTHORIZED
, NULL
, CUPSD_AUTH_NONE
))
1018 cupsdCloseClient(con
);
1023 if (!_cups_strcasecmp(httpGetField(con
->http
, HTTP_FIELD_CONNECTION
), "Upgrade") &&
1024 !httpIsEncrypted(con
->http
))
1028 * Do encryption stuff...
1031 if (!cupsdSendHeader(con
, HTTP_STATUS_SWITCHING_PROTOCOLS
, NULL
, CUPSD_AUTH_NONE
))
1033 cupsdCloseClient(con
);
1037 httpPrintf(con
->http
, "Connection: Upgrade\r\n");
1038 httpPrintf(con
->http
, "Upgrade: TLS/1.2,TLS/1.1,TLS/1.0\r\n");
1039 httpPrintf(con
->http
, "Content-Length: 0\r\n");
1040 httpPrintf(con
->http
, "\r\n");
1042 if (cupsdFlushHeader(con
) < 0)
1044 cupsdCloseClient(con
);
1048 if (!cupsdStartTLS(con
))
1050 cupsdCloseClient(con
);
1054 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
1056 cupsdCloseClient(con
);
1059 #endif /* HAVE_SSL */
1062 if (!cupsdSendHeader(con
, HTTP_STATUS_OK
, NULL
, CUPSD_AUTH_NONE
))
1064 cupsdCloseClient(con
);
1068 httpPrintf(con
->http
, "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n");
1069 httpPrintf(con
->http
, "Content-Length: 0\r\n");
1070 httpPrintf(con
->http
, "\r\n");
1072 if (cupsdFlushHeader(con
) < 0)
1074 cupsdCloseClient(con
);
1078 else if (!is_path_absolute(con
->uri
))
1081 * Protect against malicious users!
1084 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1085 "Request for non-absolute resource \"%s\".", con
->uri
);
1087 if (!cupsdSendError(con
, HTTP_STATUS_FORBIDDEN
, CUPSD_AUTH_NONE
))
1089 cupsdCloseClient(con
);
1095 if (!_cups_strcasecmp(httpGetField(con
->http
, HTTP_FIELD_CONNECTION
),
1096 "Upgrade") && con
->http
->tls
== NULL
)
1100 * Do encryption stuff...
1103 if (!cupsdSendHeader(con
, HTTP_STATUS_SWITCHING_PROTOCOLS
, NULL
,
1106 cupsdCloseClient(con
);
1110 httpPrintf(con
->http
, "Connection: Upgrade\r\n");
1111 httpPrintf(con
->http
, "Upgrade: TLS/1.2,TLS/1.1,TLS/1.0\r\n");
1112 httpPrintf(con
->http
, "Content-Length: 0\r\n");
1113 httpPrintf(con
->http
, "\r\n");
1115 if (cupsdFlushHeader(con
) < 0)
1117 cupsdCloseClient(con
);
1121 if (!cupsdStartTLS(con
))
1123 cupsdCloseClient(con
);
1127 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
1129 cupsdCloseClient(con
);
1132 #endif /* HAVE_SSL */
1135 if ((status
= cupsdIsAuthorized(con
, NULL
)) != HTTP_STATUS_OK
)
1137 cupsdSendError(con
, status
, CUPSD_AUTH_NONE
);
1138 cupsdCloseClient(con
);
1142 if (con
->http
->expect
&&
1143 (con
->operation
== HTTP_STATE_POST
|| con
->operation
== HTTP_STATE_PUT
))
1145 if (con
->http
->expect
== HTTP_STATUS_CONTINUE
)
1148 * Send 100-continue header...
1151 if (!cupsdSendHeader(con
, HTTP_STATUS_CONTINUE
, NULL
, CUPSD_AUTH_NONE
))
1153 cupsdCloseClient(con
);
1160 * Send 417-expectation-failed header...
1163 if (!cupsdSendHeader(con
, HTTP_STATUS_EXPECTATION_FAILED
, NULL
,
1166 cupsdCloseClient(con
);
1170 httpPrintf(con
->http
, "Content-Length: 0\r\n");
1171 httpPrintf(con
->http
, "\r\n");
1173 if (cupsdFlushHeader(con
) < 0)
1175 cupsdCloseClient(con
);
1181 switch (httpGetState(con
->http
))
1183 case HTTP_STATE_GET_SEND
:
1184 if ((!strncmp(con
->uri
, "/ppd/", 5) ||
1185 !strncmp(con
->uri
, "/printers/", 10) ||
1186 !strncmp(con
->uri
, "/classes/", 9)) &&
1187 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1190 * Send PPD file - get the real printer name since printer
1191 * names are not case sensitive but filenames can be...
1194 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1196 if (!strncmp(con
->uri
, "/ppd/", 5))
1197 p
= cupsdFindPrinter(con
->uri
+ 5);
1198 else if (!strncmp(con
->uri
, "/printers/", 10))
1199 p
= cupsdFindPrinter(con
->uri
+ 10);
1202 p
= cupsdFindClass(con
->uri
+ 9);
1206 int i
; /* Looping var */
1208 for (i
= 0; i
< p
->num_printers
; i
++)
1210 if (!(p
->printers
[i
]->type
& CUPS_PRINTER_CLASS
))
1212 char ppdname
[1024];/* PPD filename */
1214 snprintf(ppdname
, sizeof(ppdname
), "%s/ppd/%s.ppd",
1215 ServerRoot
, p
->printers
[i
]->name
);
1216 if (!access(ppdname
, 0))
1224 if (i
>= p
->num_printers
)
1231 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1235 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1237 cupsdCloseClient(con
);
1244 else if ((!strncmp(con
->uri
, "/icons/", 7) ||
1245 !strncmp(con
->uri
, "/printers/", 10) ||
1246 !strncmp(con
->uri
, "/classes/", 9)) &&
1247 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".png"))
1250 * Send icon file - get the real queue name since queue names are
1251 * not case sensitive but filenames can be...
1254 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".png" */
1256 if (!strncmp(con
->uri
, "/icons/", 7))
1257 p
= cupsdFindPrinter(con
->uri
+ 7);
1258 else if (!strncmp(con
->uri
, "/printers/", 10))
1259 p
= cupsdFindPrinter(con
->uri
+ 10);
1262 p
= cupsdFindClass(con
->uri
+ 9);
1266 int i
; /* Looping var */
1268 for (i
= 0; i
< p
->num_printers
; i
++)
1270 if (!(p
->printers
[i
]->type
& CUPS_PRINTER_CLASS
))
1272 char ppdname
[1024];/* PPD filename */
1274 snprintf(ppdname
, sizeof(ppdname
), "%s/ppd/%s.ppd",
1275 ServerRoot
, p
->printers
[i
]->name
);
1276 if (!access(ppdname
, 0))
1284 if (i
>= p
->num_printers
)
1290 snprintf(con
->uri
, sizeof(con
->uri
), "/icons/%s.png", p
->name
);
1293 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1295 cupsdCloseClient(con
);
1302 else if (!WebInterface
)
1305 * Web interface is disabled. Show an appropriate message...
1308 if (!cupsdSendError(con
, HTTP_STATUS_CUPS_WEBIF_DISABLED
, CUPSD_AUTH_NONE
))
1310 cupsdCloseClient(con
);
1317 if ((!strncmp(con
->uri
, "/admin", 6) &&
1318 strncmp(con
->uri
, "/admin/conf/", 12) &&
1319 strncmp(con
->uri
, "/admin/log/", 11)) ||
1320 !strncmp(con
->uri
, "/printers", 9) ||
1321 !strncmp(con
->uri
, "/classes", 8) ||
1322 !strncmp(con
->uri
, "/help", 5) ||
1323 !strncmp(con
->uri
, "/jobs", 5))
1326 * Send CGI output...
1329 if (!strncmp(con
->uri
, "/admin", 6))
1331 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1334 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1336 else if (!strncmp(con
->uri
, "/printers", 9))
1338 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1341 if (con
->uri
[9] && con
->uri
[10])
1342 cupsdSetString(&con
->options
, con
->uri
+ 9);
1344 cupsdSetString(&con
->options
, NULL
);
1346 else if (!strncmp(con
->uri
, "/classes", 8))
1348 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1351 if (con
->uri
[8] && con
->uri
[9])
1352 cupsdSetString(&con
->options
, con
->uri
+ 8);
1354 cupsdSetString(&con
->options
, NULL
);
1356 else if (!strncmp(con
->uri
, "/jobs", 5))
1358 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1361 if (con
->uri
[5] && con
->uri
[6])
1362 cupsdSetString(&con
->options
, con
->uri
+ 5);
1364 cupsdSetString(&con
->options
, NULL
);
1368 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1371 if (con
->uri
[5] && con
->uri
[6])
1372 cupsdSetString(&con
->options
, con
->uri
+ 5);
1374 cupsdSetString(&con
->options
, NULL
);
1377 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1379 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1381 cupsdCloseClient(con
);
1386 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1388 if (con
->http
->version
<= HTTP_VERSION_1_0
)
1389 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
1391 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1392 (strchr(con
->uri
+ 12, '/') ||
1393 strlen(con
->uri
) == 12)) ||
1394 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1395 (strchr(con
->uri
+ 11, '/') ||
1396 strlen(con
->uri
) == 11)))
1399 * GET can only be done to configuration files directly under
1403 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1404 "Request for subdirectory \"%s\"!", con
->uri
);
1406 if (!cupsdSendError(con
, HTTP_STATUS_FORBIDDEN
, CUPSD_AUTH_NONE
))
1408 cupsdCloseClient(con
);
1420 if ((filename
= get_file(con
, &filestats
, buf
,
1421 sizeof(buf
))) == NULL
)
1423 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1425 cupsdCloseClient(con
);
1432 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1434 if (is_cgi(con
, filename
, &filestats
, type
))
1437 * Note: con->command and con->options were set by
1441 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1443 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1445 cupsdCloseClient(con
);
1450 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1452 if (con
->http
->version
<= HTTP_VERSION_1_0
)
1453 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
1457 if (!check_if_modified(con
, &filestats
))
1459 if (!cupsdSendError(con
, HTTP_STATUS_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1461 cupsdCloseClient(con
);
1468 strlcpy(line
, "text/plain", sizeof(line
));
1470 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1472 if (!write_file(con
, HTTP_STATUS_OK
, filename
, line
, &filestats
))
1474 cupsdCloseClient(con
);
1481 case HTTP_STATE_POST_RECV
:
1483 * See if the POST request includes a Content-Length field, and if
1484 * so check the length against any limits that are set...
1487 if (httpGetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
)[0] &&
1488 MaxRequestSize
> 0 &&
1489 con
->http
->data_remaining
> MaxRequestSize
)
1492 * Request too large...
1495 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1497 cupsdCloseClient(con
);
1503 else if (con
->http
->data_remaining
< 0 ||
1504 (!httpGetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
)[0] &&
1505 con
->http
->data_encoding
== HTTP_ENCODING_LENGTH
))
1508 * Negative content lengths are invalid!
1511 if (!cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1513 cupsdCloseClient(con
);
1521 * See what kind of POST request this is; for IPP requests the
1522 * content-type field will be "application/ipp"...
1525 if (!strcmp(httpGetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
),
1527 con
->request
= ippNew();
1528 else if (!WebInterface
)
1531 * Web interface is disabled. Show an appropriate message...
1534 if (!cupsdSendError(con
, HTTP_STATUS_CUPS_WEBIF_DISABLED
, CUPSD_AUTH_NONE
))
1536 cupsdCloseClient(con
);
1542 else if ((!strncmp(con
->uri
, "/admin", 6) &&
1543 strncmp(con
->uri
, "/admin/conf/", 12) &&
1544 strncmp(con
->uri
, "/admin/log/", 11)) ||
1545 !strncmp(con
->uri
, "/printers", 9) ||
1546 !strncmp(con
->uri
, "/classes", 8) ||
1547 !strncmp(con
->uri
, "/help", 5) ||
1548 !strncmp(con
->uri
, "/jobs", 5))
1554 if (!strncmp(con
->uri
, "/admin", 6))
1556 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1559 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1561 else if (!strncmp(con
->uri
, "/printers", 9))
1563 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1566 if (con
->uri
[9] && con
->uri
[10])
1567 cupsdSetString(&con
->options
, con
->uri
+ 9);
1569 cupsdSetString(&con
->options
, NULL
);
1571 else if (!strncmp(con
->uri
, "/classes", 8))
1573 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1576 if (con
->uri
[8] && con
->uri
[9])
1577 cupsdSetString(&con
->options
, con
->uri
+ 8);
1579 cupsdSetString(&con
->options
, NULL
);
1581 else if (!strncmp(con
->uri
, "/jobs", 5))
1583 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1586 if (con
->uri
[5] && con
->uri
[6])
1587 cupsdSetString(&con
->options
, con
->uri
+ 5);
1589 cupsdSetString(&con
->options
, NULL
);
1593 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1596 if (con
->uri
[5] && con
->uri
[6])
1597 cupsdSetString(&con
->options
, con
->uri
+ 5);
1599 cupsdSetString(&con
->options
, NULL
);
1602 if (con
->http
->version
<= HTTP_VERSION_1_0
)
1603 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
1611 if ((filename
= get_file(con
, &filestats
, buf
,
1612 sizeof(buf
))) == NULL
)
1614 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1616 cupsdCloseClient(con
);
1623 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1625 if (!is_cgi(con
, filename
, &filestats
, type
))
1628 * Only POST to CGI's...
1631 if (!cupsdSendError(con
, HTTP_STATUS_UNAUTHORIZED
, CUPSD_AUTH_NONE
))
1633 cupsdCloseClient(con
);
1640 case HTTP_STATE_PUT_RECV
:
1642 * Validate the resource name...
1645 if (strcmp(con
->uri
, "/admin/conf/cupsd.conf"))
1648 * PUT can only be done to the cupsd.conf file...
1651 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1652 "Disallowed PUT request for \"%s\".", con
->uri
);
1654 if (!cupsdSendError(con
, HTTP_STATUS_FORBIDDEN
, CUPSD_AUTH_NONE
))
1656 cupsdCloseClient(con
);
1664 * See if the PUT request includes a Content-Length field, and if
1665 * so check the length against any limits that are set...
1668 if (httpGetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
)[0] &&
1669 MaxRequestSize
> 0 &&
1670 con
->http
->data_remaining
> MaxRequestSize
)
1673 * Request too large...
1676 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1678 cupsdCloseClient(con
);
1684 else if (con
->http
->data_remaining
< 0)
1687 * Negative content lengths are invalid!
1690 if (!cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1692 cupsdCloseClient(con
);
1700 * Open a temporary file to hold the request...
1703 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
1705 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1709 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1710 "Unable to create request file \"%s\": %s",
1711 con
->filename
, strerror(errno
));
1713 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1715 cupsdCloseClient(con
);
1720 fchmod(con
->file
, 0640);
1721 fchown(con
->file
, RunUser
, Group
);
1722 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1725 case HTTP_STATE_DELETE
:
1726 case HTTP_STATE_TRACE
:
1727 cupsdSendError(con
, HTTP_STATUS_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
);
1728 cupsdCloseClient(con
);
1731 case HTTP_STATE_HEAD
:
1732 if (!strncmp(con
->uri
, "/printers/", 10) &&
1733 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1736 * Send PPD file - get the real printer name since printer
1737 * names are not case sensitive but filenames can be...
1740 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1742 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1743 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1746 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1748 cupsdCloseClient(con
);
1755 else if (!strncmp(con
->uri
, "/printers/", 10) &&
1756 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".png"))
1759 * Send PNG file - get the real printer name since printer
1760 * names are not case sensitive but filenames can be...
1763 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1765 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1766 snprintf(con
->uri
, sizeof(con
->uri
), "/icons/%s.png", p
->name
);
1769 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1771 cupsdCloseClient(con
);
1778 else if (!WebInterface
)
1780 if (!cupsdSendHeader(con
, HTTP_STATUS_OK
, NULL
, CUPSD_AUTH_NONE
))
1782 cupsdCloseClient(con
);
1786 if (httpPrintf(con
->http
, "\r\n") < 0)
1788 cupsdCloseClient(con
);
1792 if (cupsdFlushHeader(con
) < 0)
1794 cupsdCloseClient(con
);
1798 con
->http
->state
= HTTP_STATE_WAITING
;
1799 DEBUG_puts("cupsdReadClient: Set state to HTTP_STATE_WAITING "
1804 if ((!strncmp(con
->uri
, "/admin", 6) &&
1805 strncmp(con
->uri
, "/admin/conf/", 12) &&
1806 strncmp(con
->uri
, "/admin/log/", 11)) ||
1807 !strncmp(con
->uri
, "/printers", 9) ||
1808 !strncmp(con
->uri
, "/classes", 8) ||
1809 !strncmp(con
->uri
, "/help", 5) ||
1810 !strncmp(con
->uri
, "/jobs", 5))
1816 if (!cupsdSendHeader(con
, HTTP_STATUS_OK
, "text/html", CUPSD_AUTH_NONE
))
1818 cupsdCloseClient(con
);
1822 if (httpPrintf(con
->http
, "\r\n") < 0)
1824 cupsdCloseClient(con
);
1828 if (cupsdFlushHeader(con
) < 0)
1830 cupsdCloseClient(con
);
1834 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1836 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1837 (strchr(con
->uri
+ 12, '/') ||
1838 strlen(con
->uri
) == 12)) ||
1839 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1840 (strchr(con
->uri
+ 11, '/') ||
1841 strlen(con
->uri
) == 11)))
1844 * HEAD can only be done to configuration files under
1848 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1849 "Request for subdirectory \"%s\".", con
->uri
);
1851 if (!cupsdSendError(con
, HTTP_STATUS_FORBIDDEN
, CUPSD_AUTH_NONE
))
1853 cupsdCloseClient(con
);
1859 else if ((filename
= get_file(con
, &filestats
, buf
,
1860 sizeof(buf
))) == NULL
)
1862 if (!cupsdSendHeader(con
, HTTP_STATUS_NOT_FOUND
, "text/html",
1865 cupsdCloseClient(con
);
1869 cupsdLogRequest(con
, HTTP_STATUS_NOT_FOUND
);
1871 else if (!check_if_modified(con
, &filestats
))
1873 if (!cupsdSendError(con
, HTTP_STATUS_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1875 cupsdCloseClient(con
);
1879 cupsdLogRequest(con
, HTTP_STATUS_NOT_MODIFIED
);
1887 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1889 strlcpy(line
, "text/plain", sizeof(line
));
1891 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1893 if (!cupsdSendHeader(con
, HTTP_STATUS_OK
, line
, CUPSD_AUTH_NONE
))
1895 cupsdCloseClient(con
);
1899 if (httpPrintf(con
->http
, "Last-Modified: %s\r\n",
1900 httpGetDateString(filestats
.st_mtime
)) < 0)
1902 cupsdCloseClient(con
);
1906 if (httpPrintf(con
->http
, "Content-Length: %lu\r\n",
1907 (unsigned long)filestats
.st_size
) < 0)
1909 cupsdCloseClient(con
);
1913 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1916 if (httpPrintf(con
->http
, "\r\n") < 0)
1918 cupsdCloseClient(con
);
1922 if (cupsdFlushHeader(con
) < 0)
1924 cupsdCloseClient(con
);
1928 con
->http
->state
= HTTP_STATE_WAITING
;
1929 DEBUG_puts("cupsdReadClient: Set state to HTTP_STATE_WAITING "
1934 break; /* Anti-compiler-warning-code */
1940 * Handle any incoming data...
1943 switch (httpGetState(con
->http
))
1945 case HTTP_STATE_PUT_RECV
:
1948 if ((bytes
= httpRead2(con
->http
, line
, sizeof(line
))) < 0)
1950 if (httpError(con
->http
) && httpError(con
->http
) != EPIPE
)
1951 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1952 "HTTP_STATE_PUT_RECV Closing for error %d (%s)",
1953 httpError(con
->http
), strerror(httpError(con
->http
)));
1955 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1956 "HTTP_STATE_PUT_RECV Closing on EOF.");
1958 cupsdCloseClient(con
);
1963 con
->bytes
+= bytes
;
1965 if (write(con
->file
, line
, bytes
) < bytes
)
1967 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1968 "Unable to write %d bytes to \"%s\": %s", bytes
,
1969 con
->filename
, strerror(errno
));
1973 unlink(con
->filename
);
1974 cupsdClearString(&con
->filename
);
1976 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1978 cupsdCloseClient(con
);
1984 while (httpGetState(con
->http
) == HTTP_STATE_PUT_RECV
&& httpGetReady(con
->http
));
1986 if (httpGetState(con
->http
) == HTTP_STATE_STATUS
)
1989 * End of file, see how big it is...
1992 fstat(con
->file
, &filestats
);
1997 if (filestats
.st_size
> MaxRequestSize
&&
2001 * Request is too big; remove it and send an error...
2004 unlink(con
->filename
);
2005 cupsdClearString(&con
->filename
);
2007 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2009 cupsdCloseClient(con
);
2015 * Install the configuration file...
2018 status
= install_cupsd_conf(con
);
2021 * Return the status to the client...
2024 if (!cupsdSendError(con
, status
, CUPSD_AUTH_NONE
))
2026 cupsdCloseClient(con
);
2032 case HTTP_STATE_POST_RECV
:
2035 if (con
->request
&& con
->file
< 0)
2038 * Grab any request data from the connection...
2041 if ((ipp_state
= ippRead(con
->http
, con
->request
)) == IPP_STATE_ERROR
)
2043 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "IPP read error: %s",
2044 cupsLastErrorString());
2046 cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
);
2047 cupsdCloseClient(con
);
2050 else if (ipp_state
!= IPP_STATE_DATA
)
2052 if (httpGetState(con
->http
) == HTTP_STATE_POST_SEND
)
2054 cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
);
2055 cupsdCloseClient(con
);
2059 if (httpGetReady(con
->http
))
2065 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "%d.%d %s %d",
2066 con
->request
->request
.op
.version
[0],
2067 con
->request
->request
.op
.version
[1],
2068 ippOpString(con
->request
->request
.op
.operation_id
),
2069 con
->request
->request
.op
.request_id
);
2070 con
->bytes
+= ippLength(con
->request
);
2074 if (con
->file
< 0 && httpGetState(con
->http
) != HTTP_STATE_POST_SEND
)
2077 * Create a file as needed for the request data...
2080 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
2082 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
2086 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
2087 "Unable to create request file \"%s\": %s",
2088 con
->filename
, strerror(errno
));
2090 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2092 cupsdCloseClient(con
);
2097 fchmod(con
->file
, 0640);
2098 fchown(con
->file
, RunUser
, Group
);
2099 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2102 if (httpGetState(con
->http
) != HTTP_STATE_POST_SEND
)
2104 if (!httpWait(con
->http
, 0))
2106 else if ((bytes
= httpRead2(con
->http
, line
, sizeof(line
))) < 0)
2108 if (httpError(con
->http
) && httpError(con
->http
) != EPIPE
)
2109 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2110 "HTTP_STATE_POST_SEND Closing for error %d (%s)",
2111 httpError(con
->http
), strerror(httpError(con
->http
)));
2113 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2114 "HTTP_STATE_POST_SEND Closing on EOF.");
2116 cupsdCloseClient(con
);
2121 con
->bytes
+= bytes
;
2123 if (write(con
->file
, line
, bytes
) < bytes
)
2125 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
2126 "Unable to write %d bytes to \"%s\": %s",
2127 bytes
, con
->filename
, strerror(errno
));
2131 unlink(con
->filename
);
2132 cupsdClearString(&con
->filename
);
2134 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
,
2137 cupsdCloseClient(con
);
2142 else if (httpGetState(con
->http
) == HTTP_STATE_POST_RECV
)
2144 else if (httpGetState(con
->http
) != HTTP_STATE_POST_SEND
)
2146 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2147 "Closing on unexpected state %s.",
2148 httpStateString(httpGetState(con
->http
)));
2149 cupsdCloseClient(con
);
2154 while (httpGetState(con
->http
) == HTTP_STATE_POST_RECV
&& httpGetReady(con
->http
));
2156 if (httpGetState(con
->http
) == HTTP_STATE_POST_SEND
)
2160 fstat(con
->file
, &filestats
);
2165 if (filestats
.st_size
> MaxRequestSize
&&
2169 * Request is too big; remove it and send an error...
2172 unlink(con
->filename
);
2173 cupsdClearString(&con
->filename
);
2178 * Delete any IPP request data...
2181 ippDelete(con
->request
);
2182 con
->request
= NULL
;
2185 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2187 cupsdCloseClient(con
);
2191 else if (filestats
.st_size
== 0)
2194 * Don't allow empty file...
2197 unlink(con
->filename
);
2198 cupsdClearString(&con
->filename
);
2203 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
2205 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
2207 cupsdCloseClient(con
);
2212 cupsdLogRequest(con
, HTTP_STATUS_OK
);
2218 cupsdProcessIPPRequest(con
);
2222 unlink(con
->filename
);
2223 cupsdClearString(&con
->filename
);
2232 break; /* Anti-compiler-warning-code */
2235 if (httpGetState(con
->http
) == HTTP_STATE_WAITING
)
2237 if (!httpGetKeepAlive(con
->http
))
2239 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2240 "Closing because Keep-Alive is disabled.");
2241 cupsdCloseClient(con
);
2245 cupsArrayRemove(ActiveClients
, con
);
2246 cupsdSetBusyState();
2253 * 'cupsdSendCommand()' - Send output from a command via HTTP.
2256 int /* O - 1 on success, 0 on failure */
2258 cupsd_client_t
*con
, /* I - Client connection */
2259 char *command
, /* I - Command to run */
2260 char *options
, /* I - Command-line options */
2261 int root
) /* I - Run as root? */
2263 int fd
; /* Standard input file descriptor */
2268 fd
= open(con
->filename
, O_RDONLY
);
2272 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
2273 "Unable to open \"%s\" for reading: %s",
2274 con
->filename
? con
->filename
: "/dev/null",
2279 fcntl(fd
, F_SETFD
, fcntl(fd
, F_GETFD
) | FD_CLOEXEC
);
2284 con
->pipe_pid
= pipe_command(con
, fd
, &(con
->file
), command
, options
, root
);
2289 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Started \"%s\" (pid=%d, file=%d)",
2290 command
, con
->pipe_pid
, con
->file
);
2292 if (con
->pipe_pid
== 0)
2295 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2297 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2299 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for CGI data.");
2301 con
->sent_header
= 0;
2302 con
->file_ready
= 0;
2303 con
->got_fields
= 0;
2304 con
->header_used
= 0;
2311 * 'cupsdSendError()' - Send an error message via HTTP.
2314 int /* O - 1 if successful, 0 otherwise */
2315 cupsdSendError(cupsd_client_t
*con
, /* I - Connection */
2316 http_status_t code
, /* I - Error code */
2317 int auth_type
)/* I - Authentication type */
2319 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "cupsdSendError code=%d, auth_type=%d",
2324 * Force client to upgrade for authentication if that is how the
2325 * server is configured...
2328 if (code
== HTTP_STATUS_UNAUTHORIZED
&&
2329 DefaultEncryption
== HTTP_ENCRYPTION_REQUIRED
&&
2330 _cups_strcasecmp(httpGetHostname(con
->http
, NULL
, 0), "localhost") &&
2331 !httpIsEncrypted(con
->http
))
2333 code
= HTTP_STATUS_UPGRADE_REQUIRED
;
2335 #endif /* HAVE_SSL */
2338 * Put the request in the access_log file...
2341 cupsdLogRequest(con
, code
);
2344 * To work around bugs in some proxies, don't use Keep-Alive for some
2347 * Kerberos authentication doesn't work without Keep-Alive, so
2348 * never disable it in that case.
2351 if (code
>= HTTP_STATUS_BAD_REQUEST
&& con
->type
!= CUPSD_AUTH_NEGOTIATE
)
2352 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
2355 * Send an error message back to the client. If the error code is a
2356 * 400 or 500 series, make sure the message contains some text, too!
2359 if (!cupsdSendHeader(con
, code
, NULL
, auth_type
))
2363 if (code
== HTTP_STATUS_UPGRADE_REQUIRED
)
2364 if (httpPrintf(con
->http
, "Connection: Upgrade\r\n") < 0)
2367 if (httpPrintf(con
->http
, "Upgrade: TLS/1.2,TLS/1.1,TLS/1.0\r\n") < 0)
2369 #endif /* HAVE_SSL */
2371 if (con
->http
->version
>= HTTP_VERSION_1_1
&&
2372 httpGetKeepAlive(con
->http
) == HTTP_KEEPALIVE_OFF
)
2374 if (httpPrintf(con
->http
, "Connection: close\r\n") < 0)
2378 if (code
>= HTTP_STATUS_BAD_REQUEST
)
2381 * Send a human-readable error message.
2384 char message
[4096], /* Message for user */
2385 urltext
[1024], /* URL redirection text */
2386 redirect
[1024]; /* Redirection link */
2387 const char *text
; /* Status-specific text */
2392 if (code
== HTTP_STATUS_UNAUTHORIZED
)
2393 text
= _cupsLangString(con
->language
,
2394 _("Enter your username and password or the "
2395 "root username and password to access this "
2396 "page. If you are using Kerberos authentication, "
2397 "make sure you have a valid Kerberos ticket."));
2398 else if (code
== HTTP_STATUS_UPGRADE_REQUIRED
)
2402 snprintf(urltext
, sizeof(urltext
),
2403 _cupsLangString(con
->language
,
2404 _("You must access this page using the URL "
2405 "<A HREF=\"https://%s:%d%s\">"
2406 "https://%s:%d%s</A>.")),
2407 con
->servername
, con
->serverport
, con
->uri
,
2408 con
->servername
, con
->serverport
, con
->uri
);
2410 snprintf(redirect
, sizeof(redirect
),
2411 "<META HTTP-EQUIV=\"Refresh\" "
2412 "CONTENT=\"3;URL=https://%s:%d%s\">\n",
2413 con
->servername
, con
->serverport
, con
->uri
);
2415 else if (code
== HTTP_STATUS_CUPS_WEBIF_DISABLED
)
2416 text
= _cupsLangString(con
->language
,
2417 _("The web interface is currently disabled. Run "
2418 "\"cupsctl WebInterface=yes\" to enable it."));
2422 snprintf(message
, sizeof(message
),
2423 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" "
2424 "\"http://www.w3.org/TR/html4/loose.dtd\">\n"
2427 "\t<META HTTP-EQUIV=\"Content-Type\" "
2428 "CONTENT=\"text/html; charset=utf-8\">\n"
2429 "\t<TITLE>%s - " CUPS_SVERSION
"</TITLE>\n"
2430 "\t<LINK REL=\"STYLESHEET\" TYPE=\"text/css\" "
2431 "HREF=\"/cups.css\">\n"
2439 _httpStatus(con
->language
, code
), redirect
,
2440 _httpStatus(con
->language
, code
), text
);
2442 if (httpPrintf(con
->http
, "Content-Type: text/html; charset=utf-8\r\n") < 0)
2444 if (httpPrintf(con
->http
, "Content-Length: %d\r\n",
2445 (int)strlen(message
)) < 0)
2447 if (httpPrintf(con
->http
, "\r\n") < 0)
2449 if (httpPrintf(con
->http
, "%s", message
) < 0)
2452 else if (httpPrintf(con
->http
, "\r\n") < 0)
2455 if (cupsdFlushHeader(con
) < 0)
2458 con
->http
->state
= HTTP_STATE_WAITING
;
2460 DEBUG_puts("cupsdSendError: Set state to HTTP_STATE_WAITING.");
2467 * 'cupsdSendHeader()' - Send an HTTP request.
2470 int /* O - 1 on success, 0 on failure */
2472 cupsd_client_t
*con
, /* I - Client to send to */
2473 http_status_t code
, /* I - HTTP status code */
2474 char *type
, /* I - MIME type of document */
2475 int auth_type
) /* I - Type of authentication */
2477 char auth_str
[1024]; /* Authorization string */
2481 * Send the HTTP status header...
2484 if (code
== HTTP_STATUS_CONTINUE
)
2487 * 100-continue doesn't send any headers...
2490 return (httpPrintf(con
->http
, "HTTP/%d.%d 100 Continue\r\n\r\n",
2491 con
->http
->version
/ 100, con
->http
->version
% 100) > 0);
2493 else if (code
== HTTP_STATUS_CUPS_WEBIF_DISABLED
)
2496 * Treat our special "web interface is disabled" status as "200 OK" for web
2500 code
= HTTP_STATUS_OK
;
2503 httpFlushWrite(con
->http
);
2505 con
->http
->data_encoding
= HTTP_ENCODING_FIELDS
;
2507 if (httpPrintf(con
->http
, "HTTP/%d.%d %d %s\r\n", con
->http
->version
/ 100,
2508 con
->http
->version
% 100, code
, httpStatus(code
)) < 0)
2510 if (httpPrintf(con
->http
, "Date: %s\r\n", httpGetDateString(time(NULL
))) < 0)
2513 if (httpPrintf(con
->http
, "Server: %s\r\n", ServerHeader
) < 0)
2515 if (httpGetKeepAlive(con
->http
) && con
->http
->version
>= HTTP_VERSION_1_0
)
2517 if (httpPrintf(con
->http
, "Connection: Keep-Alive\r\n") < 0)
2519 if (httpPrintf(con
->http
, "Keep-Alive: timeout=%d\r\n",
2520 KeepAliveTimeout
) < 0)
2523 else if (httpPrintf(con
->http
, "Connection: close\r\n") < 0)
2526 if (code
== HTTP_STATUS_METHOD_NOT_ALLOWED
)
2527 if (httpPrintf(con
->http
, "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n") < 0)
2530 if (code
== HTTP_STATUS_UNAUTHORIZED
)
2532 if (auth_type
== CUPSD_AUTH_NONE
)
2534 if (!con
->best
|| con
->best
->type
<= CUPSD_AUTH_NONE
)
2535 auth_type
= cupsdDefaultAuthType();
2537 auth_type
= con
->best
->type
;
2542 if (auth_type
== CUPSD_AUTH_BASIC
|| auth_type
== CUPSD_AUTH_BASICDIGEST
)
2543 strlcpy(auth_str
, "Basic realm=\"CUPS\"", sizeof(auth_str
));
2544 else if (auth_type
== CUPSD_AUTH_DIGEST
)
2545 snprintf(auth_str
, sizeof(auth_str
), "Digest realm=\"CUPS\", nonce=\"%s\"",
2546 httpGetHostname(con
->http
, NULL
, 0));
2548 else if (auth_type
== CUPSD_AUTH_NEGOTIATE
)
2551 if (httpAddrFamily(httpGetAddress(con
->http
)) == AF_LOCAL
)
2552 strlcpy(auth_str
, "Basic realm=\"CUPS\"", sizeof(auth_str
));
2554 # endif /* AF_LOCAL */
2555 strlcpy(auth_str
, "Negotiate", sizeof(auth_str
));
2557 #endif /* HAVE_GSSAPI */
2559 if (con
->best
&& auth_type
!= CUPSD_AUTH_NEGOTIATE
&&
2560 !_cups_strcasecmp(httpGetHostname(con
->http
, NULL
, 0), "localhost"))
2563 * Add a "trc" (try root certification) parameter for local non-Kerberos
2564 * requests when the request requires system group membership - then the
2565 * client knows the root certificate can/should be used.
2567 * Also, for OS X we also look for @AUTHKEY and add an "authkey"
2568 * parameter as needed...
2571 char *name
, /* Current user name */
2572 *auth_key
; /* Auth key buffer */
2573 size_t auth_size
; /* Size of remaining buffer */
2575 auth_key
= auth_str
+ strlen(auth_str
);
2576 auth_size
= sizeof(auth_str
) - (auth_key
- auth_str
);
2578 for (name
= (char *)cupsArrayFirst(con
->best
->names
);
2580 name
= (char *)cupsArrayNext(con
->best
->names
))
2582 #ifdef HAVE_AUTHORIZATION_H
2583 if (!_cups_strncasecmp(name
, "@AUTHKEY(", 9))
2585 snprintf(auth_key
, auth_size
, ", authkey=\"%s\"", name
+ 9);
2586 /* end parenthesis is stripped in conf.c */
2590 #endif /* HAVE_AUTHORIZATION_H */
2591 if (!_cups_strcasecmp(name
, "@SYSTEM"))
2593 #ifdef HAVE_AUTHORIZATION_H
2594 if (SystemGroupAuthKey
)
2595 snprintf(auth_key
, auth_size
,
2597 SystemGroupAuthKey
);
2600 strlcpy(auth_key
, ", trc=\"y\"", auth_size
);
2601 #endif /* HAVE_AUTHORIZATION_H */
2609 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "WWW-Authenticate: %s", auth_str
);
2611 if (httpPrintf(con
->http
, "WWW-Authenticate: %s\r\n", auth_str
) < 0)
2616 if (con
->language
&& strcmp(con
->language
->language
, "C"))
2618 if (httpPrintf(con
->http
, "Content-Language: %s\r\n",
2619 con
->language
->language
) < 0)
2625 if (!strcmp(type
, "text/html"))
2627 if (httpPrintf(con
->http
,
2628 "Content-Type: text/html; charset=utf-8\r\n") < 0)
2631 else if (httpPrintf(con
->http
, "Content-Type: %s\r\n", type
) < 0)
2640 * 'cupsdUpdateCGI()' - Read status messages from CGI scripts and programs.
2644 cupsdUpdateCGI(void)
2646 char *ptr
, /* Pointer to end of line in buffer */
2647 message
[1024]; /* Pointer to message text */
2648 int loglevel
; /* Log level for message */
2651 while ((ptr
= cupsdStatBufUpdate(CGIStatusBuffer
, &loglevel
,
2652 message
, sizeof(message
))) != NULL
)
2654 if (loglevel
== CUPSD_LOG_INFO
)
2655 cupsdLogMessage(CUPSD_LOG_INFO
, "%s", message
);
2657 if (!strchr(CGIStatusBuffer
->buffer
, '\n'))
2661 if (ptr
== NULL
&& !CGIStatusBuffer
->bufused
)
2664 * Fatal error on pipe - should never happen!
2667 cupsdLogMessage(CUPSD_LOG_CRIT
,
2668 "cupsdUpdateCGI: error reading from CGI error pipe - %s",
2675 * 'cupsdWriteClient()' - Write data to a client as needed.
2679 cupsdWriteClient(cupsd_client_t
*con
) /* I - Client connection */
2681 int bytes
, /* Number of bytes written */
2682 field_col
; /* Current column */
2683 char *bufptr
, /* Pointer into buffer */
2684 *bufend
; /* Pointer to end of buffer */
2685 ipp_state_t ipp_state
; /* IPP state value */
2688 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "con->http=%p", con
->http
);
2689 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2694 "data_encoding=HTTP_ENCODING_%s, "
2695 "data_remaining=" CUPS_LLFMT
", "
2699 httpError(con
->http
), (int)httpGetReady(con
->http
),
2700 httpStateString(httpGetState(con
->http
)),
2701 con
->http
->data_encoding
== HTTP_ENCODING_CHUNKED
?
2702 "CHUNKED" : "LENGTH",
2703 CUPS_LLCAST con
->http
->data_remaining
,
2705 con
->response
? ipp_states
[con
->response
->state
] : "",
2706 con
->pipe_pid
, con
->file
);
2708 if (httpGetState(con
->http
) != HTTP_STATE_GET_SEND
&&
2709 httpGetState(con
->http
) != HTTP_STATE_POST_SEND
)
2712 * If we get called in the wrong state, then something went wrong with the
2713 * connection and we need to shut it down...
2716 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing on unexpected HTTP state %s.",
2717 httpStateString(httpGetState(con
->http
)));
2718 cupsdCloseClient(con
);
2725 * Make sure we select on the CGI output...
2728 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2730 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for CGI data.");
2732 if (!con
->file_ready
)
2735 * Try again later when there is CGI output available...
2738 cupsdRemoveSelect(httpGetFd(con
->http
));
2742 con
->file_ready
= 0;
2745 if (con
->response
&& con
->response
->state
!= IPP_STATE_DATA
)
2747 int wused
= con
->http
->wused
; /* Previous write buffer use */
2752 * Write a single attribute or the IPP message header...
2755 ipp_state
= ippWrite(con
->http
, con
->response
);
2758 * If the write buffer has been flushed, stop buffering up attributes...
2761 if (con
->http
->wused
<= wused
)
2764 while (ipp_state
!= IPP_STATE_DATA
&& ipp_state
!= IPP_STATE_ERROR
);
2766 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2767 "Writing IPP response, ipp_state=%s, old "
2768 "wused=%d, new wused=%d",
2769 ipp_state
== IPP_STATE_ERROR
? "ERROR" :
2770 ipp_state
== IPP_STATE_IDLE
? "IDLE" :
2771 ipp_state
== IPP_STATE_HEADER
? "HEADER" :
2772 ipp_state
== IPP_STATE_ATTRIBUTE
? "ATTRIBUTE" : "DATA",
2773 wused
, con
->http
->wused
);
2775 if (con
->http
->wused
> 0)
2776 httpFlushWrite(con
->http
);
2778 bytes
= ipp_state
!= IPP_STATE_ERROR
&&
2779 (con
->file
>= 0 || ipp_state
!= IPP_STATE_DATA
);
2781 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2782 "bytes=%d, http_state=%d, data_remaining=" CUPS_LLFMT
,
2783 (int)bytes
, httpGetState(con
->http
),
2784 CUPS_LLCAST con
->http
->data_remaining
);
2786 else if ((bytes
= read(con
->file
, con
->header
+ con
->header_used
,
2787 sizeof(con
->header
) - con
->header_used
)) > 0)
2789 con
->header_used
+= bytes
;
2791 if (con
->pipe_pid
&& !con
->got_fields
)
2794 * Inspect the data for Content-Type and other fields.
2797 for (bufptr
= con
->header
, bufend
= con
->header
+ con
->header_used
,
2799 !con
->got_fields
&& bufptr
< bufend
;
2802 if (*bufptr
== '\n')
2805 * Send line to client...
2808 if (bufptr
> con
->header
&& bufptr
[-1] == '\r')
2812 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Script header: %s", con
->header
);
2814 if (!con
->sent_header
)
2817 * Handle redirection and CGI status codes...
2820 if (!_cups_strncasecmp(con
->header
, "Location:", 9))
2822 if (!cupsdSendHeader(con
, HTTP_STATUS_SEE_OTHER
, NULL
, CUPSD_AUTH_NONE
))
2824 cupsdCloseClient(con
);
2828 con
->sent_header
= 2;
2830 if (httpPrintf(con
->http
, "Content-Length: 0\r\n") < 0)
2833 else if (!_cups_strncasecmp(con
->header
, "Status:", 7))
2835 cupsdSendError(con
, (http_status_t
)atoi(con
->header
+ 7),
2837 con
->sent_header
= 2;
2841 if (!cupsdSendHeader(con
, HTTP_STATUS_OK
, NULL
, CUPSD_AUTH_NONE
))
2843 cupsdCloseClient(con
);
2847 con
->sent_header
= 1;
2849 if (con
->http
->version
== HTTP_VERSION_1_1
)
2851 if (httpPrintf(con
->http
, "Transfer-Encoding: chunked\r\n") < 0)
2857 if (_cups_strncasecmp(con
->header
, "Status:", 7))
2858 httpPrintf(con
->http
, "%s\r\n", con
->header
);
2864 con
->header_used
-= bufptr
- con
->header
;
2866 if (con
->header_used
> 0)
2867 memmove(con
->header
, bufptr
, con
->header_used
);
2869 bufptr
= con
->header
- 1;
2872 * See if the line was empty...
2877 con
->got_fields
= 1;
2879 if (cupsdFlushHeader(con
) < 0)
2881 cupsdCloseClient(con
);
2885 if (con
->http
->version
== HTTP_VERSION_1_1
)
2886 con
->http
->data_encoding
= HTTP_ENCODING_CHUNKED
;
2891 else if (*bufptr
!= '\r')
2895 if (!con
->got_fields
)
2897 con
->http
->activity
= time(NULL
);
2902 if (con
->header_used
> 0)
2904 if (httpWrite2(con
->http
, con
->header
, con
->header_used
) < 0)
2906 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing for error %d (%s)",
2907 httpError(con
->http
), strerror(httpError(con
->http
)));
2908 cupsdCloseClient(con
);
2912 if (con
->http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
2913 httpFlushWrite(con
->http
);
2915 con
->bytes
+= con
->header_used
;
2917 if (httpGetState(con
->http
) == HTTP_STATE_WAITING
)
2920 bytes
= con
->header_used
;
2922 con
->header_used
= 0;
2927 (httpGetState(con
->http
) != HTTP_STATE_GET_SEND
&&
2928 httpGetState(con
->http
) != HTTP_STATE_POST_SEND
))
2930 if (!con
->sent_header
&& con
->pipe_pid
)
2931 cupsdSendError(con
, HTTP_STATUS_SERVER_ERROR
, CUPSD_AUTH_NONE
);
2934 cupsdLogRequest(con
, HTTP_STATUS_OK
);
2936 httpFlushWrite(con
->http
);
2938 if (con
->http
->data_encoding
== HTTP_ENCODING_CHUNKED
&&
2939 con
->sent_header
== 1)
2941 if (httpWrite2(con
->http
, "", 0) < 0)
2943 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing for error %d (%s)",
2944 httpError(con
->http
), strerror(httpError(con
->http
)));
2945 cupsdCloseClient(con
);
2951 con
->http
->state
= HTTP_STATE_WAITING
;
2953 cupsdAddSelect(httpGetFd(con
->http
), (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
2955 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for request.");
2959 cupsdRemoveSelect(con
->file
);
2962 cupsdEndProcess(con
->pipe_pid
, 0);
2971 unlink(con
->filename
);
2972 cupsdClearString(&con
->filename
);
2977 ippDelete(con
->request
);
2978 con
->request
= NULL
;
2983 ippDelete(con
->response
);
2984 con
->response
= NULL
;
2987 cupsdClearString(&con
->command
);
2988 cupsdClearString(&con
->options
);
2989 cupsdClearString(&con
->query_string
);
2991 if (!httpGetKeepAlive(con
->http
))
2993 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2994 "Closing because Keep-Alive is disabled.");
2995 cupsdCloseClient(con
);
3000 cupsArrayRemove(ActiveClients
, con
);
3001 cupsdSetBusyState();
3005 con
->http
->activity
= time(NULL
);
3010 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
3013 static int /* O - 1 if modified since */
3015 cupsd_client_t
*con
, /* I - Client connection */
3016 struct stat
*filestats
) /* I - File information */
3018 const char *ptr
; /* Pointer into field */
3019 time_t date
; /* Time/date value */
3020 off_t size
; /* Size/length value */
3025 ptr
= httpGetField(con
->http
, HTTP_FIELD_IF_MODIFIED_SINCE
);
3030 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3031 "check_if_modified "
3032 "filestats=%p(" CUPS_LLFMT
", %d)) If-Modified-Since=\"%s\"",
3033 filestats
, CUPS_LLCAST filestats
->st_size
,
3034 (int)filestats
->st_mtime
, ptr
);
3036 while (*ptr
!= '\0')
3038 while (isspace(*ptr
) || *ptr
== ';')
3041 if (_cups_strncasecmp(ptr
, "length=", 7) == 0)
3044 size
= strtoll(ptr
, NULL
, 10);
3046 while (isdigit(*ptr
))
3049 else if (isalpha(*ptr
))
3051 date
= httpGetDateTime(ptr
);
3052 while (*ptr
!= '\0' && *ptr
!= ';')
3059 return ((size
!= filestats
->st_size
&& size
!= 0) ||
3060 (date
< filestats
->st_mtime
&& date
!= 0) ||
3061 (size
== 0 && date
== 0));
3066 * 'compare_clients()' - Compare two client connections.
3069 static int /* O - Result of comparison */
3070 compare_clients(cupsd_client_t
*a
, /* I - First client */
3071 cupsd_client_t
*b
, /* I - Second client */
3072 void *data
) /* I - User data (not used) */
3086 * 'get_file()' - Get a filename and state info.
3089 static char * /* O - Real filename */
3090 get_file(cupsd_client_t
*con
, /* I - Client connection */
3091 struct stat
*filestats
, /* O - File information */
3092 char *filename
, /* IO - Filename buffer */
3093 int len
) /* I - Buffer length */
3095 int status
; /* Status of filesystem calls */
3096 char *ptr
; /* Pointer info filename */
3097 int plen
; /* Remaining length after pointer */
3098 char language
[7]; /* Language subdirectory, if any */
3102 * Figure out the real filename...
3107 if (!strncmp(con
->uri
, "/ppd/", 5) && !strchr(con
->uri
+ 5, '/'))
3108 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
);
3109 else if (!strncmp(con
->uri
, "/icons/", 7) && !strchr(con
->uri
+ 7, '/'))
3111 snprintf(filename
, len
, "%s/%s", CacheDir
, con
->uri
+ 7);
3112 if (access(filename
, F_OK
) < 0)
3113 snprintf(filename
, len
, "%s/images/generic.png", DocumentRoot
);
3115 else if (!strncmp(con
->uri
, "/rss/", 5) && !strchr(con
->uri
+ 5, '/'))
3116 snprintf(filename
, len
, "%s/rss/%s", CacheDir
, con
->uri
+ 5);
3117 else if (!strncmp(con
->uri
, "/admin/conf/", 12))
3118 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
+ 11);
3119 else if (!strncmp(con
->uri
, "/admin/log/", 11))
3121 if (!strncmp(con
->uri
+ 11, "access_log", 10) && AccessLog
[0] == '/')
3122 strlcpy(filename
, AccessLog
, len
);
3123 else if (!strncmp(con
->uri
+ 11, "error_log", 9) && ErrorLog
[0] == '/')
3124 strlcpy(filename
, ErrorLog
, len
);
3125 else if (!strncmp(con
->uri
+ 11, "page_log", 8) && PageLog
[0] == '/')
3126 strlcpy(filename
, PageLog
, len
);
3130 else if (con
->language
)
3132 snprintf(language
, sizeof(language
), "/%s", con
->language
->language
);
3133 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3136 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3138 if ((ptr
= strchr(filename
, '?')) != NULL
)
3142 * Grab the status for this language; if there isn't a language-specific file
3143 * then fallback to the default one...
3146 if ((status
= stat(filename
, filestats
)) != 0 && language
[0] &&
3147 strncmp(con
->uri
, "/icons/", 7) &&
3148 strncmp(con
->uri
, "/ppd/", 5) &&
3149 strncmp(con
->uri
, "/rss/", 5) &&
3150 strncmp(con
->uri
, "/admin/conf/", 12) &&
3151 strncmp(con
->uri
, "/admin/log/", 11))
3154 * Drop the country code...
3158 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3160 if ((ptr
= strchr(filename
, '?')) != NULL
)
3163 if ((status
= stat(filename
, filestats
)) != 0)
3166 * Drop the language prefix and try the root directory...
3170 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3172 if ((ptr
= strchr(filename
, '?')) != NULL
)
3175 status
= stat(filename
, filestats
);
3180 * If we're found a directory, get the index.html file instead...
3183 if (!status
&& S_ISDIR(filestats
->st_mode
))
3186 * Make sure the URI ends with a slash...
3189 if (con
->uri
[strlen(con
->uri
) - 1] != '/')
3190 strlcat(con
->uri
, "/", sizeof(con
->uri
));
3193 * Find the directory index file, trying every language...
3198 if (status
&& language
[0])
3201 * Try a different language subset...
3205 language
[0] = '\0'; /* Strip country code */
3207 language
[0] = '\0'; /* Strip language */
3211 * Look for the index file...
3214 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3216 if ((ptr
= strchr(filename
, '?')) != NULL
)
3219 ptr
= filename
+ strlen(filename
);
3220 plen
= len
- (ptr
- filename
);
3222 strlcpy(ptr
, "index.html", plen
);
3223 status
= stat(filename
, filestats
);
3228 strlcpy(ptr
, "index.class", plen
);
3229 status
= stat(filename
, filestats
);
3231 #endif /* HAVE_JAVA */
3236 strlcpy(ptr
, "index.pl", plen
);
3237 status
= stat(filename
, filestats
);
3239 #endif /* HAVE_PERL */
3244 strlcpy(ptr
, "index.php", plen
);
3245 status
= stat(filename
, filestats
);
3247 #endif /* HAVE_PHP */
3252 strlcpy(ptr
, "index.pyc", plen
);
3253 status
= stat(filename
, filestats
);
3258 strlcpy(ptr
, "index.py", plen
);
3259 status
= stat(filename
, filestats
);
3261 #endif /* HAVE_PYTHON */
3264 while (status
&& language
[0]);
3267 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3268 "get_file filestats=%p, filename=%p, len=%d, "
3269 "returning \"%s\".", filestats
, filename
, len
,
3270 status
? "(null)" : filename
);
3280 * 'install_cupsd_conf()' - Install a configuration file.
3283 static http_status_t
/* O - Status */
3284 install_cupsd_conf(cupsd_client_t
*con
) /* I - Connection */
3286 char filename
[1024]; /* Configuration filename */
3287 cups_file_t
*in
, /* Input file */
3288 *out
; /* Output file */
3289 char buffer
[16384]; /* Copy buffer */
3290 ssize_t bytes
; /* Number of bytes */
3294 * Open the request file...
3297 if ((in
= cupsFileOpen(con
->filename
, "rb")) == NULL
)
3299 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Unable to open request file \"%s\": %s",
3300 con
->filename
, strerror(errno
));
3301 return (HTTP_STATUS_SERVER_ERROR
);
3305 * Open the new config file...
3308 if ((out
= cupsdCreateConfFile(ConfigurationFile
, ConfigFilePerm
)) == NULL
)
3311 return (HTTP_STATUS_SERVER_ERROR
);
3314 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Installing config file \"%s\"...",
3318 * Copy from the request to the new config file...
3321 while ((bytes
= cupsFileRead(in
, buffer
, sizeof(buffer
))) > 0)
3322 if (cupsFileWrite(out
, buffer
, bytes
) < bytes
)
3324 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
3325 "Unable to copy to config file \"%s\": %s",
3326 ConfigurationFile
, strerror(errno
));
3331 snprintf(filename
, sizeof(filename
), "%s.N", ConfigurationFile
);
3332 cupsdUnlinkOrRemoveFile(filename
);
3334 return (HTTP_STATUS_SERVER_ERROR
);
3338 * Close the files...
3343 if (cupsdCloseCreatedConfFile(out
, ConfigurationFile
))
3344 return (HTTP_STATUS_SERVER_ERROR
);
3347 * Remove the request file...
3350 cupsdUnlinkOrRemoveFile(con
->filename
);
3351 cupsdClearString(&con
->filename
);
3354 * Set the NeedReload flag...
3357 NeedReload
= RELOAD_CUPSD
;
3358 ReloadTime
= time(NULL
);
3361 * Return that the file was created successfully...
3364 return (HTTP_STATUS_CREATED
);
3369 * 'is_cgi()' - Is the resource a CGI script/program?
3372 static int /* O - 1 = CGI, 0 = file */
3373 is_cgi(cupsd_client_t
*con
, /* I - Client connection */
3374 const char *filename
, /* I - Real filename */
3375 struct stat
*filestats
, /* I - File information */
3376 mime_type_t
*type
) /* I - MIME type */
3378 const char *options
; /* Options on URL */
3382 * Get the options, if any...
3385 if ((options
= strchr(con
->uri
, '?')) != NULL
)
3388 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", options
);
3392 * Check for known types...
3395 if (!type
|| _cups_strcasecmp(type
->super
, "application"))
3397 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3398 "is_cgi filename=\"%s\", filestats=%p, "
3399 "type=%s/%s, returning 0", filename
,
3400 filestats
, type
? type
->super
: "unknown",
3401 type
? type
->type
: "unknown");
3405 if (!_cups_strcasecmp(type
->type
, "x-httpd-cgi") &&
3406 (filestats
->st_mode
& 0111))
3409 * "application/x-httpd-cgi" is a CGI script.
3412 cupsdSetString(&con
->command
, filename
);
3415 cupsdSetStringf(&con
->options
, " %s", options
);
3417 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3418 "is_cgi filename=\"%s\", filestats=%p, "
3419 "type=%s/%s, returning 1", filename
,
3420 filestats
, type
->super
, type
->type
);
3424 else if (!_cups_strcasecmp(type
->type
, "x-httpd-java"))
3427 * "application/x-httpd-java" is a Java servlet.
3430 cupsdSetString(&con
->command
, CUPS_JAVA
);
3433 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3435 cupsdSetStringf(&con
->options
, " %s", filename
);
3437 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3438 "is_cgi filename=\"%s\", filestats=%p, "
3439 "type=%s/%s, returning 1", filename
,
3440 filestats
, type
->super
, type
->type
);
3443 #endif /* HAVE_JAVA */
3445 else if (!_cups_strcasecmp(type
->type
, "x-httpd-perl"))
3448 * "application/x-httpd-perl" is a Perl page.
3451 cupsdSetString(&con
->command
, CUPS_PERL
);
3454 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3456 cupsdSetStringf(&con
->options
, " %s", filename
);
3458 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3459 "is_cgi filename=\"%s\", filestats=%p, "
3460 "type=%s/%s, returning 1", filename
,
3461 filestats
, type
->super
, type
->type
);
3464 #endif /* HAVE_PERL */
3466 else if (!_cups_strcasecmp(type
->type
, "x-httpd-php"))
3469 * "application/x-httpd-php" is a PHP page.
3472 cupsdSetString(&con
->command
, CUPS_PHP
);
3475 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3477 cupsdSetStringf(&con
->options
, " %s", filename
);
3479 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3480 "is_cgi filename=\"%s\", filestats=%p, "
3481 "type=%s/%s, returning 1", filename
,
3482 filestats
, type
->super
, type
->type
);
3485 #endif /* HAVE_PHP */
3487 else if (!_cups_strcasecmp(type
->type
, "x-httpd-python"))
3490 * "application/x-httpd-python" is a Python page.
3493 cupsdSetString(&con
->command
, CUPS_PYTHON
);
3496 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3498 cupsdSetStringf(&con
->options
, " %s", filename
);
3500 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3501 "is_cgi filename=\"%s\", filestats=%p, "
3502 "type=%s/%s, returning 1", filename
,
3503 filestats
, type
->super
, type
->type
);
3506 #endif /* HAVE_PYTHON */
3508 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3509 "is_cgi filename=\"%s\", filestats=%p, "
3510 "type=%s/%s, returning 0", filename
,
3511 filestats
, type
->super
, type
->type
);
3517 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
3520 static int /* O - 0 if relative, 1 if absolute */
3521 is_path_absolute(const char *path
) /* I - Input path */
3524 * Check for a leading slash...
3531 * Check for "/.." in the path...
3534 while ((path
= strstr(path
, "/..")) != NULL
)
3536 if (!path
[3] || path
[3] == '/')
3543 * If we haven't found any relative paths, return 1 indicating an
3552 * 'pipe_command()' - Pipe the output of a command to the remote client.
3555 static int /* O - Process ID */
3556 pipe_command(cupsd_client_t
*con
, /* I - Client connection */
3557 int infile
, /* I - Standard input for command */
3558 int *outfile
, /* O - Standard output for command */
3559 char *command
, /* I - Command to run */
3560 char *options
, /* I - Options for command */
3561 int root
) /* I - Run as root? */
3563 int i
; /* Looping var */
3564 int pid
; /* Process ID */
3565 char *commptr
, /* Command string pointer */
3566 commch
; /* Command string character */
3567 char *uriptr
; /* URI string pointer */
3568 int fds
[2]; /* Pipe FDs */
3569 int argc
; /* Number of arguments */
3570 int envc
; /* Number of environment variables */
3571 char argbuf
[10240], /* Argument buffer */
3572 *argv
[100], /* Argument strings */
3573 *envp
[MAX_ENV
+ 20]; /* Environment variables */
3574 char auth_type
[256], /* AUTH_TYPE environment variable */
3575 content_length
[1024], /* CONTENT_LENGTH environment variable */
3576 content_type
[1024], /* CONTENT_TYPE environment variable */
3577 http_cookie
[32768], /* HTTP_COOKIE environment variable */
3578 http_referer
[1024], /* HTTP_REFERER environment variable */
3579 http_user_agent
[1024], /* HTTP_USER_AGENT environment variable */
3580 lang
[1024], /* LANG environment variable */
3581 path_info
[1024], /* PATH_INFO environment variable */
3582 remote_addr
[1024], /* REMOTE_ADDR environment variable */
3583 remote_host
[1024], /* REMOTE_HOST environment variable */
3584 remote_user
[1024], /* REMOTE_USER environment variable */
3585 script_filename
[1024], /* SCRIPT_FILENAME environment variable */
3586 script_name
[1024], /* SCRIPT_NAME environment variable */
3587 server_name
[1024], /* SERVER_NAME environment variable */
3588 server_port
[1024]; /* SERVER_PORT environment variable */
3589 ipp_attribute_t
*attr
; /* attributes-natural-language attribute */
3593 * Parse a copy of the options string, which is of the form:
3595 * argument+argument+argument
3596 * ?argument+argument+argument
3597 * param=value¶m=value
3598 * ?param=value¶m=value
3599 * /name?argument+argument+argument
3600 * /name?param=value¶m=value
3602 * If the string contains an "=" character after the initial name,
3603 * then we treat it as a HTTP GET form request and make a copy of
3604 * the remaining string for the environment variable.
3606 * The string is always parsed out as command-line arguments, to
3607 * be consistent with Apache...
3610 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3611 "pipe_command infile=%d, outfile=%p, "
3612 "command=\"%s\", options=\"%s\", root=%d",
3613 infile
, outfile
, command
,
3614 options
? options
: "(null)", root
);
3621 if (*commptr
== ' ')
3623 strlcpy(argbuf
, commptr
, sizeof(argbuf
));
3628 if (argbuf
[0] == '/')
3631 * Found some trailing path information, set PATH_INFO...
3634 if ((commptr
= strchr(argbuf
, '?')) == NULL
)
3635 commptr
= argbuf
+ strlen(argbuf
);
3639 snprintf(path_info
, sizeof(path_info
), "PATH_INFO=%s", argbuf
);
3645 path_info
[0] = '\0';
3647 if (*commptr
== ' ')
3651 if (*commptr
== '?' && con
->operation
== HTTP_STATE_GET
&& !con
->query_string
)
3654 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", commptr
);
3661 argv
[argc
++] = commptr
;
3663 for (; *commptr
&& argc
< 99; commptr
++)
3666 * Break arguments whenever we see a + or space...
3669 if (*commptr
== ' ' || *commptr
== '+')
3671 while (*commptr
== ' ' || *commptr
== '+')
3675 * If we don't have a blank string, save it as another argument...
3680 argv
[argc
] = commptr
;
3686 else if (*commptr
== '%' && isxdigit(commptr
[1] & 255) &&
3687 isxdigit(commptr
[2] & 255))
3690 * Convert the %xx notation to the individual character.
3693 if (commptr
[1] >= '0' && commptr
[1] <= '9')
3694 *commptr
= (commptr
[1] - '0') << 4;
3696 *commptr
= (tolower(commptr
[1]) - 'a' + 10) << 4;
3698 if (commptr
[2] >= '0' && commptr
[2] <= '9')
3699 *commptr
|= commptr
[2] - '0';
3701 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
3703 _cups_strcpy(commptr
+ 1, commptr
+ 3);
3706 * Check for a %00 and break if that is the case...
3718 * Setup the environment variables as needed...
3721 if (con
->username
[0])
3723 snprintf(auth_type
, sizeof(auth_type
), "AUTH_TYPE=%s",
3724 httpGetField(con
->http
, HTTP_FIELD_AUTHORIZATION
));
3726 if ((uriptr
= strchr(auth_type
+ 10, ' ')) != NULL
)
3730 auth_type
[0] = '\0';
3733 (attr
= ippFindAttribute(con
->request
, "attributes-natural-language",
3734 IPP_TAG_LANGUAGE
)) != NULL
)
3736 switch (strlen(attr
->values
[0].string
.text
))
3740 * This is an unknown or badly formatted language code; use
3741 * the POSIX locale...
3744 strlcpy(lang
, "LANG=C", sizeof(lang
));
3749 * Just the language code (ll)...
3752 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8",
3753 attr
->values
[0].string
.text
);
3758 * Language and country code (ll-cc)...
3761 snprintf(lang
, sizeof(lang
), "LANG=%c%c_%c%c.UTF8",
3762 attr
->values
[0].string
.text
[0],
3763 attr
->values
[0].string
.text
[1],
3764 toupper(attr
->values
[0].string
.text
[3] & 255),
3765 toupper(attr
->values
[0].string
.text
[4] & 255));
3769 else if (con
->language
)
3770 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8", con
->language
->language
);
3772 strlcpy(lang
, "LANG=C", sizeof(lang
));
3774 strlcpy(remote_addr
, "REMOTE_ADDR=", sizeof(remote_addr
));
3775 httpAddrString(httpGetAddress(con
->http
), remote_addr
+ 12,
3776 sizeof(remote_addr
) - 12);
3778 snprintf(remote_host
, sizeof(remote_host
), "REMOTE_HOST=%s",
3779 httpGetHostname(con
->http
, NULL
, 0));
3781 snprintf(script_name
, sizeof(script_name
), "SCRIPT_NAME=%s", con
->uri
);
3782 if ((uriptr
= strchr(script_name
, '?')) != NULL
)
3785 snprintf(script_filename
, sizeof(script_filename
), "SCRIPT_FILENAME=%s%s",
3786 DocumentRoot
, script_name
+ 12);
3788 sprintf(server_port
, "SERVER_PORT=%d", con
->serverport
);
3790 if (httpGetField(con
->http
, HTTP_FIELD_HOST
)[0])
3792 char *nameptr
; /* Pointer to ":port" */
3794 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
3795 httpGetField(con
->http
, HTTP_FIELD_HOST
));
3796 if ((nameptr
= strrchr(server_name
, ':')) != NULL
&& !strchr(nameptr
, ']'))
3797 *nameptr
= '\0'; /* Strip trailing ":port" */
3800 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
3803 envc
= cupsdLoadEnv(envp
, (int)(sizeof(envp
) / sizeof(envp
[0])));
3806 envp
[envc
++] = auth_type
;
3808 envp
[envc
++] = lang
;
3809 envp
[envc
++] = "REDIRECT_STATUS=1";
3810 envp
[envc
++] = "GATEWAY_INTERFACE=CGI/1.1";
3811 envp
[envc
++] = server_name
;
3812 envp
[envc
++] = server_port
;
3813 envp
[envc
++] = remote_addr
;
3814 envp
[envc
++] = remote_host
;
3815 envp
[envc
++] = script_name
;
3816 envp
[envc
++] = script_filename
;
3819 envp
[envc
++] = path_info
;
3821 if (con
->username
[0])
3823 snprintf(remote_user
, sizeof(remote_user
), "REMOTE_USER=%s", con
->username
);
3825 envp
[envc
++] = remote_user
;
3828 if (con
->http
->version
== HTTP_VERSION_1_1
)
3829 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.1";
3830 else if (con
->http
->version
== HTTP_VERSION_1_0
)
3831 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.0";
3833 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/0.9";
3835 if (con
->http
->cookie
)
3837 snprintf(http_cookie
, sizeof(http_cookie
), "HTTP_COOKIE=%s",
3839 envp
[envc
++] = http_cookie
;
3842 if (httpGetField(con
->http
, HTTP_FIELD_USER_AGENT
)[0])
3844 snprintf(http_user_agent
, sizeof(http_user_agent
), "HTTP_USER_AGENT=%s",
3845 httpGetField(con
->http
, HTTP_FIELD_USER_AGENT
));
3846 envp
[envc
++] = http_user_agent
;
3849 if (httpGetField(con
->http
, HTTP_FIELD_REFERER
)[0])
3851 snprintf(http_referer
, sizeof(http_referer
), "HTTP_REFERER=%s",
3852 httpGetField(con
->http
, HTTP_FIELD_REFERER
));
3853 envp
[envc
++] = http_referer
;
3856 if (con
->operation
== HTTP_STATE_GET
)
3858 envp
[envc
++] = "REQUEST_METHOD=GET";
3860 if (con
->query_string
)
3863 * Add GET form variables after ?...
3866 envp
[envc
++] = con
->query_string
;
3869 envp
[envc
++] = "QUERY_STRING=";
3873 sprintf(content_length
, "CONTENT_LENGTH=" CUPS_LLFMT
,
3874 CUPS_LLCAST con
->bytes
);
3875 snprintf(content_type
, sizeof(content_type
), "CONTENT_TYPE=%s",
3876 httpGetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
));
3878 envp
[envc
++] = "REQUEST_METHOD=POST";
3879 envp
[envc
++] = content_length
;
3880 envp
[envc
++] = content_type
;
3884 * Tell the CGI if we are using encryption...
3888 envp
[envc
++] = "HTTPS=ON";
3891 * Terminate the environment array...
3896 if (LogLevel
>= CUPSD_LOG_DEBUG
)
3898 for (i
= 0; i
< argc
; i
++)
3899 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3900 "[CGI] argv[%d] = \"%s\"", i
, argv
[i
]);
3901 for (i
= 0; i
< envc
; i
++)
3902 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3903 "[CGI] envp[%d] = \"%s\"", i
, envp
[i
]);
3907 * Create a pipe for the output...
3910 if (cupsdOpenPipe(fds
))
3912 cupsdLogMessage(CUPSD_LOG_ERROR
, "[CGI] Unable to create pipe for %s - %s",
3913 argv
[0], strerror(errno
));
3918 * Then execute the command...
3921 if (cupsdStartProcess(command
, argv
, envp
, infile
, fds
[1], CGIPipes
[1],
3922 -1, -1, root
, DefaultProfile
, NULL
, &pid
) < 0)
3925 * Error - can't fork!
3928 cupsdLogMessage(CUPSD_LOG_ERROR
, "[CGI] Unable to start %s - %s", argv
[0],
3931 cupsdClosePipe(fds
);
3937 * Fork successful - return the PID...
3940 if (con
->username
[0])
3941 cupsdAddCert(pid
, con
->username
, con
->type
);
3943 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[CGI] Started %s (PID %d)", command
, pid
);
3954 * 'valid_host()' - Is the Host: field valid?
3957 static int /* O - 1 if valid, 0 if not */
3958 valid_host(cupsd_client_t
*con
) /* I - Client connection */
3960 cupsd_alias_t
*a
; /* Current alias */
3961 cupsd_netif_t
*netif
; /* Current network interface */
3962 const char *end
; /* End character */
3963 char *ptr
; /* Pointer into host value */
3967 * Copy the Host: header for later use...
3970 strlcpy(con
->clientname
, httpGetField(con
->http
, HTTP_FIELD_HOST
),
3971 sizeof(con
->clientname
));
3972 if ((ptr
= strrchr(con
->clientname
, ':')) != NULL
&& !strchr(ptr
, ']'))
3975 con
->clientport
= atoi(ptr
);
3978 con
->clientport
= con
->serverport
;
3984 if (httpAddrLocalhost(httpGetAddress(con
->http
)))
3987 * Only allow "localhost" or the equivalent IPv4 or IPv6 numerical
3988 * addresses when accessing CUPS via the loopback interface...
3991 return (!_cups_strcasecmp(con
->clientname
, "localhost") ||
3992 !_cups_strcasecmp(con
->clientname
, "localhost.") ||
3994 !_cups_strcasecmp(con
->clientname
, "localhost.localdomain") ||
3995 #endif /* __linux */
3996 !strcmp(con
->clientname
, "127.0.0.1") ||
3997 !strcmp(con
->clientname
, "[::1]"));
4000 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
4002 * Check if the hostname is something.local (Bonjour); if so, allow it.
4005 if ((end
= strrchr(con
->clientname
, '.')) != NULL
&& end
> con
->clientname
&&
4009 * "." on end, work back to second-to-last "."...
4012 for (end
--; end
> con
->clientname
&& *end
!= '.'; end
--);
4015 if (end
&& (!_cups_strcasecmp(end
, ".local") ||
4016 !_cups_strcasecmp(end
, ".local.")))
4018 #endif /* HAVE_DNSSD || HAVE_AVAHI */
4021 * Check if the hostname is an IP address...
4024 if (isdigit(con
->clientname
[0] & 255) || con
->clientname
[0] == '[')
4027 * Possible IPv4/IPv6 address...
4030 http_addrlist_t
*addrlist
; /* List of addresses */
4033 if ((addrlist
= httpAddrGetList(con
->clientname
, AF_UNSPEC
, NULL
)) != NULL
)
4036 * Good IPv4/IPv6 address...
4039 httpAddrFreeList(addrlist
);
4045 * Check for (alias) name matches...
4048 for (a
= (cupsd_alias_t
*)cupsArrayFirst(ServerAlias
);
4050 a
= (cupsd_alias_t
*)cupsArrayNext(ServerAlias
))
4053 * "ServerAlias *" allows all host values through...
4056 if (!strcmp(a
->name
, "*"))
4059 if (!_cups_strncasecmp(con
->clientname
, a
->name
, a
->namelen
))
4062 * Prefix matches; check the character at the end - it must be "." or nul.
4065 end
= con
->clientname
+ a
->namelen
;
4067 if (!*end
|| (*end
== '.' && !end
[1]))
4072 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
4073 for (a
= (cupsd_alias_t
*)cupsArrayFirst(DNSSDAlias
);
4075 a
= (cupsd_alias_t
*)cupsArrayNext(DNSSDAlias
))
4078 * "ServerAlias *" allows all host values through...
4081 if (!strcmp(a
->name
, "*"))
4084 if (!_cups_strncasecmp(con
->clientname
, a
->name
, a
->namelen
))
4087 * Prefix matches; check the character at the end - it must be "." or nul.
4090 end
= con
->clientname
+ a
->namelen
;
4092 if (!*end
|| (*end
== '.' && !end
[1]))
4096 #endif /* HAVE_DNSSD || HAVE_AVAHI */
4099 * Check for interface hostname matches...
4102 for (netif
= (cupsd_netif_t
*)cupsArrayFirst(NetIFList
);
4104 netif
= (cupsd_netif_t
*)cupsArrayNext(NetIFList
))
4106 if (!_cups_strncasecmp(con
->clientname
, netif
->hostname
, netif
->hostlen
))
4109 * Prefix matches; check the character at the end - it must be "." or nul.
4112 end
= con
->clientname
+ netif
->hostlen
;
4114 if (!*end
|| (*end
== '.' && !end
[1]))
4124 * 'write_file()' - Send a file via HTTP.
4127 static int /* O - 0 on failure, 1 on success */
4128 write_file(cupsd_client_t
*con
, /* I - Client connection */
4129 http_status_t code
, /* I - HTTP status */
4130 char *filename
, /* I - Filename */
4131 char *type
, /* I - File type */
4132 struct stat
*filestats
) /* O - File information */
4134 con
->file
= open(filename
, O_RDONLY
);
4136 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
4137 "write_file code=%d, filename=\"%s\" (%d), "
4138 "type=\"%s\", filestats=%p",
4139 code
, filename
, con
->file
, type
? type
: "(null)", filestats
);
4144 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
4148 if (!cupsdSendHeader(con
, code
, type
, CUPSD_AUTH_NONE
))
4151 if (httpPrintf(con
->http
, "Last-Modified: %s\r\n",
4152 httpGetDateString(filestats
->st_mtime
)) < 0)
4154 if (httpPrintf(con
->http
, "Content-Length: " CUPS_LLFMT
"\r\n",
4155 CUPS_LLCAST filestats
->st_size
) < 0)
4157 if (httpPrintf(con
->http
, "\r\n") < 0)
4160 if (cupsdFlushHeader(con
) < 0)
4163 con
->http
->data_encoding
= HTTP_ENCODING_LENGTH
;
4164 con
->http
->data_remaining
= filestats
->st_size
;
4166 if (con
->http
->data_remaining
<= INT_MAX
)
4167 con
->http
->_data_remaining
= con
->http
->data_remaining
;
4169 con
->http
->_data_remaining
= INT_MAX
;
4171 cupsdAddSelect(httpGetFd(con
->http
), (cupsd_selfunc_t
)cupsdReadClient
,
4172 (cupsd_selfunc_t
)cupsdWriteClient
, con
);
4174 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Sending file.");
4181 * 'write_pipe()' - Flag that data is available on the CGI pipe.
4185 write_pipe(cupsd_client_t
*con
) /* I - Client connection */
4187 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "write_pipe CGI output on fd %d",
4190 con
->file_ready
= 1;
4192 cupsdRemoveSelect(con
->file
);
4193 cupsdAddSelect(httpGetFd(con
->http
), NULL
, (cupsd_selfunc_t
)cupsdWriteClient
, con
);
4195 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "CGI data ready to be sent.");