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 * write_file() - Send a file via HTTP.
45 * write_pipe() - Flag that data is available on the CGI pipe.
49 * Include necessary headers...
55 # include <Security/Security.h>
56 # ifdef HAVE_SECIDENTITYSEARCHPRIV_H
57 # include <Security/SecIdentitySearchPriv.h>
58 # else /* Declare prototype for function in that header... */
59 extern OSStatus
SecIdentitySearchCreateWithPolicy(SecPolicyRef policy
,
60 CFStringRef idString
, CSSM_KEYUSE keyUsage
,
61 CFTypeRef keychainOrArray
,
62 Boolean returnOnlyValidIdentities
,
63 SecIdentitySearchRef
* searchRef
);
64 # endif /* HAVE_SECIDENTITYSEARCHPRIV_H */
65 # ifdef HAVE_SECPOLICYPRIV_H
66 # include <Security/SecPolicyPriv.h>
67 # else /* Declare prototype for function in that header... */
68 extern OSStatus
SecPolicySetValue(SecPolicyRef policyRef
,
69 const CSSM_DATA
*value
);
70 # endif /* HAVE_SECPOLICYPRIV_H */
71 # ifdef HAVE_SECBASEPRIV_H
72 # include <Security/SecBasePriv.h>
73 # else /* Declare prototype for function in that header... */
74 extern const char *cssmErrorString(int error
);
75 # endif /* HAVE_SECBASEPRIV_H */
76 #endif /* HAVE_CDSASSL */
79 # include <gnutls/x509.h>
80 #endif /* HAVE_GNUTLS */
84 #endif /* HAVE_TCPD_H */
91 static int check_if_modified(cupsd_client_t
*con
,
92 struct stat
*filestats
);
93 static int compare_clients(cupsd_client_t
*a
, cupsd_client_t
*b
,
95 static int data_ready(cupsd_client_t
*con
);
97 static int encrypt_client(cupsd_client_t
*con
);
100 static CFArrayRef
get_cdsa_certificate(cupsd_client_t
*con
);
101 #endif /* HAVE_CDSASSL */
102 static char *get_file(cupsd_client_t
*con
, struct stat
*filestats
,
103 char *filename
, int len
);
104 static http_status_t
install_conf_file(cupsd_client_t
*con
);
105 static int is_cgi(cupsd_client_t
*con
, const char *filename
,
106 struct stat
*filestats
, mime_type_t
*type
);
107 static int is_path_absolute(const char *path
);
109 static int make_certificate(cupsd_client_t
*con
);
110 #endif /* HAVE_SSL */
111 static int pipe_command(cupsd_client_t
*con
, int infile
, int *outfile
,
112 char *command
, char *options
, int root
);
113 static int write_file(cupsd_client_t
*con
, http_status_t code
,
114 char *filename
, char *type
,
115 struct stat
*filestats
);
116 static void write_pipe(cupsd_client_t
*con
);
120 * 'cupsdAcceptClient()' - Accept a new client.
124 cupsdAcceptClient(cupsd_listener_t
*lis
)/* I - Listener socket */
126 int count
; /* Count of connections on a host */
127 int val
; /* Parameter value */
128 cupsd_client_t
*con
, /* New client pointer */
129 *tempcon
; /* Temporary client pointer */
130 http_addrlist_t
*addrlist
, /* List of adddresses for host */
131 *addr
; /* Current address */
132 socklen_t addrlen
; /* Length of address */
133 char *hostname
; /* Hostname for address */
134 http_addr_t temp
; /* Temporary address variable */
135 static time_t last_dos
= 0; /* Time of last DoS attack */
137 struct request_info wrap_req
; /* TCP wrappers request information */
138 #endif /* HAVE_TCPD_H */
141 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
142 "cupsdAcceptClient(lis=%p(%d)) Clients=%d",
143 lis
, lis
->fd
, cupsArrayCount(Clients
));
146 * Make sure we don't have a full set of clients already...
149 if (cupsArrayCount(Clients
) == MaxClients
)
153 * Get a pointer to the next available client...
157 Clients
= cupsArrayNew(NULL
, NULL
);
161 cupsdLogMessage(CUPSD_LOG_ERROR
,
162 "Unable to allocate memory for clients array!");
163 cupsdPauseListening();
168 ActiveClients
= cupsArrayNew((cups_array_func_t
)compare_clients
, NULL
);
172 cupsdLogMessage(CUPSD_LOG_ERROR
,
173 "Unable to allocate memory for active clients array!");
174 cupsdPauseListening();
178 if ((con
= calloc(1, sizeof(cupsd_client_t
))) == NULL
)
180 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to allocate memory for client!");
181 cupsdPauseListening();
185 con
->http
.activity
= time(NULL
);
187 con
->http
.hostaddr
= &(con
->clientaddr
);
190 * Accept the client and get the remote address...
193 addrlen
= sizeof(http_addr_t
);
195 if ((con
->http
.fd
= accept(lis
->fd
, (struct sockaddr
*)con
->http
.hostaddr
,
198 if (errno
== ENFILE
|| errno
== EMFILE
)
199 cupsdPauseListening();
201 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to accept client connection - %s.",
209 if (lis
->address
.addr
.sa_family
== AF_INET6
)
212 * Save the connected port number...
215 con
->http
.hostaddr
->ipv6
.sin6_port
= lis
->address
.ipv6
.sin6_port
;
218 * Convert IPv4 over IPv6 addresses (::ffff:n.n.n.n) to IPv4 forms we
219 * can more easily use...
222 if (con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[0] == 0 &&
223 con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[1] == 0 &&
224 ntohl(con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[2]) == 0xffff)
225 con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[2] = 0;
228 #endif /* AF_INET6 */
229 if (lis
->address
.addr
.sa_family
== AF_INET
)
230 con
->http
.hostaddr
->ipv4
.sin_port
= lis
->address
.ipv4
.sin_port
;
233 * Check the number of clients on the same address...
236 for (count
= 0, tempcon
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
238 tempcon
= (cupsd_client_t
*)cupsArrayNext(Clients
))
239 if (httpAddrEqual(tempcon
->http
.hostaddr
, con
->http
.hostaddr
))
242 if (count
>= MaxClientsPerHost
)
246 if (count
>= MaxClientsPerHost
)
248 if ((time(NULL
) - last_dos
) >= 60)
250 last_dos
= time(NULL
);
251 cupsdLogMessage(CUPSD_LOG_WARN
,
252 "Possible DoS attack - more than %d clients connecting "
255 httpAddrString(con
->http
.hostaddr
, con
->http
.hostname
,
256 sizeof(con
->http
.hostname
)));
260 closesocket(con
->http
.fd
);
270 * Get the hostname or format the IP address as needed...
273 if (httpAddrLocalhost(con
->http
.hostaddr
))
276 * Map accesses from the loopback interface to "localhost"...
279 strlcpy(con
->http
.hostname
, "localhost", sizeof(con
->http
.hostname
));
280 hostname
= con
->http
.hostname
;
285 * Map accesses from the same host to the server name.
289 hostname
= httpAddrLookup(con
->http
.hostaddr
, con
->http
.hostname
,
290 sizeof(con
->http
.hostname
));
294 httpAddrString(con
->http
.hostaddr
, con
->http
.hostname
,
295 sizeof(con
->http
.hostname
));
299 if (hostname
== NULL
&& HostNameLookups
== 2)
302 * Can't have an unresolved IP address with double-lookups enabled...
306 closesocket(con
->http
.fd
);
311 cupsdLogMessage(CUPSD_LOG_WARN
,
312 "Name lookup failed - connection from %s closed!",
319 if (HostNameLookups
== 2)
322 * Do double lookups as needed...
325 if ((addrlist
= httpAddrGetList(con
->http
.hostname
, AF_UNSPEC
, NULL
))
329 * See if the hostname maps to the same IP address...
332 for (addr
= addrlist
; addr
; addr
= addr
->next
)
333 if (httpAddrEqual(con
->http
.hostaddr
, &(addr
->addr
)))
339 httpAddrFreeList(addrlist
);
344 * Can't have a hostname that doesn't resolve to the same IP address
345 * with double-lookups enabled...
349 closesocket(con
->http
.fd
);
354 cupsdLogMessage(CUPSD_LOG_WARN
,
355 "IP lookup failed - connection from %s closed!",
364 * See if the connection is denied by TCP wrappers...
367 request_init(&wrap_req
, RQ_DAEMON
, "cupsd", RQ_FILE
, con
->http
.fd
, NULL
);
370 if (!hosts_access(&wrap_req
))
373 closesocket(con
->http
.fd
);
378 cupsdLogMessage(CUPSD_LOG_WARN
,
379 "Connection from %s refused by /etc/hosts.allow and "
380 "/etc/hosts.deny rules.", con
->http
.hostname
);
384 #endif /* HAVE_TCPD_H */
387 if (con
->http
.hostaddr
->addr
.sa_family
== AF_INET6
)
388 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdAcceptClient: %d from %s:%d (IPv6)",
389 con
->http
.fd
, con
->http
.hostname
,
390 ntohs(con
->http
.hostaddr
->ipv6
.sin6_port
));
392 #endif /* AF_INET6 */
394 if (con
->http
.hostaddr
->addr
.sa_family
== AF_LOCAL
)
395 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdAcceptClient: %d from %s (Domain)",
396 con
->http
.fd
, con
->http
.hostname
);
398 #endif /* AF_LOCAL */
399 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdAcceptClient: %d from %s:%d (IPv4)",
400 con
->http
.fd
, con
->http
.hostname
,
401 ntohs(con
->http
.hostaddr
->ipv4
.sin_port
));
404 * Get the local address the client connected to...
407 addrlen
= sizeof(temp
);
408 if (getsockname(con
->http
.fd
, (struct sockaddr
*)&temp
, &addrlen
))
410 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to get local address - %s",
413 strcpy(con
->servername
, "localhost");
414 con
->serverport
= LocalPort
;
419 if (temp
.addr
.sa_family
== AF_INET6
)
422 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
423 else if (httpAddrLocalhost(&temp
))
424 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
426 httpAddrString(&temp
, con
->servername
, sizeof(con
->servername
));
428 con
->serverport
= ntohs(lis
->address
.ipv6
.sin6_port
);
431 #endif /* AF_INET6 */
432 if (temp
.addr
.sa_family
== AF_INET
)
435 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
436 else if (httpAddrLocalhost(&temp
))
437 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
439 httpAddrString(&temp
, con
->servername
, sizeof(con
->servername
));
441 con
->serverport
= ntohs(lis
->address
.ipv4
.sin_port
);
445 strcpy(con
->servername
, "localhost");
446 con
->serverport
= LocalPort
;
450 cupsArrayAdd(Clients
, con
);
453 * Using TCP_NODELAY improves responsiveness, especially on systems with a slow
454 * loopback interface. Since we write large buffers when sending print files
455 * and requests there shouldn't be any performance penalty for this...
459 setsockopt(con
->http
.fd
, IPPROTO_TCP
, TCP_NODELAY
, &val
, sizeof(val
));
462 * Close this file on all execs...
465 fcntl(con
->http
.fd
, F_SETFD
, fcntl(con
->http
.fd
, F_GETFD
) | FD_CLOEXEC
);
468 * Add the socket to the server select.
471 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
474 * Temporarily suspend accept()'s until we lose a client...
477 if (cupsArrayCount(Clients
) == MaxClients
)
478 cupsdPauseListening();
482 * See if we are connecting on a secure port...
485 if (lis
->encryption
== HTTP_ENCRYPT_ALWAYS
)
488 * https connection; go secure...
491 con
->http
.encryption
= HTTP_ENCRYPT_ALWAYS
;
493 if (!encrypt_client(con
))
494 cupsdCloseClient(con
);
498 #endif /* HAVE_SSL */
503 * 'cupsdCloseAllClients()' - Close all remote clients immediately.
507 cupsdCloseAllClients(void)
509 cupsd_client_t
*con
; /* Current client */
512 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdCloseAllClients() Clients=%d",
513 cupsArrayCount(Clients
));
515 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
517 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
518 if (cupsdCloseClient(con
))
519 cupsdCloseClient(con
);
524 * 'cupsdCloseClient()' - Close a remote client.
527 int /* O - 1 if partial close, 0 if fully closed */
528 cupsdCloseClient(cupsd_client_t
*con
) /* I - Client to close */
530 int partial
; /* Do partial close for SSL? */
532 SSL_CTX
*context
; /* Context for encryption */
533 SSL
*conn
; /* Connection for encryption */
534 unsigned long error
; /* Error code */
535 #elif defined(HAVE_GNUTLS)
536 http_tls_t
*conn
; /* TLS connection information */
537 int error
; /* Error code */
538 gnutls_certificate_server_credentials
*credentials
;
539 /* TLS credentials */
540 # elif defined(HAVE_CDSASSL)
541 http_tls_t
*conn
; /* CDSA connection information */
542 #endif /* HAVE_LIBSSL */
545 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdCloseClient(con=%p(%d))", con
,
549 * Flush pending writes before closing...
552 httpFlushWrite(HTTP(con
));
558 * Shutdown encryption as needed...
566 conn
= (SSL
*)(con
->http
.tls
);
567 context
= SSL_get_SSL_CTX(conn
);
569 switch (SSL_shutdown(conn
))
572 cupsdLogMessage(CUPSD_LOG_DEBUG
,
573 "SSL shutdown successful!");
576 cupsdLogMessage(CUPSD_LOG_ERROR
,
577 "Fatal error during SSL shutdown!");
579 while ((error
= ERR_get_error()) != 0)
580 cupsdLogMessage(CUPSD_LOG_ERROR
, "SSL shutdown failed: %s",
581 ERR_error_string(error
, NULL
));
585 SSL_CTX_free(context
);
588 # elif defined(HAVE_GNUTLS)
589 conn
= (http_tls_t
*)(con
->http
.tls
);
590 credentials
= (gnutls_certificate_server_credentials
*)(conn
->credentials
);
592 error
= gnutls_bye(conn
->session
, GNUTLS_SHUT_WR
);
595 case GNUTLS_E_SUCCESS
:
596 cupsdLogMessage(CUPSD_LOG_DEBUG
,
597 "SSL shutdown successful!");
600 cupsdLogMessage(CUPSD_LOG_ERROR
,
601 "SSL shutdown failed: %s", gnutls_strerror(error
));
605 gnutls_deinit(conn
->session
);
606 gnutls_certificate_free_credentials(*credentials
);
610 # elif defined(HAVE_CDSASSL)
611 conn
= (http_tls_t
*)(con
->http
.tls
);
613 while (SSLClose(conn
->session
) == errSSLWouldBlock
)
616 SSLDisposeContext(conn
->session
);
618 if (conn
->certsArray
)
619 CFRelease(conn
->certsArray
);
622 # endif /* HAVE_LIBSSL */
624 con
->http
.tls
= NULL
;
626 #endif /* HAVE_SSL */
628 if (con
->pipe_pid
!= 0)
631 * Stop any CGI process...
634 cupsdEndProcess(con
->pipe_pid
, 1);
640 cupsdRemoveSelect(con
->file
);
647 * Close the socket and clear the file from the input set for select()...
650 if (con
->http
.fd
>= 0)
652 cupsArrayRemove(ActiveClients
, con
);
658 * Only do a partial close so that the encrypted client gets everything.
661 shutdown(con
->http
.fd
, 0);
662 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
667 * Shut the socket down fully...
670 cupsdRemoveSelect(con
->http
.fd
);
682 if (con
->http
.input_set
)
683 free(con
->http
.input_set
);
685 httpClearCookie(HTTP(con
));
686 httpClearFields(HTTP(con
));
688 cupsdClearString(&con
->filename
);
689 cupsdClearString(&con
->command
);
690 cupsdClearString(&con
->options
);
691 cupsdClearString(&con
->query_string
);
695 ippDelete(con
->request
);
701 ippDelete(con
->response
);
702 con
->response
= NULL
;
707 cupsLangFree(con
->language
);
708 con
->language
= NULL
;
711 #ifdef HAVE_AUTHORIZATION_H
714 AuthorizationFree(con
->authref
, kAuthorizationFlagDefaults
);
717 #endif /* HAVE_AUTHORIZATION_H */
720 * Re-enable new client connections if we are going back under the
724 if (cupsArrayCount(Clients
) == MaxClients
)
725 cupsdResumeListening();
728 * Compact the list of clients as necessary...
731 cupsArrayRemove(Clients
, con
);
741 * 'cupsdFlushHeader()' - Flush the header fields to the client.
744 int /* I - Bytes written or -1 on error */
745 cupsdFlushHeader(cupsd_client_t
*con
) /* I - Client to flush to */
747 int bytes
= httpFlushWrite(HTTP(con
));
749 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
756 * 'cupsdReadClient()' - Read data from a client.
760 cupsdReadClient(cupsd_client_t
*con
) /* I - Client to read from */
762 char line
[32768], /* Line from client... */
763 operation
[64], /* Operation code from socket */
764 version
[64], /* HTTP version number string */
765 locale
[64], /* Locale */
766 *ptr
; /* Pointer into strings */
767 int major
, minor
; /* HTTP version numbers */
768 http_status_t status
; /* Transfer status */
769 ipp_state_t ipp_state
; /* State of IPP transfer */
770 int bytes
; /* Number of bytes to POST */
771 char *filename
; /* Name of file for GET/HEAD */
772 char buf
[1024]; /* Buffer for real filename */
773 struct stat filestats
; /* File information */
774 mime_type_t
*type
; /* MIME type of file */
775 cupsd_printer_t
*p
; /* Printer */
776 static unsigned request_id
= 0; /* Request ID for temp files */
779 status
= HTTP_CONTINUE
;
781 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
782 "cupsdReadClient(con=%p(%d)) "
783 "con->http.error=%d "
784 "con->http.used=%d, "
785 "con->http.state=%d "
786 "con->data_encoding=HTTP_ENCODE_%s, "
787 "con->data_remaining=" CUPS_LLFMT
", "
789 con
, con
->http
.fd
, con
->http
.error
, con
->http
.used
,
791 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
?
792 "CHUNKED" : "LENGTH",
793 CUPS_LLCAST con
->http
.data_remaining
, con
->file
);
797 cupsdCloseClient(con
);
805 * Automatically check for a SSL/TLS handshake...
810 if (recv(con
->http
.fd
, buf
, 1, MSG_PEEK
) == 1 &&
811 (!buf
[0] || !strchr("DGHOPT", buf
[0])))
814 * Encrypt this connection...
817 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
818 "cupsdReadClient: Saw first byte %02X, auto-negotiating "
819 "SSL/TLS session...", buf
[0] & 255);
821 if (!encrypt_client(con
))
822 cupsdCloseClient(con
);
827 #endif /* HAVE_SSL */
829 switch (con
->http
.state
)
833 * See if we've received a request line...
836 if (httpGets(line
, sizeof(line
) - 1, HTTP(con
)) == NULL
)
838 cupsdCloseClient(con
);
843 * Ignore blank request lines...
850 * Clear other state variables...
853 httpClearFields(HTTP(con
));
855 con
->http
.activity
= time(NULL
);
856 con
->http
.version
= HTTP_1_0
;
857 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
858 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
859 con
->http
.data_remaining
= 0;
860 con
->http
._data_remaining
= 0;
861 con
->operation
= HTTP_WAITING
;
866 con
->username
[0] = '\0';
867 con
->password
[0] = '\0';
870 cupsdClearString(&con
->command
);
871 cupsdClearString(&con
->options
);
872 cupsdClearString(&con
->query_string
);
876 ippDelete(con
->request
);
882 ippDelete(con
->response
);
883 con
->response
= NULL
;
888 cupsLangFree(con
->language
);
889 con
->language
= NULL
;
893 con
->gss_have_creds
= 0;
894 #endif /* HAVE_GSSAPI */
897 * Grab the request line...
900 switch (sscanf(line
, "%63s%1023s%63s", operation
, con
->uri
, version
))
905 cupsdLogMessage(CUPSD_LOG_ERROR
,
906 "Bad request line \"%s\" from %s!", line
,
908 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
909 cupsdCloseClient(con
);
913 con
->http
.version
= HTTP_0_9
;
916 if (sscanf(version
, "HTTP/%d.%d", &major
, &minor
) != 2)
918 cupsdLogMessage(CUPSD_LOG_ERROR
,
919 "Bad request line \"%s\" from %s!", line
,
921 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
922 cupsdCloseClient(con
);
928 con
->http
.version
= (http_version_t
)(major
* 100 + minor
);
929 if (con
->http
.version
== HTTP_1_1
&& KeepAlive
)
930 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
932 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
936 cupsdSendError(con
, HTTP_NOT_SUPPORTED
, CUPSD_AUTH_NONE
);
937 cupsdCloseClient(con
);
944 * Handle full URLs in the request line...
947 if (strcmp(con
->uri
, "*"))
949 char scheme
[HTTP_MAX_URI
], /* Method/scheme */
950 userpass
[HTTP_MAX_URI
], /* Username:password */
951 hostname
[HTTP_MAX_URI
], /* Hostname */
952 resource
[HTTP_MAX_URI
]; /* Resource path */
953 int port
; /* Port number */
957 * Separate the URI into its components...
960 httpSeparateURI(HTTP_URI_CODING_MOST
, con
->uri
,
961 scheme
, sizeof(scheme
),
962 userpass
, sizeof(userpass
),
963 hostname
, sizeof(hostname
), &port
,
964 resource
, sizeof(resource
));
967 * Only allow URIs with the servername, localhost, or an IP
971 if (strcmp(scheme
, "file") &&
972 strcasecmp(hostname
, ServerName
) &&
973 strcasecmp(hostname
, "localhost") &&
974 !isdigit(hostname
[0]) && hostname
[0] != '[')
977 * Nope, we don't do proxies...
980 cupsdLogMessage(CUPSD_LOG_ERROR
, "Bad URI \"%s\" in request!",
982 cupsdSendError(con
, HTTP_METHOD_NOT_ALLOWED
, CUPSD_AUTH_NONE
);
983 cupsdCloseClient(con
);
988 * Copy the resource portion back into the URI; both resource and
989 * con->uri are HTTP_MAX_URI bytes in size...
992 strcpy(con
->uri
, resource
);
996 * Process the request...
999 if (!strcmp(operation
, "GET"))
1000 con
->http
.state
= HTTP_GET
;
1001 else if (!strcmp(operation
, "PUT"))
1002 con
->http
.state
= HTTP_PUT
;
1003 else if (!strcmp(operation
, "POST"))
1004 con
->http
.state
= HTTP_POST
;
1005 else if (!strcmp(operation
, "DELETE"))
1006 con
->http
.state
= HTTP_DELETE
;
1007 else if (!strcmp(operation
, "TRACE"))
1008 con
->http
.state
= HTTP_TRACE
;
1009 else if (!strcmp(operation
, "OPTIONS"))
1010 con
->http
.state
= HTTP_OPTIONS
;
1011 else if (!strcmp(operation
, "HEAD"))
1012 con
->http
.state
= HTTP_HEAD
;
1015 cupsdLogMessage(CUPSD_LOG_ERROR
, "Bad operation \"%s\"!", operation
);
1016 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
1017 cupsdCloseClient(con
);
1021 gettimeofday(&(con
->start
), NULL
);
1022 con
->operation
= con
->http
.state
;
1024 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdReadClient: %d %s %s HTTP/%d.%d",
1025 con
->http
.fd
, operation
, con
->uri
,
1026 con
->http
.version
/ 100, con
->http
.version
% 100);
1028 con
->http
.status
= HTTP_OK
;
1030 if (!cupsArrayFind(ActiveClients
, con
))
1032 cupsArrayAdd(ActiveClients
, con
);
1033 cupsdSetBusyState();
1044 * Parse incoming parameters until the status changes...
1047 while ((status
= httpUpdate(HTTP(con
))) == HTTP_CONTINUE
)
1048 if (!data_ready(con
))
1051 if (status
!= HTTP_OK
&& status
!= HTTP_CONTINUE
)
1053 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
1054 cupsdCloseClient(con
);
1060 if (!data_ready(con
) && recv(con
->http
.fd
, buf
, 1, MSG_PEEK
) < 1)
1063 * Connection closed...
1066 cupsdCloseClient(con
);
1069 break; /* Anti-compiler-warning-code */
1073 * Handle new transfers...
1076 if (status
== HTTP_OK
)
1078 if (con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
][0])
1081 * Figure out the locale from the Accept-Language and Content-Type
1085 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ',')) != NULL
)
1088 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ';')) != NULL
)
1091 if ((ptr
= strstr(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
], "charset=")) != NULL
)
1094 * Combine language and charset, and trim any extra params in the
1098 snprintf(locale
, sizeof(locale
), "%s.%s",
1099 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ptr
+ 8);
1101 if ((ptr
= strchr(locale
, ',')) != NULL
)
1105 snprintf(locale
, sizeof(locale
), "%s.%s",
1106 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], DefaultCharset
);
1108 con
->language
= cupsLangGet(locale
);
1111 con
->language
= cupsLangGet(DefaultLocale
);
1113 cupsdAuthorize(con
);
1115 if (!strncasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Keep-Alive", 10) &&
1117 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
1118 else if (!strncasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "close", 5))
1119 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1121 if (!con
->http
.fields
[HTTP_FIELD_HOST
][0] &&
1122 con
->http
.version
>= HTTP_1_1
)
1125 * HTTP/1.1 and higher require the "Host:" field...
1128 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1130 cupsdCloseClient(con
);
1134 else if (httpAddrLocalhost(con
->http
.hostaddr
) &&
1135 strcasecmp(con
->http
.fields
[HTTP_FIELD_HOST
], "localhost") &&
1136 strncasecmp(con
->http
.fields
[HTTP_FIELD_HOST
], "localhost:", 10) &&
1137 strcmp(con
->http
.fields
[HTTP_FIELD_HOST
], "127.0.0.1") &&
1138 strncmp(con
->http
.fields
[HTTP_FIELD_HOST
], "127.0.0.1:", 10) &&
1139 strcmp(con
->http
.fields
[HTTP_FIELD_HOST
], "[::1]") &&
1140 strncmp(con
->http
.fields
[HTTP_FIELD_HOST
], "[::1]:", 6))
1143 * Access to localhost must use "localhost" or the corresponding IPv4
1144 * or IPv6 values in the Host: field.
1147 cupsdLogMessage(CUPSD_LOG_WARN
,
1148 "Request from \"%s\" using invalid Host: field \"%s\"",
1149 con
->http
.hostname
, con
->http
.fields
[HTTP_FIELD_HOST
]);
1151 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1153 cupsdCloseClient(con
);
1157 else if (con
->operation
== HTTP_OPTIONS
)
1160 * Do OPTIONS command...
1163 if (con
->best
&& con
->best
->type
!= CUPSD_AUTH_NONE
)
1165 if (!cupsdSendHeader(con
, HTTP_UNAUTHORIZED
, NULL
, CUPSD_AUTH_NONE
))
1167 cupsdCloseClient(con
);
1172 if (!strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") &&
1173 con
->http
.tls
== NULL
)
1177 * Do encryption stuff...
1180 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
, CUPSD_AUTH_NONE
))
1182 cupsdCloseClient(con
);
1186 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1187 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1188 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1189 httpPrintf(HTTP(con
), "\r\n");
1191 if (cupsdFlushHeader(con
) < 0)
1193 cupsdCloseClient(con
);
1197 if (!encrypt_client(con
))
1199 cupsdCloseClient(con
);
1203 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
1205 cupsdCloseClient(con
);
1208 #endif /* HAVE_SSL */
1211 if (!cupsdSendHeader(con
, HTTP_OK
, NULL
, CUPSD_AUTH_NONE
))
1213 cupsdCloseClient(con
);
1217 httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n");
1218 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1219 httpPrintf(HTTP(con
), "\r\n");
1221 if (cupsdFlushHeader(con
) < 0)
1223 cupsdCloseClient(con
);
1227 else if (!is_path_absolute(con
->uri
))
1230 * Protect against malicious users!
1233 cupsdLogMessage(CUPSD_LOG_ERROR
,
1234 "Request for non-absolute resource \"%s\"!", con
->uri
);
1236 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1238 cupsdCloseClient(con
);
1244 if (!strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") &&
1245 con
->http
.tls
== NULL
)
1249 * Do encryption stuff...
1252 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
, CUPSD_AUTH_NONE
))
1254 cupsdCloseClient(con
);
1258 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1259 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1260 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1261 httpPrintf(HTTP(con
), "\r\n");
1263 if (cupsdFlushHeader(con
) < 0)
1265 cupsdCloseClient(con
);
1269 if (!encrypt_client(con
))
1271 cupsdCloseClient(con
);
1275 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
1277 cupsdCloseClient(con
);
1280 #endif /* HAVE_SSL */
1283 if ((status
= cupsdIsAuthorized(con
, NULL
)) != HTTP_OK
)
1285 cupsdSendError(con
, status
, CUPSD_AUTH_NONE
);
1286 cupsdCloseClient(con
);
1290 if (con
->http
.expect
&&
1291 (con
->operation
== HTTP_POST
|| con
->operation
== HTTP_PUT
))
1293 if (con
->http
.expect
== HTTP_CONTINUE
)
1296 * Send 100-continue header...
1299 if (!cupsdSendHeader(con
, HTTP_CONTINUE
, NULL
, CUPSD_AUTH_NONE
))
1301 cupsdCloseClient(con
);
1308 * Send 417-expectation-failed header...
1311 if (!cupsdSendHeader(con
, HTTP_EXPECTATION_FAILED
, NULL
, CUPSD_AUTH_NONE
))
1313 cupsdCloseClient(con
);
1317 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1318 httpPrintf(HTTP(con
), "\r\n");
1320 if (cupsdFlushHeader(con
) < 0)
1322 cupsdCloseClient(con
);
1328 switch (con
->http
.state
)
1330 case HTTP_GET_SEND
:
1331 if (!strncmp(con
->uri
, "/printers/", 10) &&
1332 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1335 * Send PPD file - get the real printer name since printer
1336 * names are not case sensitive but filenames can be...
1339 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1341 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1342 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1345 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1347 cupsdCloseClient(con
);
1355 if ((!strncmp(con
->uri
, "/admin", 6) &&
1356 strncmp(con
->uri
, "/admin/conf/", 12) &&
1357 strncmp(con
->uri
, "/admin/log/", 11)) ||
1358 !strncmp(con
->uri
, "/printers", 9) ||
1359 !strncmp(con
->uri
, "/classes", 8) ||
1360 !strncmp(con
->uri
, "/help", 5) ||
1361 !strncmp(con
->uri
, "/jobs", 5))
1364 * Send CGI output...
1367 if (!strncmp(con
->uri
, "/admin", 6))
1369 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1372 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1374 else if (!strncmp(con
->uri
, "/printers", 9))
1376 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1379 if (con
->uri
[9] && con
->uri
[10])
1380 cupsdSetString(&con
->options
, con
->uri
+ 9);
1382 cupsdSetString(&con
->options
, NULL
);
1384 else if (!strncmp(con
->uri
, "/classes", 8))
1386 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1389 if (con
->uri
[8] && con
->uri
[9])
1390 cupsdSetString(&con
->options
, con
->uri
+ 8);
1392 cupsdSetString(&con
->options
, NULL
);
1394 else if (!strncmp(con
->uri
, "/jobs", 5))
1396 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1399 if (con
->uri
[5] && con
->uri
[6])
1400 cupsdSetString(&con
->options
, con
->uri
+ 5);
1402 cupsdSetString(&con
->options
, NULL
);
1406 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1409 if (con
->uri
[5] && con
->uri
[6])
1410 cupsdSetString(&con
->options
, con
->uri
+ 5);
1412 cupsdSetString(&con
->options
, NULL
);
1415 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1417 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1419 cupsdCloseClient(con
);
1424 cupsdLogRequest(con
, HTTP_OK
);
1426 if (con
->http
.version
<= HTTP_1_0
)
1427 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1429 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1430 (strchr(con
->uri
+ 12, '/') ||
1431 strlen(con
->uri
) == 12)) ||
1432 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1433 (strchr(con
->uri
+ 11, '/') ||
1434 strlen(con
->uri
) == 11)))
1437 * GET can only be done to configuration files directly under
1441 cupsdLogMessage(CUPSD_LOG_ERROR
,
1442 "Request for subdirectory \"%s\"!", con
->uri
);
1444 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1446 cupsdCloseClient(con
);
1458 if ((filename
= get_file(con
, &filestats
, buf
,
1459 sizeof(buf
))) == NULL
)
1461 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1463 cupsdCloseClient(con
);
1470 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1472 if (is_cgi(con
, filename
, &filestats
, type
))
1475 * Note: con->command and con->options were set by
1479 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1481 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1483 cupsdCloseClient(con
);
1488 cupsdLogRequest(con
, HTTP_OK
);
1490 if (con
->http
.version
<= HTTP_1_0
)
1491 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1495 if (!check_if_modified(con
, &filestats
))
1497 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1499 cupsdCloseClient(con
);
1506 strcpy(line
, "text/plain");
1508 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1510 if (!write_file(con
, HTTP_OK
, filename
, line
, &filestats
))
1512 cupsdCloseClient(con
);
1519 case HTTP_POST_RECV
:
1521 * See if the POST request includes a Content-Length field, and if
1522 * so check the length against any limits that are set...
1525 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1526 MaxRequestSize
> 0 &&
1527 con
->http
.data_remaining
> MaxRequestSize
)
1530 * Request too large...
1533 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1535 cupsdCloseClient(con
);
1541 else if (con
->http
.data_remaining
< 0 ||
1542 (!con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1543 con
->http
.data_encoding
== HTTP_ENCODE_LENGTH
))
1546 * Negative content lengths are invalid!
1549 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1551 cupsdCloseClient(con
);
1559 * See what kind of POST request this is; for IPP requests the
1560 * content-type field will be "application/ipp"...
1563 if (!strcmp(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
],
1565 con
->request
= ippNew();
1566 else if ((!strncmp(con
->uri
, "/admin", 6) &&
1567 strncmp(con
->uri
, "/admin/conf/", 12) &&
1568 strncmp(con
->uri
, "/admin/log/", 11)) ||
1569 !strncmp(con
->uri
, "/printers", 9) ||
1570 !strncmp(con
->uri
, "/classes", 8) ||
1571 !strncmp(con
->uri
, "/help", 5) ||
1572 !strncmp(con
->uri
, "/jobs", 5))
1578 if (!strncmp(con
->uri
, "/admin", 6))
1580 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1583 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1585 else if (!strncmp(con
->uri
, "/printers", 9))
1587 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1590 if (con
->uri
[9] && con
->uri
[10])
1591 cupsdSetString(&con
->options
, con
->uri
+ 9);
1593 cupsdSetString(&con
->options
, NULL
);
1595 else if (!strncmp(con
->uri
, "/classes", 8))
1597 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1600 if (con
->uri
[8] && con
->uri
[9])
1601 cupsdSetString(&con
->options
, con
->uri
+ 8);
1603 cupsdSetString(&con
->options
, NULL
);
1605 else if (!strncmp(con
->uri
, "/jobs", 5))
1607 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1610 if (con
->uri
[5] && con
->uri
[6])
1611 cupsdSetString(&con
->options
, con
->uri
+ 5);
1613 cupsdSetString(&con
->options
, NULL
);
1617 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1620 if (con
->uri
[5] && con
->uri
[6])
1621 cupsdSetString(&con
->options
, con
->uri
+ 5);
1623 cupsdSetString(&con
->options
, NULL
);
1626 if (con
->http
.version
<= HTTP_1_0
)
1627 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1635 if ((filename
= get_file(con
, &filestats
, buf
,
1636 sizeof(buf
))) == NULL
)
1638 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1640 cupsdCloseClient(con
);
1647 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1649 if (!is_cgi(con
, filename
, &filestats
, type
))
1652 * Only POST to CGI's...
1655 if (!cupsdSendError(con
, HTTP_UNAUTHORIZED
, CUPSD_AUTH_NONE
))
1657 cupsdCloseClient(con
);
1664 case HTTP_PUT_RECV
:
1666 * Validate the resource name...
1669 if (strncmp(con
->uri
, "/admin/conf/", 12) ||
1670 strchr(con
->uri
+ 12, '/') ||
1671 strlen(con
->uri
) == 12)
1674 * PUT can only be done to configuration files under
1678 cupsdLogMessage(CUPSD_LOG_ERROR
,
1679 "Request for subdirectory \"%s\"!", con
->uri
);
1681 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1683 cupsdCloseClient(con
);
1691 * See if the PUT request includes a Content-Length field, and if
1692 * so check the length against any limits that are set...
1695 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1696 MaxRequestSize
> 0 &&
1697 con
->http
.data_remaining
> MaxRequestSize
)
1700 * Request too large...
1703 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1705 cupsdCloseClient(con
);
1711 else if (con
->http
.data_remaining
< 0)
1714 * Negative content lengths are invalid!
1717 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1719 cupsdCloseClient(con
);
1727 * Open a temporary file to hold the request...
1730 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
1732 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1736 cupsdLogMessage(CUPSD_LOG_ERROR
,
1737 "Unable to create request file %s: %s",
1738 con
->filename
, strerror(errno
));
1740 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1742 cupsdCloseClient(con
);
1747 fchmod(con
->file
, 0640);
1748 fchown(con
->file
, RunUser
, Group
);
1749 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1754 cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
);
1755 cupsdCloseClient(con
);
1759 if (!strncmp(con
->uri
, "/printers/", 10) &&
1760 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1763 * Send PPD file - get the real printer name since printer
1764 * names are not case sensitive but filenames can be...
1767 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1769 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1770 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1773 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1775 cupsdCloseClient(con
);
1783 if ((!strncmp(con
->uri
, "/admin", 6) &&
1784 strncmp(con
->uri
, "/admin/conf/", 12) &&
1785 strncmp(con
->uri
, "/admin/log/", 11)) ||
1786 !strncmp(con
->uri
, "/printers", 9) ||
1787 !strncmp(con
->uri
, "/classes", 8) ||
1788 !strncmp(con
->uri
, "/help", 5) ||
1789 !strncmp(con
->uri
, "/jobs", 5))
1795 if (!cupsdSendHeader(con
, HTTP_OK
, "text/html", CUPSD_AUTH_NONE
))
1797 cupsdCloseClient(con
);
1801 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1803 cupsdCloseClient(con
);
1807 if (cupsdFlushHeader(con
) < 0)
1809 cupsdCloseClient(con
);
1813 cupsdLogRequest(con
, HTTP_OK
);
1815 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1816 (strchr(con
->uri
+ 12, '/') ||
1817 strlen(con
->uri
) == 12)) ||
1818 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1819 (strchr(con
->uri
+ 11, '/') ||
1820 strlen(con
->uri
) == 11)))
1823 * HEAD can only be done to configuration files under
1827 cupsdLogMessage(CUPSD_LOG_ERROR
,
1828 "Request for subdirectory \"%s\"!", con
->uri
);
1830 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1832 cupsdCloseClient(con
);
1838 else if ((filename
= get_file(con
, &filestats
, buf
,
1839 sizeof(buf
))) == NULL
)
1841 if (!cupsdSendHeader(con
, HTTP_NOT_FOUND
, "text/html", CUPSD_AUTH_NONE
))
1843 cupsdCloseClient(con
);
1847 cupsdLogRequest(con
, HTTP_NOT_FOUND
);
1849 else if (!check_if_modified(con
, &filestats
))
1851 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1853 cupsdCloseClient(con
);
1857 cupsdLogRequest(con
, HTTP_NOT_MODIFIED
);
1865 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1867 strcpy(line
, "text/plain");
1869 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1871 if (!cupsdSendHeader(con
, HTTP_OK
, line
, CUPSD_AUTH_NONE
))
1873 cupsdCloseClient(con
);
1877 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
1878 httpGetDateString(filestats
.st_mtime
)) < 0)
1880 cupsdCloseClient(con
);
1884 if (httpPrintf(HTTP(con
), "Content-Length: %lu\r\n",
1885 (unsigned long)filestats
.st_size
) < 0)
1887 cupsdCloseClient(con
);
1891 cupsdLogRequest(con
, HTTP_OK
);
1894 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1896 cupsdCloseClient(con
);
1900 if (cupsdFlushHeader(con
) < 0)
1902 cupsdCloseClient(con
);
1906 con
->http
.state
= HTTP_WAITING
;
1910 break; /* Anti-compiler-warning-code */
1916 * Handle any incoming data...
1919 switch (con
->http
.state
)
1921 case HTTP_PUT_RECV
:
1924 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
1926 cupsdCloseClient(con
);
1931 con
->bytes
+= bytes
;
1933 if (write(con
->file
, line
, bytes
) < bytes
)
1935 cupsdLogMessage(CUPSD_LOG_ERROR
,
1936 "cupsdReadClient: Unable to write %d bytes to %s: %s",
1937 bytes
, con
->filename
, strerror(errno
));
1941 unlink(con
->filename
);
1942 cupsdClearString(&con
->filename
);
1944 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1946 cupsdCloseClient(con
);
1952 while (con
->http
.state
== HTTP_PUT_RECV
&& data_ready(con
));
1954 if (con
->http
.state
== HTTP_WAITING
)
1957 * End of file, see how big it is...
1960 fstat(con
->file
, &filestats
);
1965 if (filestats
.st_size
> MaxRequestSize
&&
1969 * Request is too big; remove it and send an error...
1972 unlink(con
->filename
);
1973 cupsdClearString(&con
->filename
);
1975 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1977 cupsdCloseClient(con
);
1983 * Install the configuration file...
1986 status
= install_conf_file(con
);
1989 * Return the status to the client...
1992 if (!cupsdSendError(con
, status
, CUPSD_AUTH_NONE
))
1994 cupsdCloseClient(con
);
2000 case HTTP_POST_RECV
:
2006 * Grab any request data from the connection...
2009 if ((ipp_state
= ippRead(&(con
->http
), con
->request
)) == IPP_ERROR
)
2011 cupsdLogMessage(CUPSD_LOG_ERROR
,
2012 "cupsdReadClient: %d IPP Read Error!",
2015 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
2016 cupsdCloseClient(con
);
2019 else if (ipp_state
!= IPP_DATA
)
2021 if (con
->http
.state
== HTTP_POST_SEND
)
2023 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
2024 cupsdCloseClient(con
);
2031 con
->bytes
+= ippLength(con
->request
);
2034 if (con
->file
< 0 && con
->http
.state
!= HTTP_POST_SEND
)
2037 * Create a file as needed for the request data...
2040 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
, request_id
++);
2041 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
2045 cupsdLogMessage(CUPSD_LOG_ERROR
,
2046 "Unable to create request file %s: %s",
2047 con
->filename
, strerror(errno
));
2049 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2051 cupsdCloseClient(con
);
2056 fchmod(con
->file
, 0640);
2057 fchown(con
->file
, RunUser
, Group
);
2058 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2061 if (con
->http
.state
!= HTTP_POST_SEND
)
2063 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
2065 cupsdCloseClient(con
);
2070 con
->bytes
+= bytes
;
2072 if (write(con
->file
, line
, bytes
) < bytes
)
2074 cupsdLogMessage(CUPSD_LOG_ERROR
,
2075 "cupsdReadClient: Unable to write %d bytes to %s: %s",
2076 bytes
, con
->filename
, strerror(errno
));
2080 unlink(con
->filename
);
2081 cupsdClearString(&con
->filename
);
2083 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2085 cupsdCloseClient(con
);
2090 else if (con
->http
.state
== HTTP_POST_RECV
)
2092 else if (con
->http
.state
!= HTTP_POST_SEND
)
2094 cupsdCloseClient(con
);
2099 while (con
->http
.state
== HTTP_POST_RECV
&& data_ready(con
));
2101 if (con
->http
.state
== HTTP_POST_SEND
)
2105 fstat(con
->file
, &filestats
);
2110 if (filestats
.st_size
> MaxRequestSize
&&
2114 * Request is too big; remove it and send an error...
2117 unlink(con
->filename
);
2118 cupsdClearString(&con
->filename
);
2123 * Delete any IPP request data...
2126 ippDelete(con
->request
);
2127 con
->request
= NULL
;
2130 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2132 cupsdCloseClient(con
);
2139 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
2141 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
2143 cupsdCloseClient(con
);
2148 cupsdLogRequest(con
, HTTP_OK
);
2154 cupsdProcessIPPRequest(con
);
2158 unlink(con
->filename
);
2159 cupsdClearString(&con
->filename
);
2168 break; /* Anti-compiler-warning-code */
2171 if (con
->http
.state
== HTTP_WAITING
)
2173 if (!con
->http
.keep_alive
)
2174 cupsdCloseClient(con
);
2177 cupsArrayRemove(ActiveClients
, con
);
2178 cupsdSetBusyState();
2185 * 'cupsdSendCommand()' - Send output from a command via HTTP.
2188 int /* O - 1 on success, 0 on failure */
2190 cupsd_client_t
*con
, /* I - Client connection */
2191 char *command
, /* I - Command to run */
2192 char *options
, /* I - Command-line options */
2193 int root
) /* I - Run as root? */
2195 int fd
; /* Standard input file descriptor */
2200 fd
= open(con
->filename
, O_RDONLY
);
2204 cupsdLogMessage(CUPSD_LOG_ERROR
,
2205 "cupsdSendCommand: %d Unable to open \"%s\" for reading: %s",
2206 con
->http
.fd
, con
->filename
? con
->filename
: "/dev/null",
2211 fcntl(fd
, F_SETFD
, fcntl(fd
, F_GETFD
) | FD_CLOEXEC
);
2216 con
->pipe_pid
= pipe_command(con
, fd
, &(con
->file
), command
, options
, root
);
2221 cupsdLogMessage(CUPSD_LOG_INFO
, "Started \"%s\" (pid=%d)", command
,
2224 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendCommand: %d file=%d",
2225 con
->http
.fd
, con
->file
);
2227 if (con
->pipe_pid
== 0)
2230 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2232 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2234 con
->sent_header
= 0;
2235 con
->file_ready
= 0;
2236 con
->got_fields
= 0;
2244 * 'cupsdSendError()' - Send an error message via HTTP.
2247 int /* O - 1 if successful, 0 otherwise */
2248 cupsdSendError(cupsd_client_t
*con
, /* I - Connection */
2249 http_status_t code
, /* I - Error code */
2250 int auth_type
)/* I - Authentication type */
2252 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2253 "cupsdSendError(con=%p(%d), code=%d, auth_type=%d", con
,
2254 con
->http
.fd
, code
, auth_type
);
2258 * Force client to upgrade for authentication if that is how the
2259 * server is configured...
2262 if (code
== HTTP_UNAUTHORIZED
&&
2263 DefaultEncryption
== HTTP_ENCRYPT_REQUIRED
&&
2264 strcasecmp(con
->http
.hostname
, "localhost") &&
2267 code
= HTTP_UPGRADE_REQUIRED
;
2269 #endif /* HAVE_SSL */
2272 * Put the request in the access_log file...
2275 cupsdLogRequest(con
, code
);
2278 * To work around bugs in some proxies, don't use Keep-Alive for some
2281 * Kerberos authentication doesn't work without Keep-Alive, so
2282 * never disable it in that case.
2285 if (code
>= HTTP_BAD_REQUEST
&& con
->http
.auth_type
!= CUPSD_AUTH_NEGOTIATE
)
2286 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
2289 * Send an error message back to the client. If the error code is a
2290 * 400 or 500 series, make sure the message contains some text, too!
2293 if (!cupsdSendHeader(con
, code
, NULL
, auth_type
))
2297 if (code
== HTTP_UPGRADE_REQUIRED
)
2298 if (httpPrintf(HTTP(con
), "Connection: Upgrade\r\n") < 0)
2301 if (httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n") < 0)
2303 #endif /* HAVE_SSL */
2305 if (con
->http
.version
>= HTTP_1_1
&&
2306 con
->http
.keep_alive
== HTTP_KEEPALIVE_OFF
)
2308 if (httpPrintf(HTTP(con
), "Connection: close\r\n") < 0)
2312 if (code
>= HTTP_BAD_REQUEST
)
2315 * Send a human-readable error message.
2318 char message
[4096], /* Message for user */
2319 urltext
[1024], /* URL redirection text */
2320 redirect
[1024]; /* Redirection link */
2321 const char *text
; /* Status-specific text */
2326 if (code
== HTTP_UNAUTHORIZED
)
2327 text
= _cupsLangString(con
->language
,
2328 _("Enter your username and password or the "
2329 "root username and password to access this "
2330 "page. If you are using Kerberos authentication, "
2331 "make sure you have a valid Kerberos ticket."));
2332 else if (code
== HTTP_UPGRADE_REQUIRED
)
2336 snprintf(urltext
, sizeof(urltext
),
2337 _cupsLangString(con
->language
,
2338 _("You must access this page using the URL "
2339 "<A HREF=\"https://%s:%d%s\">"
2340 "https://%s:%d%s</A>.")),
2341 con
->servername
, con
->serverport
, con
->uri
,
2342 con
->servername
, con
->serverport
, con
->uri
);
2344 snprintf(redirect
, sizeof(redirect
),
2345 "<META HTTP-EQUIV=\"Refresh\" "
2346 "CONTENT=\"3;URL=https://%s:%d%s\">\n",
2347 con
->servername
, con
->serverport
, con
->uri
);
2352 snprintf(message
, sizeof(message
),
2353 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" "
2354 "\"http://www.w3.org/TR/html4/loose.dtd\">\n"
2357 "\t<META HTTP-EQUIV=\"Content-Type\" "
2358 "CONTENT=\"text/html; charset=utf-8\">\n"
2359 "\t<TITLE>%d %s</TITLE>\n"
2360 "\t<LINK REL=\"STYLESHEET\" TYPE=\"text/css\" "
2361 "HREF=\"/cups.css\">\n"
2369 code
, httpStatus(code
), redirect
, code
, httpStatus(code
), text
);
2371 if (httpPrintf(HTTP(con
), "Content-Type: text/html; charset=utf-8\r\n") < 0)
2373 if (httpPrintf(HTTP(con
), "Content-Length: %d\r\n",
2374 (int)strlen(message
)) < 0)
2376 if (httpPrintf(HTTP(con
), "\r\n") < 0)
2378 if (httpPrintf(HTTP(con
), "%s", message
) < 0)
2381 else if (httpPrintf(HTTP(con
), "\r\n") < 0)
2384 if (cupsdFlushHeader(con
) < 0)
2387 con
->http
.state
= HTTP_WAITING
;
2394 * 'cupsdSendHeader()' - Send an HTTP request.
2397 int /* O - 1 on success, 0 on failure */
2399 cupsd_client_t
*con
, /* I - Client to send to */
2400 http_status_t code
, /* I - HTTP status code */
2401 char *type
, /* I - MIME type of document */
2402 int auth_type
) /* I - Type of authentication */
2404 char auth_str
[1024]; /* Authorization string */
2406 static char *gss_buf
= NULL
; /* Kerberos auth data buffer */
2407 static int gss_bufsize
= 0; /* Size of Kerberos auth data buffer */
2408 #endif /* HAVE_GSSAPI */
2412 * Send the HTTP status header...
2415 if (code
== HTTP_CONTINUE
)
2418 * 100-continue doesn't send any headers...
2421 return (httpPrintf(HTTP(con
), "HTTP/%d.%d 100 Continue\r\n\r\n",
2422 con
->http
.version
/ 100, con
->http
.version
% 100) > 0);
2425 httpFlushWrite(HTTP(con
));
2427 con
->http
.data_encoding
= HTTP_ENCODE_FIELDS
;
2429 if (httpPrintf(HTTP(con
), "HTTP/%d.%d %d %s\r\n", con
->http
.version
/ 100,
2430 con
->http
.version
% 100, code
, httpStatus(code
)) < 0)
2432 if (httpPrintf(HTTP(con
), "Date: %s\r\n", httpGetDateString(time(NULL
))) < 0)
2435 if (httpPrintf(HTTP(con
), "Server: %s\r\n", ServerHeader
) < 0)
2437 if (con
->http
.keep_alive
&& con
->http
.version
>= HTTP_1_0
)
2439 if (httpPrintf(HTTP(con
), "Connection: Keep-Alive\r\n") < 0)
2441 if (httpPrintf(HTTP(con
), "Keep-Alive: timeout=%d\r\n",
2442 KeepAliveTimeout
) < 0)
2445 if (code
== HTTP_METHOD_NOT_ALLOWED
)
2446 if (httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n") < 0)
2449 if (code
== HTTP_UNAUTHORIZED
)
2451 if (auth_type
== CUPSD_AUTH_NONE
)
2453 if (!con
->best
|| con
->best
->type
<= CUPSD_AUTH_NONE
)
2454 auth_type
= DefaultAuthType
;
2456 auth_type
= con
->best
->type
;
2461 if (auth_type
== CUPSD_AUTH_BASIC
|| auth_type
== CUPSD_AUTH_BASICDIGEST
)
2462 strlcpy(auth_str
, "Basic realm=\"CUPS\"", sizeof(auth_str
));
2463 else if (auth_type
== CUPSD_AUTH_DIGEST
)
2464 snprintf(auth_str
, sizeof(auth_str
), "Digest realm=\"CUPS\", nonce=\"%s\"",
2465 con
->http
.hostname
);
2467 else if (auth_type
== CUPSD_AUTH_NEGOTIATE
&& con
->gss_output_token
.length
== 0)
2468 strlcpy(auth_str
, "Negotiate", sizeof(auth_str
));
2469 #endif /* HAVE_GSSAPI */
2471 #ifdef HAVE_AUTHORIZATION_H
2472 if (con
->best
&& auth_type
!= CUPSD_AUTH_NEGOTIATE
)
2474 int i
; /* Looping var */
2475 char *auth_key
; /* Auth key buffer */
2476 size_t auth_size
; /* Size of remaining buffer */
2479 auth_key
= auth_str
+ strlen(auth_str
);
2480 auth_size
= sizeof(auth_str
) - (auth_key
- auth_str
);
2482 for (i
= 0; i
< con
->best
->num_names
; i
++)
2484 if (!strncasecmp(con
->best
->names
[i
], "@AUTHKEY(", 9))
2486 snprintf(auth_key
, auth_size
, ", authkey=\"%s\"",
2487 con
->best
->names
[i
] + 9);
2488 /* end parenthesis is stripped in conf.c */
2491 else if (!strcasecmp(con
->best
->names
[i
], "@SYSTEM") &&
2494 snprintf(auth_key
, auth_size
, ", authkey=\"%s\"", SystemGroupAuthKey
);
2499 #endif /* HAVE_AUTHORIZATION_H */
2503 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendHeader: WWW-Authenticate: %s",
2506 if (httpPrintf(HTTP(con
), "WWW-Authenticate: %s\r\n", auth_str
) < 0)
2513 * WWW-Authenticate: Negotiate can be included even for
2514 * non-401 replies...
2517 if (con
->gss_output_token
.length
> 0 && con
->gss_output_token
.length
<= 65536)
2519 OM_uint32 minor_status
; /* Minor status code */
2520 int bufsize
; /* Size of output token buffer */
2523 bufsize
= con
->gss_output_token
.length
* 4 / 3 + 2;
2525 if (bufsize
> gss_bufsize
)
2527 char *buf
; /* New buffer */
2530 bufsize
= (bufsize
+ 1023) & 1023;/* Round up */
2533 buf
= realloc(gss_buf
, bufsize
);
2535 buf
= malloc(bufsize
);
2539 cupsdLogMessage(CUPSD_LOG_ERROR
,
2540 "Unable to allocate %d bytes for Kerberos credentials!",
2546 gss_bufsize
= bufsize
;
2549 httpEncode64_2(gss_buf
, gss_bufsize
,
2550 con
->gss_output_token
.value
,
2551 con
->gss_output_token
.length
);
2552 gss_release_buffer(&minor_status
, &con
->gss_output_token
);
2554 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2555 "cupsdSendHeader: WWW-Authenticate: Negotiate %s", gss_buf
);
2557 if (httpPrintf(HTTP(con
), "WWW-Authenticate: Negotiate %s\r\n",
2561 else if (con
->gss_output_token
.length
> 65536)
2563 cupsdLogMessage(CUPSD_LOG_ERROR
,
2564 "Kerberos credentials larger than 64k (%d)!",
2565 (int)con
->gss_output_token
.length
);
2568 #endif /* HAVE_GSSAPI */
2570 if (con
->language
&& strcmp(con
->language
->language
, "C"))
2572 if (httpPrintf(HTTP(con
), "Content-Language: %s\r\n",
2573 con
->language
->language
) < 0)
2579 if (!strcmp(type
, "text/html"))
2581 if (httpPrintf(HTTP(con
),
2582 "Content-Type: text/html; charset=utf-8\r\n") < 0)
2585 else if (httpPrintf(HTTP(con
), "Content-Type: %s\r\n", type
) < 0)
2594 * 'cupsdUpdateCGI()' - Read status messages from CGI scripts and programs.
2598 cupsdUpdateCGI(void)
2600 char *ptr
, /* Pointer to end of line in buffer */
2601 message
[1024]; /* Pointer to message text */
2602 int loglevel
; /* Log level for message */
2605 while ((ptr
= cupsdStatBufUpdate(CGIStatusBuffer
, &loglevel
,
2606 message
, sizeof(message
))) != NULL
)
2608 if (loglevel
== CUPSD_LOG_INFO
)
2609 cupsdLogMessage(CUPSD_LOG_INFO
, "%s", message
);
2611 if (!strchr(CGIStatusBuffer
->buffer
, '\n'))
2615 if (ptr
== NULL
&& !CGIStatusBuffer
->bufused
)
2618 * Fatal error on pipe - should never happen!
2621 cupsdLogMessage(CUPSD_LOG_CRIT
,
2622 "cupsdUpdateCGI: error reading from CGI error pipe - %s",
2629 * 'cupsdWriteClient()' - Write data to a client as needed.
2633 cupsdWriteClient(cupsd_client_t
*con
) /* I - Client connection */
2635 int bytes
; /* Number of bytes written */
2636 char buf
[16385]; /* Data buffer */
2637 char *bufptr
; /* Pointer into buffer */
2638 ipp_state_t ipp_state
; /* IPP state value */
2641 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2642 "cupsdWriteClient(con=%p(%d)) response=%p(%d), file=%d "
2643 "pipe_pid=%d state=%d",
2644 con
, con
->http
.fd
, con
->response
,
2645 con
->response
? con
->response
->state
: -1,
2646 con
->file
, con
->pipe_pid
, con
->http
.state
);
2648 if (con
->http
.state
!= HTTP_GET_SEND
&&
2649 con
->http
.state
!= HTTP_POST_SEND
)
2652 * If we get called in the wrong state, then something went wrong with the
2653 * connection and we need to shut it down...
2656 cupsdCloseClient(con
);
2663 * Make sure we select on the CGI output...
2666 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2668 if (!con
->file_ready
)
2671 * Try again later when there is CGI output available...
2674 cupsdRemoveSelect(con
->http
.fd
);
2678 con
->file_ready
= 0;
2681 if (con
->response
&& con
->response
->state
!= IPP_DATA
)
2683 ipp_state
= ippWrite(HTTP(con
), con
->response
);
2684 bytes
= ipp_state
!= IPP_ERROR
&&
2685 (con
->file
>= 0 || ipp_state
!= IPP_DATA
);
2687 else if ((bytes
= read(con
->file
, buf
, sizeof(buf
) - 1)) > 0)
2689 if (con
->pipe_pid
&& !con
->got_fields
)
2692 * Inspect the data for Content-Type and other fields.
2697 for (bufptr
= buf
; !con
->got_fields
&& *bufptr
; bufptr
++)
2699 if (*bufptr
== '\n')
2702 * Send line to client...
2705 if (bufptr
> buf
&& bufptr
[-1] == '\r')
2709 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Script header: %s", buf
);
2711 if (!con
->sent_header
)
2714 * Handle redirection and CGI status codes...
2717 if (!strncasecmp(buf
, "Location:", 9))
2719 cupsdSendHeader(con
, HTTP_SEE_OTHER
, NULL
, CUPSD_AUTH_NONE
);
2720 con
->sent_header
= 2;
2722 if (httpPrintf(HTTP(con
), "Content-Length: 0\r\n") < 0)
2725 else if (!strncasecmp(buf
, "Status:", 7))
2727 cupsdSendError(con
, (http_status_t
)atoi(buf
+ 7), CUPSD_AUTH_NONE
);
2728 con
->sent_header
= 2;
2732 cupsdSendHeader(con
, HTTP_OK
, NULL
, CUPSD_AUTH_NONE
);
2733 con
->sent_header
= 1;
2735 if (con
->http
.version
== HTTP_1_1
)
2737 if (httpPrintf(HTTP(con
), "Transfer-Encoding: chunked\r\n") < 0)
2743 if (strncasecmp(buf
, "Status:", 7))
2744 httpPrintf(HTTP(con
), "%s\r\n", buf
);
2750 bytes
-= (bufptr
- buf
);
2753 memmove(buf
, bufptr
, bytes
+ 1);
2760 * See if the line was empty...
2763 if (con
->field_col
== 0)
2765 con
->got_fields
= 1;
2767 if (cupsdFlushHeader(con
) < 0)
2769 cupsdCloseClient(con
);
2773 if (con
->http
.version
== HTTP_1_1
)
2774 con
->http
.data_encoding
= HTTP_ENCODE_CHUNKED
;
2779 else if (*bufptr
!= '\r')
2783 if (bytes
> 0 && !con
->got_fields
)
2786 * Remaining text needs to go out...
2789 httpPrintf(HTTP(con
), "%s", buf
);
2791 con
->http
.activity
= time(NULL
);
2794 else if (bytes
== 0)
2796 con
->http
.activity
= time(NULL
);
2803 if (httpWrite2(HTTP(con
), buf
, bytes
) < 0)
2805 cupsdCloseClient(con
);
2809 if (con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
)
2810 httpFlushWrite(HTTP(con
));
2812 con
->bytes
+= bytes
;
2814 if (con
->http
.state
== HTTP_WAITING
)
2820 (con
->http
.state
!= HTTP_GET_SEND
&& con
->http
.state
!= HTTP_POST_SEND
))
2822 if (!con
->sent_header
&& !con
->response
)
2823 cupsdSendError(con
, HTTP_SERVER_ERROR
, CUPSD_AUTH_NONE
);
2826 cupsdLogRequest(con
, HTTP_OK
);
2828 httpFlushWrite(HTTP(con
));
2830 if (con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
&& con
->sent_header
== 1)
2832 if (httpWrite2(HTTP(con
), "", 0) < 0)
2834 cupsdCloseClient(con
);
2840 con
->http
.state
= HTTP_WAITING
;
2842 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
2846 cupsdRemoveSelect(con
->file
);
2849 cupsdEndProcess(con
->pipe_pid
, 0);
2858 unlink(con
->filename
);
2859 cupsdClearString(&con
->filename
);
2864 ippDelete(con
->request
);
2865 con
->request
= NULL
;
2870 ippDelete(con
->response
);
2871 con
->response
= NULL
;
2874 cupsdClearString(&con
->command
);
2875 cupsdClearString(&con
->options
);
2876 cupsdClearString(&con
->query_string
);
2878 if (!con
->http
.keep_alive
)
2880 cupsdCloseClient(con
);
2885 con
->http
.activity
= time(NULL
);
2890 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
2893 static int /* O - 1 if modified since */
2895 cupsd_client_t
*con
, /* I - Client connection */
2896 struct stat
*filestats
) /* I - File information */
2898 char *ptr
; /* Pointer into field */
2899 time_t date
; /* Time/date value */
2900 off_t size
; /* Size/length value */
2905 ptr
= con
->http
.fields
[HTTP_FIELD_IF_MODIFIED_SINCE
];
2910 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2911 "check_if_modified(con=%p(%d), "
2912 "filestats=%p(" CUPS_LLFMT
", %d)) If-Modified-Since=\"%s\"",
2913 con
, con
->http
.fd
, filestats
, CUPS_LLCAST filestats
->st_size
,
2914 (int)filestats
->st_mtime
, ptr
);
2916 while (*ptr
!= '\0')
2918 while (isspace(*ptr
) || *ptr
== ';')
2921 if (strncasecmp(ptr
, "length=", 7) == 0)
2924 size
= strtoll(ptr
, NULL
, 10);
2926 while (isdigit(*ptr
))
2929 else if (isalpha(*ptr
))
2931 date
= httpGetDateTime(ptr
);
2932 while (*ptr
!= '\0' && *ptr
!= ';')
2939 return ((size
!= filestats
->st_size
&& size
!= 0) ||
2940 (date
< filestats
->st_mtime
&& date
!= 0) ||
2941 (size
== 0 && date
== 0));
2946 * 'compare_clients()' - Compare two client connections.
2949 static int /* O - Result of comparison */
2950 compare_clients(cupsd_client_t
*a
, /* I - First client */
2951 cupsd_client_t
*b
, /* I - Second client */
2952 void *data
) /* I - User data (not used) */
2966 * 'data_ready()' - Check whether data is available from a client.
2969 static int /* O - 1 if data is ready, 0 otherwise */
2970 data_ready(cupsd_client_t
*con
) /* I - Client */
2972 if (con
->http
.used
> 0)
2975 else if (con
->http
.tls
)
2978 if (SSL_pending((SSL
*)(con
->http
.tls
)))
2980 # elif defined(HAVE_GNUTLS)
2981 if (gnutls_record_check_pending(((http_tls_t
*)(con
->http
.tls
))->session
))
2983 # elif defined(HAVE_CDSASSL)
2984 size_t bytes
; /* Bytes that are available */
2986 if (!SSLGetBufferedReadSize(((http_tls_t
*)(con
->http
.tls
))->session
,
2987 &bytes
) && bytes
> 0)
2989 # endif /* HAVE_LIBSSL */
2991 #endif /* HAVE_SSL */
2999 * 'encrypt_client()' - Enable encryption for the client...
3002 static int /* O - 1 on success, 0 on error */
3003 encrypt_client(cupsd_client_t
*con
) /* I - Client to encrypt */
3006 SSL_CTX
*context
; /* Context for encryption */
3007 SSL
*conn
; /* Connection for encryption */
3008 BIO
*bio
; /* BIO data */
3009 unsigned long error
; /* Error code */
3012 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "encrypt_client(con=%p(%d))", con
,
3016 * Verify that we have a certificate...
3019 if (access(ServerKey
, 0) || access(ServerCertificate
, 0))
3022 * Nope, make a self-signed certificate...
3025 if (!make_certificate(con
))
3030 * Create the SSL context and accept the connection...
3033 context
= SSL_CTX_new(SSLv23_server_method());
3035 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
3036 if (SSLOptions
& CUPSD_SSL_NOEMPTY
)
3037 SSL_CTX_set_options(context
, SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
);
3038 SSL_CTX_use_PrivateKey_file(context
, ServerKey
, SSL_FILETYPE_PEM
);
3039 SSL_CTX_use_certificate_chain_file(context
, ServerCertificate
);
3041 bio
= BIO_new(_httpBIOMethods());
3042 BIO_ctrl(bio
, BIO_C_SET_FILE_PTR
, 0, (char *)HTTP(con
));
3044 conn
= SSL_new(context
);
3045 SSL_set_bio(conn
, bio
, bio
);
3047 if (SSL_accept(conn
) != 1)
3049 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to encrypt connection from %s!",
3050 con
->http
.hostname
);
3052 while ((error
= ERR_get_error()) != 0)
3053 cupsdLogMessage(CUPSD_LOG_ERROR
, "%s", ERR_error_string(error
, NULL
));
3055 SSL_CTX_free(context
);
3060 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Connection from %s now encrypted.",
3061 con
->http
.hostname
);
3063 con
->http
.tls
= conn
;
3066 # elif defined(HAVE_GNUTLS)
3067 http_tls_t
*conn
; /* TLS session object */
3068 int error
; /* Error code */
3069 gnutls_certificate_server_credentials
*credentials
;
3070 /* TLS credentials */
3073 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "encrypt_client(con=%p(%d))", con
,
3077 * Verify that we have a certificate...
3080 if (access(ServerKey
, 0) || access(ServerCertificate
, 0))
3083 * Nope, make a self-signed certificate...
3086 if (!make_certificate(con
))
3091 * Create the SSL object and perform the SSL handshake...
3094 conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
));
3099 credentials
= (gnutls_certificate_server_credentials
*)
3100 malloc(sizeof(gnutls_certificate_server_credentials
));
3101 if (credentials
== NULL
)
3103 cupsdLogMessage(CUPSD_LOG_ERROR
,
3104 "Unable to encrypt connection from %s - %s",
3105 con
->http
.hostname
, strerror(errno
));
3111 gnutls_certificate_allocate_credentials(credentials
);
3112 gnutls_certificate_set_x509_key_file(*credentials
, ServerCertificate
,
3113 ServerKey
, GNUTLS_X509_FMT_PEM
);
3115 gnutls_init(&(conn
->session
), GNUTLS_SERVER
);
3116 gnutls_set_default_priority(conn
->session
);
3117 gnutls_credentials_set(conn
->session
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
3118 gnutls_transport_set_ptr(conn
->session
, (gnutls_transport_ptr
)HTTP(con
));
3119 gnutls_transport_set_pull_function(conn
->session
, _httpReadGNUTLS
);
3120 gnutls_transport_set_push_function(conn
->session
, _httpWriteGNUTLS
);
3122 error
= gnutls_handshake(conn
->session
);
3124 if (error
!= GNUTLS_E_SUCCESS
)
3126 cupsdLogMessage(CUPSD_LOG_ERROR
,
3127 "Unable to encrypt connection from %s - %s",
3128 con
->http
.hostname
, gnutls_strerror(error
));
3130 gnutls_deinit(conn
->session
);
3131 gnutls_certificate_free_credentials(*credentials
);
3137 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Connection from %s now encrypted.",
3138 con
->http
.hostname
);
3140 conn
->credentials
= credentials
;
3141 con
->http
.tls
= conn
;
3144 # elif defined(HAVE_CDSASSL)
3145 OSStatus error
; /* Error code */
3146 http_tls_t
*conn
; /* CDSA connection information */
3149 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "encrypt_client(con=%p(%d))", con
,
3152 if ((conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
))) == NULL
)
3156 conn
->session
= NULL
;
3157 conn
->certsArray
= get_cdsa_certificate(con
);
3159 if (!conn
->certsArray
)
3162 * No keychain (yet), make a self-signed certificate...
3165 if (make_certificate(con
))
3166 conn
->certsArray
= get_cdsa_certificate(con
);
3169 if (!conn
->certsArray
)
3171 cupsdLogMessage(CUPSD_LOG_ERROR
,
3172 "Could not find signing key in keychain \"%s\"",
3174 error
= errSSLBadCert
; /* errSSLBadConfiguration is a better choice, but not available on 10.2.x */
3178 error
= SSLNewContext(true, &conn
->session
);
3181 error
= SSLSetIOFuncs(conn
->session
, _httpReadCDSA
, _httpWriteCDSA
);
3184 error
= SSLSetProtocolVersionEnabled(conn
->session
, kSSLProtocol2
, false);
3187 error
= SSLSetConnection(conn
->session
, HTTP(con
));
3190 error
= SSLSetAllowsExpiredCerts(conn
->session
, true);
3193 error
= SSLSetAllowsAnyRoot(conn
->session
, true);
3196 error
= SSLSetCertificate(conn
->session
, conn
->certsArray
);
3201 * Perform SSL/TLS handshake
3204 while ((error
= SSLHandshake(conn
->session
)) == errSSLWouldBlock
)
3210 cupsdLogMessage(CUPSD_LOG_ERROR
,
3211 "Unable to encrypt connection from %s - %s (%d)",
3212 con
->http
.hostname
, cssmErrorString(error
), (int)error
);
3214 con
->http
.error
= error
;
3215 con
->http
.status
= HTTP_ERROR
;
3218 SSLDisposeContext(conn
->session
);
3220 if (conn
->certsArray
)
3221 CFRelease(conn
->certsArray
);
3228 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Connection from %s now encrypted.",
3229 con
->http
.hostname
);
3231 con
->http
.tls
= conn
;
3234 # endif /* HAVE_LIBSSL */
3236 #endif /* HAVE_SSL */
3241 * 'get_cdsa_certificate()' - Get a SSL/TLS certificate from the System keychain.
3244 static CFArrayRef
/* O - Array of certificates */
3245 get_cdsa_certificate(cupsd_client_t
*con
) /* I - Client connection */
3247 OSStatus err
; /* Error info */
3248 SecKeychainRef keychain
; /* Keychain reference */
3249 SecIdentitySearchRef search
; /* Search reference */
3250 SecIdentityRef identity
; /* Identity */
3251 CFArrayRef certificates
= NULL
;
3252 /* Certificate array */
3255 if ((err
= SecKeychainOpen(ServerCertificate
, &keychain
)))
3257 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot open keychain \"%s\" - %s (%d)",
3258 ServerCertificate
, cssmErrorString(err
), (int)err
);
3262 # if HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY
3264 * Use a policy to search for valid certificates who's common name matches the
3268 SecPolicySearchRef policy_search
; /* Policy search ref */
3269 SecPolicyRef policy
; /* Policy ref */
3270 CSSM_DATA options
; /* Policy options */
3271 CSSM_APPLE_TP_SSL_OPTIONS
3272 ssl_options
; /* SSL Option for hostname */
3275 if (SecPolicySearchCreate(CSSM_CERT_X_509v3
, &CSSMOID_APPLE_TP_SSL
,
3276 NULL
, &policy_search
))
3278 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot create a policy search reference");
3279 CFRelease(keychain
);
3283 if (SecPolicySearchCopyNext(policy_search
, &policy
))
3285 cupsdLogMessage(CUPSD_LOG_ERROR
,
3286 "Cannot find a policy to use for searching");
3287 CFRelease(keychain
);
3288 CFRelease(policy_search
);
3292 memset(&ssl_options
, 0, sizeof(ssl_options
));
3293 ssl_options
.Version
= CSSM_APPLE_TP_SSL_OPTS_VERSION
;
3294 ssl_options
.ServerName
= con
->servername
;
3295 ssl_options
.ServerNameLen
= strlen(con
->servername
);
3297 options
.Data
= (uint8
*)&ssl_options
;
3298 options
.Length
= sizeof(ssl_options
);
3300 if (SecPolicySetValue(policy
, &options
))
3302 cupsdLogMessage(CUPSD_LOG_ERROR
,
3303 "Cannot set policy value to use for searching");
3304 CFRelease(keychain
);
3305 CFRelease(policy_search
);
3309 err
= SecIdentitySearchCreateWithPolicy(policy
, NULL
, CSSM_KEYUSE_SIGN
,
3310 keychain
, FALSE
, &search
);
3313 * Assume there is exactly one SecIdentity in the keychain...
3316 err
= SecIdentitySearchCreate(keychain
, CSSM_KEYUSE_SIGN
, &search
);
3317 # endif /* HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY */
3320 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3321 "Cannot create keychain search reference: %s (%d)",
3322 cssmErrorString(err
), (int)err
);
3325 if ((err
= SecIdentitySearchCopyNext(search
, &identity
)))
3327 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3328 "Cannot find signing key in keychain \"%s\": %s (%d)",
3329 ServerCertificate
, cssmErrorString(err
), (int)err
);
3333 if (CFGetTypeID(identity
) != SecIdentityGetTypeID())
3334 cupsdLogMessage(CUPSD_LOG_ERROR
,
3335 "SecIdentitySearchCopyNext CFTypeID failure!");
3338 if ((certificates
= CFArrayCreate(NULL
, (const void **)&identity
,
3339 1, &kCFTypeArrayCallBacks
)) == NULL
)
3340 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot create certificate array");
3343 CFRelease(identity
);
3349 # if HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY
3351 CFRelease(policy_search
);
3352 # endif /* HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY */
3354 return (certificates
);
3356 #endif /* HAVE_CDSASSL */
3360 * 'get_file()' - Get a filename and state info.
3363 static char * /* O - Real filename */
3364 get_file(cupsd_client_t
*con
, /* I - Client connection */
3365 struct stat
*filestats
, /* O - File information */
3366 char *filename
, /* IO - Filename buffer */
3367 int len
) /* I - Buffer length */
3369 int status
; /* Status of filesystem calls */
3370 char *ptr
; /* Pointer info filename */
3371 int plen
; /* Remaining length after pointer */
3372 char language
[7]; /* Language subdirectory, if any */
3376 * Figure out the real filename...
3381 if (!strncmp(con
->uri
, "/ppd/", 5))
3382 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
);
3383 else if (!strncmp(con
->uri
, "/rss/", 5) && !strchr(con
->uri
+ 5, '/'))
3384 snprintf(filename
, len
, "%s/rss/%s", CacheDir
, con
->uri
+ 5);
3385 else if (!strncmp(con
->uri
, "/admin/conf/", 12))
3386 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
+ 11);
3387 else if (!strncmp(con
->uri
, "/admin/log/", 11))
3389 if (!strncmp(con
->uri
+ 11, "access_log", 10) && AccessLog
[0] == '/')
3390 strlcpy(filename
, AccessLog
, len
);
3391 else if (!strncmp(con
->uri
+ 11, "error_log", 9) && ErrorLog
[0] == '/')
3392 strlcpy(filename
, ErrorLog
, len
);
3393 else if (!strncmp(con
->uri
+ 11, "page_log", 8) && PageLog
[0] == '/')
3394 strlcpy(filename
, PageLog
, len
);
3398 else if (con
->language
)
3400 snprintf(language
, sizeof(language
), "/%s", con
->language
->language
);
3401 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3404 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3406 if ((ptr
= strchr(filename
, '?')) != NULL
)
3410 * Grab the status for this language; if there isn't a language-specific file
3411 * then fallback to the default one...
3414 if ((status
= stat(filename
, filestats
)) != 0 && language
[0] &&
3415 strncmp(con
->uri
, "/ppd/", 5) &&
3416 strncmp(con
->uri
, "/admin/conf/", 12) &&
3417 strncmp(con
->uri
, "/admin/log/", 11))
3420 * Drop the country code...
3424 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3426 if ((ptr
= strchr(filename
, '?')) != NULL
)
3429 if ((status
= stat(filename
, filestats
)) != 0)
3432 * Drop the language prefix and try the root directory...
3436 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3438 if ((ptr
= strchr(filename
, '?')) != NULL
)
3441 status
= stat(filename
, filestats
);
3446 * If we're found a directory, get the index.html file instead...
3449 if (!status
&& S_ISDIR(filestats
->st_mode
))
3452 * Make sure the URI ends with a slash...
3455 if (con
->uri
[strlen(con
->uri
) - 1] != '/')
3456 strlcat(con
->uri
, "/", sizeof(con
->uri
));
3459 * Find the directory index file, trying every language...
3464 if (status
&& language
[0])
3467 * Try a different language subset...
3471 language
[0] = '\0'; /* Strip country code */
3473 language
[0] = '\0'; /* Strip language */
3477 * Look for the index file...
3480 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3482 if ((ptr
= strchr(filename
, '?')) != NULL
)
3485 ptr
= filename
+ strlen(filename
);
3486 plen
= len
- (ptr
- filename
);
3488 strlcpy(ptr
, "index.html", plen
);
3489 status
= stat(filename
, filestats
);
3494 strlcpy(ptr
, "index.class", plen
);
3495 status
= stat(filename
, filestats
);
3497 #endif /* HAVE_JAVA */
3502 strlcpy(ptr
, "index.pl", plen
);
3503 status
= stat(filename
, filestats
);
3505 #endif /* HAVE_PERL */
3510 strlcpy(ptr
, "index.php", plen
);
3511 status
= stat(filename
, filestats
);
3513 #endif /* HAVE_PHP */
3518 strlcpy(ptr
, "index.pyc", plen
);
3519 status
= stat(filename
, filestats
);
3524 strlcpy(ptr
, "index.py", plen
);
3525 status
= stat(filename
, filestats
);
3527 #endif /* HAVE_PYTHON */
3530 while (status
&& language
[0]);
3533 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3534 "get_file(con=%p(%d), filestats=%p, filename=%p, len=%d) = "
3535 "%s", con
, con
->http
.fd
, filestats
, filename
, len
,
3536 status
? "(null)" : filename
);
3539 con
->http
.data_remaining
= (int)filestats
->st_size
;
3549 * 'install_conf_file()' - Install a configuration file.
3552 static http_status_t
/* O - Status */
3553 install_conf_file(cupsd_client_t
*con
) /* I - Connection */
3555 cups_file_t
*in
, /* Input file */
3556 *out
; /* Output file */
3557 char buffer
[1024]; /* Copy buffer */
3558 int bytes
; /* Number of bytes */
3559 char conffile
[1024], /* Configuration filename */
3560 newfile
[1024], /* New config filename */
3561 oldfile
[1024]; /* Old config filename */
3562 struct stat confinfo
; /* Config file info */
3566 * First construct the filenames...
3569 snprintf(conffile
, sizeof(conffile
), "%s%s", ServerRoot
, con
->uri
+ 11);
3570 snprintf(newfile
, sizeof(newfile
), "%s%s.N", ServerRoot
, con
->uri
+ 11);
3571 snprintf(oldfile
, sizeof(oldfile
), "%s%s.O", ServerRoot
, con
->uri
+ 11);
3573 cupsdLogMessage(CUPSD_LOG_INFO
, "Installing config file \"%s\"...", conffile
);
3576 * Get the owner, group, and permissions of the configuration file.
3577 * If it doesn't exist, assign it to the User and Group in the
3578 * cupsd.conf file with mode 0640 permissions.
3581 if (stat(conffile
, &confinfo
))
3583 confinfo
.st_uid
= User
;
3584 confinfo
.st_gid
= Group
;
3585 confinfo
.st_mode
= ConfigFilePerm
;
3589 * Open the request file and new config file...
3592 if ((in
= cupsFileOpen(con
->filename
, "rb")) == NULL
)
3594 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open request file \"%s\" - %s",
3595 con
->filename
, strerror(errno
));
3596 return (HTTP_SERVER_ERROR
);
3599 if ((out
= cupsFileOpen(newfile
, "wb")) == NULL
)
3602 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open config file \"%s\" - %s",
3603 newfile
, strerror(errno
));
3604 return (HTTP_SERVER_ERROR
);
3607 fchmod(cupsFileNumber(out
), confinfo
.st_mode
);
3608 fchown(cupsFileNumber(out
), confinfo
.st_uid
, confinfo
.st_gid
);
3611 * Copy from the request to the new config file...
3614 while ((bytes
= cupsFileRead(in
, buffer
, sizeof(buffer
))) > 0)
3615 if (cupsFileWrite(out
, buffer
, bytes
) < bytes
)
3617 cupsdLogMessage(CUPSD_LOG_ERROR
,
3618 "Unable to copy to config file \"%s\" - %s",
3619 newfile
, strerror(errno
));
3625 return (HTTP_SERVER_ERROR
);
3629 * Close the files...
3633 if (cupsFileClose(out
))
3635 cupsdLogMessage(CUPSD_LOG_ERROR
,
3636 "Error file closing config file \"%s\" - %s",
3637 newfile
, strerror(errno
));
3641 return (HTTP_SERVER_ERROR
);
3645 * Remove the request file...
3648 unlink(con
->filename
);
3649 cupsdClearString(&con
->filename
);
3652 * Unlink the old backup, rename the current config file to the backup
3653 * filename, and rename the new config file to the config file name...
3656 if (unlink(oldfile
))
3657 if (errno
!= ENOENT
)
3659 cupsdLogMessage(CUPSD_LOG_ERROR
,
3660 "Unable to remove backup config file \"%s\" - %s",
3661 oldfile
, strerror(errno
));
3665 return (HTTP_SERVER_ERROR
);
3668 if (rename(conffile
, oldfile
))
3669 if (errno
!= ENOENT
)
3671 cupsdLogMessage(CUPSD_LOG_ERROR
,
3672 "Unable to rename old config file \"%s\" - %s",
3673 conffile
, strerror(errno
));
3677 return (HTTP_SERVER_ERROR
);
3680 if (rename(newfile
, conffile
))
3682 cupsdLogMessage(CUPSD_LOG_ERROR
,
3683 "Unable to rename new config file \"%s\" - %s",
3684 newfile
, strerror(errno
));
3686 rename(oldfile
, conffile
);
3689 return (HTTP_SERVER_ERROR
);
3693 * If the cupsd.conf file was updated, set the NeedReload flag...
3696 if (!strcmp(con
->uri
, "/admin/conf/cupsd.conf"))
3697 NeedReload
= RELOAD_CUPSD
;
3699 NeedReload
= RELOAD_ALL
;
3701 ReloadTime
= time(NULL
);
3704 * Return that the file was created successfully...
3707 return (HTTP_CREATED
);
3712 * 'is_cgi()' - Is the resource a CGI script/program?
3715 static int /* O - 1 = CGI, 0 = file */
3716 is_cgi(cupsd_client_t
*con
, /* I - Client connection */
3717 const char *filename
, /* I - Real filename */
3718 struct stat
*filestats
, /* I - File information */
3719 mime_type_t
*type
) /* I - MIME type */
3721 const char *options
; /* Options on URL */
3725 * Get the options, if any...
3728 if ((options
= strchr(con
->uri
, '?')) != NULL
)
3731 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", options
);
3735 * Check for known types...
3738 if (!type
|| strcasecmp(type
->super
, "application"))
3740 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3741 "is_cgi(con=%p(%d), filename=\"%s\", filestats=%p, "
3742 "type=%s/%s) = 0", con
, con
->http
.fd
, filename
, filestats
,
3743 type
? type
->super
: "unknown",
3744 type
? type
->type
: "unknown");
3748 if (!strcasecmp(type
->type
, "x-httpd-cgi") &&
3749 (filestats
->st_mode
& 0111))
3752 * "application/x-httpd-cgi" is a CGI script.
3755 cupsdSetString(&con
->command
, filename
);
3758 cupsdSetStringf(&con
->options
, " %s", options
);
3760 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3761 "is_cgi(con=%p(%d), filename=\"%s\", filestats=%p, "
3762 "type=%s/%s) = 1", con
, con
->http
.fd
, filename
, filestats
,
3763 type
? type
->super
: "unknown",
3764 type
? type
->type
: "unknown");
3768 else if (!strcasecmp(type
->type
, "x-httpd-java"))
3771 * "application/x-httpd-java" is a Java servlet.
3774 cupsdSetString(&con
->command
, CUPS_JAVA
);
3777 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3779 cupsdSetStringf(&con
->options
, " %s", filename
);
3781 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3782 "is_cgi(con=%p(%d), filename=\"%s\", filestats=%p, "
3783 "type=%s/%s) = 1", con
, con
->http
.fd
, filename
, filestats
,
3784 type
? type
->super
: "unknown",
3785 type
? type
->type
: "unknown");
3788 #endif /* HAVE_JAVA */
3790 else if (!strcasecmp(type
->type
, "x-httpd-perl"))
3793 * "application/x-httpd-perl" is a Perl page.
3796 cupsdSetString(&con
->command
, CUPS_PERL
);
3799 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3801 cupsdSetStringf(&con
->options
, " %s", filename
);
3803 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3804 "is_cgi(con=%p(%d), filename=\"%s\", filestats=%p, "
3805 "type=%s/%s) = 1", con
, con
->http
.fd
, filename
, filestats
,
3806 type
? type
->super
: "unknown",
3807 type
? type
->type
: "unknown");
3810 #endif /* HAVE_PERL */
3812 else if (!strcasecmp(type
->type
, "x-httpd-php"))
3815 * "application/x-httpd-php" is a PHP page.
3818 cupsdSetString(&con
->command
, CUPS_PHP
);
3821 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3823 cupsdSetStringf(&con
->options
, " %s", filename
);
3825 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3826 "is_cgi(con=%p(%d), filename=\"%s\", filestats=%p, "
3827 "type=%s/%s) = 1", con
, con
->http
.fd
, filename
, filestats
,
3828 type
? type
->super
: "unknown",
3829 type
? type
->type
: "unknown");
3832 #endif /* HAVE_PHP */
3834 else if (!strcasecmp(type
->type
, "x-httpd-python"))
3837 * "application/x-httpd-python" is a Python page.
3840 cupsdSetString(&con
->command
, CUPS_PYTHON
);
3843 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3845 cupsdSetStringf(&con
->options
, " %s", filename
);
3847 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3848 "is_cgi(con=%p(%d), filename=\"%s\", filestats=%p, "
3849 "type=%s/%s) = 1", con
, con
->http
.fd
, filename
, filestats
,
3850 type
? type
->super
: "unknown",
3851 type
? type
->type
: "unknown");
3854 #endif /* HAVE_PYTHON */
3856 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3857 "is_cgi(con=%p(%d), filename=\"%s\", filestats=%p, "
3858 "type=%s/%s) = 0", con
, con
->http
.fd
, filename
, filestats
,
3859 type
? type
->super
: "unknown",
3860 type
? type
->type
: "unknown");
3866 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
3869 static int /* O - 0 if relative, 1 if absolute */
3870 is_path_absolute(const char *path
) /* I - Input path */
3873 * Check for a leading slash...
3880 * Check for "/.." in the path...
3883 while ((path
= strstr(path
, "/..")) != NULL
)
3885 if (!path
[3] || path
[3] == '/')
3892 * If we haven't found any relative paths, return 1 indicating an
3902 * 'make_certificate()' - Make a self-signed SSL/TLS certificate.
3905 static int /* O - 1 on success, 0 on failure */
3906 make_certificate(cupsd_client_t
*con
) /* I - Client connection */
3908 #if defined(HAVE_LIBSSL) && defined(HAVE_WAITPID)
3909 int pid
, /* Process ID of command */
3910 status
; /* Status of command */
3911 char command
[1024], /* Command */
3912 *argv
[12], /* Command-line arguments */
3913 *envp
[MAX_ENV
+ 1], /* Environment variables */
3914 home
[1024], /* HOME environment variable */
3915 infofile
[1024], /* Type-in information for cert */
3916 seedfile
[1024]; /* Random number seed file */
3917 int envc
, /* Number of environment variables */
3918 bytes
; /* Bytes written */
3919 cups_file_t
*fp
; /* Seed/info file */
3920 int infofd
; /* Info file descriptor */
3924 * Run the "openssl" command to seed the random number generator and
3925 * generate a self-signed certificate that is good for 10 years:
3927 * openssl rand -rand seedfile 1
3929 * openssl req -new -x509 -keyout ServerKey \
3930 * -out ServerCertificate -days 3650 -nodes
3932 * The seeding step is crucial in ensuring that the openssl command
3933 * does not block on systems without sufficient entropy...
3936 if (!cupsFileFind("openssl", getenv("PATH"), 1, command
, sizeof(command
)))
3938 cupsdLogMessage(CUPSD_LOG_ERROR
,
3939 "No SSL certificate and openssl command not found!");
3943 if (access("/dev/urandom", 0))
3946 * If the system doesn't provide /dev/urandom, then any random source
3947 * will probably be blocking-style, so generate some random data to
3948 * use as a seed for the certificate. Note that we have already
3949 * seeded the random number generator in cupsdInitCerts()...
3952 cupsdLogMessage(CUPSD_LOG_INFO
,
3953 "Seeding the random number generator...");
3955 snprintf(home
, sizeof(home
), "HOME=%s", TempDir
);
3958 * Write the seed file...
3961 if ((fp
= cupsTempFile2(seedfile
, sizeof(seedfile
))) == NULL
)
3963 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to create seed file %s - %s",
3964 seedfile
, strerror(errno
));
3968 for (bytes
= 0; bytes
< 262144; bytes
++)
3969 cupsFilePutChar(fp
, random());
3974 * Run the openssl command to seed its random number generator...
3977 argv
[0] = "openssl";
3984 envc
= cupsdLoadEnv(envp
, MAX_ENV
);
3985 envp
[envc
++] = home
;
3988 if (!cupsdStartProcess(command
, argv
, envp
, -1, -1, -1, -1, -1, 1, NULL
, 0,
3995 while (waitpid(pid
, &status
, 0) < 0)
4002 cupsdFinishProcess(pid
, command
, sizeof(command
), NULL
);
4005 * Remove the seed file, as it is no longer needed...
4012 if (WIFEXITED(status
))
4013 cupsdLogMessage(CUPSD_LOG_ERROR
,
4014 "Unable to seed random number generator - "
4015 "the openssl command stopped with status %d!",
4016 WEXITSTATUS(status
));
4018 cupsdLogMessage(CUPSD_LOG_ERROR
,
4019 "Unable to seed random number generator - "
4020 "the openssl command crashed on signal %d!",
4028 * Create a file with the certificate information fields...
4030 * Note: This assumes that the default questions are asked by the openssl
4034 if ((fp
= cupsTempFile2(infofile
, sizeof(infofile
))) == NULL
)
4036 cupsdLogMessage(CUPSD_LOG_ERROR
,
4037 "Unable to create certificate information file %s - %s",
4038 infofile
, strerror(errno
));
4042 cupsFilePrintf(fp
, ".\n.\n.\n%s\n.\n%s\n%s\n",
4043 ServerName
, ServerName
, ServerAdmin
);
4046 cupsdLogMessage(CUPSD_LOG_INFO
,
4047 "Generating SSL server key and certificate...");
4049 argv
[0] = "openssl";
4053 argv
[4] = "-keyout";
4054 argv
[5] = ServerKey
;
4056 argv
[7] = ServerCertificate
;
4059 argv
[10] = "-nodes";
4062 cupsdLoadEnv(envp
, MAX_ENV
);
4064 infofd
= open(infofile
, O_RDONLY
);
4066 if (!cupsdStartProcess(command
, argv
, envp
, infofd
, -1, -1, -1, -1, 1, NULL
,
4077 while (waitpid(pid
, &status
, 0) < 0)
4084 cupsdFinishProcess(pid
, command
, sizeof(command
), NULL
);
4088 if (WIFEXITED(status
))
4089 cupsdLogMessage(CUPSD_LOG_ERROR
,
4090 "Unable to create SSL server key and certificate - "
4091 "the openssl command stopped with status %d!",
4092 WEXITSTATUS(status
));
4094 cupsdLogMessage(CUPSD_LOG_ERROR
,
4095 "Unable to create SSL server key and certificate - "
4096 "the openssl command crashed on signal %d!",
4101 cupsdLogMessage(CUPSD_LOG_INFO
, "Created SSL server key file \"%s\"...",
4103 cupsdLogMessage(CUPSD_LOG_INFO
,
4104 "Created SSL server certificate file \"%s\"...",
4110 #elif defined(HAVE_GNUTLS)
4111 gnutls_x509_crt crt
; /* Self-signed certificate */
4112 gnutls_x509_privkey key
; /* Encryption key */
4113 cups_lang_t
*language
; /* Default language info */
4114 cups_file_t
*fp
; /* Key/cert file */
4115 unsigned char buffer
[8192]; /* Buffer for x509 data */
4116 size_t bytes
; /* Number of bytes of data */
4117 unsigned char serial
[4]; /* Serial number buffer */
4118 time_t curtime
; /* Current time */
4119 int result
; /* Result of GNU TLS calls */
4123 * Create the encryption key...
4126 cupsdLogMessage(CUPSD_LOG_INFO
, "Generating SSL server key...");
4128 gnutls_x509_privkey_init(&key
);
4129 gnutls_x509_privkey_generate(key
, GNUTLS_PK_RSA
, 2048, 0);
4135 bytes
= sizeof(buffer
);
4137 if ((result
= gnutls_x509_privkey_export(key
, GNUTLS_X509_FMT_PEM
,
4138 buffer
, &bytes
)) < 0)
4140 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to export SSL server key - %s",
4141 gnutls_strerror(result
));
4142 gnutls_x509_privkey_deinit(key
);
4145 else if ((fp
= cupsFileOpen(ServerKey
, "w")) != NULL
)
4147 cupsFileWrite(fp
, (char *)buffer
, bytes
);
4150 cupsdLogMessage(CUPSD_LOG_INFO
, "Created SSL server key file \"%s\"...",
4155 cupsdLogMessage(CUPSD_LOG_ERROR
,
4156 "Unable to create SSL server key file \"%s\" - %s",
4157 ServerKey
, strerror(errno
));
4158 gnutls_x509_privkey_deinit(key
);
4163 * Create the self-signed certificate...
4166 cupsdLogMessage(CUPSD_LOG_INFO
, "Generating self-signed SSL certificate...");
4168 language
= cupsLangDefault();
4169 curtime
= time(NULL
);
4170 serial
[0] = curtime
>> 24;
4171 serial
[1] = curtime
>> 16;
4172 serial
[2] = curtime
>> 8;
4173 serial
[3] = curtime
;
4175 gnutls_x509_crt_init(&crt
);
4176 if (strlen(language
->language
) == 5)
4177 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
4178 language
->language
+ 3, 2);
4180 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
4182 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COMMON_NAME
, 0,
4183 ServerName
, strlen(ServerName
));
4184 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATION_NAME
, 0,
4185 ServerName
, strlen(ServerName
));
4186 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATIONAL_UNIT_NAME
,
4188 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_STATE_OR_PROVINCE_NAME
, 0,
4190 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_LOCALITY_NAME
, 0,
4192 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_PKCS9_EMAIL
, 0,
4193 ServerAdmin
, strlen(ServerAdmin
));
4194 gnutls_x509_crt_set_key(crt
, key
);
4195 gnutls_x509_crt_set_serial(crt
, serial
, sizeof(serial
));
4196 gnutls_x509_crt_set_activation_time(crt
, curtime
);
4197 gnutls_x509_crt_set_expiration_time(crt
, curtime
+ 10 * 365 * 86400);
4198 gnutls_x509_crt_set_ca_status(crt
, 0);
4199 gnutls_x509_crt_set_subject_alternative_name(crt
, GNUTLS_SAN_DNSNAME
,
4201 gnutls_x509_crt_set_key_purpose_oid(crt
, GNUTLS_KP_TLS_WWW_SERVER
, 0);
4202 gnutls_x509_crt_set_key_usage(crt
, GNUTLS_KEY_KEY_ENCIPHERMENT
);
4203 gnutls_x509_crt_set_version(crt
, 3);
4205 bytes
= sizeof(buffer
);
4206 if (gnutls_x509_crt_get_key_id(crt
, 0, buffer
, &bytes
) >= 0)
4207 gnutls_x509_crt_set_subject_key_id(crt
, buffer
, bytes
);
4209 gnutls_x509_crt_sign(crt
, crt
, key
);
4215 bytes
= sizeof(buffer
);
4216 if ((result
= gnutls_x509_crt_export(crt
, GNUTLS_X509_FMT_PEM
,
4217 buffer
, &bytes
)) < 0)
4218 cupsdLogMessage(CUPSD_LOG_ERROR
,
4219 "Unable to export SSL server certificate - %s",
4220 gnutls_strerror(result
));
4221 else if ((fp
= cupsFileOpen(ServerCertificate
, "w")) != NULL
)
4223 cupsFileWrite(fp
, (char *)buffer
, bytes
);
4226 cupsdLogMessage(CUPSD_LOG_INFO
,
4227 "Created SSL server certificate file \"%s\"...",
4231 cupsdLogMessage(CUPSD_LOG_ERROR
,
4232 "Unable to create SSL server certificate file \"%s\" - %s",
4233 ServerCertificate
, strerror(errno
));
4239 gnutls_x509_crt_deinit(crt
);
4240 gnutls_x509_privkey_deinit(key
);
4244 #elif defined(HAVE_CDSASSL) && defined(HAVE_WAITPID)
4245 int pid
, /* Process ID of command */
4246 status
; /* Status of command */
4247 char command
[1024], /* Command */
4248 *argv
[4], /* Command-line arguments */
4249 *envp
[MAX_ENV
+ 1], /* Environment variables */
4250 keychain
[1024], /* Keychain argument */
4251 infofile
[1024]; /* Type-in information for cert */
4252 cups_file_t
*fp
; /* Seed/info file */
4253 int infofd
; /* Info file descriptor */
4257 * Run the "certtool" command to generate a self-signed certificate...
4260 if (!cupsFileFind("certtool", getenv("PATH"), 1, command
, sizeof(command
)))
4262 cupsdLogMessage(CUPSD_LOG_ERROR
,
4263 "No SSL certificate and certtool command not found!");
4268 * Create a file with the certificate information fields...
4270 * Note: This assumes that the default questions are asked by the certtool
4274 if ((fp
= cupsTempFile2(infofile
, sizeof(infofile
))) == NULL
)
4276 cupsdLogMessage(CUPSD_LOG_ERROR
,
4277 "Unable to create certificate information file %s - %s",
4278 infofile
, strerror(errno
));
4282 cupsFilePrintf(fp
, "%s\nr\n\ny\nb\ns\ny\n%s\n\n\n\n\n%s\ny\n",
4283 con
->servername
, con
->servername
, ServerAdmin
);
4286 cupsdLogMessage(CUPSD_LOG_INFO
,
4287 "Generating SSL server key and certificate...");
4289 snprintf(keychain
, sizeof(keychain
), "k=%s", ServerCertificate
);
4291 argv
[0] = "certtool";
4296 cupsdLoadEnv(envp
, MAX_ENV
);
4298 infofd
= open(infofile
, O_RDONLY
);
4300 if (!cupsdStartProcess(command
, argv
, envp
, infofd
, -1, -1, -1, -1, 1, NULL
,
4311 while (waitpid(pid
, &status
, 0) < 0)
4318 cupsdFinishProcess(pid
, command
, sizeof(command
), NULL
);
4322 if (WIFEXITED(status
))
4323 cupsdLogMessage(CUPSD_LOG_ERROR
,
4324 "Unable to create SSL server key and certificate - "
4325 "the certtool command stopped with status %d!",
4326 WEXITSTATUS(status
));
4328 cupsdLogMessage(CUPSD_LOG_ERROR
,
4329 "Unable to create SSL server key and certificate - "
4330 "the certtool command crashed on signal %d!",
4335 cupsdLogMessage(CUPSD_LOG_INFO
,
4336 "Created SSL server certificate file \"%s\"...",
4344 #endif /* HAVE_LIBSSL && HAVE_WAITPID */
4346 #endif /* HAVE_SSL */
4350 * 'pipe_command()' - Pipe the output of a command to the remote client.
4353 static int /* O - Process ID */
4354 pipe_command(cupsd_client_t
*con
, /* I - Client connection */
4355 int infile
, /* I - Standard input for command */
4356 int *outfile
, /* O - Standard output for command */
4357 char *command
, /* I - Command to run */
4358 char *options
, /* I - Options for command */
4359 int root
) /* I - Run as root? */
4361 int i
; /* Looping var */
4362 int pid
; /* Process ID */
4363 char *commptr
, /* Command string pointer */
4364 commch
; /* Command string character */
4365 char *uriptr
; /* URI string pointer */
4366 int fds
[2]; /* Pipe FDs */
4367 int argc
; /* Number of arguments */
4368 int envc
; /* Number of environment variables */
4369 char argbuf
[10240], /* Argument buffer */
4370 *argv
[100], /* Argument strings */
4371 *envp
[MAX_ENV
+ 20]; /* Environment variables */
4372 char auth_type
[256], /* CUPSD_AUTH_TYPE environment variable */
4373 content_length
[1024], /* CONTENT_LENGTH environment variable */
4374 content_type
[1024], /* CONTENT_TYPE environment variable */
4375 http_cookie
[32768], /* HTTP_COOKIE environment variable */
4376 http_referer
[1024], /* HTTP_REFERER environment variable */
4377 http_user_agent
[1024], /* HTTP_USER_AGENT environment variable */
4378 lang
[1024], /* LANG environment variable */
4379 path_info
[1024], /* PATH_INFO environment variable */
4380 remote_addr
[1024], /* REMOTE_ADDR environment variable */
4381 remote_host
[1024], /* REMOTE_HOST environment variable */
4382 remote_user
[1024], /* REMOTE_USER environment variable */
4383 script_filename
[1024], /* SCRIPT_FILENAME environment variable */
4384 script_name
[1024], /* SCRIPT_NAME environment variable */
4385 server_name
[1024], /* SERVER_NAME environment variable */
4386 server_port
[1024]; /* SERVER_PORT environment variable */
4387 ipp_attribute_t
*attr
; /* attributes-natural-language attribute */
4389 krb5_ccache ccache
= NULL
; /* Kerberos credentials */
4390 # if defined(HAVE_KRB5_CC_NEW_UNIQUE) || defined(HAVE_HEIMDAL)
4391 char krb5ccname
[1024]; /* KRB5CCNAME environment variable */
4392 # endif /* HAVE_KRB5_CC_NEW_UNIQUE || HAVE_HEIMDAL */
4393 #endif /* HAVE_GSSAPI */
4397 * Parse a copy of the options string, which is of the form:
4399 * argument+argument+argument
4400 * ?argument+argument+argument
4401 * param=value¶m=value
4402 * ?param=value¶m=value
4403 * /name?argument+argument+argument
4404 * /name?param=value¶m=value
4406 * If the string contains an "=" character after the initial name,
4407 * then we treat it as a HTTP GET form request and make a copy of
4408 * the remaining string for the environment variable.
4410 * The string is always parsed out as command-line arguments, to
4411 * be consistent with Apache...
4414 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4415 "pipe_command(con=%p(%d), infile=%d, outfile=%p, "
4416 "command=\"%s\", options=\"%s\", root=%d)",
4417 con
, con
->http
.fd
, infile
, outfile
, command
,
4418 options
? options
: "(null)", root
);
4423 strlcpy(argbuf
, options
, sizeof(argbuf
));
4427 if (argbuf
[0] == '/')
4430 * Found some trailing path information, set PATH_INFO...
4433 if ((commptr
= strchr(argbuf
, '?')) == NULL
)
4434 commptr
= argbuf
+ strlen(argbuf
);
4438 snprintf(path_info
, sizeof(path_info
), "PATH_INFO=%s", argbuf
);
4444 path_info
[0] = '\0';
4446 if (*commptr
== ' ')
4450 if (*commptr
== '?' && con
->operation
== HTTP_GET
&& !con
->query_string
)
4453 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", commptr
);
4460 argv
[argc
++] = commptr
;
4462 for (; *commptr
&& argc
< 99; commptr
++)
4465 * Break arguments whenever we see a + or space...
4468 if (*commptr
== ' ' || *commptr
== '+')
4470 while (*commptr
== ' ' || *commptr
== '+')
4474 * If we don't have a blank string, save it as another argument...
4479 argv
[argc
] = commptr
;
4485 else if (*commptr
== '%' && isxdigit(commptr
[1] & 255) &&
4486 isxdigit(commptr
[2] & 255))
4489 * Convert the %xx notation to the individual character.
4492 if (commptr
[1] >= '0' && commptr
[1] <= '9')
4493 *commptr
= (commptr
[1] - '0') << 4;
4495 *commptr
= (tolower(commptr
[1]) - 'a' + 10) << 4;
4497 if (commptr
[2] >= '0' && commptr
[2] <= '9')
4498 *commptr
|= commptr
[2] - '0';
4500 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
4502 _cups_strcpy(commptr
+ 1, commptr
+ 3);
4505 * Check for a %00 and break if that is the case...
4517 * Setup the environment variables as needed...
4520 if (con
->username
[0])
4522 snprintf(auth_type
, sizeof(auth_type
), "CUPSD_AUTH_TYPE=%s",
4523 httpGetField(HTTP(con
), HTTP_FIELD_AUTHORIZATION
));
4525 if ((uriptr
= strchr(auth_type
+ 10, ' ')) != NULL
)
4529 auth_type
[0] = '\0';
4532 (attr
= ippFindAttribute(con
->request
, "attributes-natural-language",
4533 IPP_TAG_LANGUAGE
)) != NULL
)
4535 switch (strlen(attr
->values
[0].string
.text
))
4539 * This is an unknown or badly formatted language code; use
4540 * the POSIX locale...
4543 strcpy(lang
, "LANG=C");
4548 * Just the language code (ll)...
4551 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8",
4552 attr
->values
[0].string
.text
);
4557 * Language and country code (ll-cc)...
4560 snprintf(lang
, sizeof(lang
), "LANG=%c%c_%c%c.UTF8",
4561 attr
->values
[0].string
.text
[0],
4562 attr
->values
[0].string
.text
[1],
4563 toupper(attr
->values
[0].string
.text
[3] & 255),
4564 toupper(attr
->values
[0].string
.text
[4] & 255));
4568 else if (con
->language
)
4569 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8", con
->language
->language
);
4571 strcpy(lang
, "LANG=C");
4573 strcpy(remote_addr
, "REMOTE_ADDR=");
4574 httpAddrString(con
->http
.hostaddr
, remote_addr
+ 12,
4575 sizeof(remote_addr
) - 12);
4577 snprintf(remote_host
, sizeof(remote_host
), "REMOTE_HOST=%s",
4578 con
->http
.hostname
);
4580 snprintf(script_name
, sizeof(script_name
), "SCRIPT_NAME=%s", con
->uri
);
4581 if ((uriptr
= strchr(script_name
, '?')) != NULL
)
4584 snprintf(script_filename
, sizeof(script_filename
), "SCRIPT_FILENAME=%s%s",
4585 DocumentRoot
, script_name
+ 12);
4587 sprintf(server_port
, "SERVER_PORT=%d", con
->serverport
);
4589 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
4592 envc
= cupsdLoadEnv(envp
, (int)(sizeof(envp
) / sizeof(envp
[0])));
4595 envp
[envc
++] = auth_type
;
4597 envp
[envc
++] = lang
;
4598 envp
[envc
++] = "REDIRECT_STATUS=1";
4599 envp
[envc
++] = "GATEWAY_INTERFACE=CGI/1.1";
4600 envp
[envc
++] = server_name
;
4601 envp
[envc
++] = server_port
;
4602 envp
[envc
++] = remote_addr
;
4603 envp
[envc
++] = remote_host
;
4604 envp
[envc
++] = script_name
;
4605 envp
[envc
++] = script_filename
;
4608 envp
[envc
++] = path_info
;
4610 if (con
->username
[0])
4612 snprintf(remote_user
, sizeof(remote_user
), "REMOTE_USER=%s", con
->username
);
4614 envp
[envc
++] = remote_user
;
4617 * Save Kerberos credentials, if any...
4621 if (con
->gss_have_creds
)
4623 # if !defined(HAVE_KRB5_CC_NEW_UNIQUE) && !defined(HAVE_HEIMDAL)
4624 cupsdLogMessage(CUPSD_LOG_INFO
,
4625 "Sorry, your version of Kerberos does not support "
4626 "delegated credentials!");
4629 krb5_error_code error
; /* Kerberos error code */
4630 OM_uint32 major_status
, /* Major status code */
4631 minor_status
; /* Minor status code */
4632 krb5_principal principal
; /* Kerberos principal */
4637 * If the weak-linked GSSAPI/Kerberos library is not present, don't try
4641 if (krb5_init_context
!= NULL
)
4643 # endif /* __APPLE__ */
4645 if (!KerberosInitialized
)
4648 * Setup a Kerberos context for the scheduler to use...
4651 KerberosInitialized
= 1;
4653 if (krb5_init_context(&KerberosContext
))
4655 KerberosContext
= NULL
;
4657 cupsdLogMessage(CUPSD_LOG_ERROR
,
4658 "Unable to initialize Kerberos context");
4663 * We MUST create a file-based cache because memory-based caches are
4664 * only valid for the current process/address space.
4666 * Due to various bugs/features in different versions of Kerberos, we
4667 * need either the krb5_cc_new_unique() function or Heimdal's version
4668 * of krb5_cc_gen_new() to create a new FILE: credential cache that
4669 * can be passed to the backend. These functions create a temporary
4670 * file (typically in /tmp) containing the cached credentials, which
4671 * are removed when we have successfully printed a job.
4674 if (KerberosContext
)
4676 # ifdef HAVE_KRB5_CC_NEW_UNIQUE
4677 if ((error
= krb5_cc_new_unique(KerberosContext
, "FILE", NULL
,
4679 # else /* HAVE_HEIMDAL */
4680 if ((error
= krb5_cc_gen_new(KerberosContext
, &krb5_fcc_ops
,
4682 # endif /* HAVE_KRB5_CC_NEW_UNIQUE */
4684 cupsdLogMessage(CUPSD_LOG_ERROR
,
4685 "Unable to create new credentials cache (%d/%s)",
4686 error
, strerror(errno
));
4689 else if ((error
= krb5_parse_name(KerberosContext
, con
->username
,
4692 cupsdLogMessage(CUPSD_LOG_ERROR
,
4693 "Unable to parse kerberos username (%d/%s)", error
,
4695 krb5_cc_destroy(KerberosContext
, ccache
);
4698 else if ((error
= krb5_cc_initialize(KerberosContext
, ccache
,
4701 cupsdLogMessage(CUPSD_LOG_ERROR
,
4702 "Unable to initialize credentials cache (%d/%s)",
4703 error
, strerror(errno
));
4704 krb5_cc_destroy(KerberosContext
, ccache
);
4705 krb5_free_principal(KerberosContext
, principal
);
4710 krb5_free_principal(KerberosContext
, principal
);
4713 * Copy the user's credentials to the new cache file...
4716 major_status
= gss_krb5_copy_ccache(&minor_status
,
4717 con
->gss_delegated_cred
, ccache
);
4719 if (GSS_ERROR(major_status
))
4721 cupsdLogGSSMessage(CUPSD_LOG_ERROR
, major_status
, minor_status
,
4722 "Unable to import client credentials cache");
4723 krb5_cc_destroy(KerberosContext
, ccache
);
4729 * Add the KRB5CCNAME environment variable to the job so that the
4730 * backend can use the credentials when printing.
4733 snprintf(krb5ccname
, sizeof(krb5ccname
), "KRB5CCNAME=FILE:%s",
4734 krb5_cc_get_name(KerberosContext
, ccache
));
4735 envp
[envc
++] = krb5ccname
;
4738 chown(krb5_cc_get_name(KerberosContext
, ccache
), User
, Group
);
4744 # endif /* __APPLE__ */
4745 # endif /* HAVE_KRB5_CC_NEW_UNIQUE || HAVE_HEIMDAL */
4747 #endif /* HAVE_GSSAPI */
4750 if (con
->http
.version
== HTTP_1_1
)
4751 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.1";
4752 else if (con
->http
.version
== HTTP_1_0
)
4753 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.0";
4755 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/0.9";
4757 if (con
->http
.cookie
)
4759 snprintf(http_cookie
, sizeof(http_cookie
), "HTTP_COOKIE=%s",
4761 envp
[envc
++] = http_cookie
;
4764 if (con
->http
.fields
[HTTP_FIELD_USER_AGENT
][0])
4766 snprintf(http_user_agent
, sizeof(http_user_agent
), "HTTP_USER_AGENT=%s",
4767 con
->http
.fields
[HTTP_FIELD_USER_AGENT
]);
4768 envp
[envc
++] = http_user_agent
;
4771 if (con
->http
.fields
[HTTP_FIELD_REFERER
][0])
4773 snprintf(http_referer
, sizeof(http_referer
), "HTTP_REFERER=%s",
4774 con
->http
.fields
[HTTP_FIELD_REFERER
]);
4775 envp
[envc
++] = http_referer
;
4778 if (con
->operation
== HTTP_GET
)
4780 envp
[envc
++] = "REQUEST_METHOD=GET";
4782 if (con
->query_string
)
4785 * Add GET form variables after ?...
4788 envp
[envc
++] = con
->query_string
;
4791 envp
[envc
++] = "QUERY_STRING=";
4795 sprintf(content_length
, "CONTENT_LENGTH=" CUPS_LLFMT
,
4796 CUPS_LLCAST con
->bytes
);
4797 snprintf(content_type
, sizeof(content_type
), "CONTENT_TYPE=%s",
4798 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
4800 envp
[envc
++] = "REQUEST_METHOD=POST";
4801 envp
[envc
++] = content_length
;
4802 envp
[envc
++] = content_type
;
4806 * Tell the CGI if we are using encryption...
4810 envp
[envc
++] = "HTTPS=ON";
4813 * Terminate the environment array...
4818 if (LogLevel
== CUPSD_LOG_DEBUG2
)
4820 for (i
= 0; i
< argc
; i
++)
4821 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4822 "pipe_command: argv[%d] = \"%s\"", i
, argv
[i
]);
4823 for (i
= 0; i
< envc
; i
++)
4824 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4825 "pipe_command: envp[%d] = \"%s\"", i
, envp
[i
]);
4829 * Create a pipe for the output...
4832 if (cupsdOpenPipe(fds
))
4834 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to create pipes for CGI %s - %s",
4835 argv
[0], strerror(errno
));
4840 * Then execute the command...
4843 if (cupsdStartProcess(command
, argv
, envp
, infile
, fds
[1], CGIPipes
[1],
4844 -1, -1, root
, DefaultProfile
, 0, &pid
) < 0)
4847 * Error - can't fork!
4850 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to fork for CGI %s - %s", argv
[0],
4853 cupsdClosePipe(fds
);
4859 * Fork successful - return the PID...
4862 if (con
->username
[0])
4864 cupsdAddCert(pid
, con
->username
, ccache
);
4866 cupsdAddCert(pid
, con
->username
, NULL
);
4867 #endif /* HAVE_GSSAPI */
4869 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[CGI] %s started - PID = %d",
4881 * 'write_file()' - Send a file via HTTP.
4884 static int /* O - 0 on failure, 1 on success */
4885 write_file(cupsd_client_t
*con
, /* I - Client connection */
4886 http_status_t code
, /* I - HTTP status */
4887 char *filename
, /* I - Filename */
4888 char *type
, /* I - File type */
4889 struct stat
*filestats
) /* O - File information */
4891 con
->file
= open(filename
, O_RDONLY
);
4893 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4894 "write_file(con=%p(%d), code=%d, filename=\"%s\" (%d), "
4895 "type=\"%s\", filestats=%p)", con
, con
->http
.fd
,
4896 code
, filename
, con
->file
, type
? type
: "(null)", filestats
);
4901 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
4905 if (!cupsdSendHeader(con
, code
, type
, CUPSD_AUTH_NONE
))
4908 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
4909 httpGetDateString(filestats
->st_mtime
)) < 0)
4911 if (httpPrintf(HTTP(con
), "Content-Length: " CUPS_LLFMT
"\r\n",
4912 CUPS_LLCAST filestats
->st_size
) < 0)
4914 if (httpPrintf(HTTP(con
), "\r\n") < 0)
4917 if (cupsdFlushHeader(con
) < 0)
4920 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
4921 con
->http
.data_remaining
= filestats
->st_size
;
4923 if (con
->http
.data_remaining
<= INT_MAX
)
4924 con
->http
._data_remaining
= con
->http
.data_remaining
;
4926 con
->http
._data_remaining
= INT_MAX
;
4928 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
,
4929 (cupsd_selfunc_t
)cupsdWriteClient
, con
);
4936 * 'write_pipe()' - Flag that data is available on the CGI pipe.
4940 write_pipe(cupsd_client_t
*con
) /* I - Client connection */
4942 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4943 "write_pipe(con=%p(%d)) CGI output on fd %d",
4944 con
, con
->http
.fd
, con
->file
);
4946 con
->file_ready
= 1;
4948 cupsdRemoveSelect(con
->file
);
4949 cupsdAddSelect(con
->http
.fd
, NULL
, (cupsd_selfunc_t
)cupsdWriteClient
, con
);
4954 * End of "$Id: client.c 7950 2008-09-17 00:21:59Z mike $".