2 * "$Id: client.c 7950 2008-09-17 00:21:59Z mike $"
4 * Client routines for the Common UNIX Printing System (CUPS) scheduler.
6 * Copyright 2007-2009 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 * encrypt_client() - Enable encryption for the client...
35 * get_cdsa_certificate() - Get a SSL/TLS certificate from the System
37 * get_file() - Get a filename and state info.
38 * install_conf_file() - Install a configuration file.
39 * is_cgi() - Is the resource a CGI script/program?
40 * is_path_absolute() - Is a path absolute and free of relative elements
42 * make_certificate() - Make a self-signed SSL/TLS certificate.
43 * pipe_command() - Pipe the output of a command to the remote client.
44 * valid_host() - Is the Host: field valid?
45 * write_file() - Send a file via HTTP.
46 * write_pipe() - Flag that data is available on the CGI pipe.
50 * Include necessary headers...
56 # include <Security/Security.h>
57 # ifdef HAVE_SECIDENTITYSEARCHPRIV_H
58 # include <Security/SecIdentitySearchPriv.h>
59 # else /* Declare prototype for function in that header... */
60 extern OSStatus
SecIdentitySearchCreateWithPolicy(SecPolicyRef policy
,
61 CFStringRef idString
, CSSM_KEYUSE keyUsage
,
62 CFTypeRef keychainOrArray
,
63 Boolean returnOnlyValidIdentities
,
64 SecIdentitySearchRef
* searchRef
);
65 # endif /* HAVE_SECIDENTITYSEARCHPRIV_H */
66 # ifdef HAVE_SECPOLICYPRIV_H
67 # include <Security/SecPolicyPriv.h>
68 # else /* Declare prototype for function in that header... */
69 extern OSStatus
SecPolicySetValue(SecPolicyRef policyRef
,
70 const CSSM_DATA
*value
);
71 # endif /* HAVE_SECPOLICYPRIV_H */
72 # ifdef HAVE_SECBASEPRIV_H
73 # include <Security/SecBasePriv.h>
74 # else /* Declare prototype for function in that header... */
75 extern const char *cssmErrorString(int error
);
76 # endif /* HAVE_SECBASEPRIV_H */
77 #endif /* HAVE_CDSASSL */
80 # include <gnutls/x509.h>
81 #endif /* HAVE_GNUTLS */
85 #endif /* HAVE_TCPD_H */
92 static int check_if_modified(cupsd_client_t
*con
,
93 struct stat
*filestats
);
94 static int compare_clients(cupsd_client_t
*a
, cupsd_client_t
*b
,
96 static int data_ready(cupsd_client_t
*con
);
98 static int encrypt_client(cupsd_client_t
*con
);
101 static CFArrayRef
get_cdsa_certificate(cupsd_client_t
*con
);
102 #endif /* HAVE_CDSASSL */
103 static char *get_file(cupsd_client_t
*con
, struct stat
*filestats
,
104 char *filename
, int len
);
105 static http_status_t
install_conf_file(cupsd_client_t
*con
);
106 static int is_cgi(cupsd_client_t
*con
, const char *filename
,
107 struct stat
*filestats
, mime_type_t
*type
);
108 static int is_path_absolute(const char *path
);
110 static int make_certificate(cupsd_client_t
*con
);
111 #endif /* HAVE_SSL */
112 static int pipe_command(cupsd_client_t
*con
, int infile
, int *outfile
,
113 char *command
, char *options
, int root
);
114 static int valid_host(cupsd_client_t
*con
);
115 static int write_file(cupsd_client_t
*con
, http_status_t code
,
116 char *filename
, char *type
,
117 struct stat
*filestats
);
118 static void write_pipe(cupsd_client_t
*con
);
122 * 'cupsdAcceptClient()' - Accept a new client.
126 cupsdAcceptClient(cupsd_listener_t
*lis
)/* I - Listener socket */
128 int count
; /* Count of connections on a host */
129 int val
; /* Parameter value */
130 cupsd_client_t
*con
, /* New client pointer */
131 *tempcon
; /* Temporary client pointer */
132 http_addrlist_t
*addrlist
, /* List of adddresses for host */
133 *addr
; /* Current address */
134 socklen_t addrlen
; /* Length of address */
135 char *hostname
; /* Hostname for address */
136 http_addr_t temp
; /* Temporary address variable */
137 static time_t last_dos
= 0; /* Time of last DoS attack */
139 struct request_info wrap_req
; /* TCP wrappers request information */
140 #endif /* HAVE_TCPD_H */
143 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
144 "cupsdAcceptClient(lis=%p(%d)) Clients=%d",
145 lis
, lis
->fd
, cupsArrayCount(Clients
));
148 * Make sure we don't have a full set of clients already...
151 if (cupsArrayCount(Clients
) == MaxClients
)
155 * Get a pointer to the next available client...
159 Clients
= cupsArrayNew(NULL
, NULL
);
163 cupsdLogMessage(CUPSD_LOG_ERROR
,
164 "Unable to allocate memory for clients array!");
165 cupsdPauseListening();
170 ActiveClients
= cupsArrayNew((cups_array_func_t
)compare_clients
, NULL
);
174 cupsdLogMessage(CUPSD_LOG_ERROR
,
175 "Unable to allocate memory for active clients array!");
176 cupsdPauseListening();
180 if ((con
= calloc(1, sizeof(cupsd_client_t
))) == NULL
)
182 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to allocate memory for client!");
183 cupsdPauseListening();
187 con
->http
.activity
= time(NULL
);
189 con
->http
.hostaddr
= &(con
->clientaddr
);
192 * Accept the client and get the remote address...
195 addrlen
= sizeof(http_addr_t
);
197 if ((con
->http
.fd
= accept(lis
->fd
, (struct sockaddr
*)con
->http
.hostaddr
,
200 if (errno
== ENFILE
|| errno
== EMFILE
)
201 cupsdPauseListening();
203 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to accept client connection - %s.",
211 if (lis
->address
.addr
.sa_family
== AF_INET6
)
214 * Save the connected port number...
217 con
->http
.hostaddr
->ipv6
.sin6_port
= lis
->address
.ipv6
.sin6_port
;
220 * Convert IPv4 over IPv6 addresses (::ffff:n.n.n.n) to IPv4 forms we
221 * can more easily use...
224 if (con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[0] == 0 &&
225 con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[1] == 0 &&
226 ntohl(con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[2]) == 0xffff)
227 con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[2] = 0;
230 #endif /* AF_INET6 */
231 if (lis
->address
.addr
.sa_family
== AF_INET
)
232 con
->http
.hostaddr
->ipv4
.sin_port
= lis
->address
.ipv4
.sin_port
;
235 * Check the number of clients on the same address...
238 for (count
= 0, tempcon
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
240 tempcon
= (cupsd_client_t
*)cupsArrayNext(Clients
))
241 if (httpAddrEqual(tempcon
->http
.hostaddr
, con
->http
.hostaddr
))
244 if (count
>= MaxClientsPerHost
)
248 if (count
>= MaxClientsPerHost
)
250 if ((time(NULL
) - last_dos
) >= 60)
252 last_dos
= time(NULL
);
253 cupsdLogMessage(CUPSD_LOG_WARN
,
254 "Possible DoS attack - more than %d clients connecting "
257 httpAddrString(con
->http
.hostaddr
, con
->http
.hostname
,
258 sizeof(con
->http
.hostname
)));
262 closesocket(con
->http
.fd
);
272 * Get the hostname or format the IP address as needed...
275 if (httpAddrLocalhost(con
->http
.hostaddr
))
278 * Map accesses from the loopback interface to "localhost"...
281 strlcpy(con
->http
.hostname
, "localhost", sizeof(con
->http
.hostname
));
282 hostname
= con
->http
.hostname
;
287 * Map accesses from the same host to the server name.
291 hostname
= httpAddrLookup(con
->http
.hostaddr
, con
->http
.hostname
,
292 sizeof(con
->http
.hostname
));
296 httpAddrString(con
->http
.hostaddr
, con
->http
.hostname
,
297 sizeof(con
->http
.hostname
));
301 if (hostname
== NULL
&& HostNameLookups
== 2)
304 * Can't have an unresolved IP address with double-lookups enabled...
308 closesocket(con
->http
.fd
);
313 cupsdLogMessage(CUPSD_LOG_WARN
,
314 "Name lookup failed - connection from %s closed!",
321 if (HostNameLookups
== 2)
324 * Do double lookups as needed...
327 if ((addrlist
= httpAddrGetList(con
->http
.hostname
, AF_UNSPEC
, NULL
))
331 * See if the hostname maps to the same IP address...
334 for (addr
= addrlist
; addr
; addr
= addr
->next
)
335 if (httpAddrEqual(con
->http
.hostaddr
, &(addr
->addr
)))
341 httpAddrFreeList(addrlist
);
346 * Can't have a hostname that doesn't resolve to the same IP address
347 * with double-lookups enabled...
351 closesocket(con
->http
.fd
);
356 cupsdLogMessage(CUPSD_LOG_WARN
,
357 "IP lookup failed - connection from %s closed!",
366 * See if the connection is denied by TCP wrappers...
369 request_init(&wrap_req
, RQ_DAEMON
, "cupsd", RQ_FILE
, con
->http
.fd
, NULL
);
372 if (!hosts_access(&wrap_req
))
375 closesocket(con
->http
.fd
);
380 cupsdLogMessage(CUPSD_LOG_WARN
,
381 "Connection from %s refused by /etc/hosts.allow and "
382 "/etc/hosts.deny rules.", con
->http
.hostname
);
386 #endif /* HAVE_TCPD_H */
389 if (con
->http
.hostaddr
->addr
.sa_family
== AF_INET6
)
390 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdAcceptClient: %d from %s:%d (IPv6)",
391 con
->http
.fd
, con
->http
.hostname
,
392 ntohs(con
->http
.hostaddr
->ipv6
.sin6_port
));
394 #endif /* AF_INET6 */
396 if (con
->http
.hostaddr
->addr
.sa_family
== AF_LOCAL
)
397 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdAcceptClient: %d from %s (Domain)",
398 con
->http
.fd
, con
->http
.hostname
);
400 #endif /* AF_LOCAL */
401 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdAcceptClient: %d from %s:%d (IPv4)",
402 con
->http
.fd
, con
->http
.hostname
,
403 ntohs(con
->http
.hostaddr
->ipv4
.sin_port
));
406 * Get the local address the client connected to...
409 addrlen
= sizeof(temp
);
410 if (getsockname(con
->http
.fd
, (struct sockaddr
*)&temp
, &addrlen
))
412 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to get local address - %s",
415 strcpy(con
->servername
, "localhost");
416 con
->serverport
= LocalPort
;
421 if (temp
.addr
.sa_family
== AF_INET6
)
423 if (httpAddrLocalhost(&temp
))
424 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
425 else if (HostNameLookups
|| RemoteAccessEnabled
)
426 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
428 httpAddrString(&temp
, con
->servername
, sizeof(con
->servername
));
430 con
->serverport
= ntohs(lis
->address
.ipv6
.sin6_port
);
433 #endif /* AF_INET6 */
434 if (temp
.addr
.sa_family
== AF_INET
)
436 if (httpAddrLocalhost(&temp
))
437 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
438 else if (HostNameLookups
|| RemoteAccessEnabled
)
439 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
441 httpAddrString(&temp
, con
->servername
, sizeof(con
->servername
));
443 con
->serverport
= ntohs(lis
->address
.ipv4
.sin_port
);
447 strcpy(con
->servername
, "localhost");
448 con
->serverport
= LocalPort
;
452 cupsArrayAdd(Clients
, con
);
455 * Using TCP_NODELAY improves responsiveness, especially on systems with a slow
456 * loopback interface. Since we write large buffers when sending print files
457 * and requests there shouldn't be any performance penalty for this...
461 setsockopt(con
->http
.fd
, IPPROTO_TCP
, TCP_NODELAY
, &val
, sizeof(val
));
464 * Close this file on all execs...
467 fcntl(con
->http
.fd
, F_SETFD
, fcntl(con
->http
.fd
, F_GETFD
) | FD_CLOEXEC
);
470 * Add the socket to the server select.
473 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
476 * Temporarily suspend accept()'s until we lose a client...
479 if (cupsArrayCount(Clients
) == MaxClients
)
480 cupsdPauseListening();
484 * See if we are connecting on a secure port...
487 if (lis
->encryption
== HTTP_ENCRYPT_ALWAYS
)
490 * https connection; go secure...
493 con
->http
.encryption
= HTTP_ENCRYPT_ALWAYS
;
495 if (!encrypt_client(con
))
496 cupsdCloseClient(con
);
500 #endif /* HAVE_SSL */
505 * 'cupsdCloseAllClients()' - Close all remote clients immediately.
509 cupsdCloseAllClients(void)
511 cupsd_client_t
*con
; /* Current client */
514 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdCloseAllClients() Clients=%d",
515 cupsArrayCount(Clients
));
517 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
519 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
520 if (cupsdCloseClient(con
))
521 cupsdCloseClient(con
);
526 * 'cupsdCloseClient()' - Close a remote client.
529 int /* O - 1 if partial close, 0 if fully closed */
530 cupsdCloseClient(cupsd_client_t
*con
) /* I - Client to close */
532 int partial
; /* Do partial close for SSL? */
534 SSL_CTX
*context
; /* Context for encryption */
535 SSL
*conn
; /* Connection for encryption */
536 unsigned long error
; /* Error code */
537 #elif defined(HAVE_GNUTLS)
538 http_tls_t
*conn
; /* TLS connection information */
539 int error
; /* Error code */
540 gnutls_certificate_server_credentials
*credentials
;
541 /* TLS credentials */
542 # elif defined(HAVE_CDSASSL)
543 http_tls_t
*conn
; /* CDSA connection information */
544 #endif /* HAVE_LIBSSL */
547 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdCloseClient(con=%p(%d))", con
,
551 * Flush pending writes before closing...
554 httpFlushWrite(HTTP(con
));
560 * Shutdown encryption as needed...
568 conn
= (SSL
*)(con
->http
.tls
);
569 context
= SSL_get_SSL_CTX(conn
);
571 switch (SSL_shutdown(conn
))
574 cupsdLogMessage(CUPSD_LOG_DEBUG
,
575 "SSL shutdown successful!");
578 cupsdLogMessage(CUPSD_LOG_ERROR
,
579 "Fatal error during SSL shutdown!");
581 while ((error
= ERR_get_error()) != 0)
582 cupsdLogMessage(CUPSD_LOG_ERROR
, "SSL shutdown failed: %s",
583 ERR_error_string(error
, NULL
));
587 SSL_CTX_free(context
);
590 # elif defined(HAVE_GNUTLS)
591 conn
= (http_tls_t
*)(con
->http
.tls
);
592 credentials
= (gnutls_certificate_server_credentials
*)(conn
->credentials
);
594 error
= gnutls_bye(conn
->session
, GNUTLS_SHUT_WR
);
597 case GNUTLS_E_SUCCESS
:
598 cupsdLogMessage(CUPSD_LOG_DEBUG
,
599 "SSL shutdown successful!");
602 cupsdLogMessage(CUPSD_LOG_ERROR
,
603 "SSL shutdown failed: %s", gnutls_strerror(error
));
607 gnutls_deinit(conn
->session
);
608 gnutls_certificate_free_credentials(*credentials
);
612 # elif defined(HAVE_CDSASSL)
613 conn
= (http_tls_t
*)(con
->http
.tls
);
615 while (SSLClose(conn
->session
) == errSSLWouldBlock
)
618 SSLDisposeContext(conn
->session
);
620 if (conn
->certsArray
)
621 CFRelease(conn
->certsArray
);
624 # endif /* HAVE_LIBSSL */
626 con
->http
.tls
= NULL
;
628 #endif /* HAVE_SSL */
630 if (con
->pipe_pid
!= 0)
633 * Stop any CGI process...
636 cupsdEndProcess(con
->pipe_pid
, 1);
642 cupsdRemoveSelect(con
->file
);
649 * Close the socket and clear the file from the input set for select()...
652 if (con
->http
.fd
>= 0)
654 cupsArrayRemove(ActiveClients
, con
);
660 * Only do a partial close so that the encrypted client gets everything.
663 shutdown(con
->http
.fd
, 0);
664 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
669 * Shut the socket down fully...
672 cupsdRemoveSelect(con
->http
.fd
);
684 if (con
->http
.input_set
)
685 free(con
->http
.input_set
);
687 httpClearCookie(HTTP(con
));
688 httpClearFields(HTTP(con
));
690 cupsdClearString(&con
->filename
);
691 cupsdClearString(&con
->command
);
692 cupsdClearString(&con
->options
);
693 cupsdClearString(&con
->query_string
);
697 ippDelete(con
->request
);
703 ippDelete(con
->response
);
704 con
->response
= NULL
;
709 cupsLangFree(con
->language
);
710 con
->language
= NULL
;
713 #ifdef HAVE_AUTHORIZATION_H
716 AuthorizationFree(con
->authref
, kAuthorizationFlagDefaults
);
719 #endif /* HAVE_AUTHORIZATION_H */
722 * Re-enable new client connections if we are going back under the
726 if (cupsArrayCount(Clients
) == MaxClients
)
727 cupsdResumeListening();
730 * Compact the list of clients as necessary...
733 cupsArrayRemove(Clients
, con
);
743 * 'cupsdFlushHeader()' - Flush the header fields to the client.
746 int /* I - Bytes written or -1 on error */
747 cupsdFlushHeader(cupsd_client_t
*con
) /* I - Client to flush to */
749 int bytes
= httpFlushWrite(HTTP(con
));
751 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
758 * 'cupsdReadClient()' - Read data from a client.
762 cupsdReadClient(cupsd_client_t
*con
) /* I - Client to read from */
764 char line
[32768], /* Line from client... */
765 operation
[64], /* Operation code from socket */
766 version
[64], /* HTTP version number string */
767 locale
[64], /* Locale */
768 *ptr
; /* Pointer into strings */
769 int major
, minor
; /* HTTP version numbers */
770 http_status_t status
; /* Transfer status */
771 ipp_state_t ipp_state
; /* State of IPP transfer */
772 int bytes
; /* Number of bytes to POST */
773 char *filename
; /* Name of file for GET/HEAD */
774 char buf
[1024]; /* Buffer for real filename */
775 struct stat filestats
; /* File information */
776 mime_type_t
*type
; /* MIME type of file */
777 cupsd_printer_t
*p
; /* Printer */
778 static unsigned request_id
= 0; /* Request ID for temp files */
781 status
= HTTP_CONTINUE
;
783 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
784 "cupsdReadClient(con=%p(%d)) "
785 "con->http.error=%d "
786 "con->http.used=%d, "
787 "con->http.state=%d "
788 "con->data_encoding=HTTP_ENCODE_%s, "
789 "con->data_remaining=" CUPS_LLFMT
", "
791 con
, con
->http
.fd
, con
->http
.error
, con
->http
.used
,
793 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
?
794 "CHUNKED" : "LENGTH",
795 CUPS_LLCAST con
->http
.data_remaining
, con
->file
);
799 cupsdCloseClient(con
);
807 * Automatically check for a SSL/TLS handshake...
812 if (recv(con
->http
.fd
, buf
, 1, MSG_PEEK
) == 1 &&
813 (!buf
[0] || !strchr("DGHOPT", buf
[0])))
816 * Encrypt this connection...
819 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
820 "cupsdReadClient: Saw first byte %02X, auto-negotiating "
821 "SSL/TLS session...", buf
[0] & 255);
823 if (!encrypt_client(con
))
824 cupsdCloseClient(con
);
829 #endif /* HAVE_SSL */
831 switch (con
->http
.state
)
835 * See if we've received a request line...
838 if (httpGets(line
, sizeof(line
) - 1, HTTP(con
)) == NULL
)
840 cupsdCloseClient(con
);
845 * Ignore blank request lines...
852 * Clear other state variables...
855 httpClearFields(HTTP(con
));
857 con
->http
.activity
= time(NULL
);
858 con
->http
.version
= HTTP_1_0
;
859 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
860 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
861 con
->http
.data_remaining
= 0;
862 con
->http
._data_remaining
= 0;
863 con
->operation
= HTTP_WAITING
;
868 con
->username
[0] = '\0';
869 con
->password
[0] = '\0';
872 cupsdClearString(&con
->command
);
873 cupsdClearString(&con
->options
);
874 cupsdClearString(&con
->query_string
);
878 ippDelete(con
->request
);
884 ippDelete(con
->response
);
885 con
->response
= NULL
;
890 cupsLangFree(con
->language
);
891 con
->language
= NULL
;
896 OM_uint32 minor_status
;
897 gss_release_cred(&minor_status
, &con
->gss_creds
);
899 #endif /* HAVE_GSSAPI */
902 * Grab the request line...
905 switch (sscanf(line
, "%63s%1023s%63s", operation
, con
->uri
, version
))
910 cupsdLogMessage(CUPSD_LOG_ERROR
,
911 "Bad request line \"%s\" from %s!", line
,
913 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
914 cupsdCloseClient(con
);
918 con
->http
.version
= HTTP_0_9
;
921 if (sscanf(version
, "HTTP/%d.%d", &major
, &minor
) != 2)
923 cupsdLogMessage(CUPSD_LOG_ERROR
,
924 "Bad request line \"%s\" from %s!", line
,
926 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
927 cupsdCloseClient(con
);
933 con
->http
.version
= (http_version_t
)(major
* 100 + minor
);
934 if (con
->http
.version
== HTTP_1_1
&& KeepAlive
)
935 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
937 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
941 cupsdSendError(con
, HTTP_NOT_SUPPORTED
, CUPSD_AUTH_NONE
);
942 cupsdCloseClient(con
);
949 * Handle full URLs in the request line...
952 if (strcmp(con
->uri
, "*"))
954 char scheme
[HTTP_MAX_URI
], /* Method/scheme */
955 userpass
[HTTP_MAX_URI
], /* Username:password */
956 hostname
[HTTP_MAX_URI
], /* Hostname */
957 resource
[HTTP_MAX_URI
]; /* Resource path */
958 int port
; /* Port number */
962 * Separate the URI into its components...
965 httpSeparateURI(HTTP_URI_CODING_MOST
, con
->uri
,
966 scheme
, sizeof(scheme
),
967 userpass
, sizeof(userpass
),
968 hostname
, sizeof(hostname
), &port
,
969 resource
, sizeof(resource
));
972 * Only allow URIs with the servername, localhost, or an IP
976 if (strcmp(scheme
, "file") &&
977 strcasecmp(hostname
, ServerName
) &&
978 strcasecmp(hostname
, "localhost") &&
979 !isdigit(hostname
[0]) && hostname
[0] != '[')
982 * Nope, we don't do proxies...
985 cupsdLogMessage(CUPSD_LOG_ERROR
, "Bad URI \"%s\" in request!",
987 cupsdSendError(con
, HTTP_METHOD_NOT_ALLOWED
, CUPSD_AUTH_NONE
);
988 cupsdCloseClient(con
);
993 * Copy the resource portion back into the URI; both resource and
994 * con->uri are HTTP_MAX_URI bytes in size...
997 strcpy(con
->uri
, resource
);
1001 * Process the request...
1004 if (!strcmp(operation
, "GET"))
1005 con
->http
.state
= HTTP_GET
;
1006 else if (!strcmp(operation
, "PUT"))
1007 con
->http
.state
= HTTP_PUT
;
1008 else if (!strcmp(operation
, "POST"))
1009 con
->http
.state
= HTTP_POST
;
1010 else if (!strcmp(operation
, "DELETE"))
1011 con
->http
.state
= HTTP_DELETE
;
1012 else if (!strcmp(operation
, "TRACE"))
1013 con
->http
.state
= HTTP_TRACE
;
1014 else if (!strcmp(operation
, "OPTIONS"))
1015 con
->http
.state
= HTTP_OPTIONS
;
1016 else if (!strcmp(operation
, "HEAD"))
1017 con
->http
.state
= HTTP_HEAD
;
1020 cupsdLogMessage(CUPSD_LOG_ERROR
, "Bad operation \"%s\"!", operation
);
1021 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
1022 cupsdCloseClient(con
);
1026 gettimeofday(&(con
->start
), NULL
);
1027 con
->operation
= con
->http
.state
;
1029 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdReadClient: %d %s %s HTTP/%d.%d",
1030 con
->http
.fd
, operation
, con
->uri
,
1031 con
->http
.version
/ 100, con
->http
.version
% 100);
1033 con
->http
.status
= HTTP_OK
;
1035 if (!cupsArrayFind(ActiveClients
, con
))
1037 cupsArrayAdd(ActiveClients
, con
);
1038 cupsdSetBusyState();
1049 * Parse incoming parameters until the status changes...
1052 while ((status
= httpUpdate(HTTP(con
))) == HTTP_CONTINUE
)
1053 if (!data_ready(con
))
1056 if (status
!= HTTP_OK
&& status
!= HTTP_CONTINUE
)
1058 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
1059 cupsdCloseClient(con
);
1065 if (!data_ready(con
) && recv(con
->http
.fd
, buf
, 1, MSG_PEEK
) < 1)
1068 * Connection closed...
1071 cupsdCloseClient(con
);
1074 break; /* Anti-compiler-warning-code */
1078 * Handle new transfers...
1081 if (status
== HTTP_OK
)
1083 if (con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
][0])
1086 * Figure out the locale from the Accept-Language and Content-Type
1090 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ',')) != NULL
)
1093 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ';')) != NULL
)
1096 if ((ptr
= strstr(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
], "charset=")) != NULL
)
1099 * Combine language and charset, and trim any extra params in the
1103 snprintf(locale
, sizeof(locale
), "%s.%s",
1104 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ptr
+ 8);
1106 if ((ptr
= strchr(locale
, ',')) != NULL
)
1110 snprintf(locale
, sizeof(locale
), "%s.%s",
1111 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], DefaultCharset
);
1113 con
->language
= cupsLangGet(locale
);
1116 con
->language
= cupsLangGet(DefaultLocale
);
1118 cupsdAuthorize(con
);
1120 if (!strncasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Keep-Alive", 10) &&
1122 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
1123 else if (!strncasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "close", 5))
1124 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1126 if (!con
->http
.fields
[HTTP_FIELD_HOST
][0] &&
1127 con
->http
.version
>= HTTP_1_1
)
1130 * HTTP/1.1 and higher require the "Host:" field...
1133 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1135 cupsdCloseClient(con
);
1139 else if (!valid_host(con
))
1142 * Access to localhost must use "localhost" or the corresponding IPv4
1143 * or IPv6 values in the Host: field.
1146 cupsdLogMessage(CUPSD_LOG_WARN
,
1147 "Request from \"%s\" using invalid Host: field \"%s\"",
1148 con
->http
.hostname
, con
->http
.fields
[HTTP_FIELD_HOST
]);
1150 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1152 cupsdCloseClient(con
);
1156 else if (con
->operation
== HTTP_OPTIONS
)
1159 * Do OPTIONS command...
1162 if (con
->best
&& con
->best
->type
!= CUPSD_AUTH_NONE
)
1164 if (!cupsdSendHeader(con
, HTTP_UNAUTHORIZED
, NULL
, CUPSD_AUTH_NONE
))
1166 cupsdCloseClient(con
);
1171 if (!strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") &&
1172 con
->http
.tls
== NULL
)
1176 * Do encryption stuff...
1179 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
, CUPSD_AUTH_NONE
))
1181 cupsdCloseClient(con
);
1185 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1186 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1187 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1188 httpPrintf(HTTP(con
), "\r\n");
1190 if (cupsdFlushHeader(con
) < 0)
1192 cupsdCloseClient(con
);
1196 if (!encrypt_client(con
))
1198 cupsdCloseClient(con
);
1202 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
1204 cupsdCloseClient(con
);
1207 #endif /* HAVE_SSL */
1210 if (!cupsdSendHeader(con
, HTTP_OK
, NULL
, CUPSD_AUTH_NONE
))
1212 cupsdCloseClient(con
);
1216 httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n");
1217 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1218 httpPrintf(HTTP(con
), "\r\n");
1220 if (cupsdFlushHeader(con
) < 0)
1222 cupsdCloseClient(con
);
1226 else if (!is_path_absolute(con
->uri
))
1229 * Protect against malicious users!
1232 cupsdLogMessage(CUPSD_LOG_ERROR
,
1233 "Request for non-absolute resource \"%s\"!", con
->uri
);
1235 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1237 cupsdCloseClient(con
);
1243 if (!strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") &&
1244 con
->http
.tls
== NULL
)
1248 * Do encryption stuff...
1251 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
, CUPSD_AUTH_NONE
))
1253 cupsdCloseClient(con
);
1257 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1258 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1259 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1260 httpPrintf(HTTP(con
), "\r\n");
1262 if (cupsdFlushHeader(con
) < 0)
1264 cupsdCloseClient(con
);
1268 if (!encrypt_client(con
))
1270 cupsdCloseClient(con
);
1274 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
1276 cupsdCloseClient(con
);
1279 #endif /* HAVE_SSL */
1282 if ((status
= cupsdIsAuthorized(con
, NULL
)) != HTTP_OK
)
1284 cupsdSendError(con
, status
, CUPSD_AUTH_NONE
);
1285 cupsdCloseClient(con
);
1289 if (con
->http
.expect
&&
1290 (con
->operation
== HTTP_POST
|| con
->operation
== HTTP_PUT
))
1292 if (con
->http
.expect
== HTTP_CONTINUE
)
1295 * Send 100-continue header...
1298 if (!cupsdSendHeader(con
, HTTP_CONTINUE
, NULL
, CUPSD_AUTH_NONE
))
1300 cupsdCloseClient(con
);
1307 * Send 417-expectation-failed header...
1310 if (!cupsdSendHeader(con
, HTTP_EXPECTATION_FAILED
, NULL
, CUPSD_AUTH_NONE
))
1312 cupsdCloseClient(con
);
1316 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1317 httpPrintf(HTTP(con
), "\r\n");
1319 if (cupsdFlushHeader(con
) < 0)
1321 cupsdCloseClient(con
);
1327 switch (con
->http
.state
)
1329 case HTTP_GET_SEND
:
1330 if (!strncmp(con
->uri
, "/printers/", 10) &&
1331 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1334 * Send PPD file - get the real printer name since printer
1335 * names are not case sensitive but filenames can be...
1338 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1340 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1341 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1344 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1346 cupsdCloseClient(con
);
1354 if ((!strncmp(con
->uri
, "/admin", 6) &&
1355 strncmp(con
->uri
, "/admin/conf/", 12) &&
1356 strncmp(con
->uri
, "/admin/log/", 11)) ||
1357 !strncmp(con
->uri
, "/printers", 9) ||
1358 !strncmp(con
->uri
, "/classes", 8) ||
1359 !strncmp(con
->uri
, "/help", 5) ||
1360 !strncmp(con
->uri
, "/jobs", 5))
1363 * Send CGI output...
1366 if (!strncmp(con
->uri
, "/admin", 6))
1368 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1371 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1373 else if (!strncmp(con
->uri
, "/printers", 9))
1375 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1378 if (con
->uri
[9] && con
->uri
[10])
1379 cupsdSetString(&con
->options
, con
->uri
+ 9);
1381 cupsdSetString(&con
->options
, NULL
);
1383 else if (!strncmp(con
->uri
, "/classes", 8))
1385 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1388 if (con
->uri
[8] && con
->uri
[9])
1389 cupsdSetString(&con
->options
, con
->uri
+ 8);
1391 cupsdSetString(&con
->options
, NULL
);
1393 else if (!strncmp(con
->uri
, "/jobs", 5))
1395 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1398 if (con
->uri
[5] && con
->uri
[6])
1399 cupsdSetString(&con
->options
, con
->uri
+ 5);
1401 cupsdSetString(&con
->options
, NULL
);
1405 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1408 if (con
->uri
[5] && con
->uri
[6])
1409 cupsdSetString(&con
->options
, con
->uri
+ 5);
1411 cupsdSetString(&con
->options
, NULL
);
1414 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1416 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1418 cupsdCloseClient(con
);
1423 cupsdLogRequest(con
, HTTP_OK
);
1425 if (con
->http
.version
<= HTTP_1_0
)
1426 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1428 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1429 (strchr(con
->uri
+ 12, '/') ||
1430 strlen(con
->uri
) == 12)) ||
1431 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1432 (strchr(con
->uri
+ 11, '/') ||
1433 strlen(con
->uri
) == 11)))
1436 * GET can only be done to configuration files directly under
1440 cupsdLogMessage(CUPSD_LOG_ERROR
,
1441 "Request for subdirectory \"%s\"!", con
->uri
);
1443 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1445 cupsdCloseClient(con
);
1457 if ((filename
= get_file(con
, &filestats
, buf
,
1458 sizeof(buf
))) == NULL
)
1460 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1462 cupsdCloseClient(con
);
1469 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1471 if (is_cgi(con
, filename
, &filestats
, type
))
1474 * Note: con->command and con->options were set by
1478 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1480 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1482 cupsdCloseClient(con
);
1487 cupsdLogRequest(con
, HTTP_OK
);
1489 if (con
->http
.version
<= HTTP_1_0
)
1490 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1494 if (!check_if_modified(con
, &filestats
))
1496 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1498 cupsdCloseClient(con
);
1505 strcpy(line
, "text/plain");
1507 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1509 if (!write_file(con
, HTTP_OK
, filename
, line
, &filestats
))
1511 cupsdCloseClient(con
);
1518 case HTTP_POST_RECV
:
1520 * See if the POST request includes a Content-Length field, and if
1521 * so check the length against any limits that are set...
1524 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1525 MaxRequestSize
> 0 &&
1526 con
->http
.data_remaining
> MaxRequestSize
)
1529 * Request too large...
1532 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1534 cupsdCloseClient(con
);
1540 else if (con
->http
.data_remaining
< 0 ||
1541 (!con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1542 con
->http
.data_encoding
== HTTP_ENCODE_LENGTH
))
1545 * Negative content lengths are invalid!
1548 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1550 cupsdCloseClient(con
);
1558 * See what kind of POST request this is; for IPP requests the
1559 * content-type field will be "application/ipp"...
1562 if (!strcmp(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
],
1564 con
->request
= ippNew();
1565 else if ((!strncmp(con
->uri
, "/admin", 6) &&
1566 strncmp(con
->uri
, "/admin/conf/", 12) &&
1567 strncmp(con
->uri
, "/admin/log/", 11)) ||
1568 !strncmp(con
->uri
, "/printers", 9) ||
1569 !strncmp(con
->uri
, "/classes", 8) ||
1570 !strncmp(con
->uri
, "/help", 5) ||
1571 !strncmp(con
->uri
, "/jobs", 5))
1577 if (!strncmp(con
->uri
, "/admin", 6))
1579 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1582 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1584 else if (!strncmp(con
->uri
, "/printers", 9))
1586 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1589 if (con
->uri
[9] && con
->uri
[10])
1590 cupsdSetString(&con
->options
, con
->uri
+ 9);
1592 cupsdSetString(&con
->options
, NULL
);
1594 else if (!strncmp(con
->uri
, "/classes", 8))
1596 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1599 if (con
->uri
[8] && con
->uri
[9])
1600 cupsdSetString(&con
->options
, con
->uri
+ 8);
1602 cupsdSetString(&con
->options
, NULL
);
1604 else if (!strncmp(con
->uri
, "/jobs", 5))
1606 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1609 if (con
->uri
[5] && con
->uri
[6])
1610 cupsdSetString(&con
->options
, con
->uri
+ 5);
1612 cupsdSetString(&con
->options
, NULL
);
1616 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1619 if (con
->uri
[5] && con
->uri
[6])
1620 cupsdSetString(&con
->options
, con
->uri
+ 5);
1622 cupsdSetString(&con
->options
, NULL
);
1625 if (con
->http
.version
<= HTTP_1_0
)
1626 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1634 if ((filename
= get_file(con
, &filestats
, buf
,
1635 sizeof(buf
))) == NULL
)
1637 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1639 cupsdCloseClient(con
);
1646 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1648 if (!is_cgi(con
, filename
, &filestats
, type
))
1651 * Only POST to CGI's...
1654 if (!cupsdSendError(con
, HTTP_UNAUTHORIZED
, CUPSD_AUTH_NONE
))
1656 cupsdCloseClient(con
);
1663 case HTTP_PUT_RECV
:
1665 * Validate the resource name...
1668 if (strncmp(con
->uri
, "/admin/conf/", 12) ||
1669 strchr(con
->uri
+ 12, '/') ||
1670 strlen(con
->uri
) == 12)
1673 * PUT can only be done to configuration files under
1677 cupsdLogMessage(CUPSD_LOG_ERROR
,
1678 "Request for subdirectory \"%s\"!", con
->uri
);
1680 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1682 cupsdCloseClient(con
);
1690 * See if the PUT request includes a Content-Length field, and if
1691 * so check the length against any limits that are set...
1694 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1695 MaxRequestSize
> 0 &&
1696 con
->http
.data_remaining
> MaxRequestSize
)
1699 * Request too large...
1702 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1704 cupsdCloseClient(con
);
1710 else if (con
->http
.data_remaining
< 0)
1713 * Negative content lengths are invalid!
1716 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1718 cupsdCloseClient(con
);
1726 * Open a temporary file to hold the request...
1729 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
1731 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1735 cupsdLogMessage(CUPSD_LOG_ERROR
,
1736 "Unable to create request file %s: %s",
1737 con
->filename
, strerror(errno
));
1739 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1741 cupsdCloseClient(con
);
1746 fchmod(con
->file
, 0640);
1747 fchown(con
->file
, RunUser
, Group
);
1748 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1753 cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
);
1754 cupsdCloseClient(con
);
1758 if (!strncmp(con
->uri
, "/printers/", 10) &&
1759 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1762 * Send PPD file - get the real printer name since printer
1763 * names are not case sensitive but filenames can be...
1766 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1768 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1769 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1772 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1774 cupsdCloseClient(con
);
1782 if ((!strncmp(con
->uri
, "/admin", 6) &&
1783 strncmp(con
->uri
, "/admin/conf/", 12) &&
1784 strncmp(con
->uri
, "/admin/log/", 11)) ||
1785 !strncmp(con
->uri
, "/printers", 9) ||
1786 !strncmp(con
->uri
, "/classes", 8) ||
1787 !strncmp(con
->uri
, "/help", 5) ||
1788 !strncmp(con
->uri
, "/jobs", 5))
1794 if (!cupsdSendHeader(con
, HTTP_OK
, "text/html", CUPSD_AUTH_NONE
))
1796 cupsdCloseClient(con
);
1800 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1802 cupsdCloseClient(con
);
1806 if (cupsdFlushHeader(con
) < 0)
1808 cupsdCloseClient(con
);
1812 cupsdLogRequest(con
, HTTP_OK
);
1814 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1815 (strchr(con
->uri
+ 12, '/') ||
1816 strlen(con
->uri
) == 12)) ||
1817 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1818 (strchr(con
->uri
+ 11, '/') ||
1819 strlen(con
->uri
) == 11)))
1822 * HEAD can only be done to configuration files under
1826 cupsdLogMessage(CUPSD_LOG_ERROR
,
1827 "Request for subdirectory \"%s\"!", con
->uri
);
1829 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1831 cupsdCloseClient(con
);
1837 else if ((filename
= get_file(con
, &filestats
, buf
,
1838 sizeof(buf
))) == NULL
)
1840 if (!cupsdSendHeader(con
, HTTP_NOT_FOUND
, "text/html", CUPSD_AUTH_NONE
))
1842 cupsdCloseClient(con
);
1846 cupsdLogRequest(con
, HTTP_NOT_FOUND
);
1848 else if (!check_if_modified(con
, &filestats
))
1850 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1852 cupsdCloseClient(con
);
1856 cupsdLogRequest(con
, HTTP_NOT_MODIFIED
);
1864 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1866 strcpy(line
, "text/plain");
1868 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1870 if (!cupsdSendHeader(con
, HTTP_OK
, line
, CUPSD_AUTH_NONE
))
1872 cupsdCloseClient(con
);
1876 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
1877 httpGetDateString(filestats
.st_mtime
)) < 0)
1879 cupsdCloseClient(con
);
1883 if (httpPrintf(HTTP(con
), "Content-Length: %lu\r\n",
1884 (unsigned long)filestats
.st_size
) < 0)
1886 cupsdCloseClient(con
);
1890 cupsdLogRequest(con
, HTTP_OK
);
1893 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1895 cupsdCloseClient(con
);
1899 if (cupsdFlushHeader(con
) < 0)
1901 cupsdCloseClient(con
);
1905 con
->http
.state
= HTTP_WAITING
;
1909 break; /* Anti-compiler-warning-code */
1915 * Handle any incoming data...
1918 switch (con
->http
.state
)
1920 case HTTP_PUT_RECV
:
1923 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
1925 cupsdCloseClient(con
);
1930 con
->bytes
+= bytes
;
1932 if (write(con
->file
, line
, bytes
) < bytes
)
1934 cupsdLogMessage(CUPSD_LOG_ERROR
,
1935 "cupsdReadClient: Unable to write %d bytes to %s: %s",
1936 bytes
, con
->filename
, strerror(errno
));
1940 unlink(con
->filename
);
1941 cupsdClearString(&con
->filename
);
1943 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1945 cupsdCloseClient(con
);
1951 while (con
->http
.state
== HTTP_PUT_RECV
&& data_ready(con
));
1953 if (con
->http
.state
== HTTP_WAITING
)
1956 * End of file, see how big it is...
1959 fstat(con
->file
, &filestats
);
1964 if (filestats
.st_size
> MaxRequestSize
&&
1968 * Request is too big; remove it and send an error...
1971 unlink(con
->filename
);
1972 cupsdClearString(&con
->filename
);
1974 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1976 cupsdCloseClient(con
);
1982 * Install the configuration file...
1985 status
= install_conf_file(con
);
1988 * Return the status to the client...
1991 if (!cupsdSendError(con
, status
, CUPSD_AUTH_NONE
))
1993 cupsdCloseClient(con
);
1999 case HTTP_POST_RECV
:
2005 * Grab any request data from the connection...
2008 if ((ipp_state
= ippRead(&(con
->http
), con
->request
)) == IPP_ERROR
)
2010 cupsdLogMessage(CUPSD_LOG_ERROR
,
2011 "cupsdReadClient: %d IPP Read Error!",
2014 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
2015 cupsdCloseClient(con
);
2018 else if (ipp_state
!= IPP_DATA
)
2020 if (con
->http
.state
== HTTP_POST_SEND
)
2022 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
2023 cupsdCloseClient(con
);
2030 con
->bytes
+= ippLength(con
->request
);
2033 if (con
->file
< 0 && con
->http
.state
!= HTTP_POST_SEND
)
2036 * Create a file as needed for the request data...
2039 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
, request_id
++);
2040 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
2044 cupsdLogMessage(CUPSD_LOG_ERROR
,
2045 "Unable to create request file %s: %s",
2046 con
->filename
, strerror(errno
));
2048 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2050 cupsdCloseClient(con
);
2055 fchmod(con
->file
, 0640);
2056 fchown(con
->file
, RunUser
, Group
);
2057 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2060 if (con
->http
.state
!= HTTP_POST_SEND
)
2062 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
2064 cupsdCloseClient(con
);
2069 con
->bytes
+= bytes
;
2071 if (write(con
->file
, line
, bytes
) < bytes
)
2073 cupsdLogMessage(CUPSD_LOG_ERROR
,
2074 "cupsdReadClient: Unable to write %d bytes to %s: %s",
2075 bytes
, con
->filename
, strerror(errno
));
2079 unlink(con
->filename
);
2080 cupsdClearString(&con
->filename
);
2082 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2084 cupsdCloseClient(con
);
2089 else if (con
->http
.state
== HTTP_POST_RECV
)
2091 else if (con
->http
.state
!= HTTP_POST_SEND
)
2093 cupsdCloseClient(con
);
2098 while (con
->http
.state
== HTTP_POST_RECV
&& data_ready(con
));
2100 if (con
->http
.state
== HTTP_POST_SEND
)
2104 fstat(con
->file
, &filestats
);
2109 if (filestats
.st_size
> MaxRequestSize
&&
2113 * Request is too big; remove it and send an error...
2116 unlink(con
->filename
);
2117 cupsdClearString(&con
->filename
);
2122 * Delete any IPP request data...
2125 ippDelete(con
->request
);
2126 con
->request
= NULL
;
2129 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2131 cupsdCloseClient(con
);
2138 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
2140 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
2142 cupsdCloseClient(con
);
2147 cupsdLogRequest(con
, HTTP_OK
);
2153 cupsdProcessIPPRequest(con
);
2157 unlink(con
->filename
);
2158 cupsdClearString(&con
->filename
);
2167 break; /* Anti-compiler-warning-code */
2170 if (con
->http
.state
== HTTP_WAITING
)
2172 if (!con
->http
.keep_alive
)
2173 cupsdCloseClient(con
);
2176 cupsArrayRemove(ActiveClients
, con
);
2177 cupsdSetBusyState();
2184 * 'cupsdSendCommand()' - Send output from a command via HTTP.
2187 int /* O - 1 on success, 0 on failure */
2189 cupsd_client_t
*con
, /* I - Client connection */
2190 char *command
, /* I - Command to run */
2191 char *options
, /* I - Command-line options */
2192 int root
) /* I - Run as root? */
2194 int fd
; /* Standard input file descriptor */
2199 fd
= open(con
->filename
, O_RDONLY
);
2203 cupsdLogMessage(CUPSD_LOG_ERROR
,
2204 "cupsdSendCommand: %d Unable to open \"%s\" for reading: %s",
2205 con
->http
.fd
, con
->filename
? con
->filename
: "/dev/null",
2210 fcntl(fd
, F_SETFD
, fcntl(fd
, F_GETFD
) | FD_CLOEXEC
);
2215 con
->pipe_pid
= pipe_command(con
, fd
, &(con
->file
), command
, options
, root
);
2220 cupsdLogMessage(CUPSD_LOG_INFO
, "Started \"%s\" (pid=%d)", command
,
2223 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendCommand: %d file=%d",
2224 con
->http
.fd
, con
->file
);
2226 if (con
->pipe_pid
== 0)
2229 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2231 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2233 con
->sent_header
= 0;
2234 con
->file_ready
= 0;
2235 con
->got_fields
= 0;
2243 * 'cupsdSendError()' - Send an error message via HTTP.
2246 int /* O - 1 if successful, 0 otherwise */
2247 cupsdSendError(cupsd_client_t
*con
, /* I - Connection */
2248 http_status_t code
, /* I - Error code */
2249 int auth_type
)/* I - Authentication type */
2251 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2252 "cupsdSendError(con=%p(%d), code=%d, auth_type=%d", con
,
2253 con
->http
.fd
, code
, auth_type
);
2257 * Force client to upgrade for authentication if that is how the
2258 * server is configured...
2261 if (code
== HTTP_UNAUTHORIZED
&&
2262 DefaultEncryption
== HTTP_ENCRYPT_REQUIRED
&&
2263 strcasecmp(con
->http
.hostname
, "localhost") &&
2266 code
= HTTP_UPGRADE_REQUIRED
;
2268 #endif /* HAVE_SSL */
2271 * Put the request in the access_log file...
2274 cupsdLogRequest(con
, code
);
2277 * To work around bugs in some proxies, don't use Keep-Alive for some
2280 * Kerberos authentication doesn't work without Keep-Alive, so
2281 * never disable it in that case.
2284 if (code
>= HTTP_BAD_REQUEST
&& con
->http
.auth_type
!= CUPSD_AUTH_NEGOTIATE
)
2285 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
2288 * Send an error message back to the client. If the error code is a
2289 * 400 or 500 series, make sure the message contains some text, too!
2292 if (!cupsdSendHeader(con
, code
, NULL
, auth_type
))
2296 if (code
== HTTP_UPGRADE_REQUIRED
)
2297 if (httpPrintf(HTTP(con
), "Connection: Upgrade\r\n") < 0)
2300 if (httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n") < 0)
2302 #endif /* HAVE_SSL */
2304 if (con
->http
.version
>= HTTP_1_1
&&
2305 con
->http
.keep_alive
== HTTP_KEEPALIVE_OFF
)
2307 if (httpPrintf(HTTP(con
), "Connection: close\r\n") < 0)
2311 if (code
>= HTTP_BAD_REQUEST
)
2314 * Send a human-readable error message.
2317 char message
[4096], /* Message for user */
2318 urltext
[1024], /* URL redirection text */
2319 redirect
[1024]; /* Redirection link */
2320 const char *text
; /* Status-specific text */
2325 if (code
== HTTP_UNAUTHORIZED
)
2326 text
= _cupsLangString(con
->language
,
2327 _("Enter your username and password or the "
2328 "root username and password to access this "
2329 "page. If you are using Kerberos authentication, "
2330 "make sure you have a valid Kerberos ticket."));
2331 else if (code
== HTTP_UPGRADE_REQUIRED
)
2335 snprintf(urltext
, sizeof(urltext
),
2336 _cupsLangString(con
->language
,
2337 _("You must access this page using the URL "
2338 "<A HREF=\"https://%s:%d%s\">"
2339 "https://%s:%d%s</A>.")),
2340 con
->servername
, con
->serverport
, con
->uri
,
2341 con
->servername
, con
->serverport
, con
->uri
);
2343 snprintf(redirect
, sizeof(redirect
),
2344 "<META HTTP-EQUIV=\"Refresh\" "
2345 "CONTENT=\"3;URL=https://%s:%d%s\">\n",
2346 con
->servername
, con
->serverport
, con
->uri
);
2351 snprintf(message
, sizeof(message
),
2352 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" "
2353 "\"http://www.w3.org/TR/html4/loose.dtd\">\n"
2356 "\t<META HTTP-EQUIV=\"Content-Type\" "
2357 "CONTENT=\"text/html; charset=utf-8\">\n"
2358 "\t<TITLE>%d %s</TITLE>\n"
2359 "\t<LINK REL=\"STYLESHEET\" TYPE=\"text/css\" "
2360 "HREF=\"/cups.css\">\n"
2368 code
, httpStatus(code
), redirect
, code
, httpStatus(code
), text
);
2370 if (httpPrintf(HTTP(con
), "Content-Type: text/html; charset=utf-8\r\n") < 0)
2372 if (httpPrintf(HTTP(con
), "Content-Length: %d\r\n",
2373 (int)strlen(message
)) < 0)
2375 if (httpPrintf(HTTP(con
), "\r\n") < 0)
2377 if (httpPrintf(HTTP(con
), "%s", message
) < 0)
2380 else if (httpPrintf(HTTP(con
), "\r\n") < 0)
2383 if (cupsdFlushHeader(con
) < 0)
2386 con
->http
.state
= HTTP_WAITING
;
2393 * 'cupsdSendHeader()' - Send an HTTP request.
2396 int /* O - 1 on success, 0 on failure */
2398 cupsd_client_t
*con
, /* I - Client to send to */
2399 http_status_t code
, /* I - HTTP status code */
2400 char *type
, /* I - MIME type of document */
2401 int auth_type
) /* I - Type of authentication */
2403 char auth_str
[1024]; /* Authorization string */
2405 static char *gss_buf
= NULL
; /* Kerberos auth data buffer */
2406 static int gss_bufsize
= 0; /* Size of Kerberos auth data buffer */
2407 #endif /* HAVE_GSSAPI */
2411 * Send the HTTP status header...
2414 if (code
== HTTP_CONTINUE
)
2417 * 100-continue doesn't send any headers...
2420 return (httpPrintf(HTTP(con
), "HTTP/%d.%d 100 Continue\r\n\r\n",
2421 con
->http
.version
/ 100, con
->http
.version
% 100) > 0);
2424 httpFlushWrite(HTTP(con
));
2426 con
->http
.data_encoding
= HTTP_ENCODE_FIELDS
;
2428 if (httpPrintf(HTTP(con
), "HTTP/%d.%d %d %s\r\n", con
->http
.version
/ 100,
2429 con
->http
.version
% 100, code
, httpStatus(code
)) < 0)
2431 if (httpPrintf(HTTP(con
), "Date: %s\r\n", httpGetDateString(time(NULL
))) < 0)
2434 if (httpPrintf(HTTP(con
), "Server: %s\r\n", ServerHeader
) < 0)
2436 if (con
->http
.keep_alive
&& con
->http
.version
>= HTTP_1_0
)
2438 if (httpPrintf(HTTP(con
), "Connection: Keep-Alive\r\n") < 0)
2440 if (httpPrintf(HTTP(con
), "Keep-Alive: timeout=%d\r\n",
2441 KeepAliveTimeout
) < 0)
2444 if (code
== HTTP_METHOD_NOT_ALLOWED
)
2445 if (httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n") < 0)
2448 if (code
== HTTP_UNAUTHORIZED
)
2450 if (auth_type
== CUPSD_AUTH_NONE
)
2452 if (!con
->best
|| con
->best
->type
<= CUPSD_AUTH_NONE
)
2453 auth_type
= DefaultAuthType
;
2455 auth_type
= con
->best
->type
;
2460 if (auth_type
== CUPSD_AUTH_BASIC
|| auth_type
== CUPSD_AUTH_BASICDIGEST
)
2461 strlcpy(auth_str
, "Basic realm=\"CUPS\"", sizeof(auth_str
));
2462 else if (auth_type
== CUPSD_AUTH_DIGEST
)
2463 snprintf(auth_str
, sizeof(auth_str
), "Digest realm=\"CUPS\", nonce=\"%s\"",
2464 con
->http
.hostname
);
2466 else if (auth_type
== CUPSD_AUTH_NEGOTIATE
&& con
->gss_output_token
.length
== 0)
2467 strlcpy(auth_str
, "Negotiate", sizeof(auth_str
));
2468 #endif /* HAVE_GSSAPI */
2470 if (con
->best
&& auth_type
!= CUPSD_AUTH_NEGOTIATE
&&
2471 !strcasecmp(con
->http
.hostname
, "localhost"))
2474 * Add a "trc" (try root certification) parameter for local non-Kerberos
2475 * requests when the request requires system group membership - then the
2476 * client knows the root certificate can/should be used.
2478 * Also, for Mac OS X we also look for @AUTHKEY and add an "authkey"
2479 * parameter as needed...
2482 int i
; /* Looping var */
2483 char *auth_key
; /* Auth key buffer */
2484 size_t auth_size
; /* Size of remaining buffer */
2486 auth_key
= auth_str
+ strlen(auth_str
);
2487 auth_size
= sizeof(auth_str
) - (auth_key
- auth_str
);
2489 for (i
= 0; i
< con
->best
->num_names
; i
++)
2491 #ifdef HAVE_AUTHORIZATION_H
2492 if (!strncasecmp(con
->best
->names
[i
], "@AUTHKEY(", 9))
2494 snprintf(auth_key
, auth_size
, ", authkey=\"%s\"",
2495 con
->best
->names
[i
] + 9);
2496 /* end parenthesis is stripped in conf.c */
2500 #endif /* HAVE_AUTHORIZATION_H */
2501 if (!strcasecmp(con
->best
->names
[i
], "@SYSTEM"))
2503 #ifdef HAVE_AUTHORIZATION_H
2504 if (SystemGroupAuthKey
)
2505 snprintf(auth_key
, auth_size
,
2506 ", authkey=\"%s\", trc=\"y\"",
2507 SystemGroupAuthKey
);
2510 strlcpy(auth_key
, ", trc=\"y\"", auth_size
));
2511 #endif /* HAVE_AUTHORIZATION_H */
2519 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendHeader: WWW-Authenticate: %s",
2522 if (httpPrintf(HTTP(con
), "WWW-Authenticate: %s\r\n", auth_str
) < 0)
2529 * WWW-Authenticate: Negotiate can be included even for
2530 * non-401 replies...
2533 if (con
->gss_output_token
.length
> 0 && con
->gss_output_token
.length
<= 65536)
2535 OM_uint32 minor_status
; /* Minor status code */
2536 int bufsize
; /* Size of output token buffer */
2539 bufsize
= con
->gss_output_token
.length
* 4 / 3 + 2;
2541 if (bufsize
> gss_bufsize
)
2543 char *buf
; /* New buffer */
2546 bufsize
= (bufsize
+ 1023) & 1023;/* Round up */
2549 buf
= realloc(gss_buf
, bufsize
);
2551 buf
= malloc(bufsize
);
2555 cupsdLogMessage(CUPSD_LOG_ERROR
,
2556 "Unable to allocate %d bytes for Kerberos credentials!",
2562 gss_bufsize
= bufsize
;
2565 httpEncode64_2(gss_buf
, gss_bufsize
,
2566 con
->gss_output_token
.value
,
2567 con
->gss_output_token
.length
);
2568 gss_release_buffer(&minor_status
, &con
->gss_output_token
);
2570 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2571 "cupsdSendHeader: WWW-Authenticate: Negotiate %s", gss_buf
);
2573 if (httpPrintf(HTTP(con
), "WWW-Authenticate: Negotiate %s\r\n",
2577 else if (con
->gss_output_token
.length
> 65536)
2579 cupsdLogMessage(CUPSD_LOG_ERROR
,
2580 "Kerberos credentials larger than 64k (%d)!",
2581 (int)con
->gss_output_token
.length
);
2584 #endif /* HAVE_GSSAPI */
2586 if (con
->language
&& strcmp(con
->language
->language
, "C"))
2588 if (httpPrintf(HTTP(con
), "Content-Language: %s\r\n",
2589 con
->language
->language
) < 0)
2595 if (!strcmp(type
, "text/html"))
2597 if (httpPrintf(HTTP(con
),
2598 "Content-Type: text/html; charset=utf-8\r\n") < 0)
2601 else if (httpPrintf(HTTP(con
), "Content-Type: %s\r\n", type
) < 0)
2610 * 'cupsdUpdateCGI()' - Read status messages from CGI scripts and programs.
2614 cupsdUpdateCGI(void)
2616 char *ptr
, /* Pointer to end of line in buffer */
2617 message
[1024]; /* Pointer to message text */
2618 int loglevel
; /* Log level for message */
2621 while ((ptr
= cupsdStatBufUpdate(CGIStatusBuffer
, &loglevel
,
2622 message
, sizeof(message
))) != NULL
)
2624 if (loglevel
== CUPSD_LOG_INFO
)
2625 cupsdLogMessage(CUPSD_LOG_INFO
, "%s", message
);
2627 if (!strchr(CGIStatusBuffer
->buffer
, '\n'))
2631 if (ptr
== NULL
&& !CGIStatusBuffer
->bufused
)
2634 * Fatal error on pipe - should never happen!
2637 cupsdLogMessage(CUPSD_LOG_CRIT
,
2638 "cupsdUpdateCGI: error reading from CGI error pipe - %s",
2645 * 'cupsdWriteClient()' - Write data to a client as needed.
2649 cupsdWriteClient(cupsd_client_t
*con
) /* I - Client connection */
2651 int bytes
; /* Number of bytes written */
2652 char buf
[16385]; /* Data buffer */
2653 char *bufptr
; /* Pointer into buffer */
2654 ipp_state_t ipp_state
; /* IPP state value */
2657 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2658 "cupsdWriteClient(con=%p(%d)) response=%p(%d), file=%d "
2659 "pipe_pid=%d state=%d",
2660 con
, con
->http
.fd
, con
->response
,
2661 con
->response
? con
->response
->state
: -1,
2662 con
->file
, con
->pipe_pid
, con
->http
.state
);
2664 if (con
->http
.state
!= HTTP_GET_SEND
&&
2665 con
->http
.state
!= HTTP_POST_SEND
)
2668 * If we get called in the wrong state, then something went wrong with the
2669 * connection and we need to shut it down...
2672 cupsdCloseClient(con
);
2679 * Make sure we select on the CGI output...
2682 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2684 if (!con
->file_ready
)
2687 * Try again later when there is CGI output available...
2690 cupsdRemoveSelect(con
->http
.fd
);
2694 con
->file_ready
= 0;
2697 if (con
->response
&& con
->response
->state
!= IPP_DATA
)
2699 ipp_state
= ippWrite(HTTP(con
), con
->response
);
2700 bytes
= ipp_state
!= IPP_ERROR
&&
2701 (con
->file
>= 0 || ipp_state
!= IPP_DATA
);
2703 else if ((bytes
= read(con
->file
, buf
, sizeof(buf
) - 1)) > 0)
2705 if (con
->pipe_pid
&& !con
->got_fields
)
2708 * Inspect the data for Content-Type and other fields.
2713 for (bufptr
= buf
; !con
->got_fields
&& *bufptr
; bufptr
++)
2715 if (*bufptr
== '\n')
2718 * Send line to client...
2721 if (bufptr
> buf
&& bufptr
[-1] == '\r')
2725 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Script header: %s", buf
);
2727 if (!con
->sent_header
)
2730 * Handle redirection and CGI status codes...
2733 if (!strncasecmp(buf
, "Location:", 9))
2735 cupsdSendHeader(con
, HTTP_SEE_OTHER
, NULL
, CUPSD_AUTH_NONE
);
2736 con
->sent_header
= 2;
2738 if (httpPrintf(HTTP(con
), "Content-Length: 0\r\n") < 0)
2741 else if (!strncasecmp(buf
, "Status:", 7))
2743 cupsdSendError(con
, (http_status_t
)atoi(buf
+ 7), CUPSD_AUTH_NONE
);
2744 con
->sent_header
= 2;
2748 cupsdSendHeader(con
, HTTP_OK
, NULL
, CUPSD_AUTH_NONE
);
2749 con
->sent_header
= 1;
2751 if (con
->http
.version
== HTTP_1_1
)
2753 if (httpPrintf(HTTP(con
), "Transfer-Encoding: chunked\r\n") < 0)
2759 if (strncasecmp(buf
, "Status:", 7))
2760 httpPrintf(HTTP(con
), "%s\r\n", buf
);
2766 bytes
-= (bufptr
- buf
);
2769 memmove(buf
, bufptr
, bytes
+ 1);
2776 * See if the line was empty...
2779 if (con
->field_col
== 0)
2781 con
->got_fields
= 1;
2783 if (cupsdFlushHeader(con
) < 0)
2785 cupsdCloseClient(con
);
2789 if (con
->http
.version
== HTTP_1_1
)
2790 con
->http
.data_encoding
= HTTP_ENCODE_CHUNKED
;
2795 else if (*bufptr
!= '\r')
2799 if (bytes
> 0 && !con
->got_fields
)
2802 * Remaining text needs to go out...
2805 httpPrintf(HTTP(con
), "%s", buf
);
2807 con
->http
.activity
= time(NULL
);
2810 else if (bytes
== 0)
2812 con
->http
.activity
= time(NULL
);
2819 if (httpWrite2(HTTP(con
), buf
, bytes
) < 0)
2821 cupsdCloseClient(con
);
2825 if (con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
)
2826 httpFlushWrite(HTTP(con
));
2828 con
->bytes
+= bytes
;
2830 if (con
->http
.state
== HTTP_WAITING
)
2836 (con
->http
.state
!= HTTP_GET_SEND
&& con
->http
.state
!= HTTP_POST_SEND
))
2838 if (!con
->sent_header
&& con
->pipe_pid
)
2839 cupsdSendError(con
, HTTP_SERVER_ERROR
, CUPSD_AUTH_NONE
);
2842 cupsdLogRequest(con
, HTTP_OK
);
2844 httpFlushWrite(HTTP(con
));
2846 if (con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
&& con
->sent_header
== 1)
2848 if (httpWrite2(HTTP(con
), "", 0) < 0)
2850 cupsdCloseClient(con
);
2856 con
->http
.state
= HTTP_WAITING
;
2858 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
2862 cupsdRemoveSelect(con
->file
);
2865 cupsdEndProcess(con
->pipe_pid
, 0);
2874 unlink(con
->filename
);
2875 cupsdClearString(&con
->filename
);
2880 ippDelete(con
->request
);
2881 con
->request
= NULL
;
2886 ippDelete(con
->response
);
2887 con
->response
= NULL
;
2890 cupsdClearString(&con
->command
);
2891 cupsdClearString(&con
->options
);
2892 cupsdClearString(&con
->query_string
);
2894 if (!con
->http
.keep_alive
)
2896 cupsdCloseClient(con
);
2901 con
->http
.activity
= time(NULL
);
2906 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
2909 static int /* O - 1 if modified since */
2911 cupsd_client_t
*con
, /* I - Client connection */
2912 struct stat
*filestats
) /* I - File information */
2914 char *ptr
; /* Pointer into field */
2915 time_t date
; /* Time/date value */
2916 off_t size
; /* Size/length value */
2921 ptr
= con
->http
.fields
[HTTP_FIELD_IF_MODIFIED_SINCE
];
2926 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2927 "check_if_modified(con=%p(%d), "
2928 "filestats=%p(" CUPS_LLFMT
", %d)) If-Modified-Since=\"%s\"",
2929 con
, con
->http
.fd
, filestats
, CUPS_LLCAST filestats
->st_size
,
2930 (int)filestats
->st_mtime
, ptr
);
2932 while (*ptr
!= '\0')
2934 while (isspace(*ptr
) || *ptr
== ';')
2937 if (strncasecmp(ptr
, "length=", 7) == 0)
2940 size
= strtoll(ptr
, NULL
, 10);
2942 while (isdigit(*ptr
))
2945 else if (isalpha(*ptr
))
2947 date
= httpGetDateTime(ptr
);
2948 while (*ptr
!= '\0' && *ptr
!= ';')
2955 return ((size
!= filestats
->st_size
&& size
!= 0) ||
2956 (date
< filestats
->st_mtime
&& date
!= 0) ||
2957 (size
== 0 && date
== 0));
2962 * 'compare_clients()' - Compare two client connections.
2965 static int /* O - Result of comparison */
2966 compare_clients(cupsd_client_t
*a
, /* I - First client */
2967 cupsd_client_t
*b
, /* I - Second client */
2968 void *data
) /* I - User data (not used) */
2982 * 'data_ready()' - Check whether data is available from a client.
2985 static int /* O - 1 if data is ready, 0 otherwise */
2986 data_ready(cupsd_client_t
*con
) /* I - Client */
2988 if (con
->http
.used
> 0)
2991 else if (con
->http
.tls
)
2994 if (SSL_pending((SSL
*)(con
->http
.tls
)))
2996 # elif defined(HAVE_GNUTLS)
2997 if (gnutls_record_check_pending(((http_tls_t
*)(con
->http
.tls
))->session
))
2999 # elif defined(HAVE_CDSASSL)
3000 size_t bytes
; /* Bytes that are available */
3002 if (!SSLGetBufferedReadSize(((http_tls_t
*)(con
->http
.tls
))->session
,
3003 &bytes
) && bytes
> 0)
3005 # endif /* HAVE_LIBSSL */
3007 #endif /* HAVE_SSL */
3015 * 'encrypt_client()' - Enable encryption for the client...
3018 static int /* O - 1 on success, 0 on error */
3019 encrypt_client(cupsd_client_t
*con
) /* I - Client to encrypt */
3022 SSL_CTX
*context
; /* Context for encryption */
3023 SSL
*conn
; /* Connection for encryption */
3024 BIO
*bio
; /* BIO data */
3025 unsigned long error
; /* Error code */
3028 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "encrypt_client(con=%p(%d))", con
,
3032 * Verify that we have a certificate...
3035 if (access(ServerKey
, 0) || access(ServerCertificate
, 0))
3038 * Nope, make a self-signed certificate...
3041 if (!make_certificate(con
))
3046 * Create the SSL context and accept the connection...
3049 context
= SSL_CTX_new(SSLv23_server_method());
3051 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
3052 if (SSLOptions
& CUPSD_SSL_NOEMPTY
)
3053 SSL_CTX_set_options(context
, SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
);
3054 SSL_CTX_use_PrivateKey_file(context
, ServerKey
, SSL_FILETYPE_PEM
);
3055 SSL_CTX_use_certificate_chain_file(context
, ServerCertificate
);
3057 bio
= BIO_new(_httpBIOMethods());
3058 BIO_ctrl(bio
, BIO_C_SET_FILE_PTR
, 0, (char *)HTTP(con
));
3060 conn
= SSL_new(context
);
3061 SSL_set_bio(conn
, bio
, bio
);
3063 if (SSL_accept(conn
) != 1)
3065 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to encrypt connection from %s!",
3066 con
->http
.hostname
);
3068 while ((error
= ERR_get_error()) != 0)
3069 cupsdLogMessage(CUPSD_LOG_ERROR
, "%s", ERR_error_string(error
, NULL
));
3071 SSL_CTX_free(context
);
3076 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Connection from %s now encrypted.",
3077 con
->http
.hostname
);
3079 con
->http
.tls
= conn
;
3082 # elif defined(HAVE_GNUTLS)
3083 http_tls_t
*conn
; /* TLS session object */
3084 int error
; /* Error code */
3085 gnutls_certificate_server_credentials
*credentials
;
3086 /* TLS credentials */
3089 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "encrypt_client(con=%p(%d))", con
,
3093 * Verify that we have a certificate...
3096 if (access(ServerKey
, 0) || access(ServerCertificate
, 0))
3099 * Nope, make a self-signed certificate...
3102 if (!make_certificate(con
))
3107 * Create the SSL object and perform the SSL handshake...
3110 conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
));
3115 credentials
= (gnutls_certificate_server_credentials
*)
3116 malloc(sizeof(gnutls_certificate_server_credentials
));
3117 if (credentials
== NULL
)
3119 cupsdLogMessage(CUPSD_LOG_ERROR
,
3120 "Unable to encrypt connection from %s - %s",
3121 con
->http
.hostname
, strerror(errno
));
3127 gnutls_certificate_allocate_credentials(credentials
);
3128 gnutls_certificate_set_x509_key_file(*credentials
, ServerCertificate
,
3129 ServerKey
, GNUTLS_X509_FMT_PEM
);
3131 gnutls_init(&(conn
->session
), GNUTLS_SERVER
);
3132 gnutls_set_default_priority(conn
->session
);
3133 gnutls_credentials_set(conn
->session
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
3134 gnutls_transport_set_ptr(conn
->session
, (gnutls_transport_ptr
)HTTP(con
));
3135 gnutls_transport_set_pull_function(conn
->session
, _httpReadGNUTLS
);
3136 gnutls_transport_set_push_function(conn
->session
, _httpWriteGNUTLS
);
3138 error
= gnutls_handshake(conn
->session
);
3140 if (error
!= GNUTLS_E_SUCCESS
)
3142 cupsdLogMessage(CUPSD_LOG_ERROR
,
3143 "Unable to encrypt connection from %s - %s",
3144 con
->http
.hostname
, gnutls_strerror(error
));
3146 gnutls_deinit(conn
->session
);
3147 gnutls_certificate_free_credentials(*credentials
);
3153 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Connection from %s now encrypted.",
3154 con
->http
.hostname
);
3156 conn
->credentials
= credentials
;
3157 con
->http
.tls
= conn
;
3160 # elif defined(HAVE_CDSASSL)
3161 OSStatus error
; /* Error code */
3162 http_tls_t
*conn
; /* CDSA connection information */
3165 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "encrypt_client(con=%p(%d))", con
,
3168 if ((conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
))) == NULL
)
3172 conn
->session
= NULL
;
3173 conn
->certsArray
= get_cdsa_certificate(con
);
3175 if (!conn
->certsArray
)
3178 * No keychain (yet), make a self-signed certificate...
3181 if (make_certificate(con
))
3182 conn
->certsArray
= get_cdsa_certificate(con
);
3185 if (!conn
->certsArray
)
3187 cupsdLogMessage(CUPSD_LOG_ERROR
,
3188 "Could not find signing key in keychain \"%s\"",
3190 error
= errSSLBadCert
; /* errSSLBadConfiguration is a better choice, but not available on 10.2.x */
3194 error
= SSLNewContext(true, &conn
->session
);
3197 error
= SSLSetIOFuncs(conn
->session
, _httpReadCDSA
, _httpWriteCDSA
);
3200 error
= SSLSetProtocolVersionEnabled(conn
->session
, kSSLProtocol2
, false);
3203 error
= SSLSetConnection(conn
->session
, HTTP(con
));
3206 error
= SSLSetAllowsExpiredCerts(conn
->session
, true);
3209 error
= SSLSetAllowsAnyRoot(conn
->session
, true);
3212 error
= SSLSetCertificate(conn
->session
, conn
->certsArray
);
3217 * Perform SSL/TLS handshake
3220 while ((error
= SSLHandshake(conn
->session
)) == errSSLWouldBlock
)
3226 cupsdLogMessage(CUPSD_LOG_ERROR
,
3227 "Unable to encrypt connection from %s - %s (%d)",
3228 con
->http
.hostname
, cssmErrorString(error
), (int)error
);
3230 con
->http
.error
= error
;
3231 con
->http
.status
= HTTP_ERROR
;
3234 SSLDisposeContext(conn
->session
);
3236 if (conn
->certsArray
)
3237 CFRelease(conn
->certsArray
);
3244 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Connection from %s now encrypted.",
3245 con
->http
.hostname
);
3247 con
->http
.tls
= conn
;
3250 # endif /* HAVE_LIBSSL */
3252 #endif /* HAVE_SSL */
3257 * 'get_cdsa_certificate()' - Get a SSL/TLS certificate from the System keychain.
3260 static CFArrayRef
/* O - Array of certificates */
3261 get_cdsa_certificate(cupsd_client_t
*con
) /* I - Client connection */
3263 OSStatus err
; /* Error info */
3264 SecKeychainRef keychain
; /* Keychain reference */
3265 SecIdentitySearchRef search
; /* Search reference */
3266 SecIdentityRef identity
; /* Identity */
3267 CFArrayRef certificates
= NULL
;
3268 /* Certificate array */
3271 if ((err
= SecKeychainOpen(ServerCertificate
, &keychain
)))
3273 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot open keychain \"%s\" - %s (%d)",
3274 ServerCertificate
, cssmErrorString(err
), (int)err
);
3278 # if HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY
3280 * Use a policy to search for valid certificates who's common name matches the
3284 SecPolicySearchRef policy_search
; /* Policy search ref */
3285 SecPolicyRef policy
; /* Policy ref */
3286 CSSM_DATA options
; /* Policy options */
3287 CSSM_APPLE_TP_SSL_OPTIONS
3288 ssl_options
; /* SSL Option for hostname */
3291 if (SecPolicySearchCreate(CSSM_CERT_X_509v3
, &CSSMOID_APPLE_TP_SSL
,
3292 NULL
, &policy_search
))
3294 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot create a policy search reference");
3295 CFRelease(keychain
);
3299 if (SecPolicySearchCopyNext(policy_search
, &policy
))
3301 cupsdLogMessage(CUPSD_LOG_ERROR
,
3302 "Cannot find a policy to use for searching");
3303 CFRelease(keychain
);
3304 CFRelease(policy_search
);
3308 memset(&ssl_options
, 0, sizeof(ssl_options
));
3309 ssl_options
.Version
= CSSM_APPLE_TP_SSL_OPTS_VERSION
;
3310 ssl_options
.ServerName
= con
->servername
;
3311 ssl_options
.ServerNameLen
= strlen(con
->servername
);
3313 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3314 "get_cdsa_certificate: Looking for certs for \"%s\"...",
3317 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3318 "get_cdsa_certificate: Looking for certs for \"%s\"...",
3321 options
.Data
= (uint8
*)&ssl_options
;
3322 options
.Length
= sizeof(ssl_options
);
3324 if (SecPolicySetValue(policy
, &options
))
3326 cupsdLogMessage(CUPSD_LOG_ERROR
,
3327 "Cannot set policy value to use for searching");
3328 CFRelease(keychain
);
3329 CFRelease(policy_search
);
3333 err
= SecIdentitySearchCreateWithPolicy(policy
, NULL
, CSSM_KEYUSE_SIGN
,
3334 keychain
, FALSE
, &search
);
3337 * Assume there is exactly one SecIdentity in the keychain...
3340 err
= SecIdentitySearchCreate(keychain
, CSSM_KEYUSE_SIGN
, &search
);
3341 # endif /* HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY */
3344 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3345 "Cannot create keychain search reference: %s (%d)",
3346 cssmErrorString(err
), (int)err
);
3349 if ((err
= SecIdentitySearchCopyNext(search
, &identity
)))
3351 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3352 "Cannot find signing key in keychain \"%s\": %s (%d)",
3353 ServerCertificate
, cssmErrorString(err
), (int)err
);
3357 if (CFGetTypeID(identity
) != SecIdentityGetTypeID())
3358 cupsdLogMessage(CUPSD_LOG_ERROR
,
3359 "SecIdentitySearchCopyNext CFTypeID failure!");
3362 if ((certificates
= CFArrayCreate(NULL
, (const void **)&identity
,
3363 1, &kCFTypeArrayCallBacks
)) == NULL
)
3364 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot create certificate array");
3367 CFRelease(identity
);
3373 # if HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY
3375 CFRelease(policy_search
);
3376 # endif /* HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY */
3378 return (certificates
);
3380 #endif /* HAVE_CDSASSL */
3384 * 'get_file()' - Get a filename and state info.
3387 static char * /* O - Real filename */
3388 get_file(cupsd_client_t
*con
, /* I - Client connection */
3389 struct stat
*filestats
, /* O - File information */
3390 char *filename
, /* IO - Filename buffer */
3391 int len
) /* I - Buffer length */
3393 int status
; /* Status of filesystem calls */
3394 char *ptr
; /* Pointer info filename */
3395 int plen
; /* Remaining length after pointer */
3396 char language
[7]; /* Language subdirectory, if any */
3400 * Figure out the real filename...
3405 if (!strncmp(con
->uri
, "/ppd/", 5))
3406 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
);
3407 else if (!strncmp(con
->uri
, "/rss/", 5) && !strchr(con
->uri
+ 5, '/'))
3408 snprintf(filename
, len
, "%s/rss/%s", CacheDir
, con
->uri
+ 5);
3409 else if (!strncmp(con
->uri
, "/admin/conf/", 12))
3410 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
+ 11);
3411 else if (!strncmp(con
->uri
, "/admin/log/", 11))
3413 if (!strncmp(con
->uri
+ 11, "access_log", 10) && AccessLog
[0] == '/')
3414 strlcpy(filename
, AccessLog
, len
);
3415 else if (!strncmp(con
->uri
+ 11, "error_log", 9) && ErrorLog
[0] == '/')
3416 strlcpy(filename
, ErrorLog
, len
);
3417 else if (!strncmp(con
->uri
+ 11, "page_log", 8) && PageLog
[0] == '/')
3418 strlcpy(filename
, PageLog
, len
);
3422 else if (con
->language
)
3424 snprintf(language
, sizeof(language
), "/%s", con
->language
->language
);
3425 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3428 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3430 if ((ptr
= strchr(filename
, '?')) != NULL
)
3434 * Grab the status for this language; if there isn't a language-specific file
3435 * then fallback to the default one...
3438 if ((status
= stat(filename
, filestats
)) != 0 && language
[0] &&
3439 strncmp(con
->uri
, "/ppd/", 5) &&
3440 strncmp(con
->uri
, "/admin/conf/", 12) &&
3441 strncmp(con
->uri
, "/admin/log/", 11))
3444 * Drop the country code...
3448 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3450 if ((ptr
= strchr(filename
, '?')) != NULL
)
3453 if ((status
= stat(filename
, filestats
)) != 0)
3456 * Drop the language prefix and try the root directory...
3460 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3462 if ((ptr
= strchr(filename
, '?')) != NULL
)
3465 status
= stat(filename
, filestats
);
3470 * If we're found a directory, get the index.html file instead...
3473 if (!status
&& S_ISDIR(filestats
->st_mode
))
3476 * Make sure the URI ends with a slash...
3479 if (con
->uri
[strlen(con
->uri
) - 1] != '/')
3480 strlcat(con
->uri
, "/", sizeof(con
->uri
));
3483 * Find the directory index file, trying every language...
3488 if (status
&& language
[0])
3491 * Try a different language subset...
3495 language
[0] = '\0'; /* Strip country code */
3497 language
[0] = '\0'; /* Strip language */
3501 * Look for the index file...
3504 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3506 if ((ptr
= strchr(filename
, '?')) != NULL
)
3509 ptr
= filename
+ strlen(filename
);
3510 plen
= len
- (ptr
- filename
);
3512 strlcpy(ptr
, "index.html", plen
);
3513 status
= stat(filename
, filestats
);
3518 strlcpy(ptr
, "index.class", plen
);
3519 status
= stat(filename
, filestats
);
3521 #endif /* HAVE_JAVA */
3526 strlcpy(ptr
, "index.pl", plen
);
3527 status
= stat(filename
, filestats
);
3529 #endif /* HAVE_PERL */
3534 strlcpy(ptr
, "index.php", plen
);
3535 status
= stat(filename
, filestats
);
3537 #endif /* HAVE_PHP */
3542 strlcpy(ptr
, "index.pyc", plen
);
3543 status
= stat(filename
, filestats
);
3548 strlcpy(ptr
, "index.py", plen
);
3549 status
= stat(filename
, filestats
);
3551 #endif /* HAVE_PYTHON */
3554 while (status
&& language
[0]);
3557 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3558 "get_file(con=%p(%d), filestats=%p, filename=%p, len=%d) = "
3559 "%s", con
, con
->http
.fd
, filestats
, filename
, len
,
3560 status
? "(null)" : filename
);
3563 con
->http
.data_remaining
= (int)filestats
->st_size
;
3573 * 'install_conf_file()' - Install a configuration file.
3576 static http_status_t
/* O - Status */
3577 install_conf_file(cupsd_client_t
*con
) /* I - Connection */
3579 cups_file_t
*in
, /* Input file */
3580 *out
; /* Output file */
3581 char buffer
[1024]; /* Copy buffer */
3582 int bytes
; /* Number of bytes */
3583 char conffile
[1024], /* Configuration filename */
3584 newfile
[1024], /* New config filename */
3585 oldfile
[1024]; /* Old config filename */
3586 struct stat confinfo
; /* Config file info */
3590 * First construct the filenames...
3593 snprintf(conffile
, sizeof(conffile
), "%s%s", ServerRoot
, con
->uri
+ 11);
3594 snprintf(newfile
, sizeof(newfile
), "%s%s.N", ServerRoot
, con
->uri
+ 11);
3595 snprintf(oldfile
, sizeof(oldfile
), "%s%s.O", ServerRoot
, con
->uri
+ 11);
3597 cupsdLogMessage(CUPSD_LOG_INFO
, "Installing config file \"%s\"...", conffile
);
3600 * Get the owner, group, and permissions of the configuration file.
3601 * If it doesn't exist, assign it to the User and Group in the
3602 * cupsd.conf file with mode 0640 permissions.
3605 if (stat(conffile
, &confinfo
))
3607 confinfo
.st_uid
= User
;
3608 confinfo
.st_gid
= Group
;
3609 confinfo
.st_mode
= ConfigFilePerm
;
3613 * Open the request file and new config file...
3616 if ((in
= cupsFileOpen(con
->filename
, "rb")) == NULL
)
3618 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open request file \"%s\" - %s",
3619 con
->filename
, strerror(errno
));
3620 return (HTTP_SERVER_ERROR
);
3623 if ((out
= cupsFileOpen(newfile
, "wb")) == NULL
)
3626 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open config file \"%s\" - %s",
3627 newfile
, strerror(errno
));
3628 return (HTTP_SERVER_ERROR
);
3631 fchmod(cupsFileNumber(out
), confinfo
.st_mode
);
3632 fchown(cupsFileNumber(out
), confinfo
.st_uid
, confinfo
.st_gid
);
3635 * Copy from the request to the new config file...
3638 while ((bytes
= cupsFileRead(in
, buffer
, sizeof(buffer
))) > 0)
3639 if (cupsFileWrite(out
, buffer
, bytes
) < bytes
)
3641 cupsdLogMessage(CUPSD_LOG_ERROR
,
3642 "Unable to copy to config file \"%s\" - %s",
3643 newfile
, strerror(errno
));
3649 return (HTTP_SERVER_ERROR
);
3653 * Close the files...
3657 if (cupsFileClose(out
))
3659 cupsdLogMessage(CUPSD_LOG_ERROR
,
3660 "Error file closing config file \"%s\" - %s",
3661 newfile
, strerror(errno
));
3665 return (HTTP_SERVER_ERROR
);
3669 * Remove the request file...
3672 unlink(con
->filename
);
3673 cupsdClearString(&con
->filename
);
3676 * Unlink the old backup, rename the current config file to the backup
3677 * filename, and rename the new config file to the config file name...
3680 if (unlink(oldfile
))
3681 if (errno
!= ENOENT
)
3683 cupsdLogMessage(CUPSD_LOG_ERROR
,
3684 "Unable to remove backup config file \"%s\" - %s",
3685 oldfile
, strerror(errno
));
3689 return (HTTP_SERVER_ERROR
);
3692 if (rename(conffile
, oldfile
))
3693 if (errno
!= ENOENT
)
3695 cupsdLogMessage(CUPSD_LOG_ERROR
,
3696 "Unable to rename old config file \"%s\" - %s",
3697 conffile
, strerror(errno
));
3701 return (HTTP_SERVER_ERROR
);
3704 if (rename(newfile
, conffile
))
3706 cupsdLogMessage(CUPSD_LOG_ERROR
,
3707 "Unable to rename new config file \"%s\" - %s",
3708 newfile
, strerror(errno
));
3710 rename(oldfile
, conffile
);
3713 return (HTTP_SERVER_ERROR
);
3717 * If the cupsd.conf file was updated, set the NeedReload flag...
3720 if (!strcmp(con
->uri
, "/admin/conf/cupsd.conf"))
3721 NeedReload
= RELOAD_CUPSD
;
3723 NeedReload
= RELOAD_ALL
;
3725 ReloadTime
= time(NULL
);
3728 * Return that the file was created successfully...
3731 return (HTTP_CREATED
);
3736 * 'is_cgi()' - Is the resource a CGI script/program?
3739 static int /* O - 1 = CGI, 0 = file */
3740 is_cgi(cupsd_client_t
*con
, /* I - Client connection */
3741 const char *filename
, /* I - Real filename */
3742 struct stat
*filestats
, /* I - File information */
3743 mime_type_t
*type
) /* I - MIME type */
3745 const char *options
; /* Options on URL */
3749 * Get the options, if any...
3752 if ((options
= strchr(con
->uri
, '?')) != NULL
)
3755 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", options
);
3759 * Check for known types...
3762 if (!type
|| strcasecmp(type
->super
, "application"))
3764 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3765 "is_cgi(con=%p(%d), filename=\"%s\", filestats=%p, "
3766 "type=%s/%s) = 0", con
, con
->http
.fd
, filename
, filestats
,
3767 type
? type
->super
: "unknown",
3768 type
? type
->type
: "unknown");
3772 if (!strcasecmp(type
->type
, "x-httpd-cgi") &&
3773 (filestats
->st_mode
& 0111))
3776 * "application/x-httpd-cgi" is a CGI script.
3779 cupsdSetString(&con
->command
, filename
);
3782 cupsdSetStringf(&con
->options
, " %s", options
);
3784 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3785 "is_cgi(con=%p(%d), filename=\"%s\", filestats=%p, "
3786 "type=%s/%s) = 1", con
, con
->http
.fd
, filename
, filestats
,
3787 type
? type
->super
: "unknown",
3788 type
? type
->type
: "unknown");
3792 else if (!strcasecmp(type
->type
, "x-httpd-java"))
3795 * "application/x-httpd-java" is a Java servlet.
3798 cupsdSetString(&con
->command
, CUPS_JAVA
);
3801 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3803 cupsdSetStringf(&con
->options
, " %s", filename
);
3805 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3806 "is_cgi(con=%p(%d), filename=\"%s\", filestats=%p, "
3807 "type=%s/%s) = 1", con
, con
->http
.fd
, filename
, filestats
,
3808 type
? type
->super
: "unknown",
3809 type
? type
->type
: "unknown");
3812 #endif /* HAVE_JAVA */
3814 else if (!strcasecmp(type
->type
, "x-httpd-perl"))
3817 * "application/x-httpd-perl" is a Perl page.
3820 cupsdSetString(&con
->command
, CUPS_PERL
);
3823 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3825 cupsdSetStringf(&con
->options
, " %s", filename
);
3827 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3828 "is_cgi(con=%p(%d), filename=\"%s\", filestats=%p, "
3829 "type=%s/%s) = 1", con
, con
->http
.fd
, filename
, filestats
,
3830 type
? type
->super
: "unknown",
3831 type
? type
->type
: "unknown");
3834 #endif /* HAVE_PERL */
3836 else if (!strcasecmp(type
->type
, "x-httpd-php"))
3839 * "application/x-httpd-php" is a PHP page.
3842 cupsdSetString(&con
->command
, CUPS_PHP
);
3845 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3847 cupsdSetStringf(&con
->options
, " %s", filename
);
3849 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3850 "is_cgi(con=%p(%d), filename=\"%s\", filestats=%p, "
3851 "type=%s/%s) = 1", con
, con
->http
.fd
, filename
, filestats
,
3852 type
? type
->super
: "unknown",
3853 type
? type
->type
: "unknown");
3856 #endif /* HAVE_PHP */
3858 else if (!strcasecmp(type
->type
, "x-httpd-python"))
3861 * "application/x-httpd-python" is a Python page.
3864 cupsdSetString(&con
->command
, CUPS_PYTHON
);
3867 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3869 cupsdSetStringf(&con
->options
, " %s", filename
);
3871 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3872 "is_cgi(con=%p(%d), filename=\"%s\", filestats=%p, "
3873 "type=%s/%s) = 1", con
, con
->http
.fd
, filename
, filestats
,
3874 type
? type
->super
: "unknown",
3875 type
? type
->type
: "unknown");
3878 #endif /* HAVE_PYTHON */
3880 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3881 "is_cgi(con=%p(%d), filename=\"%s\", filestats=%p, "
3882 "type=%s/%s) = 0", con
, con
->http
.fd
, filename
, filestats
,
3883 type
? type
->super
: "unknown",
3884 type
? type
->type
: "unknown");
3890 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
3893 static int /* O - 0 if relative, 1 if absolute */
3894 is_path_absolute(const char *path
) /* I - Input path */
3897 * Check for a leading slash...
3904 * Check for "/.." in the path...
3907 while ((path
= strstr(path
, "/..")) != NULL
)
3909 if (!path
[3] || path
[3] == '/')
3916 * If we haven't found any relative paths, return 1 indicating an
3926 * 'make_certificate()' - Make a self-signed SSL/TLS certificate.
3929 static int /* O - 1 on success, 0 on failure */
3930 make_certificate(cupsd_client_t
*con
) /* I - Client connection */
3932 #if defined(HAVE_LIBSSL) && defined(HAVE_WAITPID)
3933 int pid
, /* Process ID of command */
3934 status
; /* Status of command */
3935 char command
[1024], /* Command */
3936 *argv
[12], /* Command-line arguments */
3937 *envp
[MAX_ENV
+ 1], /* Environment variables */
3938 home
[1024], /* HOME environment variable */
3939 infofile
[1024], /* Type-in information for cert */
3940 seedfile
[1024]; /* Random number seed file */
3941 int envc
, /* Number of environment variables */
3942 bytes
; /* Bytes written */
3943 cups_file_t
*fp
; /* Seed/info file */
3944 int infofd
; /* Info file descriptor */
3948 * Run the "openssl" command to seed the random number generator and
3949 * generate a self-signed certificate that is good for 10 years:
3951 * openssl rand -rand seedfile 1
3953 * openssl req -new -x509 -keyout ServerKey \
3954 * -out ServerCertificate -days 3650 -nodes
3956 * The seeding step is crucial in ensuring that the openssl command
3957 * does not block on systems without sufficient entropy...
3960 if (!cupsFileFind("openssl", getenv("PATH"), 1, command
, sizeof(command
)))
3962 cupsdLogMessage(CUPSD_LOG_ERROR
,
3963 "No SSL certificate and openssl command not found!");
3967 if (access("/dev/urandom", 0))
3970 * If the system doesn't provide /dev/urandom, then any random source
3971 * will probably be blocking-style, so generate some random data to
3972 * use as a seed for the certificate. Note that we have already
3973 * seeded the random number generator in cupsdInitCerts()...
3976 cupsdLogMessage(CUPSD_LOG_INFO
,
3977 "Seeding the random number generator...");
3979 snprintf(home
, sizeof(home
), "HOME=%s", TempDir
);
3982 * Write the seed file...
3985 if ((fp
= cupsTempFile2(seedfile
, sizeof(seedfile
))) == NULL
)
3987 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to create seed file %s - %s",
3988 seedfile
, strerror(errno
));
3992 for (bytes
= 0; bytes
< 262144; bytes
++)
3993 cupsFilePutChar(fp
, random());
3998 * Run the openssl command to seed its random number generator...
4001 argv
[0] = "openssl";
4008 envc
= cupsdLoadEnv(envp
, MAX_ENV
);
4009 envp
[envc
++] = home
;
4012 if (!cupsdStartProcess(command
, argv
, envp
, -1, -1, -1, -1, -1, 1, NULL
, 0,
4019 while (waitpid(pid
, &status
, 0) < 0)
4026 cupsdFinishProcess(pid
, command
, sizeof(command
), NULL
);
4029 * Remove the seed file, as it is no longer needed...
4036 if (WIFEXITED(status
))
4037 cupsdLogMessage(CUPSD_LOG_ERROR
,
4038 "Unable to seed random number generator - "
4039 "the openssl command stopped with status %d!",
4040 WEXITSTATUS(status
));
4042 cupsdLogMessage(CUPSD_LOG_ERROR
,
4043 "Unable to seed random number generator - "
4044 "the openssl command crashed on signal %d!",
4052 * Create a file with the certificate information fields...
4054 * Note: This assumes that the default questions are asked by the openssl
4058 if ((fp
= cupsTempFile2(infofile
, sizeof(infofile
))) == NULL
)
4060 cupsdLogMessage(CUPSD_LOG_ERROR
,
4061 "Unable to create certificate information file %s - %s",
4062 infofile
, strerror(errno
));
4066 cupsFilePrintf(fp
, ".\n.\n.\n%s\n.\n%s\n%s\n",
4067 ServerName
, ServerName
, ServerAdmin
);
4070 cupsdLogMessage(CUPSD_LOG_INFO
,
4071 "Generating SSL server key and certificate...");
4073 argv
[0] = "openssl";
4077 argv
[4] = "-keyout";
4078 argv
[5] = ServerKey
;
4080 argv
[7] = ServerCertificate
;
4083 argv
[10] = "-nodes";
4086 cupsdLoadEnv(envp
, MAX_ENV
);
4088 infofd
= open(infofile
, O_RDONLY
);
4090 if (!cupsdStartProcess(command
, argv
, envp
, infofd
, -1, -1, -1, -1, 1, NULL
,
4101 while (waitpid(pid
, &status
, 0) < 0)
4108 cupsdFinishProcess(pid
, command
, sizeof(command
), NULL
);
4112 if (WIFEXITED(status
))
4113 cupsdLogMessage(CUPSD_LOG_ERROR
,
4114 "Unable to create SSL server key and certificate - "
4115 "the openssl command stopped with status %d!",
4116 WEXITSTATUS(status
));
4118 cupsdLogMessage(CUPSD_LOG_ERROR
,
4119 "Unable to create SSL server key and certificate - "
4120 "the openssl command crashed on signal %d!",
4125 cupsdLogMessage(CUPSD_LOG_INFO
, "Created SSL server key file \"%s\"...",
4127 cupsdLogMessage(CUPSD_LOG_INFO
,
4128 "Created SSL server certificate file \"%s\"...",
4134 #elif defined(HAVE_GNUTLS)
4135 gnutls_x509_crt crt
; /* Self-signed certificate */
4136 gnutls_x509_privkey key
; /* Encryption key */
4137 cups_lang_t
*language
; /* Default language info */
4138 cups_file_t
*fp
; /* Key/cert file */
4139 unsigned char buffer
[8192]; /* Buffer for x509 data */
4140 size_t bytes
; /* Number of bytes of data */
4141 unsigned char serial
[4]; /* Serial number buffer */
4142 time_t curtime
; /* Current time */
4143 int result
; /* Result of GNU TLS calls */
4147 * Create the encryption key...
4150 cupsdLogMessage(CUPSD_LOG_INFO
, "Generating SSL server key...");
4152 gnutls_x509_privkey_init(&key
);
4153 gnutls_x509_privkey_generate(key
, GNUTLS_PK_RSA
, 2048, 0);
4159 bytes
= sizeof(buffer
);
4161 if ((result
= gnutls_x509_privkey_export(key
, GNUTLS_X509_FMT_PEM
,
4162 buffer
, &bytes
)) < 0)
4164 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to export SSL server key - %s",
4165 gnutls_strerror(result
));
4166 gnutls_x509_privkey_deinit(key
);
4169 else if ((fp
= cupsFileOpen(ServerKey
, "w")) != NULL
)
4171 cupsFileWrite(fp
, (char *)buffer
, bytes
);
4174 cupsdLogMessage(CUPSD_LOG_INFO
, "Created SSL server key file \"%s\"...",
4179 cupsdLogMessage(CUPSD_LOG_ERROR
,
4180 "Unable to create SSL server key file \"%s\" - %s",
4181 ServerKey
, strerror(errno
));
4182 gnutls_x509_privkey_deinit(key
);
4187 * Create the self-signed certificate...
4190 cupsdLogMessage(CUPSD_LOG_INFO
, "Generating self-signed SSL certificate...");
4192 language
= cupsLangDefault();
4193 curtime
= time(NULL
);
4194 serial
[0] = curtime
>> 24;
4195 serial
[1] = curtime
>> 16;
4196 serial
[2] = curtime
>> 8;
4197 serial
[3] = curtime
;
4199 gnutls_x509_crt_init(&crt
);
4200 if (strlen(language
->language
) == 5)
4201 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
4202 language
->language
+ 3, 2);
4204 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
4206 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COMMON_NAME
, 0,
4207 ServerName
, strlen(ServerName
));
4208 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATION_NAME
, 0,
4209 ServerName
, strlen(ServerName
));
4210 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATIONAL_UNIT_NAME
,
4212 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_STATE_OR_PROVINCE_NAME
, 0,
4214 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_LOCALITY_NAME
, 0,
4216 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_PKCS9_EMAIL
, 0,
4217 ServerAdmin
, strlen(ServerAdmin
));
4218 gnutls_x509_crt_set_key(crt
, key
);
4219 gnutls_x509_crt_set_serial(crt
, serial
, sizeof(serial
));
4220 gnutls_x509_crt_set_activation_time(crt
, curtime
);
4221 gnutls_x509_crt_set_expiration_time(crt
, curtime
+ 10 * 365 * 86400);
4222 gnutls_x509_crt_set_ca_status(crt
, 0);
4223 gnutls_x509_crt_set_subject_alternative_name(crt
, GNUTLS_SAN_DNSNAME
,
4225 gnutls_x509_crt_set_key_purpose_oid(crt
, GNUTLS_KP_TLS_WWW_SERVER
, 0);
4226 gnutls_x509_crt_set_key_usage(crt
, GNUTLS_KEY_KEY_ENCIPHERMENT
);
4227 gnutls_x509_crt_set_version(crt
, 3);
4229 bytes
= sizeof(buffer
);
4230 if (gnutls_x509_crt_get_key_id(crt
, 0, buffer
, &bytes
) >= 0)
4231 gnutls_x509_crt_set_subject_key_id(crt
, buffer
, bytes
);
4233 gnutls_x509_crt_sign(crt
, crt
, key
);
4239 bytes
= sizeof(buffer
);
4240 if ((result
= gnutls_x509_crt_export(crt
, GNUTLS_X509_FMT_PEM
,
4241 buffer
, &bytes
)) < 0)
4242 cupsdLogMessage(CUPSD_LOG_ERROR
,
4243 "Unable to export SSL server certificate - %s",
4244 gnutls_strerror(result
));
4245 else if ((fp
= cupsFileOpen(ServerCertificate
, "w")) != NULL
)
4247 cupsFileWrite(fp
, (char *)buffer
, bytes
);
4250 cupsdLogMessage(CUPSD_LOG_INFO
,
4251 "Created SSL server certificate file \"%s\"...",
4255 cupsdLogMessage(CUPSD_LOG_ERROR
,
4256 "Unable to create SSL server certificate file \"%s\" - %s",
4257 ServerCertificate
, strerror(errno
));
4263 gnutls_x509_crt_deinit(crt
);
4264 gnutls_x509_privkey_deinit(key
);
4268 #elif defined(HAVE_CDSASSL) && defined(HAVE_WAITPID)
4269 int pid
, /* Process ID of command */
4270 status
; /* Status of command */
4271 char command
[1024], /* Command */
4272 *argv
[4], /* Command-line arguments */
4273 *envp
[MAX_ENV
+ 1], /* Environment variables */
4274 keychain
[1024], /* Keychain argument */
4275 infofile
[1024]; /* Type-in information for cert */
4276 cups_file_t
*fp
; /* Seed/info file */
4277 int infofd
; /* Info file descriptor */
4281 * Run the "certtool" command to generate a self-signed certificate...
4284 if (!cupsFileFind("certtool", getenv("PATH"), 1, command
, sizeof(command
)))
4286 cupsdLogMessage(CUPSD_LOG_ERROR
,
4287 "No SSL certificate and certtool command not found!");
4292 * Create a file with the certificate information fields...
4294 * Note: This assumes that the default questions are asked by the certtool
4298 if ((fp
= cupsTempFile2(infofile
, sizeof(infofile
))) == NULL
)
4300 cupsdLogMessage(CUPSD_LOG_ERROR
,
4301 "Unable to create certificate information file %s - %s",
4302 infofile
, strerror(errno
));
4306 cupsFilePrintf(fp
, "%s\nr\n\ny\nb\ns\ny\n%s\n\n\n\n\n%s\ny\n",
4307 con
->servername
, con
->servername
, ServerAdmin
);
4310 cupsdLogMessage(CUPSD_LOG_INFO
,
4311 "Generating SSL server key and certificate...");
4313 snprintf(keychain
, sizeof(keychain
), "k=%s", ServerCertificate
);
4315 argv
[0] = "certtool";
4320 cupsdLoadEnv(envp
, MAX_ENV
);
4322 infofd
= open(infofile
, O_RDONLY
);
4324 if (!cupsdStartProcess(command
, argv
, envp
, infofd
, -1, -1, -1, -1, 1, NULL
,
4335 while (waitpid(pid
, &status
, 0) < 0)
4342 cupsdFinishProcess(pid
, command
, sizeof(command
), NULL
);
4346 if (WIFEXITED(status
))
4347 cupsdLogMessage(CUPSD_LOG_ERROR
,
4348 "Unable to create SSL server key and certificate - "
4349 "the certtool command stopped with status %d!",
4350 WEXITSTATUS(status
));
4352 cupsdLogMessage(CUPSD_LOG_ERROR
,
4353 "Unable to create SSL server key and certificate - "
4354 "the certtool command crashed on signal %d!",
4359 cupsdLogMessage(CUPSD_LOG_INFO
,
4360 "Created SSL server certificate file \"%s\"...",
4368 #endif /* HAVE_LIBSSL && HAVE_WAITPID */
4370 #endif /* HAVE_SSL */
4374 * 'pipe_command()' - Pipe the output of a command to the remote client.
4377 static int /* O - Process ID */
4378 pipe_command(cupsd_client_t
*con
, /* I - Client connection */
4379 int infile
, /* I - Standard input for command */
4380 int *outfile
, /* O - Standard output for command */
4381 char *command
, /* I - Command to run */
4382 char *options
, /* I - Options for command */
4383 int root
) /* I - Run as root? */
4385 int i
; /* Looping var */
4386 int pid
; /* Process ID */
4387 char *commptr
, /* Command string pointer */
4388 commch
; /* Command string character */
4389 char *uriptr
; /* URI string pointer */
4390 int fds
[2]; /* Pipe FDs */
4391 int argc
; /* Number of arguments */
4392 int envc
; /* Number of environment variables */
4393 char argbuf
[10240], /* Argument buffer */
4394 *argv
[100], /* Argument strings */
4395 *envp
[MAX_ENV
+ 20]; /* Environment variables */
4396 char auth_type
[256], /* CUPSD_AUTH_TYPE environment variable */
4397 content_length
[1024], /* CONTENT_LENGTH environment variable */
4398 content_type
[1024], /* CONTENT_TYPE environment variable */
4399 http_cookie
[32768], /* HTTP_COOKIE environment variable */
4400 http_referer
[1024], /* HTTP_REFERER environment variable */
4401 http_user_agent
[1024], /* HTTP_USER_AGENT environment variable */
4402 lang
[1024], /* LANG environment variable */
4403 path_info
[1024], /* PATH_INFO environment variable */
4404 remote_addr
[1024], /* REMOTE_ADDR environment variable */
4405 remote_host
[1024], /* REMOTE_HOST environment variable */
4406 remote_user
[1024], /* REMOTE_USER environment variable */
4407 script_filename
[1024], /* SCRIPT_FILENAME environment variable */
4408 script_name
[1024], /* SCRIPT_NAME environment variable */
4409 server_name
[1024], /* SERVER_NAME environment variable */
4410 server_port
[1024]; /* SERVER_PORT environment variable */
4411 ipp_attribute_t
*attr
; /* attributes-natural-language attribute */
4412 void *ccache
= NULL
; /* Kerberos credentials */
4416 * Parse a copy of the options string, which is of the form:
4418 * argument+argument+argument
4419 * ?argument+argument+argument
4420 * param=value¶m=value
4421 * ?param=value¶m=value
4422 * /name?argument+argument+argument
4423 * /name?param=value¶m=value
4425 * If the string contains an "=" character after the initial name,
4426 * then we treat it as a HTTP GET form request and make a copy of
4427 * the remaining string for the environment variable.
4429 * The string is always parsed out as command-line arguments, to
4430 * be consistent with Apache...
4433 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4434 "pipe_command(con=%p(%d), infile=%d, outfile=%p, "
4435 "command=\"%s\", options=\"%s\", root=%d)",
4436 con
, con
->http
.fd
, infile
, outfile
, command
,
4437 options
? options
: "(null)", root
);
4442 strlcpy(argbuf
, options
, sizeof(argbuf
));
4446 if (argbuf
[0] == '/')
4449 * Found some trailing path information, set PATH_INFO...
4452 if ((commptr
= strchr(argbuf
, '?')) == NULL
)
4453 commptr
= argbuf
+ strlen(argbuf
);
4457 snprintf(path_info
, sizeof(path_info
), "PATH_INFO=%s", argbuf
);
4463 path_info
[0] = '\0';
4465 if (*commptr
== ' ')
4469 if (*commptr
== '?' && con
->operation
== HTTP_GET
&& !con
->query_string
)
4472 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", commptr
);
4479 argv
[argc
++] = commptr
;
4481 for (; *commptr
&& argc
< 99; commptr
++)
4484 * Break arguments whenever we see a + or space...
4487 if (*commptr
== ' ' || *commptr
== '+')
4489 while (*commptr
== ' ' || *commptr
== '+')
4493 * If we don't have a blank string, save it as another argument...
4498 argv
[argc
] = commptr
;
4504 else if (*commptr
== '%' && isxdigit(commptr
[1] & 255) &&
4505 isxdigit(commptr
[2] & 255))
4508 * Convert the %xx notation to the individual character.
4511 if (commptr
[1] >= '0' && commptr
[1] <= '9')
4512 *commptr
= (commptr
[1] - '0') << 4;
4514 *commptr
= (tolower(commptr
[1]) - 'a' + 10) << 4;
4516 if (commptr
[2] >= '0' && commptr
[2] <= '9')
4517 *commptr
|= commptr
[2] - '0';
4519 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
4521 _cups_strcpy(commptr
+ 1, commptr
+ 3);
4524 * Check for a %00 and break if that is the case...
4536 * Setup the environment variables as needed...
4539 if (con
->username
[0])
4541 snprintf(auth_type
, sizeof(auth_type
), "CUPSD_AUTH_TYPE=%s",
4542 httpGetField(HTTP(con
), HTTP_FIELD_AUTHORIZATION
));
4544 if ((uriptr
= strchr(auth_type
+ 10, ' ')) != NULL
)
4548 auth_type
[0] = '\0';
4551 (attr
= ippFindAttribute(con
->request
, "attributes-natural-language",
4552 IPP_TAG_LANGUAGE
)) != NULL
)
4554 switch (strlen(attr
->values
[0].string
.text
))
4558 * This is an unknown or badly formatted language code; use
4559 * the POSIX locale...
4562 strcpy(lang
, "LANG=C");
4567 * Just the language code (ll)...
4570 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8",
4571 attr
->values
[0].string
.text
);
4576 * Language and country code (ll-cc)...
4579 snprintf(lang
, sizeof(lang
), "LANG=%c%c_%c%c.UTF8",
4580 attr
->values
[0].string
.text
[0],
4581 attr
->values
[0].string
.text
[1],
4582 toupper(attr
->values
[0].string
.text
[3] & 255),
4583 toupper(attr
->values
[0].string
.text
[4] & 255));
4587 else if (con
->language
)
4588 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8", con
->language
->language
);
4590 strcpy(lang
, "LANG=C");
4592 strcpy(remote_addr
, "REMOTE_ADDR=");
4593 httpAddrString(con
->http
.hostaddr
, remote_addr
+ 12,
4594 sizeof(remote_addr
) - 12);
4596 snprintf(remote_host
, sizeof(remote_host
), "REMOTE_HOST=%s",
4597 con
->http
.hostname
);
4599 snprintf(script_name
, sizeof(script_name
), "SCRIPT_NAME=%s", con
->uri
);
4600 if ((uriptr
= strchr(script_name
, '?')) != NULL
)
4603 snprintf(script_filename
, sizeof(script_filename
), "SCRIPT_FILENAME=%s%s",
4604 DocumentRoot
, script_name
+ 12);
4606 sprintf(server_port
, "SERVER_PORT=%d", con
->serverport
);
4608 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
4611 envc
= cupsdLoadEnv(envp
, (int)(sizeof(envp
) / sizeof(envp
[0])));
4614 envp
[envc
++] = auth_type
;
4616 envp
[envc
++] = lang
;
4617 envp
[envc
++] = "REDIRECT_STATUS=1";
4618 envp
[envc
++] = "GATEWAY_INTERFACE=CGI/1.1";
4619 envp
[envc
++] = server_name
;
4620 envp
[envc
++] = server_port
;
4621 envp
[envc
++] = remote_addr
;
4622 envp
[envc
++] = remote_host
;
4623 envp
[envc
++] = script_name
;
4624 envp
[envc
++] = script_filename
;
4627 envp
[envc
++] = path_info
;
4629 if (con
->username
[0])
4631 snprintf(remote_user
, sizeof(remote_user
), "REMOTE_USER=%s", con
->username
);
4633 envp
[envc
++] = remote_user
;
4636 * Save Kerberos credentials, if any...
4641 ccache
= cupsdCopyKrb5Creds(con
);
4642 #endif /* HAVE_GSSAPI */
4645 if (con
->http
.version
== HTTP_1_1
)
4646 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.1";
4647 else if (con
->http
.version
== HTTP_1_0
)
4648 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.0";
4650 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/0.9";
4652 if (con
->http
.cookie
)
4654 snprintf(http_cookie
, sizeof(http_cookie
), "HTTP_COOKIE=%s",
4656 envp
[envc
++] = http_cookie
;
4659 if (con
->http
.fields
[HTTP_FIELD_USER_AGENT
][0])
4661 snprintf(http_user_agent
, sizeof(http_user_agent
), "HTTP_USER_AGENT=%s",
4662 con
->http
.fields
[HTTP_FIELD_USER_AGENT
]);
4663 envp
[envc
++] = http_user_agent
;
4666 if (con
->http
.fields
[HTTP_FIELD_REFERER
][0])
4668 snprintf(http_referer
, sizeof(http_referer
), "HTTP_REFERER=%s",
4669 con
->http
.fields
[HTTP_FIELD_REFERER
]);
4670 envp
[envc
++] = http_referer
;
4673 if (con
->operation
== HTTP_GET
)
4675 envp
[envc
++] = "REQUEST_METHOD=GET";
4677 if (con
->query_string
)
4680 * Add GET form variables after ?...
4683 envp
[envc
++] = con
->query_string
;
4686 envp
[envc
++] = "QUERY_STRING=";
4690 sprintf(content_length
, "CONTENT_LENGTH=" CUPS_LLFMT
,
4691 CUPS_LLCAST con
->bytes
);
4692 snprintf(content_type
, sizeof(content_type
), "CONTENT_TYPE=%s",
4693 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
4695 envp
[envc
++] = "REQUEST_METHOD=POST";
4696 envp
[envc
++] = content_length
;
4697 envp
[envc
++] = content_type
;
4701 * Tell the CGI if we are using encryption...
4705 envp
[envc
++] = "HTTPS=ON";
4708 * Terminate the environment array...
4713 if (LogLevel
>= CUPSD_LOG_DEBUG
)
4715 for (i
= 0; i
< argc
; i
++)
4716 cupsdLogMessage(CUPSD_LOG_DEBUG
,
4717 "[CGI] argv[%d] = \"%s\"", i
, argv
[i
]);
4718 for (i
= 0; i
< envc
; i
++)
4719 cupsdLogMessage(CUPSD_LOG_DEBUG
,
4720 "[CGI] envp[%d] = \"%s\"", i
, envp
[i
]);
4724 * Create a pipe for the output...
4727 if (cupsdOpenPipe(fds
))
4729 cupsdLogMessage(CUPSD_LOG_ERROR
, "[CGI] Unable to create pipe for %s - %s",
4730 argv
[0], strerror(errno
));
4735 * Then execute the command...
4738 if (cupsdStartProcess(command
, argv
, envp
, infile
, fds
[1], CGIPipes
[1],
4739 -1, -1, root
, DefaultProfile
, NULL
, &pid
) < 0)
4742 * Error - can't fork!
4745 cupsdLogMessage(CUPSD_LOG_ERROR
, "[CGI] Unable to start %s - %s", argv
[0],
4748 cupsdClosePipe(fds
);
4754 * Fork successful - return the PID...
4757 if (con
->username
[0])
4758 cupsdAddCert(pid
, con
->username
, ccache
);
4760 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[CGI] Started %s (PID %d)", command
, pid
);
4771 * 'valid_host()' - Is the Host: field valid?
4774 static int /* O - 1 if valid, 0 if not */
4775 valid_host(cupsd_client_t
*con
) /* I - Client connection */
4777 cupsd_alias_t
*a
; /* Current alias */
4778 cupsd_netif_t
*netif
; /* Current network interface */
4779 const char *host
, /* Host field */
4780 *end
; /* End character */
4783 host
= con
->http
.fields
[HTTP_FIELD_HOST
];
4785 if (httpAddrLocalhost(con
->http
.hostaddr
))
4788 * Only allow "localhost" or the equivalent IPv4 or IPv6 numerical
4789 * addresses when accessing CUPS via the loopback interface...
4792 return (!strcasecmp(host
, "localhost") ||
4793 !strncasecmp(host
, "localhost:", 10) ||
4794 !strcasecmp(host
, "localhost.") ||
4795 !strncasecmp(host
, "localhost.:", 11) ||
4797 !strcasecmp(host
, "localhost.localdomain") ||
4798 !strncasecmp(host
, "localhost.localdomain:", 22) ||
4799 #endif /* __linux */
4800 !strcmp(host
, "127.0.0.1") ||
4801 !strncmp(host
, "127.0.0.1:", 10) ||
4802 !strcmp(host
, "[::1]") ||
4803 !strncmp(host
, "[::1]:", 6));
4808 * Check if the hostname is something.local (Bonjour); if so, allow it.
4811 if ((end
= strrchr(host
, '.')) != NULL
&&
4812 (!strcasecmp(end
, ".local") || !strncasecmp(end
, ".local:", 7) ||
4813 !strcasecmp(end
, ".local.") || !strncasecmp(end
, ".local.:", 8)))
4815 #endif /* HAVE_DNSSD */
4818 * Check if the hostname is an IP address...
4821 if (isdigit(*host
& 255) || *host
== '[')
4824 * Possible IPv4/IPv6 address...
4827 char temp
[1024], /* Temporary string */
4828 *ptr
; /* Pointer into temporary string */
4829 http_addrlist_t
*addrlist
; /* List of addresses */
4832 strlcpy(temp
, host
, sizeof(temp
));
4833 if ((ptr
= strrchr(temp
, ':')) != NULL
&& !strchr(ptr
, ']'))
4834 *ptr
= '\0'; /* Strip :port from host value */
4836 if ((addrlist
= httpAddrGetList(temp
, AF_UNSPEC
, NULL
)) != NULL
)
4839 * Good IPv4/IPv6 address...
4842 httpAddrFreeList(addrlist
);
4848 * Check for (alias) name matches...
4851 for (a
= (cupsd_alias_t
*)cupsArrayFirst(ServerAlias
);
4853 a
= (cupsd_alias_t
*)cupsArrayNext(ServerAlias
))
4856 * "ServerAlias *" allows all host values through...
4859 if (!strcmp(a
->name
, "*"))
4862 if (!strncasecmp(host
, a
->name
, a
->namelen
))
4865 * Prefix matches; check the character at the end - it must be ":", ".",
4869 end
= host
+ a
->namelen
;
4871 if (!*end
|| *end
== ':' || (*end
== '.' && (!end
[1] || end
[1] == ':')))
4877 for (a
= (cupsd_alias_t
*)cupsArrayFirst(DNSSDAlias
);
4879 a
= (cupsd_alias_t
*)cupsArrayNext(DNSSDAlias
))
4882 * "ServerAlias *" allows all host values through...
4885 if (!strcmp(a
->name
, "*"))
4888 if (!strncasecmp(host
, a
->name
, a
->namelen
))
4891 * Prefix matches; check the character at the end - it must be ":", ".",
4895 end
= host
+ a
->namelen
;
4897 if (!*end
|| *end
== ':' || (*end
== '.' && (!end
[1] || end
[1] == ':')))
4901 #endif /* HAVE_DNSSD */
4904 * Check for interface hostname matches...
4907 for (netif
= (cupsd_netif_t
*)cupsArrayFirst(NetIFList
);
4909 netif
= (cupsd_netif_t
*)cupsArrayNext(NetIFList
))
4911 if (!strncasecmp(host
, netif
->hostname
, netif
->hostlen
))
4914 * Prefix matches; check the character at the end - it must be ":", ".",
4918 end
= host
+ netif
->hostlen
;
4920 if (!*end
|| *end
== ':' || (*end
== '.' && (!end
[1] || end
[1] == ':')))
4930 * 'write_file()' - Send a file via HTTP.
4933 static int /* O - 0 on failure, 1 on success */
4934 write_file(cupsd_client_t
*con
, /* I - Client connection */
4935 http_status_t code
, /* I - HTTP status */
4936 char *filename
, /* I - Filename */
4937 char *type
, /* I - File type */
4938 struct stat
*filestats
) /* O - File information */
4940 con
->file
= open(filename
, O_RDONLY
);
4942 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4943 "write_file(con=%p(%d), code=%d, filename=\"%s\" (%d), "
4944 "type=\"%s\", filestats=%p)", con
, con
->http
.fd
,
4945 code
, filename
, con
->file
, type
? type
: "(null)", filestats
);
4950 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
4954 if (!cupsdSendHeader(con
, code
, type
, CUPSD_AUTH_NONE
))
4957 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
4958 httpGetDateString(filestats
->st_mtime
)) < 0)
4960 if (httpPrintf(HTTP(con
), "Content-Length: " CUPS_LLFMT
"\r\n",
4961 CUPS_LLCAST filestats
->st_size
) < 0)
4963 if (httpPrintf(HTTP(con
), "\r\n") < 0)
4966 if (cupsdFlushHeader(con
) < 0)
4969 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
4970 con
->http
.data_remaining
= filestats
->st_size
;
4972 if (con
->http
.data_remaining
<= INT_MAX
)
4973 con
->http
._data_remaining
= con
->http
.data_remaining
;
4975 con
->http
._data_remaining
= INT_MAX
;
4977 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
,
4978 (cupsd_selfunc_t
)cupsdWriteClient
, con
);
4985 * 'write_pipe()' - Flag that data is available on the CGI pipe.
4989 write_pipe(cupsd_client_t
*con
) /* I - Client connection */
4991 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4992 "write_pipe(con=%p(%d)) CGI output on fd %d",
4993 con
, con
->http
.fd
, con
->file
);
4995 con
->file_ready
= 1;
4997 cupsdRemoveSelect(con
->file
);
4998 cupsdAddSelect(con
->http
.fd
, NULL
, (cupsd_selfunc_t
)cupsdWriteClient
, con
);
5003 * End of "$Id: client.c 7950 2008-09-17 00:21:59Z mike $".