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 * cupsdAcceptClient() - Accept a new client.
21 * cupsdCloseAllClients() - Close all remote clients immediately.
22 * cupsdCloseClient() - Close a remote client.
23 * cupsdFlushHeader() - Flush the header fields to the client.
24 * cupsdReadClient() - Read data from a client.
25 * cupsdSendCommand() - Send output from a command via HTTP.
26 * cupsdSendError() - Send an error message via HTTP.
27 * cupsdSendHeader() - Send an HTTP request.
28 * cupsdUpdateCGI() - Read status messages from CGI scripts and
30 * cupsdWriteClient() - Write data to a client as needed.
31 * check_if_modified() - Decode an "If-Modified-Since" line.
32 * compare_clients() - Compare two client connections.
33 * data_ready() - Check whether data is available from a client.
34 * get_file() - Get a filename and state info.
35 * install_cupsd_conf() - Install a configuration file.
36 * is_cgi() - Is the resource a CGI script/program?
37 * is_path_absolute() - Is a path absolute and free of relative elements
39 * pipe_command() - Pipe the output of a command to the remote
41 * valid_host() - Is the Host: field valid?
42 * write_file() - Send a file via HTTP.
43 * write_pipe() - Flag that data is available on the CGI pipe.
47 * Include necessary headers...
54 #endif /* __APPLE__ */
57 #endif /* HAVE_TCPD_H */
64 static const char * const http_states
[] =
65 { /* HTTP state strings */
70 "HTTP_STATE_GET_SEND",
73 "HTTP_STATE_POST_RECV",
74 "HTTP_STATE_POST_SEND",
76 "HTTP_STATE_PUT_RECV",
81 "HTTP_STATE_UNKNOWN_METHOD",
82 "HTTP_STATE_UNKNOWN_VERSION"
84 static const char * const ipp_states
[] =
85 { /* IPP state strings */
97 static int check_if_modified(cupsd_client_t
*con
,
98 struct stat
*filestats
);
99 static int compare_clients(cupsd_client_t
*a
, cupsd_client_t
*b
,
101 static int data_ready(cupsd_client_t
*con
);
102 static char *get_file(cupsd_client_t
*con
, struct stat
*filestats
,
103 char *filename
, int len
);
104 static http_status_t
install_cupsd_conf(cupsd_client_t
*con
);
105 static int is_cgi(cupsd_client_t
*con
, const char *filename
,
106 struct stat
*filestats
, mime_type_t
*type
);
107 static int is_path_absolute(const char *path
);
108 static int pipe_command(cupsd_client_t
*con
, int infile
, int *outfile
,
109 char *command
, char *options
, int root
);
110 static int valid_host(cupsd_client_t
*con
);
111 static int write_file(cupsd_client_t
*con
, http_status_t code
,
112 char *filename
, char *type
,
113 struct stat
*filestats
);
114 static void write_pipe(cupsd_client_t
*con
);
118 * 'cupsdAcceptClient()' - Accept a new client.
122 cupsdAcceptClient(cupsd_listener_t
*lis
)/* I - Listener socket */
124 int count
; /* Count of connections on a host */
125 int val
; /* Parameter value */
126 cupsd_client_t
*con
, /* New client pointer */
127 *tempcon
; /* Temporary client pointer */
128 http_addrlist_t
*addrlist
, /* List of adddresses for host */
129 *addr
; /* Current address */
130 socklen_t addrlen
; /* Length of address */
131 char *hostname
; /* Hostname for address */
132 http_addr_t temp
; /* Temporary address variable */
133 static time_t last_dos
= 0; /* Time of last DoS attack */
135 struct request_info wrap_req
; /* TCP wrappers request information */
136 #endif /* HAVE_TCPD_H */
139 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
140 "cupsdAcceptClient(lis=%p(%d)) Clients=%d",
141 lis
, lis
->fd
, cupsArrayCount(Clients
));
144 * Make sure we don't have a full set of clients already...
147 if (cupsArrayCount(Clients
) == MaxClients
)
151 * Get a pointer to the next available client...
155 Clients
= cupsArrayNew(NULL
, NULL
);
159 cupsdLogMessage(CUPSD_LOG_ERROR
,
160 "Unable to allocate memory for clients array!");
161 cupsdPauseListening();
166 ActiveClients
= cupsArrayNew((cups_array_func_t
)compare_clients
, NULL
);
170 cupsdLogMessage(CUPSD_LOG_ERROR
,
171 "Unable to allocate memory for active clients array!");
172 cupsdPauseListening();
176 if ((con
= calloc(1, sizeof(cupsd_client_t
))) == NULL
)
178 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to allocate memory for client!");
179 cupsdPauseListening();
184 con
->http
.activity
= time(NULL
);
185 con
->http
.hostaddr
= &(con
->clientaddr
);
186 con
->http
.wait_value
= 10000;
187 con
->http
.mode
= _HTTP_MODE_SERVER
;
190 * Accept the client and get the remote address...
193 addrlen
= sizeof(http_addr_t
);
195 if ((con
->http
.fd
= accept(lis
->fd
, (struct sockaddr
*)con
->http
.hostaddr
,
198 if (errno
== ENFILE
|| errno
== EMFILE
)
199 cupsdPauseListening();
201 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to accept client connection - %s.",
209 * Save the connected port number...
212 _httpAddrSetPort(con
->http
.hostaddr
, httpAddrPort(&(lis
->address
)));
216 * Convert IPv4 over IPv6 addresses (::ffff:n.n.n.n) to IPv4 forms we
217 * can more easily use...
220 if (lis
->address
.addr
.sa_family
== AF_INET6
&&
221 con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[0] == 0 &&
222 con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[1] == 0 &&
223 ntohl(con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[2]) == 0xffff)
224 con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[2] = 0;
225 #endif /* AF_INET6 */
228 * Check the number of clients on the same address...
231 for (count
= 0, tempcon
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
233 tempcon
= (cupsd_client_t
*)cupsArrayNext(Clients
))
234 if (httpAddrEqual(tempcon
->http
.hostaddr
, con
->http
.hostaddr
))
237 if (count
>= MaxClientsPerHost
)
241 if (count
>= MaxClientsPerHost
)
243 if ((time(NULL
) - last_dos
) >= 60)
245 last_dos
= time(NULL
);
246 cupsdLogMessage(CUPSD_LOG_WARN
,
247 "Possible DoS attack - more than %d clients connecting "
250 httpAddrString(con
->http
.hostaddr
, con
->http
.hostname
,
251 sizeof(con
->http
.hostname
)));
255 closesocket(con
->http
.fd
);
265 * Get the hostname or format the IP address as needed...
268 if (httpAddrLocalhost(con
->http
.hostaddr
))
271 * Map accesses from the loopback interface to "localhost"...
274 strlcpy(con
->http
.hostname
, "localhost", sizeof(con
->http
.hostname
));
275 hostname
= con
->http
.hostname
;
280 * Map accesses from the same host to the server name.
284 hostname
= httpAddrLookup(con
->http
.hostaddr
, con
->http
.hostname
,
285 sizeof(con
->http
.hostname
));
289 httpAddrString(con
->http
.hostaddr
, con
->http
.hostname
,
290 sizeof(con
->http
.hostname
));
294 if (hostname
== NULL
&& HostNameLookups
== 2)
297 * Can't have an unresolved IP address with double-lookups enabled...
301 closesocket(con
->http
.fd
);
306 cupsdLogMessage(CUPSD_LOG_WARN
,
307 "Name lookup failed - connection from %s closed!",
314 if (HostNameLookups
== 2)
317 * Do double lookups as needed...
320 if ((addrlist
= httpAddrGetList(con
->http
.hostname
, AF_UNSPEC
, NULL
))
324 * See if the hostname maps to the same IP address...
327 for (addr
= addrlist
; addr
; addr
= addr
->next
)
328 if (httpAddrEqual(con
->http
.hostaddr
, &(addr
->addr
)))
334 httpAddrFreeList(addrlist
);
339 * Can't have a hostname that doesn't resolve to the same IP address
340 * with double-lookups enabled...
344 closesocket(con
->http
.fd
);
349 cupsdLogMessage(CUPSD_LOG_WARN
,
350 "IP lookup failed - connection from %s closed!",
359 * See if the connection is denied by TCP wrappers...
362 request_init(&wrap_req
, RQ_DAEMON
, "cupsd", RQ_FILE
, con
->http
.fd
, NULL
);
365 if (!hosts_access(&wrap_req
))
368 closesocket(con
->http
.fd
);
373 cupsdLogMessage(CUPSD_LOG_WARN
,
374 "Connection from %s refused by /etc/hosts.allow and "
375 "/etc/hosts.deny rules.", con
->http
.hostname
);
379 #endif /* HAVE_TCPD_H */
382 if (con
->http
.hostaddr
->addr
.sa_family
== AF_LOCAL
)
385 socklen_t peersize
; /* Size of peer credentials */
386 pid_t peerpid
; /* Peer process ID */
387 char name
[256]; /* Name of process */
389 peersize
= sizeof(peerpid
);
390 if (!getsockopt(con
->http
.fd
, SOL_LOCAL
, LOCAL_PEERPID
, &peerpid
,
393 if (!proc_name(peerpid
, name
, sizeof(name
)))
394 cupsdLogMessage(CUPSD_LOG_DEBUG
,
395 "[Client %d] Accepted from %s (Domain ???[%d])",
396 con
->http
.fd
, con
->http
.hostname
, (int)peerpid
);
398 cupsdLogMessage(CUPSD_LOG_DEBUG
,
399 "[Client %d] Accepted from %s (Domain %s[%d])",
400 con
->http
.fd
, con
->http
.hostname
, name
, (int)peerpid
);
403 # endif /* __APPLE__ */
405 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[Client %d] Accepted from %s (Domain)",
406 con
->http
.fd
, con
->http
.hostname
);
409 #endif /* AF_LOCAL */
410 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[Client %d] Accepted from %s:%d (IPv%d)",
411 con
->http
.fd
, con
->http
.hostname
,
412 httpAddrPort(con
->http
.hostaddr
),
413 _httpAddrFamily(con
->http
.hostaddr
) == AF_INET
? 4 : 6);
416 * Get the local address the client connected to...
419 addrlen
= sizeof(temp
);
420 if (getsockname(con
->http
.fd
, (struct sockaddr
*)&temp
, &addrlen
))
422 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to get local address - %s",
425 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
426 con
->serverport
= LocalPort
;
429 else if (_httpAddrFamily(&temp
) == AF_LOCAL
)
431 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
432 con
->serverport
= LocalPort
;
434 #endif /* AF_LOCAL */
437 if (httpAddrLocalhost(&temp
))
438 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
439 else if (HostNameLookups
)
440 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
442 httpAddrString(&temp
, con
->servername
, sizeof(con
->servername
));
444 con
->serverport
= httpAddrPort(&(lis
->address
));
448 * Add the connection to the array of active clients...
451 cupsArrayAdd(Clients
, con
);
454 * Using TCP_NODELAY improves responsiveness, especially on systems with a slow
455 * loopback interface. Since we write large buffers when sending print files
456 * and requests there shouldn't be any performance penalty for this...
460 setsockopt(con
->http
.fd
, IPPROTO_TCP
, TCP_NODELAY
, &val
, sizeof(val
));
463 * Close this file on all execs...
466 fcntl(con
->http
.fd
, F_SETFD
, fcntl(con
->http
.fd
, F_GETFD
) | FD_CLOEXEC
);
469 * Add the socket to the server select.
472 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
474 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[Client %d] Waiting for request.",
478 * Temporarily suspend accept()'s until we lose a client...
481 if (cupsArrayCount(Clients
) == MaxClients
)
482 cupsdPauseListening();
486 * See if we are connecting on a secure port...
489 if (lis
->encryption
== HTTP_ENCRYPT_ALWAYS
)
492 * https connection; go secure...
495 con
->http
.encryption
= HTTP_ENCRYPT_ALWAYS
;
497 if (!cupsdStartTLS(con
))
498 cupsdCloseClient(con
);
502 #endif /* HAVE_SSL */
507 * 'cupsdCloseAllClients()' - Close all remote clients immediately.
511 cupsdCloseAllClients(void)
513 cupsd_client_t
*con
; /* Current client */
516 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdCloseAllClients() Clients=%d",
517 cupsArrayCount(Clients
));
519 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
521 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
522 if (cupsdCloseClient(con
))
523 cupsdCloseClient(con
);
528 * 'cupsdCloseClient()' - Close a remote client.
531 int /* O - 1 if partial close, 0 if fully closed */
532 cupsdCloseClient(cupsd_client_t
*con
) /* I - Client to close */
534 int partial
; /* Do partial close for SSL? */
536 #elif defined(HAVE_GNUTLS)
537 # elif defined(HAVE_CDSASSL)
538 #endif /* HAVE_LIBSSL */
541 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[Client %d] Closing connection.",
545 * Flush pending writes before closing...
548 httpFlushWrite(HTTP(con
));
554 * Shutdown encryption as needed...
563 #endif /* HAVE_SSL */
565 if (con
->pipe_pid
!= 0)
568 * Stop any CGI process...
571 cupsdEndProcess(con
->pipe_pid
, 1);
577 cupsdRemoveSelect(con
->file
);
584 * Close the socket and clear the file from the input set for select()...
587 if (con
->http
.fd
>= 0)
589 cupsArrayRemove(ActiveClients
, con
);
595 * Only do a partial close so that the encrypted client gets everything.
598 shutdown(con
->http
.fd
, 0);
599 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
601 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[Client %d] Waiting for socket close.",
607 * Shut the socket down fully...
610 cupsdRemoveSelect(con
->http
.fd
);
622 if (con
->http
.input_set
)
623 free(con
->http
.input_set
);
625 httpClearCookie(HTTP(con
));
626 httpClearFields(HTTP(con
));
628 cupsdClearString(&con
->filename
);
629 cupsdClearString(&con
->command
);
630 cupsdClearString(&con
->options
);
631 cupsdClearString(&con
->query_string
);
635 ippDelete(con
->request
);
641 ippDelete(con
->response
);
642 con
->response
= NULL
;
647 cupsLangFree(con
->language
);
648 con
->language
= NULL
;
651 #ifdef HAVE_AUTHORIZATION_H
654 AuthorizationFree(con
->authref
, kAuthorizationFlagDefaults
);
657 #endif /* HAVE_AUTHORIZATION_H */
660 * Re-enable new client connections if we are going back under the
664 if (cupsArrayCount(Clients
) == MaxClients
)
665 cupsdResumeListening();
668 * Compact the list of clients as necessary...
671 cupsArrayRemove(Clients
, con
);
681 * 'cupsdFlushHeader()' - Flush the header fields to the client.
684 int /* I - Bytes written or -1 on error */
685 cupsdFlushHeader(cupsd_client_t
*con
) /* I - Client to flush to */
687 int bytes
= httpFlushWrite(HTTP(con
));
689 con
->http
.data_encoding
= HTTP_ENCODING_LENGTH
;
696 * 'cupsdReadClient()' - Read data from a client.
700 cupsdReadClient(cupsd_client_t
*con
) /* I - Client to read from */
702 char line
[32768], /* Line from client... */
703 operation
[64], /* Operation code from socket */
704 version
[64], /* HTTP version number string */
705 locale
[64], /* Locale */
706 *ptr
; /* Pointer into strings */
707 int major
, minor
; /* HTTP version numbers */
708 http_status_t status
; /* Transfer status */
709 ipp_state_t ipp_state
; /* State of IPP transfer */
710 int bytes
; /* Number of bytes to POST */
711 char *filename
; /* Name of file for GET/HEAD */
712 char buf
[1024]; /* Buffer for real filename */
713 struct stat filestats
; /* File information */
714 mime_type_t
*type
; /* MIME type of file */
715 cupsd_printer_t
*p
; /* Printer */
716 static unsigned request_id
= 0; /* Request ID for temp files */
719 status
= HTTP_CONTINUE
;
721 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
722 "[Client %d] cupsdReadClient "
726 "data_encoding=HTTP_ENCODING_%s, "
727 "data_remaining=" CUPS_LLFMT
", "
730 con
->http
.fd
, con
->http
.error
, con
->http
.used
,
731 http_states
[con
->http
.state
+ 1],
732 con
->http
.data_encoding
== HTTP_ENCODING_CHUNKED
?
733 "CHUNKED" : "LENGTH",
734 CUPS_LLCAST con
->http
.data_remaining
,
736 con
->request
? ipp_states
[con
->request
->state
] : "",
743 * Automatically check for a SSL/TLS handshake...
748 if (recv(con
->http
.fd
, buf
, 1, MSG_PEEK
) == 1 &&
749 (!buf
[0] || !strchr("DGHOPT", buf
[0])))
752 * Encrypt this connection...
755 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
756 "[Client %d] Saw first byte %02X, auto-negotiating "
757 "SSL/TLS session.", con
->http
.fd
, buf
[0] & 255);
759 if (!cupsdStartTLS(con
))
760 cupsdCloseClient(con
);
765 #endif /* HAVE_SSL */
767 switch (con
->http
.state
)
769 case HTTP_STATE_WAITING
:
771 * See if we've received a request line...
774 if (httpGets(line
, sizeof(line
) - 1, HTTP(con
)) == NULL
)
776 if (con
->http
.error
&& con
->http
.error
!= EPIPE
)
777 cupsdLogMessage(CUPSD_LOG_DEBUG
,
778 "[Client %d] HTTP_STATE_WAITING Closing for error %d "
779 "(%s)", con
->http
.fd
, con
->http
.error
,
780 strerror(con
->http
.error
));
782 cupsdLogMessage(CUPSD_LOG_DEBUG
,
783 "[Client %d] HTTP_STATE_WAITING Closing on EOF",
786 cupsdCloseClient(con
);
791 * Ignore blank request lines...
798 * Clear other state variables...
801 httpClearFields(HTTP(con
));
803 con
->http
.activity
= time(NULL
);
804 con
->http
.version
= HTTP_1_0
;
805 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
806 con
->http
.data_encoding
= HTTP_ENCODING_LENGTH
;
807 con
->http
.data_remaining
= 0;
808 con
->http
._data_remaining
= 0;
809 con
->operation
= HTTP_STATE_WAITING
;
814 con
->username
[0] = '\0';
815 con
->password
[0] = '\0';
818 cupsdClearString(&con
->command
);
819 cupsdClearString(&con
->options
);
820 cupsdClearString(&con
->query_string
);
824 ippDelete(con
->request
);
830 ippDelete(con
->response
);
831 con
->response
= NULL
;
836 cupsLangFree(con
->language
);
837 con
->language
= NULL
;
843 #endif /* HAVE_GSSAPI */
846 * Grab the request line...
849 switch (sscanf(line
, "%63s%1023s%63s", operation
, con
->uri
, version
))
854 cupsdLogMessage(CUPSD_LOG_ERROR
,
855 "[Client %d] Bad request line \"%s\" from %s.",
857 _httpEncodeURI(buf
, line
, sizeof(buf
)),
859 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
860 cupsdCloseClient(con
);
864 con
->http
.version
= HTTP_0_9
;
867 if (sscanf(version
, "HTTP/%d.%d", &major
, &minor
) != 2)
869 cupsdLogMessage(CUPSD_LOG_ERROR
,
870 "[Client %d] Bad request line \"%s\" from %s.",
872 _httpEncodeURI(buf
, line
, sizeof(buf
)),
874 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
875 cupsdCloseClient(con
);
881 con
->http
.version
= (http_version_t
)(major
* 100 + minor
);
882 if (con
->http
.version
== HTTP_1_1
&& KeepAlive
)
883 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
885 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
889 cupsdLogMessage(CUPSD_LOG_ERROR
,
890 "[Client %d] Unsupported request line \"%s\" "
891 "from %s.", con
->http
.fd
,
892 _httpEncodeURI(buf
, line
, sizeof(buf
)),
894 cupsdSendError(con
, HTTP_NOT_SUPPORTED
, CUPSD_AUTH_NONE
);
895 cupsdCloseClient(con
);
902 * Handle full URLs in the request line...
905 if (strcmp(con
->uri
, "*"))
907 char scheme
[HTTP_MAX_URI
], /* Method/scheme */
908 userpass
[HTTP_MAX_URI
], /* Username:password */
909 hostname
[HTTP_MAX_URI
], /* Hostname */
910 resource
[HTTP_MAX_URI
]; /* Resource path */
911 int port
; /* Port number */
915 * Separate the URI into its components...
918 httpSeparateURI(HTTP_URI_CODING_MOST
, con
->uri
,
919 scheme
, sizeof(scheme
),
920 userpass
, sizeof(userpass
),
921 hostname
, sizeof(hostname
), &port
,
922 resource
, sizeof(resource
));
925 * Only allow URIs with the servername, localhost, or an IP
929 if (strcmp(scheme
, "file") &&
930 _cups_strcasecmp(hostname
, ServerName
) &&
931 _cups_strcasecmp(hostname
, "localhost") &&
932 !isdigit(hostname
[0]) && hostname
[0] != '[')
935 * Nope, we don't do proxies...
938 cupsdLogMessage(CUPSD_LOG_ERROR
,
939 "[Client %d] Bad URI \"%s\" in request.",
940 con
->http
.fd
, con
->uri
);
941 cupsdSendError(con
, HTTP_METHOD_NOT_ALLOWED
, CUPSD_AUTH_NONE
);
942 cupsdCloseClient(con
);
947 * Copy the resource portion back into the URI; both resource and
948 * con->uri are HTTP_MAX_URI bytes in size...
951 strlcpy(con
->uri
, resource
, sizeof(con
->uri
));
955 * Process the request...
958 if (!strcmp(operation
, "GET"))
959 con
->http
.state
= HTTP_STATE_GET
;
960 else if (!strcmp(operation
, "PUT"))
961 con
->http
.state
= HTTP_STATE_PUT
;
962 else if (!strcmp(operation
, "POST"))
963 con
->http
.state
= HTTP_STATE_POST
;
964 else if (!strcmp(operation
, "DELETE"))
965 con
->http
.state
= HTTP_STATE_DELETE
;
966 else if (!strcmp(operation
, "TRACE"))
967 con
->http
.state
= HTTP_STATE_TRACE
;
968 else if (!strcmp(operation
, "OPTIONS"))
969 con
->http
.state
= HTTP_STATE_OPTIONS
;
970 else if (!strcmp(operation
, "HEAD"))
971 con
->http
.state
= HTTP_STATE_HEAD
;
974 cupsdLogMessage(CUPSD_LOG_ERROR
,
975 "[Client %d] Bad operation \"%s\".", con
->http
.fd
,
977 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
978 cupsdCloseClient(con
);
982 gettimeofday(&(con
->start
), NULL
);
983 con
->operation
= con
->http
.state
;
985 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[Client %d] %s %s HTTP/%d.%d",
986 con
->http
.fd
, operation
, con
->uri
,
987 con
->http
.version
/ 100, con
->http
.version
% 100);
989 con
->http
.status
= HTTP_OK
;
991 if (!cupsArrayFind(ActiveClients
, con
))
993 cupsArrayAdd(ActiveClients
, con
);
997 case HTTP_STATE_OPTIONS
:
998 case HTTP_STATE_DELETE
:
999 case HTTP_STATE_GET
:
1000 case HTTP_STATE_HEAD
:
1001 case HTTP_STATE_POST
:
1002 case HTTP_STATE_PUT
:
1003 case HTTP_STATE_TRACE
:
1005 * Parse incoming parameters until the status changes...
1008 while ((status
= httpUpdate(HTTP(con
))) == HTTP_CONTINUE
)
1009 if (!data_ready(con
))
1012 if (status
!= HTTP_OK
&& status
!= HTTP_CONTINUE
)
1014 if (con
->http
.error
&& con
->http
.error
!= EPIPE
)
1015 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1016 "[Client %d] Closing for error %d (%s) while "
1018 con
->http
.fd
, con
->http
.error
,
1019 strerror(con
->http
.error
));
1021 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1022 "[Client %d] Closing on EOF while reading headers.",
1025 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
1026 cupsdCloseClient(con
);
1032 if (!data_ready(con
) && recv(con
->http
.fd
, buf
, 1, MSG_PEEK
) < 1)
1035 * Connection closed...
1038 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1039 "[Client %d] Closing on EOF", con
->http
.fd
);
1040 cupsdCloseClient(con
);
1043 break; /* Anti-compiler-warning-code */
1047 * Handle new transfers...
1050 if (status
== HTTP_OK
)
1052 if (con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
][0])
1055 * Figure out the locale from the Accept-Language and Content-Type
1059 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
],
1063 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
],
1067 if ((ptr
= strstr(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
],
1068 "charset=")) != NULL
)
1071 * Combine language and charset, and trim any extra params in the
1075 snprintf(locale
, sizeof(locale
), "%s.%s",
1076 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ptr
+ 8);
1078 if ((ptr
= strchr(locale
, ',')) != NULL
)
1082 snprintf(locale
, sizeof(locale
), "%s.UTF-8",
1083 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
]);
1085 con
->language
= cupsLangGet(locale
);
1088 con
->language
= cupsLangGet(DefaultLocale
);
1090 cupsdAuthorize(con
);
1092 if (!_cups_strncasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
],
1093 "Keep-Alive", 10) && KeepAlive
)
1094 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
1095 else if (!_cups_strncasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
],
1097 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1099 if (!con
->http
.fields
[HTTP_FIELD_HOST
][0] &&
1100 con
->http
.version
>= HTTP_1_1
)
1103 * HTTP/1.1 and higher require the "Host:" field...
1106 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1108 cupsdLogMessage(CUPSD_LOG_ERROR
,
1109 "[Client %d] Missing Host: field in request.",
1111 cupsdCloseClient(con
);
1115 else if (!valid_host(con
))
1118 * Access to localhost must use "localhost" or the corresponding IPv4
1119 * or IPv6 values in the Host: field.
1122 cupsdLogMessage(CUPSD_LOG_ERROR
,
1123 "[Client %d] Request from \"%s\" using invalid Host: "
1124 "field \"%s\"", con
->http
.fd
, con
->http
.hostname
,
1125 con
->http
.fields
[HTTP_FIELD_HOST
]);
1127 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1129 cupsdCloseClient(con
);
1133 else if (con
->operation
== HTTP_STATE_OPTIONS
)
1136 * Do OPTIONS command...
1139 if (con
->best
&& con
->best
->type
!= CUPSD_AUTH_NONE
)
1141 if (!cupsdSendHeader(con
, HTTP_UNAUTHORIZED
, NULL
, CUPSD_AUTH_NONE
))
1143 cupsdCloseClient(con
);
1148 if (!_cups_strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") &&
1149 con
->http
.tls
== NULL
)
1153 * Do encryption stuff...
1156 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
, CUPSD_AUTH_NONE
))
1158 cupsdCloseClient(con
);
1162 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1163 httpPrintf(HTTP(con
), "Upgrade: TLS/1.2,TLS/1.1,TLS/1.0\r\n");
1164 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1165 httpPrintf(HTTP(con
), "\r\n");
1167 if (cupsdFlushHeader(con
) < 0)
1169 cupsdCloseClient(con
);
1173 if (!cupsdStartTLS(con
))
1175 cupsdCloseClient(con
);
1179 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
1181 cupsdCloseClient(con
);
1184 #endif /* HAVE_SSL */
1187 if (!cupsdSendHeader(con
, HTTP_OK
, NULL
, CUPSD_AUTH_NONE
))
1189 cupsdCloseClient(con
);
1193 httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n");
1194 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1195 httpPrintf(HTTP(con
), "\r\n");
1197 if (cupsdFlushHeader(con
) < 0)
1199 cupsdCloseClient(con
);
1203 else if (!is_path_absolute(con
->uri
))
1206 * Protect against malicious users!
1209 cupsdLogMessage(CUPSD_LOG_ERROR
,
1210 "[Client %d] Request for non-absolute resource \"%s\".",
1211 con
->http
.fd
, con
->uri
);
1213 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1215 cupsdCloseClient(con
);
1221 if (!_cups_strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
],
1222 "Upgrade") && con
->http
.tls
== NULL
)
1226 * Do encryption stuff...
1229 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
,
1232 cupsdCloseClient(con
);
1236 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1237 httpPrintf(HTTP(con
), "Upgrade: TLS/1.2,TLS/1.1,TLS/1.0\r\n");
1238 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1239 httpPrintf(HTTP(con
), "\r\n");
1241 if (cupsdFlushHeader(con
) < 0)
1243 cupsdCloseClient(con
);
1247 if (!cupsdStartTLS(con
))
1249 cupsdCloseClient(con
);
1253 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
1255 cupsdCloseClient(con
);
1258 #endif /* HAVE_SSL */
1261 if ((status
= cupsdIsAuthorized(con
, NULL
)) != HTTP_OK
)
1263 cupsdSendError(con
, status
, CUPSD_AUTH_NONE
);
1264 cupsdCloseClient(con
);
1268 if (con
->http
.expect
&&
1269 (con
->operation
== HTTP_STATE_POST
|| con
->operation
== HTTP_STATE_PUT
))
1271 if (con
->http
.expect
== HTTP_CONTINUE
)
1274 * Send 100-continue header...
1277 if (!cupsdSendHeader(con
, HTTP_CONTINUE
, NULL
, CUPSD_AUTH_NONE
))
1279 cupsdCloseClient(con
);
1286 * Send 417-expectation-failed header...
1289 if (!cupsdSendHeader(con
, HTTP_EXPECTATION_FAILED
, NULL
,
1292 cupsdCloseClient(con
);
1296 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1297 httpPrintf(HTTP(con
), "\r\n");
1299 if (cupsdFlushHeader(con
) < 0)
1301 cupsdCloseClient(con
);
1307 switch (con
->http
.state
)
1309 case HTTP_STATE_GET_SEND
:
1310 if ((!strncmp(con
->uri
, "/ppd/", 5) ||
1311 !strncmp(con
->uri
, "/printers/", 10) ||
1312 !strncmp(con
->uri
, "/classes/", 9)) &&
1313 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1316 * Send PPD file - get the real printer name since printer
1317 * names are not case sensitive but filenames can be...
1320 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1322 if (!strncmp(con
->uri
, "/ppd/", 5))
1323 p
= cupsdFindPrinter(con
->uri
+ 5);
1324 else if (!strncmp(con
->uri
, "/printers/", 10))
1325 p
= cupsdFindPrinter(con
->uri
+ 10);
1328 p
= cupsdFindClass(con
->uri
+ 9);
1332 int i
; /* Looping var */
1334 for (i
= 0; i
< p
->num_printers
; i
++)
1336 if (!(p
->printers
[i
]->type
& CUPS_PRINTER_CLASS
))
1338 char ppdname
[1024];/* PPD filename */
1340 snprintf(ppdname
, sizeof(ppdname
), "%s/ppd/%s.ppd",
1341 ServerRoot
, p
->printers
[i
]->name
);
1342 if (!access(ppdname
, 0))
1350 if (i
>= p
->num_printers
)
1357 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1361 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1363 cupsdCloseClient(con
);
1370 else if ((!strncmp(con
->uri
, "/icons/", 7) ||
1371 !strncmp(con
->uri
, "/printers/", 10) ||
1372 !strncmp(con
->uri
, "/classes/", 9)) &&
1373 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".png"))
1376 * Send icon file - get the real queue name since queue names are
1377 * not case sensitive but filenames can be...
1380 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".png" */
1382 if (!strncmp(con
->uri
, "/icons/", 7))
1383 p
= cupsdFindPrinter(con
->uri
+ 7);
1384 else if (!strncmp(con
->uri
, "/printers/", 10))
1385 p
= cupsdFindPrinter(con
->uri
+ 10);
1388 p
= cupsdFindClass(con
->uri
+ 9);
1392 int i
; /* Looping var */
1394 for (i
= 0; i
< p
->num_printers
; i
++)
1396 if (!(p
->printers
[i
]->type
& CUPS_PRINTER_CLASS
))
1398 char ppdname
[1024];/* PPD filename */
1400 snprintf(ppdname
, sizeof(ppdname
), "%s/ppd/%s.ppd",
1401 ServerRoot
, p
->printers
[i
]->name
);
1402 if (!access(ppdname
, 0))
1410 if (i
>= p
->num_printers
)
1416 snprintf(con
->uri
, sizeof(con
->uri
), "/icons/%s.png", p
->name
);
1419 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1421 cupsdCloseClient(con
);
1428 else if (!WebInterface
)
1431 * Web interface is disabled. Show an appropriate message...
1434 if (!cupsdSendError(con
, HTTP_WEBIF_DISABLED
, CUPSD_AUTH_NONE
))
1436 cupsdCloseClient(con
);
1443 if ((!strncmp(con
->uri
, "/admin", 6) &&
1444 strncmp(con
->uri
, "/admin/conf/", 12) &&
1445 strncmp(con
->uri
, "/admin/log/", 11)) ||
1446 !strncmp(con
->uri
, "/printers", 9) ||
1447 !strncmp(con
->uri
, "/classes", 8) ||
1448 !strncmp(con
->uri
, "/help", 5) ||
1449 !strncmp(con
->uri
, "/jobs", 5))
1452 * Send CGI output...
1455 if (!strncmp(con
->uri
, "/admin", 6))
1457 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1460 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1462 else if (!strncmp(con
->uri
, "/printers", 9))
1464 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1467 if (con
->uri
[9] && con
->uri
[10])
1468 cupsdSetString(&con
->options
, con
->uri
+ 9);
1470 cupsdSetString(&con
->options
, NULL
);
1472 else if (!strncmp(con
->uri
, "/classes", 8))
1474 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1477 if (con
->uri
[8] && con
->uri
[9])
1478 cupsdSetString(&con
->options
, con
->uri
+ 8);
1480 cupsdSetString(&con
->options
, NULL
);
1482 else if (!strncmp(con
->uri
, "/jobs", 5))
1484 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1487 if (con
->uri
[5] && con
->uri
[6])
1488 cupsdSetString(&con
->options
, con
->uri
+ 5);
1490 cupsdSetString(&con
->options
, NULL
);
1494 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1497 if (con
->uri
[5] && con
->uri
[6])
1498 cupsdSetString(&con
->options
, con
->uri
+ 5);
1500 cupsdSetString(&con
->options
, NULL
);
1503 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1505 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1507 cupsdCloseClient(con
);
1512 cupsdLogRequest(con
, HTTP_OK
);
1514 if (con
->http
.version
<= HTTP_1_0
)
1515 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1517 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1518 (strchr(con
->uri
+ 12, '/') ||
1519 strlen(con
->uri
) == 12)) ||
1520 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1521 (strchr(con
->uri
+ 11, '/') ||
1522 strlen(con
->uri
) == 11)))
1525 * GET can only be done to configuration files directly under
1529 cupsdLogMessage(CUPSD_LOG_ERROR
,
1530 "Request for subdirectory \"%s\"!", con
->uri
);
1532 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1534 cupsdCloseClient(con
);
1546 if ((filename
= get_file(con
, &filestats
, buf
,
1547 sizeof(buf
))) == NULL
)
1549 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1551 cupsdCloseClient(con
);
1558 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1560 if (is_cgi(con
, filename
, &filestats
, type
))
1563 * Note: con->command and con->options were set by
1567 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1569 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1571 cupsdCloseClient(con
);
1576 cupsdLogRequest(con
, HTTP_OK
);
1578 if (con
->http
.version
<= HTTP_1_0
)
1579 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1583 if (!check_if_modified(con
, &filestats
))
1585 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1587 cupsdCloseClient(con
);
1594 strlcpy(line
, "text/plain", sizeof(line
));
1596 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1598 if (!write_file(con
, HTTP_OK
, filename
, line
, &filestats
))
1600 cupsdCloseClient(con
);
1607 case HTTP_STATE_POST_RECV
:
1609 * See if the POST request includes a Content-Length field, and if
1610 * so check the length against any limits that are set...
1613 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1614 MaxRequestSize
> 0 &&
1615 con
->http
.data_remaining
> MaxRequestSize
)
1618 * Request too large...
1621 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1623 cupsdCloseClient(con
);
1629 else if (con
->http
.data_remaining
< 0 ||
1630 (!con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1631 con
->http
.data_encoding
== HTTP_ENCODING_LENGTH
))
1634 * Negative content lengths are invalid!
1637 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1639 cupsdCloseClient(con
);
1647 * See what kind of POST request this is; for IPP requests the
1648 * content-type field will be "application/ipp"...
1651 if (!strcmp(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
],
1653 con
->request
= ippNew();
1654 else if (!WebInterface
)
1657 * Web interface is disabled. Show an appropriate message...
1660 if (!cupsdSendError(con
, HTTP_WEBIF_DISABLED
, CUPSD_AUTH_NONE
))
1662 cupsdCloseClient(con
);
1668 else if ((!strncmp(con
->uri
, "/admin", 6) &&
1669 strncmp(con
->uri
, "/admin/conf/", 12) &&
1670 strncmp(con
->uri
, "/admin/log/", 11)) ||
1671 !strncmp(con
->uri
, "/printers", 9) ||
1672 !strncmp(con
->uri
, "/classes", 8) ||
1673 !strncmp(con
->uri
, "/help", 5) ||
1674 !strncmp(con
->uri
, "/jobs", 5))
1680 if (!strncmp(con
->uri
, "/admin", 6))
1682 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1685 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1687 else if (!strncmp(con
->uri
, "/printers", 9))
1689 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1692 if (con
->uri
[9] && con
->uri
[10])
1693 cupsdSetString(&con
->options
, con
->uri
+ 9);
1695 cupsdSetString(&con
->options
, NULL
);
1697 else if (!strncmp(con
->uri
, "/classes", 8))
1699 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1702 if (con
->uri
[8] && con
->uri
[9])
1703 cupsdSetString(&con
->options
, con
->uri
+ 8);
1705 cupsdSetString(&con
->options
, NULL
);
1707 else if (!strncmp(con
->uri
, "/jobs", 5))
1709 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1712 if (con
->uri
[5] && con
->uri
[6])
1713 cupsdSetString(&con
->options
, con
->uri
+ 5);
1715 cupsdSetString(&con
->options
, NULL
);
1719 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1722 if (con
->uri
[5] && con
->uri
[6])
1723 cupsdSetString(&con
->options
, con
->uri
+ 5);
1725 cupsdSetString(&con
->options
, NULL
);
1728 if (con
->http
.version
<= HTTP_1_0
)
1729 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1737 if ((filename
= get_file(con
, &filestats
, buf
,
1738 sizeof(buf
))) == NULL
)
1740 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1742 cupsdCloseClient(con
);
1749 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1751 if (!is_cgi(con
, filename
, &filestats
, type
))
1754 * Only POST to CGI's...
1757 if (!cupsdSendError(con
, HTTP_UNAUTHORIZED
, CUPSD_AUTH_NONE
))
1759 cupsdCloseClient(con
);
1766 case HTTP_STATE_PUT_RECV
:
1768 * Validate the resource name...
1771 if (strcmp(con
->uri
, "/admin/conf/cupsd.conf"))
1774 * PUT can only be done to the cupsd.conf file...
1777 cupsdLogMessage(CUPSD_LOG_ERROR
,
1778 "[Client %d] Disallowed PUT request for \"%s\".",
1779 con
->http
.fd
, con
->uri
);
1781 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1783 cupsdCloseClient(con
);
1791 * See if the PUT request includes a Content-Length field, and if
1792 * so check the length against any limits that are set...
1795 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1796 MaxRequestSize
> 0 &&
1797 con
->http
.data_remaining
> MaxRequestSize
)
1800 * Request too large...
1803 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1805 cupsdCloseClient(con
);
1811 else if (con
->http
.data_remaining
< 0)
1814 * Negative content lengths are invalid!
1817 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1819 cupsdCloseClient(con
);
1827 * Open a temporary file to hold the request...
1830 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
1832 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1836 cupsdLogMessage(CUPSD_LOG_ERROR
,
1837 "[Client %d] Unable to create request file "
1838 "\"%s\": %s", con
->http
.fd
, con
->filename
,
1841 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1843 cupsdCloseClient(con
);
1848 fchmod(con
->file
, 0640);
1849 fchown(con
->file
, RunUser
, Group
);
1850 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1853 case HTTP_STATE_DELETE
:
1854 case HTTP_STATE_TRACE
:
1855 cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
);
1856 cupsdCloseClient(con
);
1859 case HTTP_STATE_HEAD
:
1860 if (!strncmp(con
->uri
, "/printers/", 10) &&
1861 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1864 * Send PPD file - get the real printer name since printer
1865 * names are not case sensitive but filenames can be...
1868 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1870 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1871 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1874 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1876 cupsdCloseClient(con
);
1883 else if (!strncmp(con
->uri
, "/printers/", 10) &&
1884 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".png"))
1887 * Send PNG file - get the real printer name since printer
1888 * names are not case sensitive but filenames can be...
1891 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1893 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1894 snprintf(con
->uri
, sizeof(con
->uri
), "/icons/%s.png", p
->name
);
1897 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1899 cupsdCloseClient(con
);
1906 else if (!WebInterface
)
1908 if (!cupsdSendHeader(con
, HTTP_OK
, NULL
, CUPSD_AUTH_NONE
))
1910 cupsdCloseClient(con
);
1914 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1916 cupsdCloseClient(con
);
1920 if (cupsdFlushHeader(con
) < 0)
1922 cupsdCloseClient(con
);
1926 con
->http
.state
= HTTP_STATE_WAITING
;
1927 DEBUG_puts("cupsdReadClient: Set state to HTTP_STATE_WAITING "
1932 if ((!strncmp(con
->uri
, "/admin", 6) &&
1933 strncmp(con
->uri
, "/admin/conf/", 12) &&
1934 strncmp(con
->uri
, "/admin/log/", 11)) ||
1935 !strncmp(con
->uri
, "/printers", 9) ||
1936 !strncmp(con
->uri
, "/classes", 8) ||
1937 !strncmp(con
->uri
, "/help", 5) ||
1938 !strncmp(con
->uri
, "/jobs", 5))
1944 if (!cupsdSendHeader(con
, HTTP_OK
, "text/html", CUPSD_AUTH_NONE
))
1946 cupsdCloseClient(con
);
1950 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1952 cupsdCloseClient(con
);
1956 if (cupsdFlushHeader(con
) < 0)
1958 cupsdCloseClient(con
);
1962 cupsdLogRequest(con
, HTTP_OK
);
1964 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1965 (strchr(con
->uri
+ 12, '/') ||
1966 strlen(con
->uri
) == 12)) ||
1967 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1968 (strchr(con
->uri
+ 11, '/') ||
1969 strlen(con
->uri
) == 11)))
1972 * HEAD can only be done to configuration files under
1976 cupsdLogMessage(CUPSD_LOG_ERROR
,
1977 "[Client %d] Request for subdirectory \"%s\".",
1978 con
->http
.fd
, con
->uri
);
1980 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1982 cupsdCloseClient(con
);
1988 else if ((filename
= get_file(con
, &filestats
, buf
,
1989 sizeof(buf
))) == NULL
)
1991 if (!cupsdSendHeader(con
, HTTP_NOT_FOUND
, "text/html",
1994 cupsdCloseClient(con
);
1998 cupsdLogRequest(con
, HTTP_NOT_FOUND
);
2000 else if (!check_if_modified(con
, &filestats
))
2002 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
2004 cupsdCloseClient(con
);
2008 cupsdLogRequest(con
, HTTP_NOT_MODIFIED
);
2016 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
2018 strlcpy(line
, "text/plain", sizeof(line
));
2020 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
2022 if (!cupsdSendHeader(con
, HTTP_OK
, line
, CUPSD_AUTH_NONE
))
2024 cupsdCloseClient(con
);
2028 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
2029 httpGetDateString(filestats
.st_mtime
)) < 0)
2031 cupsdCloseClient(con
);
2035 if (httpPrintf(HTTP(con
), "Content-Length: %lu\r\n",
2036 (unsigned long)filestats
.st_size
) < 0)
2038 cupsdCloseClient(con
);
2042 cupsdLogRequest(con
, HTTP_OK
);
2045 if (httpPrintf(HTTP(con
), "\r\n") < 0)
2047 cupsdCloseClient(con
);
2051 if (cupsdFlushHeader(con
) < 0)
2053 cupsdCloseClient(con
);
2057 con
->http
.state
= HTTP_STATE_WAITING
;
2058 DEBUG_puts("cupsdReadClient: Set state to HTTP_STATE_WAITING "
2063 break; /* Anti-compiler-warning-code */
2069 * Handle any incoming data...
2072 switch (con
->http
.state
)
2074 case HTTP_STATE_PUT_RECV
:
2077 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
2079 if (con
->http
.error
&& con
->http
.error
!= EPIPE
)
2080 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2081 "[Client %d] HTTP_STATE_PUT_RECV Closing for error "
2082 "%d (%s)", con
->http
.fd
, con
->http
.error
,
2083 strerror(con
->http
.error
));
2085 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2086 "[Client %d] HTTP_STATE_PUT_RECV Closing on EOF",
2089 cupsdCloseClient(con
);
2094 con
->bytes
+= bytes
;
2096 if (write(con
->file
, line
, bytes
) < bytes
)
2098 cupsdLogMessage(CUPSD_LOG_ERROR
,
2099 "[Client %d] Unable to write %d bytes to "
2100 "\"%s\": %s", con
->http
.fd
, bytes
, con
->filename
,
2105 unlink(con
->filename
);
2106 cupsdClearString(&con
->filename
);
2108 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2110 cupsdCloseClient(con
);
2116 while (con
->http
.state
== HTTP_STATE_PUT_RECV
&& data_ready(con
));
2118 if (con
->http
.state
== HTTP_STATE_STATUS
)
2121 * End of file, see how big it is...
2124 fstat(con
->file
, &filestats
);
2129 if (filestats
.st_size
> MaxRequestSize
&&
2133 * Request is too big; remove it and send an error...
2136 unlink(con
->filename
);
2137 cupsdClearString(&con
->filename
);
2139 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2141 cupsdCloseClient(con
);
2147 * Install the configuration file...
2150 status
= install_cupsd_conf(con
);
2153 * Return the status to the client...
2156 if (!cupsdSendError(con
, status
, CUPSD_AUTH_NONE
))
2158 cupsdCloseClient(con
);
2164 case HTTP_STATE_POST_RECV
:
2167 if (con
->request
&& con
->file
< 0)
2170 * Grab any request data from the connection...
2173 if ((ipp_state
= ippRead(&(con
->http
), con
->request
)) == IPP_ERROR
)
2175 cupsdLogMessage(CUPSD_LOG_ERROR
,
2176 "[Client %d] IPP read error: %s", con
->http
.fd
,
2177 cupsLastErrorString());
2179 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
2180 cupsdCloseClient(con
);
2183 else if (ipp_state
!= IPP_DATA
)
2185 if (con
->http
.state
== HTTP_STATE_POST_SEND
)
2187 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
2188 cupsdCloseClient(con
);
2192 if (data_ready(con
))
2198 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[Client %d] %d.%d %s %d",
2199 con
->http
.fd
, con
->request
->request
.op
.version
[0],
2200 con
->request
->request
.op
.version
[1],
2201 ippOpString(con
->request
->request
.op
.operation_id
),
2202 con
->request
->request
.op
.request_id
);
2203 con
->bytes
+= ippLength(con
->request
);
2207 if (con
->file
< 0 && con
->http
.state
!= HTTP_STATE_POST_SEND
)
2210 * Create a file as needed for the request data...
2213 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
2215 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
2219 cupsdLogMessage(CUPSD_LOG_ERROR
,
2220 "[Client %d] Unable to create request file "
2221 "\"%s\": %s", con
->http
.fd
, con
->filename
,
2224 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2226 cupsdCloseClient(con
);
2231 fchmod(con
->file
, 0640);
2232 fchown(con
->file
, RunUser
, Group
);
2233 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2236 if (con
->http
.state
!= HTTP_STATE_POST_SEND
)
2238 if (!httpWait(HTTP(con
), 0))
2240 else if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
2242 if (con
->http
.error
&& con
->http
.error
!= EPIPE
)
2243 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2244 "[Client %d] HTTP_STATE_POST_SEND Closing for "
2245 "error %d (%s)", con
->http
.fd
, con
->http
.error
,
2246 strerror(con
->http
.error
));
2248 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2249 "[Client %d] HTTP_STATE_POST_SEND Closing on EOF",
2252 cupsdCloseClient(con
);
2257 con
->bytes
+= bytes
;
2259 if (write(con
->file
, line
, bytes
) < bytes
)
2261 cupsdLogMessage(CUPSD_LOG_ERROR
,
2262 "[Client %d] Unable to write %d bytes to "
2263 "\"%s\": %s", con
->http
.fd
, bytes
,
2264 con
->filename
, strerror(errno
));
2268 unlink(con
->filename
);
2269 cupsdClearString(&con
->filename
);
2271 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
,
2274 cupsdCloseClient(con
);
2279 else if (con
->http
.state
== HTTP_STATE_POST_RECV
)
2281 else if (con
->http
.state
!= HTTP_STATE_POST_SEND
)
2283 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2284 "[Client %d] Closing on unexpected state %s.",
2285 con
->http
.fd
, http_states
[con
->http
.state
+ 1]);
2286 cupsdCloseClient(con
);
2291 while (con
->http
.state
== HTTP_STATE_POST_RECV
&& data_ready(con
));
2293 if (con
->http
.state
== HTTP_STATE_POST_SEND
)
2297 fstat(con
->file
, &filestats
);
2302 if (filestats
.st_size
> MaxRequestSize
&&
2306 * Request is too big; remove it and send an error...
2309 unlink(con
->filename
);
2310 cupsdClearString(&con
->filename
);
2315 * Delete any IPP request data...
2318 ippDelete(con
->request
);
2319 con
->request
= NULL
;
2322 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2324 cupsdCloseClient(con
);
2328 else if (filestats
.st_size
== 0)
2331 * Don't allow empty file...
2334 unlink(con
->filename
);
2335 cupsdClearString(&con
->filename
);
2340 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
2342 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
2344 cupsdCloseClient(con
);
2349 cupsdLogRequest(con
, HTTP_OK
);
2355 cupsdProcessIPPRequest(con
);
2359 unlink(con
->filename
);
2360 cupsdClearString(&con
->filename
);
2369 break; /* Anti-compiler-warning-code */
2372 if (con
->http
.state
== HTTP_STATE_WAITING
)
2374 if (!con
->http
.keep_alive
)
2376 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2377 "[Client %d] Closing because Keep-Alive disabled",
2379 cupsdCloseClient(con
);
2383 cupsArrayRemove(ActiveClients
, con
);
2384 cupsdSetBusyState();
2391 * 'cupsdSendCommand()' - Send output from a command via HTTP.
2394 int /* O - 1 on success, 0 on failure */
2396 cupsd_client_t
*con
, /* I - Client connection */
2397 char *command
, /* I - Command to run */
2398 char *options
, /* I - Command-line options */
2399 int root
) /* I - Run as root? */
2401 int fd
; /* Standard input file descriptor */
2406 fd
= open(con
->filename
, O_RDONLY
);
2410 cupsdLogMessage(CUPSD_LOG_ERROR
,
2411 "[Client %d] Unable to open \"%s\" for reading: %s",
2412 con
->http
.fd
, con
->filename
? con
->filename
: "/dev/null",
2417 fcntl(fd
, F_SETFD
, fcntl(fd
, F_GETFD
) | FD_CLOEXEC
);
2422 con
->pipe_pid
= pipe_command(con
, fd
, &(con
->file
), command
, options
, root
);
2427 cupsdLogMessage(CUPSD_LOG_INFO
, "[Client %d] Started \"%s\" (pid=%d)",
2428 con
->http
.fd
, command
, con
->pipe_pid
);
2430 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[Client %d] file=%d", con
->http
.fd
,
2433 if (con
->pipe_pid
== 0)
2436 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2438 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2440 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[Client %d] Waiting for CGI data.",
2443 con
->sent_header
= 0;
2444 con
->file_ready
= 0;
2445 con
->got_fields
= 0;
2446 con
->header_used
= 0;
2453 * 'cupsdSendError()' - Send an error message via HTTP.
2456 int /* O - 1 if successful, 0 otherwise */
2457 cupsdSendError(cupsd_client_t
*con
, /* I - Connection */
2458 http_status_t code
, /* I - Error code */
2459 int auth_type
)/* I - Authentication type */
2461 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2462 "[Client %d] cupsdSendError code=%d, auth_type=%d",
2463 con
->http
.fd
, code
, auth_type
);
2467 * Force client to upgrade for authentication if that is how the
2468 * server is configured...
2471 if (code
== HTTP_UNAUTHORIZED
&&
2472 DefaultEncryption
== HTTP_ENCRYPT_REQUIRED
&&
2473 _cups_strcasecmp(con
->http
.hostname
, "localhost") &&
2476 code
= HTTP_UPGRADE_REQUIRED
;
2478 #endif /* HAVE_SSL */
2481 * Put the request in the access_log file...
2484 cupsdLogRequest(con
, code
);
2487 * To work around bugs in some proxies, don't use Keep-Alive for some
2490 * Kerberos authentication doesn't work without Keep-Alive, so
2491 * never disable it in that case.
2494 if (code
>= HTTP_BAD_REQUEST
&& con
->http
.auth_type
!= CUPSD_AUTH_NEGOTIATE
)
2495 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
2498 * Send an error message back to the client. If the error code is a
2499 * 400 or 500 series, make sure the message contains some text, too!
2502 if (!cupsdSendHeader(con
, code
, NULL
, auth_type
))
2506 if (code
== HTTP_UPGRADE_REQUIRED
)
2507 if (httpPrintf(HTTP(con
), "Connection: Upgrade\r\n") < 0)
2510 if (httpPrintf(HTTP(con
), "Upgrade: TLS/1.2,TLS/1.1,TLS/1.0\r\n") < 0)
2512 #endif /* HAVE_SSL */
2514 if (con
->http
.version
>= HTTP_1_1
&&
2515 con
->http
.keep_alive
== HTTP_KEEPALIVE_OFF
)
2517 if (httpPrintf(HTTP(con
), "Connection: close\r\n") < 0)
2521 if (code
>= HTTP_BAD_REQUEST
)
2524 * Send a human-readable error message.
2527 char message
[4096], /* Message for user */
2528 urltext
[1024], /* URL redirection text */
2529 redirect
[1024]; /* Redirection link */
2530 const char *text
; /* Status-specific text */
2535 if (code
== HTTP_UNAUTHORIZED
)
2536 text
= _cupsLangString(con
->language
,
2537 _("Enter your username and password or the "
2538 "root username and password to access this "
2539 "page. If you are using Kerberos authentication, "
2540 "make sure you have a valid Kerberos ticket."));
2541 else if (code
== HTTP_UPGRADE_REQUIRED
)
2545 snprintf(urltext
, sizeof(urltext
),
2546 _cupsLangString(con
->language
,
2547 _("You must access this page using the URL "
2548 "<A HREF=\"https://%s:%d%s\">"
2549 "https://%s:%d%s</A>.")),
2550 con
->servername
, con
->serverport
, con
->uri
,
2551 con
->servername
, con
->serverport
, con
->uri
);
2553 snprintf(redirect
, sizeof(redirect
),
2554 "<META HTTP-EQUIV=\"Refresh\" "
2555 "CONTENT=\"3;URL=https://%s:%d%s\">\n",
2556 con
->servername
, con
->serverport
, con
->uri
);
2558 else if (code
== HTTP_WEBIF_DISABLED
)
2559 text
= _cupsLangString(con
->language
,
2560 _("The web interface is currently disabled. Run "
2561 "\"cupsctl WebInterface=yes\" to enable it."));
2565 snprintf(message
, sizeof(message
),
2566 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" "
2567 "\"http://www.w3.org/TR/html4/loose.dtd\">\n"
2570 "\t<META HTTP-EQUIV=\"Content-Type\" "
2571 "CONTENT=\"text/html; charset=utf-8\">\n"
2572 "\t<TITLE>%s - " CUPS_SVERSION
"</TITLE>\n"
2573 "\t<LINK REL=\"STYLESHEET\" TYPE=\"text/css\" "
2574 "HREF=\"/cups.css\">\n"
2582 _httpStatus(con
->language
, code
), redirect
,
2583 _httpStatus(con
->language
, code
), text
);
2585 if (httpPrintf(HTTP(con
), "Content-Type: text/html; charset=utf-8\r\n") < 0)
2587 if (httpPrintf(HTTP(con
), "Content-Length: %d\r\n",
2588 (int)strlen(message
)) < 0)
2590 if (httpPrintf(HTTP(con
), "\r\n") < 0)
2592 if (httpPrintf(HTTP(con
), "%s", message
) < 0)
2595 else if (httpPrintf(HTTP(con
), "\r\n") < 0)
2598 if (cupsdFlushHeader(con
) < 0)
2601 con
->http
.state
= HTTP_STATE_WAITING
;
2603 DEBUG_puts("cupsdSendError: Set state to HTTP_STATE_WAITING.");
2610 * 'cupsdSendHeader()' - Send an HTTP request.
2613 int /* O - 1 on success, 0 on failure */
2615 cupsd_client_t
*con
, /* I - Client to send to */
2616 http_status_t code
, /* I - HTTP status code */
2617 char *type
, /* I - MIME type of document */
2618 int auth_type
) /* I - Type of authentication */
2620 char auth_str
[1024]; /* Authorization string */
2624 * Send the HTTP status header...
2627 if (code
== HTTP_CONTINUE
)
2630 * 100-continue doesn't send any headers...
2633 return (httpPrintf(HTTP(con
), "HTTP/%d.%d 100 Continue\r\n\r\n",
2634 con
->http
.version
/ 100, con
->http
.version
% 100) > 0);
2636 else if (code
== HTTP_WEBIF_DISABLED
)
2639 * Treat our special "web interface is disabled" status as "200 OK" for web
2646 httpFlushWrite(HTTP(con
));
2648 con
->http
.data_encoding
= HTTP_ENCODING_FIELDS
;
2650 if (httpPrintf(HTTP(con
), "HTTP/%d.%d %d %s\r\n", con
->http
.version
/ 100,
2651 con
->http
.version
% 100, code
, httpStatus(code
)) < 0)
2653 if (httpPrintf(HTTP(con
), "Date: %s\r\n", httpGetDateString(time(NULL
))) < 0)
2656 if (httpPrintf(HTTP(con
), "Server: %s\r\n", ServerHeader
) < 0)
2658 if (con
->http
.keep_alive
&& con
->http
.version
>= HTTP_1_0
)
2660 if (httpPrintf(HTTP(con
), "Connection: Keep-Alive\r\n") < 0)
2662 if (httpPrintf(HTTP(con
), "Keep-Alive: timeout=%d\r\n",
2663 KeepAliveTimeout
) < 0)
2666 if (code
== HTTP_METHOD_NOT_ALLOWED
)
2667 if (httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n") < 0)
2670 if (code
== HTTP_UNAUTHORIZED
)
2672 if (auth_type
== CUPSD_AUTH_NONE
)
2674 if (!con
->best
|| con
->best
->type
<= CUPSD_AUTH_NONE
)
2675 auth_type
= cupsdDefaultAuthType();
2677 auth_type
= con
->best
->type
;
2682 if (auth_type
== CUPSD_AUTH_BASIC
|| auth_type
== CUPSD_AUTH_BASICDIGEST
)
2683 strlcpy(auth_str
, "Basic realm=\"CUPS\"", sizeof(auth_str
));
2684 else if (auth_type
== CUPSD_AUTH_DIGEST
)
2685 snprintf(auth_str
, sizeof(auth_str
), "Digest realm=\"CUPS\", nonce=\"%s\"",
2686 con
->http
.hostname
);
2688 else if (auth_type
== CUPSD_AUTH_NEGOTIATE
)
2691 if (_httpAddrFamily(con
->http
.hostaddr
) == AF_LOCAL
)
2692 strlcpy(auth_str
, "Basic realm=\"CUPS\"", sizeof(auth_str
));
2694 # endif /* AF_LOCAL */
2695 strlcpy(auth_str
, "Negotiate", sizeof(auth_str
));
2697 #endif /* HAVE_GSSAPI */
2699 if (con
->best
&& auth_type
!= CUPSD_AUTH_NEGOTIATE
&&
2700 !_cups_strcasecmp(con
->http
.hostname
, "localhost"))
2703 * Add a "trc" (try root certification) parameter for local non-Kerberos
2704 * requests when the request requires system group membership - then the
2705 * client knows the root certificate can/should be used.
2707 * Also, for OS X we also look for @AUTHKEY and add an "authkey"
2708 * parameter as needed...
2711 char *name
, /* Current user name */
2712 *auth_key
; /* Auth key buffer */
2713 size_t auth_size
; /* Size of remaining buffer */
2715 auth_key
= auth_str
+ strlen(auth_str
);
2716 auth_size
= sizeof(auth_str
) - (auth_key
- auth_str
);
2718 for (name
= (char *)cupsArrayFirst(con
->best
->names
);
2720 name
= (char *)cupsArrayNext(con
->best
->names
))
2722 #ifdef HAVE_AUTHORIZATION_H
2723 if (!_cups_strncasecmp(name
, "@AUTHKEY(", 9))
2725 snprintf(auth_key
, auth_size
, ", authkey=\"%s\"", name
+ 9);
2726 /* end parenthesis is stripped in conf.c */
2730 #endif /* HAVE_AUTHORIZATION_H */
2731 if (!_cups_strcasecmp(name
, "@SYSTEM"))
2733 #ifdef HAVE_AUTHORIZATION_H
2734 if (SystemGroupAuthKey
)
2735 snprintf(auth_key
, auth_size
,
2737 SystemGroupAuthKey
);
2740 strlcpy(auth_key
, ", trc=\"y\"", auth_size
);
2741 #endif /* HAVE_AUTHORIZATION_H */
2749 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2750 "[Client %d] WWW-Authenticate: %s", con
->http
.fd
,
2753 if (httpPrintf(HTTP(con
), "WWW-Authenticate: %s\r\n", auth_str
) < 0)
2758 if (con
->language
&& strcmp(con
->language
->language
, "C"))
2760 if (httpPrintf(HTTP(con
), "Content-Language: %s\r\n",
2761 con
->language
->language
) < 0)
2767 if (!strcmp(type
, "text/html"))
2769 if (httpPrintf(HTTP(con
),
2770 "Content-Type: text/html; charset=utf-8\r\n") < 0)
2773 else if (httpPrintf(HTTP(con
), "Content-Type: %s\r\n", type
) < 0)
2782 * 'cupsdUpdateCGI()' - Read status messages from CGI scripts and programs.
2786 cupsdUpdateCGI(void)
2788 char *ptr
, /* Pointer to end of line in buffer */
2789 message
[1024]; /* Pointer to message text */
2790 int loglevel
; /* Log level for message */
2793 while ((ptr
= cupsdStatBufUpdate(CGIStatusBuffer
, &loglevel
,
2794 message
, sizeof(message
))) != NULL
)
2796 if (loglevel
== CUPSD_LOG_INFO
)
2797 cupsdLogMessage(CUPSD_LOG_INFO
, "%s", message
);
2799 if (!strchr(CGIStatusBuffer
->buffer
, '\n'))
2803 if (ptr
== NULL
&& !CGIStatusBuffer
->bufused
)
2806 * Fatal error on pipe - should never happen!
2809 cupsdLogMessage(CUPSD_LOG_CRIT
,
2810 "cupsdUpdateCGI: error reading from CGI error pipe - %s",
2817 * 'cupsdWriteClient()' - Write data to a client as needed.
2821 cupsdWriteClient(cupsd_client_t
*con
) /* I - Client connection */
2823 int bytes
, /* Number of bytes written */
2824 field_col
; /* Current column */
2825 char *bufptr
, /* Pointer into buffer */
2826 *bufend
; /* Pointer to end of buffer */
2827 ipp_state_t ipp_state
; /* IPP state value */
2830 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2831 "[Client %d] cupsdWriteClient "
2835 "data_encoding=HTTP_ENCODING_%s, "
2836 "data_remaining=" CUPS_LLFMT
", "
2840 con
->http
.fd
, con
->http
.error
, con
->http
.used
,
2841 http_states
[con
->http
.state
+ 1],
2842 con
->http
.data_encoding
== HTTP_ENCODING_CHUNKED
?
2843 "CHUNKED" : "LENGTH",
2844 CUPS_LLCAST con
->http
.data_remaining
,
2846 con
->response
? ipp_states
[con
->response
->state
] : "",
2847 con
->pipe_pid
, con
->file
);
2849 if (con
->http
.state
!= HTTP_STATE_GET_SEND
&&
2850 con
->http
.state
!= HTTP_STATE_POST_SEND
)
2853 * If we get called in the wrong state, then something went wrong with the
2854 * connection and we need to shut it down...
2857 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2858 "[Client %d] Closing on unexpected HTTP state %s.",
2859 con
->http
.fd
, http_states
[con
->http
.state
+ 1]);
2860 cupsdCloseClient(con
);
2867 * Make sure we select on the CGI output...
2870 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2872 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[Client %d] Waiting for CGI data.",
2875 if (!con
->file_ready
)
2878 * Try again later when there is CGI output available...
2881 cupsdRemoveSelect(con
->http
.fd
);
2885 con
->file_ready
= 0;
2888 if (con
->response
&& con
->response
->state
!= IPP_DATA
)
2890 int wused
= con
->http
.wused
; /* Previous write buffer use */
2895 * Write a single attribute or the IPP message header...
2898 ipp_state
= ippWrite(HTTP(con
), con
->response
);
2901 * If the write buffer has been flushed, stop buffering up attributes...
2904 if (con
->http
.wused
<= wused
)
2907 while (ipp_state
!= IPP_STATE_DATA
&& ipp_state
!= IPP_STATE_ERROR
);
2909 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2910 "[Client %d] Writing IPP response, ipp_state=%s, old "
2911 "wused=%d, new wused=%d", con
->http
.fd
,
2912 ipp_state
== IPP_STATE_ERROR
? "ERROR" :
2913 ipp_state
== IPP_STATE_IDLE
? "IDLE" :
2914 ipp_state
== IPP_STATE_HEADER
? "HEADER" :
2915 ipp_state
== IPP_STATE_ATTRIBUTE
? "ATTRIBUTE" : "DATA",
2916 wused
, con
->http
.wused
);
2918 if (con
->http
.wused
> 0)
2919 httpFlushWrite(HTTP(con
));
2921 bytes
= ipp_state
!= IPP_STATE_ERROR
&&
2922 (con
->file
>= 0 || ipp_state
!= IPP_STATE_DATA
);
2924 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2925 "[Client %d] bytes=%d, http_state=%d, "
2926 "data_remaining=" CUPS_LLFMT
,
2927 con
->http
.fd
, (int)bytes
, con
->http
.state
,
2928 CUPS_LLCAST con
->http
.data_remaining
);
2930 else if ((bytes
= read(con
->file
, con
->header
+ con
->header_used
,
2931 sizeof(con
->header
) - con
->header_used
)) > 0)
2933 con
->header_used
+= bytes
;
2935 if (con
->pipe_pid
&& !con
->got_fields
)
2938 * Inspect the data for Content-Type and other fields.
2941 for (bufptr
= con
->header
, bufend
= con
->header
+ con
->header_used
,
2943 !con
->got_fields
&& bufptr
< bufend
;
2946 if (*bufptr
== '\n')
2949 * Send line to client...
2952 if (bufptr
> con
->header
&& bufptr
[-1] == '\r')
2956 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Script header: %s", con
->header
);
2958 if (!con
->sent_header
)
2961 * Handle redirection and CGI status codes...
2964 if (!_cups_strncasecmp(con
->header
, "Location:", 9))
2966 if (!cupsdSendHeader(con
, HTTP_SEE_OTHER
, NULL
, CUPSD_AUTH_NONE
))
2968 cupsdCloseClient(con
);
2972 con
->sent_header
= 2;
2974 if (httpPrintf(HTTP(con
), "Content-Length: 0\r\n") < 0)
2977 else if (!_cups_strncasecmp(con
->header
, "Status:", 7))
2979 cupsdSendError(con
, (http_status_t
)atoi(con
->header
+ 7),
2981 con
->sent_header
= 2;
2985 if (!cupsdSendHeader(con
, HTTP_OK
, NULL
, CUPSD_AUTH_NONE
))
2987 cupsdCloseClient(con
);
2991 con
->sent_header
= 1;
2993 if (con
->http
.version
== HTTP_1_1
)
2995 if (httpPrintf(HTTP(con
), "Transfer-Encoding: chunked\r\n") < 0)
3001 if (_cups_strncasecmp(con
->header
, "Status:", 7))
3002 httpPrintf(HTTP(con
), "%s\r\n", con
->header
);
3008 con
->header_used
-= bufptr
- con
->header
;
3010 if (con
->header_used
> 0)
3011 memmove(con
->header
, bufptr
, con
->header_used
);
3013 bufptr
= con
->header
- 1;
3016 * See if the line was empty...
3021 con
->got_fields
= 1;
3023 if (cupsdFlushHeader(con
) < 0)
3025 cupsdCloseClient(con
);
3029 if (con
->http
.version
== HTTP_1_1
)
3030 con
->http
.data_encoding
= HTTP_ENCODING_CHUNKED
;
3035 else if (*bufptr
!= '\r')
3039 if (!con
->got_fields
)
3041 con
->http
.activity
= time(NULL
);
3046 if (con
->header_used
> 0)
3048 if (httpWrite2(HTTP(con
), con
->header
, con
->header_used
) < 0)
3050 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3051 "[Client %d] Closing for error %d (%s)",
3052 con
->http
.fd
, con
->http
.error
,
3053 strerror(con
->http
.error
));
3054 cupsdCloseClient(con
);
3058 if (con
->http
.data_encoding
== HTTP_ENCODING_CHUNKED
)
3059 httpFlushWrite(HTTP(con
));
3061 con
->bytes
+= con
->header_used
;
3063 if (con
->http
.state
== HTTP_STATE_WAITING
)
3066 bytes
= con
->header_used
;
3068 con
->header_used
= 0;
3073 (con
->http
.state
!= HTTP_STATE_GET_SEND
&&
3074 con
->http
.state
!= HTTP_STATE_POST_SEND
))
3076 if (!con
->sent_header
&& con
->pipe_pid
)
3077 cupsdSendError(con
, HTTP_SERVER_ERROR
, CUPSD_AUTH_NONE
);
3080 cupsdLogRequest(con
, HTTP_OK
);
3082 httpFlushWrite(HTTP(con
));
3084 if (con
->http
.data_encoding
== HTTP_ENCODING_CHUNKED
&&
3085 con
->sent_header
== 1)
3087 if (httpWrite2(HTTP(con
), "", 0) < 0)
3089 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3090 "[Client %d] Closing for error %d (%s)",
3091 con
->http
.fd
, con
->http
.error
,
3092 strerror(con
->http
.error
));
3093 cupsdCloseClient(con
);
3099 con
->http
.state
= HTTP_STATE_WAITING
;
3101 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
3103 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[Client %d] Waiting for request.",
3108 cupsdRemoveSelect(con
->file
);
3111 cupsdEndProcess(con
->pipe_pid
, 0);
3120 unlink(con
->filename
);
3121 cupsdClearString(&con
->filename
);
3126 ippDelete(con
->request
);
3127 con
->request
= NULL
;
3132 ippDelete(con
->response
);
3133 con
->response
= NULL
;
3136 cupsdClearString(&con
->command
);
3137 cupsdClearString(&con
->options
);
3138 cupsdClearString(&con
->query_string
);
3140 if (!con
->http
.keep_alive
)
3142 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3143 "[Client %d] Closing because Keep-Alive disabled.",
3145 cupsdCloseClient(con
);
3150 cupsArrayRemove(ActiveClients
, con
);
3151 cupsdSetBusyState();
3155 con
->http
.activity
= time(NULL
);
3160 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
3163 static int /* O - 1 if modified since */
3165 cupsd_client_t
*con
, /* I - Client connection */
3166 struct stat
*filestats
) /* I - File information */
3168 char *ptr
; /* Pointer into field */
3169 time_t date
; /* Time/date value */
3170 off_t size
; /* Size/length value */
3175 ptr
= con
->http
.fields
[HTTP_FIELD_IF_MODIFIED_SINCE
];
3180 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3181 "[Client %d] check_if_modified "
3182 "filestats=%p(" CUPS_LLFMT
", %d)) If-Modified-Since=\"%s\"",
3183 con
->http
.fd
, filestats
, CUPS_LLCAST filestats
->st_size
,
3184 (int)filestats
->st_mtime
, ptr
);
3186 while (*ptr
!= '\0')
3188 while (isspace(*ptr
) || *ptr
== ';')
3191 if (_cups_strncasecmp(ptr
, "length=", 7) == 0)
3194 size
= strtoll(ptr
, NULL
, 10);
3196 while (isdigit(*ptr
))
3199 else if (isalpha(*ptr
))
3201 date
= httpGetDateTime(ptr
);
3202 while (*ptr
!= '\0' && *ptr
!= ';')
3209 return ((size
!= filestats
->st_size
&& size
!= 0) ||
3210 (date
< filestats
->st_mtime
&& date
!= 0) ||
3211 (size
== 0 && date
== 0));
3216 * 'compare_clients()' - Compare two client connections.
3219 static int /* O - Result of comparison */
3220 compare_clients(cupsd_client_t
*a
, /* I - First client */
3221 cupsd_client_t
*b
, /* I - Second client */
3222 void *data
) /* I - User data (not used) */
3236 * 'data_ready()' - Check whether data is available from a client.
3239 static int /* O - 1 if data is ready, 0 otherwise */
3240 data_ready(cupsd_client_t
*con
) /* I - Client */
3242 if (con
->http
.used
> 0)
3245 else if (con
->http
.tls
)
3248 if (SSL_pending((SSL
*)(con
->http
.tls
)))
3250 # elif defined(HAVE_GNUTLS)
3251 if (gnutls_record_check_pending(con
->http
.tls
))
3253 # elif defined(HAVE_CDSASSL)
3254 size_t bytes
; /* Bytes that are available */
3256 if (!SSLGetBufferedReadSize(con
->http
.tls
, &bytes
) && bytes
> 0)
3258 # endif /* HAVE_LIBSSL */
3260 #endif /* HAVE_SSL */
3267 * 'get_file()' - Get a filename and state info.
3270 static char * /* O - Real filename */
3271 get_file(cupsd_client_t
*con
, /* I - Client connection */
3272 struct stat
*filestats
, /* O - File information */
3273 char *filename
, /* IO - Filename buffer */
3274 int len
) /* I - Buffer length */
3276 int status
; /* Status of filesystem calls */
3277 char *ptr
; /* Pointer info filename */
3278 int plen
; /* Remaining length after pointer */
3279 char language
[7]; /* Language subdirectory, if any */
3283 * Figure out the real filename...
3288 if (!strncmp(con
->uri
, "/ppd/", 5) && !strchr(con
->uri
+ 5, '/'))
3289 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
);
3290 else if (!strncmp(con
->uri
, "/icons/", 7) && !strchr(con
->uri
+ 7, '/'))
3292 snprintf(filename
, len
, "%s/%s", CacheDir
, con
->uri
+ 7);
3293 if (access(filename
, F_OK
) < 0)
3294 snprintf(filename
, len
, "%s/images/generic.png", DocumentRoot
);
3296 else if (!strncmp(con
->uri
, "/rss/", 5) && !strchr(con
->uri
+ 5, '/'))
3297 snprintf(filename
, len
, "%s/rss/%s", CacheDir
, con
->uri
+ 5);
3298 else if (!strncmp(con
->uri
, "/admin/conf/", 12))
3299 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
+ 11);
3300 else if (!strncmp(con
->uri
, "/admin/log/", 11))
3302 if (!strncmp(con
->uri
+ 11, "access_log", 10) && AccessLog
[0] == '/')
3303 strlcpy(filename
, AccessLog
, len
);
3304 else if (!strncmp(con
->uri
+ 11, "error_log", 9) && ErrorLog
[0] == '/')
3305 strlcpy(filename
, ErrorLog
, len
);
3306 else if (!strncmp(con
->uri
+ 11, "page_log", 8) && PageLog
[0] == '/')
3307 strlcpy(filename
, PageLog
, len
);
3311 else if (con
->language
)
3313 snprintf(language
, sizeof(language
), "/%s", con
->language
->language
);
3314 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3317 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3319 if ((ptr
= strchr(filename
, '?')) != NULL
)
3323 * Grab the status for this language; if there isn't a language-specific file
3324 * then fallback to the default one...
3327 if ((status
= stat(filename
, filestats
)) != 0 && language
[0] &&
3328 strncmp(con
->uri
, "/icons/", 7) &&
3329 strncmp(con
->uri
, "/ppd/", 5) &&
3330 strncmp(con
->uri
, "/rss/", 5) &&
3331 strncmp(con
->uri
, "/admin/conf/", 12) &&
3332 strncmp(con
->uri
, "/admin/log/", 11))
3335 * Drop the country code...
3339 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3341 if ((ptr
= strchr(filename
, '?')) != NULL
)
3344 if ((status
= stat(filename
, filestats
)) != 0)
3347 * Drop the language prefix and try the root directory...
3351 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3353 if ((ptr
= strchr(filename
, '?')) != NULL
)
3356 status
= stat(filename
, filestats
);
3361 * If we're found a directory, get the index.html file instead...
3364 if (!status
&& S_ISDIR(filestats
->st_mode
))
3367 * Make sure the URI ends with a slash...
3370 if (con
->uri
[strlen(con
->uri
) - 1] != '/')
3371 strlcat(con
->uri
, "/", sizeof(con
->uri
));
3374 * Find the directory index file, trying every language...
3379 if (status
&& language
[0])
3382 * Try a different language subset...
3386 language
[0] = '\0'; /* Strip country code */
3388 language
[0] = '\0'; /* Strip language */
3392 * Look for the index file...
3395 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3397 if ((ptr
= strchr(filename
, '?')) != NULL
)
3400 ptr
= filename
+ strlen(filename
);
3401 plen
= len
- (ptr
- filename
);
3403 strlcpy(ptr
, "index.html", plen
);
3404 status
= stat(filename
, filestats
);
3409 strlcpy(ptr
, "index.class", plen
);
3410 status
= stat(filename
, filestats
);
3412 #endif /* HAVE_JAVA */
3417 strlcpy(ptr
, "index.pl", plen
);
3418 status
= stat(filename
, filestats
);
3420 #endif /* HAVE_PERL */
3425 strlcpy(ptr
, "index.php", plen
);
3426 status
= stat(filename
, filestats
);
3428 #endif /* HAVE_PHP */
3433 strlcpy(ptr
, "index.pyc", plen
);
3434 status
= stat(filename
, filestats
);
3439 strlcpy(ptr
, "index.py", plen
);
3440 status
= stat(filename
, filestats
);
3442 #endif /* HAVE_PYTHON */
3445 while (status
&& language
[0]);
3448 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3449 "[Client %d] get_file filestats=%p, filename=%p, len=%d, "
3450 "returning \"%s\".", con
->http
.fd
, filestats
, filename
, len
,
3451 status
? "(null)" : filename
);
3461 * 'install_cupsd_conf()' - Install a configuration file.
3464 static http_status_t
/* O - Status */
3465 install_cupsd_conf(cupsd_client_t
*con
) /* I - Connection */
3467 char filename
[1024]; /* Configuration filename */
3468 cups_file_t
*in
, /* Input file */
3469 *out
; /* Output file */
3470 char buffer
[16384]; /* Copy buffer */
3471 ssize_t bytes
; /* Number of bytes */
3475 * Open the request file...
3478 if ((in
= cupsFileOpen(con
->filename
, "rb")) == NULL
)
3480 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open request file \"%s\": %s",
3481 con
->filename
, strerror(errno
));
3482 return (HTTP_SERVER_ERROR
);
3486 * Open the new config file...
3489 if ((out
= cupsdCreateConfFile(ConfigurationFile
, ConfigFilePerm
)) == NULL
)
3492 return (HTTP_SERVER_ERROR
);
3495 cupsdLogMessage(CUPSD_LOG_INFO
, "Installing config file \"%s\"...",
3499 * Copy from the request to the new config file...
3502 while ((bytes
= cupsFileRead(in
, buffer
, sizeof(buffer
))) > 0)
3503 if (cupsFileWrite(out
, buffer
, bytes
) < bytes
)
3505 cupsdLogMessage(CUPSD_LOG_ERROR
,
3506 "Unable to copy to config file \"%s\": %s",
3507 ConfigurationFile
, strerror(errno
));
3512 snprintf(filename
, sizeof(filename
), "%s.N", ConfigurationFile
);
3513 cupsdUnlinkOrRemoveFile(filename
);
3515 return (HTTP_SERVER_ERROR
);
3519 * Close the files...
3524 if (cupsdCloseCreatedConfFile(out
, ConfigurationFile
))
3525 return (HTTP_SERVER_ERROR
);
3528 * Remove the request file...
3531 cupsdUnlinkOrRemoveFile(con
->filename
);
3532 cupsdClearString(&con
->filename
);
3535 * Set the NeedReload flag...
3538 NeedReload
= RELOAD_CUPSD
;
3539 ReloadTime
= time(NULL
);
3542 * Return that the file was created successfully...
3545 return (HTTP_CREATED
);
3550 * 'is_cgi()' - Is the resource a CGI script/program?
3553 static int /* O - 1 = CGI, 0 = file */
3554 is_cgi(cupsd_client_t
*con
, /* I - Client connection */
3555 const char *filename
, /* I - Real filename */
3556 struct stat
*filestats
, /* I - File information */
3557 mime_type_t
*type
) /* I - MIME type */
3559 const char *options
; /* Options on URL */
3563 * Get the options, if any...
3566 if ((options
= strchr(con
->uri
, '?')) != NULL
)
3569 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", options
);
3573 * Check for known types...
3576 if (!type
|| _cups_strcasecmp(type
->super
, "application"))
3578 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3579 "[Client %d] is_cgi filename=\"%s\", filestats=%p, "
3580 "type=%s/%s, returning 0", con
->http
.fd
, filename
,
3581 filestats
, type
? type
->super
: "unknown",
3582 type
? type
->type
: "unknown");
3586 if (!_cups_strcasecmp(type
->type
, "x-httpd-cgi") &&
3587 (filestats
->st_mode
& 0111))
3590 * "application/x-httpd-cgi" is a CGI script.
3593 cupsdSetString(&con
->command
, filename
);
3596 cupsdSetStringf(&con
->options
, " %s", options
);
3598 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3599 "[Client %d] is_cgi filename=\"%s\", filestats=%p, "
3600 "type=%s/%s, returning 1", con
->http
.fd
, filename
,
3601 filestats
, type
->super
, type
->type
);
3605 else if (!_cups_strcasecmp(type
->type
, "x-httpd-java"))
3608 * "application/x-httpd-java" is a Java servlet.
3611 cupsdSetString(&con
->command
, CUPS_JAVA
);
3614 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3616 cupsdSetStringf(&con
->options
, " %s", filename
);
3618 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3619 "[Client %d] is_cgi filename=\"%s\", filestats=%p, "
3620 "type=%s/%s, returning 1", con
->http
.fd
, filename
,
3621 filestats
, type
->super
, type
->type
);
3624 #endif /* HAVE_JAVA */
3626 else if (!_cups_strcasecmp(type
->type
, "x-httpd-perl"))
3629 * "application/x-httpd-perl" is a Perl page.
3632 cupsdSetString(&con
->command
, CUPS_PERL
);
3635 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3637 cupsdSetStringf(&con
->options
, " %s", filename
);
3639 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3640 "[Client %d] is_cgi filename=\"%s\", filestats=%p, "
3641 "type=%s/%s, returning 1", con
->http
.fd
, filename
,
3642 filestats
, type
->super
, type
->type
);
3645 #endif /* HAVE_PERL */
3647 else if (!_cups_strcasecmp(type
->type
, "x-httpd-php"))
3650 * "application/x-httpd-php" is a PHP page.
3653 cupsdSetString(&con
->command
, CUPS_PHP
);
3656 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3658 cupsdSetStringf(&con
->options
, " %s", filename
);
3660 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3661 "[Client %d] is_cgi filename=\"%s\", filestats=%p, "
3662 "type=%s/%s, returning 1", con
->http
.fd
, filename
,
3663 filestats
, type
->super
, type
->type
);
3666 #endif /* HAVE_PHP */
3668 else if (!_cups_strcasecmp(type
->type
, "x-httpd-python"))
3671 * "application/x-httpd-python" is a Python page.
3674 cupsdSetString(&con
->command
, CUPS_PYTHON
);
3677 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3679 cupsdSetStringf(&con
->options
, " %s", filename
);
3681 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3682 "[Client %d] is_cgi filename=\"%s\", filestats=%p, "
3683 "type=%s/%s, returning 1", con
->http
.fd
, filename
,
3684 filestats
, type
->super
, type
->type
);
3687 #endif /* HAVE_PYTHON */
3689 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3690 "[Client %d] is_cgi filename=\"%s\", filestats=%p, "
3691 "type=%s/%s, returning 0", con
->http
.fd
, filename
,
3692 filestats
, type
->super
, type
->type
);
3698 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
3701 static int /* O - 0 if relative, 1 if absolute */
3702 is_path_absolute(const char *path
) /* I - Input path */
3705 * Check for a leading slash...
3712 * Check for "/.." in the path...
3715 while ((path
= strstr(path
, "/..")) != NULL
)
3717 if (!path
[3] || path
[3] == '/')
3724 * If we haven't found any relative paths, return 1 indicating an
3733 * 'pipe_command()' - Pipe the output of a command to the remote client.
3736 static int /* O - Process ID */
3737 pipe_command(cupsd_client_t
*con
, /* I - Client connection */
3738 int infile
, /* I - Standard input for command */
3739 int *outfile
, /* O - Standard output for command */
3740 char *command
, /* I - Command to run */
3741 char *options
, /* I - Options for command */
3742 int root
) /* I - Run as root? */
3744 int i
; /* Looping var */
3745 int pid
; /* Process ID */
3746 char *commptr
, /* Command string pointer */
3747 commch
; /* Command string character */
3748 char *uriptr
; /* URI string pointer */
3749 int fds
[2]; /* Pipe FDs */
3750 int argc
; /* Number of arguments */
3751 int envc
; /* Number of environment variables */
3752 char argbuf
[10240], /* Argument buffer */
3753 *argv
[100], /* Argument strings */
3754 *envp
[MAX_ENV
+ 20]; /* Environment variables */
3755 char auth_type
[256], /* AUTH_TYPE environment variable */
3756 content_length
[1024], /* CONTENT_LENGTH environment variable */
3757 content_type
[1024], /* CONTENT_TYPE environment variable */
3758 http_cookie
[32768], /* HTTP_COOKIE environment variable */
3759 http_referer
[1024], /* HTTP_REFERER environment variable */
3760 http_user_agent
[1024], /* HTTP_USER_AGENT environment variable */
3761 lang
[1024], /* LANG environment variable */
3762 path_info
[1024], /* PATH_INFO environment variable */
3763 remote_addr
[1024], /* REMOTE_ADDR environment variable */
3764 remote_host
[1024], /* REMOTE_HOST environment variable */
3765 remote_user
[1024], /* REMOTE_USER environment variable */
3766 script_filename
[1024], /* SCRIPT_FILENAME environment variable */
3767 script_name
[1024], /* SCRIPT_NAME environment variable */
3768 server_name
[1024], /* SERVER_NAME environment variable */
3769 server_port
[1024]; /* SERVER_PORT environment variable */
3770 ipp_attribute_t
*attr
; /* attributes-natural-language attribute */
3774 * Parse a copy of the options string, which is of the form:
3776 * argument+argument+argument
3777 * ?argument+argument+argument
3778 * param=value¶m=value
3779 * ?param=value¶m=value
3780 * /name?argument+argument+argument
3781 * /name?param=value¶m=value
3783 * If the string contains an "=" character after the initial name,
3784 * then we treat it as a HTTP GET form request and make a copy of
3785 * the remaining string for the environment variable.
3787 * The string is always parsed out as command-line arguments, to
3788 * be consistent with Apache...
3791 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3792 "[Client %d] pipe_command infile=%d, outfile=%p, "
3793 "command=\"%s\", options=\"%s\", root=%d",
3794 con
->http
.fd
, infile
, outfile
, command
,
3795 options
? options
: "(null)", root
);
3802 if (*commptr
== ' ')
3804 strlcpy(argbuf
, commptr
, sizeof(argbuf
));
3809 if (argbuf
[0] == '/')
3812 * Found some trailing path information, set PATH_INFO...
3815 if ((commptr
= strchr(argbuf
, '?')) == NULL
)
3816 commptr
= argbuf
+ strlen(argbuf
);
3820 snprintf(path_info
, sizeof(path_info
), "PATH_INFO=%s", argbuf
);
3826 path_info
[0] = '\0';
3828 if (*commptr
== ' ')
3832 if (*commptr
== '?' && con
->operation
== HTTP_STATE_GET
&& !con
->query_string
)
3835 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", commptr
);
3842 argv
[argc
++] = commptr
;
3844 for (; *commptr
&& argc
< 99; commptr
++)
3847 * Break arguments whenever we see a + or space...
3850 if (*commptr
== ' ' || *commptr
== '+')
3852 while (*commptr
== ' ' || *commptr
== '+')
3856 * If we don't have a blank string, save it as another argument...
3861 argv
[argc
] = commptr
;
3867 else if (*commptr
== '%' && isxdigit(commptr
[1] & 255) &&
3868 isxdigit(commptr
[2] & 255))
3871 * Convert the %xx notation to the individual character.
3874 if (commptr
[1] >= '0' && commptr
[1] <= '9')
3875 *commptr
= (commptr
[1] - '0') << 4;
3877 *commptr
= (tolower(commptr
[1]) - 'a' + 10) << 4;
3879 if (commptr
[2] >= '0' && commptr
[2] <= '9')
3880 *commptr
|= commptr
[2] - '0';
3882 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
3884 _cups_strcpy(commptr
+ 1, commptr
+ 3);
3887 * Check for a %00 and break if that is the case...
3899 * Setup the environment variables as needed...
3902 if (con
->username
[0])
3904 snprintf(auth_type
, sizeof(auth_type
), "AUTH_TYPE=%s",
3905 httpGetField(HTTP(con
), HTTP_FIELD_AUTHORIZATION
));
3907 if ((uriptr
= strchr(auth_type
+ 10, ' ')) != NULL
)
3911 auth_type
[0] = '\0';
3914 (attr
= ippFindAttribute(con
->request
, "attributes-natural-language",
3915 IPP_TAG_LANGUAGE
)) != NULL
)
3917 switch (strlen(attr
->values
[0].string
.text
))
3921 * This is an unknown or badly formatted language code; use
3922 * the POSIX locale...
3925 strlcpy(lang
, "LANG=C", sizeof(lang
));
3930 * Just the language code (ll)...
3933 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8",
3934 attr
->values
[0].string
.text
);
3939 * Language and country code (ll-cc)...
3942 snprintf(lang
, sizeof(lang
), "LANG=%c%c_%c%c.UTF8",
3943 attr
->values
[0].string
.text
[0],
3944 attr
->values
[0].string
.text
[1],
3945 toupper(attr
->values
[0].string
.text
[3] & 255),
3946 toupper(attr
->values
[0].string
.text
[4] & 255));
3950 else if (con
->language
)
3951 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8", con
->language
->language
);
3953 strlcpy(lang
, "LANG=C", sizeof(lang
));
3955 strlcpy(remote_addr
, "REMOTE_ADDR=", sizeof(remote_addr
));
3956 httpAddrString(con
->http
.hostaddr
, remote_addr
+ 12,
3957 sizeof(remote_addr
) - 12);
3959 snprintf(remote_host
, sizeof(remote_host
), "REMOTE_HOST=%s",
3960 con
->http
.hostname
);
3962 snprintf(script_name
, sizeof(script_name
), "SCRIPT_NAME=%s", con
->uri
);
3963 if ((uriptr
= strchr(script_name
, '?')) != NULL
)
3966 snprintf(script_filename
, sizeof(script_filename
), "SCRIPT_FILENAME=%s%s",
3967 DocumentRoot
, script_name
+ 12);
3969 sprintf(server_port
, "SERVER_PORT=%d", con
->serverport
);
3971 if (con
->http
.fields
[HTTP_FIELD_HOST
][0])
3973 char *nameptr
; /* Pointer to ":port" */
3975 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
3976 con
->http
.fields
[HTTP_FIELD_HOST
]);
3977 if ((nameptr
= strrchr(server_name
, ':')) != NULL
&& !strchr(nameptr
, ']'))
3978 *nameptr
= '\0'; /* Strip trailing ":port" */
3981 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
3984 envc
= cupsdLoadEnv(envp
, (int)(sizeof(envp
) / sizeof(envp
[0])));
3987 envp
[envc
++] = auth_type
;
3989 envp
[envc
++] = lang
;
3990 envp
[envc
++] = "REDIRECT_STATUS=1";
3991 envp
[envc
++] = "GATEWAY_INTERFACE=CGI/1.1";
3992 envp
[envc
++] = server_name
;
3993 envp
[envc
++] = server_port
;
3994 envp
[envc
++] = remote_addr
;
3995 envp
[envc
++] = remote_host
;
3996 envp
[envc
++] = script_name
;
3997 envp
[envc
++] = script_filename
;
4000 envp
[envc
++] = path_info
;
4002 if (con
->username
[0])
4004 snprintf(remote_user
, sizeof(remote_user
), "REMOTE_USER=%s", con
->username
);
4006 envp
[envc
++] = remote_user
;
4009 if (con
->http
.version
== HTTP_1_1
)
4010 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.1";
4011 else if (con
->http
.version
== HTTP_1_0
)
4012 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.0";
4014 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/0.9";
4016 if (con
->http
.cookie
)
4018 snprintf(http_cookie
, sizeof(http_cookie
), "HTTP_COOKIE=%s",
4020 envp
[envc
++] = http_cookie
;
4023 if (con
->http
.fields
[HTTP_FIELD_USER_AGENT
][0])
4025 snprintf(http_user_agent
, sizeof(http_user_agent
), "HTTP_USER_AGENT=%s",
4026 con
->http
.fields
[HTTP_FIELD_USER_AGENT
]);
4027 envp
[envc
++] = http_user_agent
;
4030 if (con
->http
.fields
[HTTP_FIELD_REFERER
][0])
4032 snprintf(http_referer
, sizeof(http_referer
), "HTTP_REFERER=%s",
4033 con
->http
.fields
[HTTP_FIELD_REFERER
]);
4034 envp
[envc
++] = http_referer
;
4037 if (con
->operation
== HTTP_STATE_GET
)
4039 envp
[envc
++] = "REQUEST_METHOD=GET";
4041 if (con
->query_string
)
4044 * Add GET form variables after ?...
4047 envp
[envc
++] = con
->query_string
;
4050 envp
[envc
++] = "QUERY_STRING=";
4054 sprintf(content_length
, "CONTENT_LENGTH=" CUPS_LLFMT
,
4055 CUPS_LLCAST con
->bytes
);
4056 snprintf(content_type
, sizeof(content_type
), "CONTENT_TYPE=%s",
4057 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
4059 envp
[envc
++] = "REQUEST_METHOD=POST";
4060 envp
[envc
++] = content_length
;
4061 envp
[envc
++] = content_type
;
4065 * Tell the CGI if we are using encryption...
4069 envp
[envc
++] = "HTTPS=ON";
4072 * Terminate the environment array...
4077 if (LogLevel
>= CUPSD_LOG_DEBUG
)
4079 for (i
= 0; i
< argc
; i
++)
4080 cupsdLogMessage(CUPSD_LOG_DEBUG
,
4081 "[CGI] argv[%d] = \"%s\"", i
, argv
[i
]);
4082 for (i
= 0; i
< envc
; i
++)
4083 cupsdLogMessage(CUPSD_LOG_DEBUG
,
4084 "[CGI] envp[%d] = \"%s\"", i
, envp
[i
]);
4088 * Create a pipe for the output...
4091 if (cupsdOpenPipe(fds
))
4093 cupsdLogMessage(CUPSD_LOG_ERROR
, "[CGI] Unable to create pipe for %s - %s",
4094 argv
[0], strerror(errno
));
4099 * Then execute the command...
4102 if (cupsdStartProcess(command
, argv
, envp
, infile
, fds
[1], CGIPipes
[1],
4103 -1, -1, root
, DefaultProfile
, NULL
, &pid
) < 0)
4106 * Error - can't fork!
4109 cupsdLogMessage(CUPSD_LOG_ERROR
, "[CGI] Unable to start %s - %s", argv
[0],
4112 cupsdClosePipe(fds
);
4118 * Fork successful - return the PID...
4121 if (con
->username
[0])
4122 cupsdAddCert(pid
, con
->username
, con
->type
);
4124 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[CGI] Started %s (PID %d)", command
, pid
);
4135 * 'valid_host()' - Is the Host: field valid?
4138 static int /* O - 1 if valid, 0 if not */
4139 valid_host(cupsd_client_t
*con
) /* I - Client connection */
4141 cupsd_alias_t
*a
; /* Current alias */
4142 cupsd_netif_t
*netif
; /* Current network interface */
4143 const char *end
; /* End character */
4144 char *ptr
; /* Pointer into host value */
4148 * Copy the Host: header for later use...
4151 strlcpy(con
->clientname
, con
->http
.fields
[HTTP_FIELD_HOST
],
4152 sizeof(con
->clientname
));
4153 if ((ptr
= strrchr(con
->clientname
, ':')) != NULL
&& !strchr(ptr
, ']'))
4156 con
->clientport
= atoi(ptr
);
4159 con
->clientport
= con
->serverport
;
4165 if (httpAddrLocalhost(con
->http
.hostaddr
))
4168 * Only allow "localhost" or the equivalent IPv4 or IPv6 numerical
4169 * addresses when accessing CUPS via the loopback interface...
4172 return (!_cups_strcasecmp(con
->clientname
, "localhost") ||
4173 !_cups_strcasecmp(con
->clientname
, "localhost.") ||
4175 !_cups_strcasecmp(con
->clientname
, "localhost.localdomain") ||
4176 #endif /* __linux */
4177 !strcmp(con
->clientname
, "127.0.0.1") ||
4178 !strcmp(con
->clientname
, "[::1]"));
4181 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
4183 * Check if the hostname is something.local (Bonjour); if so, allow it.
4186 if ((end
= strrchr(con
->clientname
, '.')) != NULL
&& end
> con
->clientname
&&
4190 * "." on end, work back to second-to-last "."...
4193 for (end
--; end
> con
->clientname
&& *end
!= '.'; end
--);
4196 if (end
&& (!_cups_strcasecmp(end
, ".local") ||
4197 !_cups_strcasecmp(end
, ".local.")))
4199 #endif /* HAVE_DNSSD || HAVE_AVAHI */
4202 * Check if the hostname is an IP address...
4205 if (isdigit(con
->clientname
[0] & 255) || con
->clientname
[0] == '[')
4208 * Possible IPv4/IPv6 address...
4211 http_addrlist_t
*addrlist
; /* List of addresses */
4214 if ((addrlist
= httpAddrGetList(con
->clientname
, AF_UNSPEC
, NULL
)) != NULL
)
4217 * Good IPv4/IPv6 address...
4220 httpAddrFreeList(addrlist
);
4226 * Check for (alias) name matches...
4229 for (a
= (cupsd_alias_t
*)cupsArrayFirst(ServerAlias
);
4231 a
= (cupsd_alias_t
*)cupsArrayNext(ServerAlias
))
4234 * "ServerAlias *" allows all host values through...
4237 if (!strcmp(a
->name
, "*"))
4240 if (!_cups_strncasecmp(con
->clientname
, a
->name
, a
->namelen
))
4243 * Prefix matches; check the character at the end - it must be "." or nul.
4246 end
= con
->clientname
+ a
->namelen
;
4248 if (!*end
|| (*end
== '.' && !end
[1]))
4253 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
4254 for (a
= (cupsd_alias_t
*)cupsArrayFirst(DNSSDAlias
);
4256 a
= (cupsd_alias_t
*)cupsArrayNext(DNSSDAlias
))
4259 * "ServerAlias *" allows all host values through...
4262 if (!strcmp(a
->name
, "*"))
4265 if (!_cups_strncasecmp(con
->clientname
, a
->name
, a
->namelen
))
4268 * Prefix matches; check the character at the end - it must be "." or nul.
4271 end
= con
->clientname
+ a
->namelen
;
4273 if (!*end
|| (*end
== '.' && !end
[1]))
4277 #endif /* HAVE_DNSSD || HAVE_AVAHI */
4280 * Check for interface hostname matches...
4283 for (netif
= (cupsd_netif_t
*)cupsArrayFirst(NetIFList
);
4285 netif
= (cupsd_netif_t
*)cupsArrayNext(NetIFList
))
4287 if (!_cups_strncasecmp(con
->clientname
, netif
->hostname
, netif
->hostlen
))
4290 * Prefix matches; check the character at the end - it must be "." or nul.
4293 end
= con
->clientname
+ netif
->hostlen
;
4295 if (!*end
|| (*end
== '.' && !end
[1]))
4305 * 'write_file()' - Send a file via HTTP.
4308 static int /* O - 0 on failure, 1 on success */
4309 write_file(cupsd_client_t
*con
, /* I - Client connection */
4310 http_status_t code
, /* I - HTTP status */
4311 char *filename
, /* I - Filename */
4312 char *type
, /* I - File type */
4313 struct stat
*filestats
) /* O - File information */
4315 con
->file
= open(filename
, O_RDONLY
);
4317 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4318 "[Client %d] write_file code=%d, filename=\"%s\" (%d), "
4319 "type=\"%s\", filestats=%p", con
->http
.fd
,
4320 code
, filename
, con
->file
, type
? type
: "(null)", filestats
);
4325 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
4329 if (!cupsdSendHeader(con
, code
, type
, CUPSD_AUTH_NONE
))
4332 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
4333 httpGetDateString(filestats
->st_mtime
)) < 0)
4335 if (httpPrintf(HTTP(con
), "Content-Length: " CUPS_LLFMT
"\r\n",
4336 CUPS_LLCAST filestats
->st_size
) < 0)
4338 if (httpPrintf(HTTP(con
), "\r\n") < 0)
4341 if (cupsdFlushHeader(con
) < 0)
4344 con
->http
.data_encoding
= HTTP_ENCODING_LENGTH
;
4345 con
->http
.data_remaining
= filestats
->st_size
;
4347 if (con
->http
.data_remaining
<= INT_MAX
)
4348 con
->http
._data_remaining
= con
->http
.data_remaining
;
4350 con
->http
._data_remaining
= INT_MAX
;
4352 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
,
4353 (cupsd_selfunc_t
)cupsdWriteClient
, con
);
4355 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[Client %d] Sending file.", con
->http
.fd
);
4362 * 'write_pipe()' - Flag that data is available on the CGI pipe.
4366 write_pipe(cupsd_client_t
*con
) /* I - Client connection */
4368 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4369 "[Client %d] write_pipe CGI output on fd %d",
4370 con
->http
.fd
, con
->file
);
4372 con
->file_ready
= 1;
4374 cupsdRemoveSelect(con
->file
);
4375 cupsdAddSelect(con
->http
.fd
, NULL
, (cupsd_selfunc_t
)cupsdWriteClient
, con
);
4377 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[Client %d] CGI data ready to be sent.",