2 * "$Id: client.c 7673 2008-06-18 22:31:26Z mike $"
4 * Client routines for the Common UNIX Printing System (CUPS) scheduler.
6 * Copyright 2007-2008 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 programs.
29 * cupsdWriteClient() - Write data to a client as needed.
30 * check_if_modified() - Decode an "If-Modified-Since" line.
31 * compare_clients() - Compare two client connections.
32 * data_ready() - Check whether data is available from a client.
33 * encrypt_client() - Enable encryption for the client...
34 * get_cdsa_certificate() - Convert a keychain name into the CFArrayRef
35 * required by SSLSetCertificate.
36 * get_file() - Get a filename and state info.
37 * install_conf_file() - Install a configuration file.
38 * is_cgi() - Is the resource a CGI script/program?
39 * is_path_absolute() - Is a path absolute and free of relative elements.
40 * make_certificate() - Make a self-signed SSL/TLS certificate.
41 * pipe_command() - Pipe the output of a command to the remote client.
42 * write_file() - Send a file via HTTP.
43 * write_pipe() - Flag that data is available on the CGI pipe.
47 * Include necessary headers...
53 # include <Security/Security.h>
54 # ifdef HAVE_SECIDENTITYSEARCHPRIV_H
55 # include <Security/SecIdentitySearchPriv.h>
56 # else /* Declare prototype for function in that header... */
57 extern OSStatus
SecIdentitySearchCreateWithPolicy(SecPolicyRef policy
,
58 CFStringRef idString
, CSSM_KEYUSE keyUsage
,
59 CFTypeRef keychainOrArray
,
60 Boolean returnOnlyValidIdentities
,
61 SecIdentitySearchRef
* searchRef
);
62 # endif /* HAVE_SECIDENTITYSEARCHPRIV_H */
63 # ifdef HAVE_SECPOLICYPRIV_H
64 # include <Security/SecPolicyPriv.h>
65 # else /* Declare prototype for function in that header... */
66 extern OSStatus
SecPolicySetValue(SecPolicyRef policyRef
,
67 const CSSM_DATA
*value
);
68 # endif /* HAVE_SECPOLICYPRIV_H */
69 # ifdef HAVE_SECBASEPRIV_H
70 # include <Security/SecBasePriv.h>
71 # else /* Declare prototype for function in that header... */
72 extern const char *cssmErrorString(int error
);
73 # endif /* HAVE_SECBASEPRIV_H */
74 #endif /* HAVE_CDSASSL */
77 # include <gnutls/x509.h>
78 #endif /* HAVE_GNUTLS */
82 #endif /* HAVE_TCPD_H */
89 static int check_if_modified(cupsd_client_t
*con
,
90 struct stat
*filestats
);
91 static int compare_clients(cupsd_client_t
*a
, cupsd_client_t
*b
,
93 static int data_ready(cupsd_client_t
*con
);
95 static int encrypt_client(cupsd_client_t
*con
);
98 static CFArrayRef
get_cdsa_certificate(cupsd_client_t
*con
);
99 #endif /* HAVE_CDSASSL */
100 static char *get_file(cupsd_client_t
*con
, struct stat
*filestats
,
101 char *filename
, int len
);
102 static http_status_t
install_conf_file(cupsd_client_t
*con
);
103 static int is_cgi(cupsd_client_t
*con
, const char *filename
,
104 struct stat
*filestats
, mime_type_t
*type
);
105 static int is_path_absolute(const char *path
);
107 static int make_certificate(cupsd_client_t
*con
);
108 #endif /* HAVE_SSL */
109 static int pipe_command(cupsd_client_t
*con
, int infile
, int *outfile
,
110 char *command
, char *options
, int root
);
111 static int write_file(cupsd_client_t
*con
, http_status_t code
,
112 char *filename
, char *type
,
113 struct stat
*filestats
);
114 static void write_pipe(cupsd_client_t
*con
);
118 * 'cupsdAcceptClient()' - Accept a new client.
122 cupsdAcceptClient(cupsd_listener_t
*lis
)/* I - Listener socket */
124 int count
; /* Count of connections on a host */
125 int val
; /* Parameter value */
126 cupsd_client_t
*con
, /* New client pointer */
127 *tempcon
; /* Temporary client pointer */
128 http_addrlist_t
*addrlist
, /* List of adddresses for host */
129 *addr
; /* Current address */
130 socklen_t addrlen
; /* Length of address */
131 char *hostname
; /* Hostname for address */
132 http_addr_t temp
; /* Temporary address variable */
133 static time_t last_dos
= 0; /* Time of last DoS attack */
135 struct request_info wrap_req
; /* TCP wrappers request information */
136 #endif /* HAVE_TCPD_H */
139 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
140 "cupsdAcceptClient(lis=%p) %d Clients = %d",
141 lis
, lis
->fd
, cupsArrayCount(Clients
));
144 * Make sure we don't have a full set of clients already...
147 if (cupsArrayCount(Clients
) == MaxClients
)
151 * Get a pointer to the next available client...
155 Clients
= cupsArrayNew(NULL
, NULL
);
159 cupsdLogMessage(CUPSD_LOG_ERROR
,
160 "Unable to allocate memory for clients array!");
161 cupsdPauseListening();
166 ActiveClients
= cupsArrayNew((cups_array_func_t
)compare_clients
, NULL
);
170 cupsdLogMessage(CUPSD_LOG_ERROR
,
171 "Unable to allocate memory for active clients array!");
172 cupsdPauseListening();
176 if ((con
= calloc(1, sizeof(cupsd_client_t
))) == NULL
)
178 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to allocate memory for client!");
179 cupsdPauseListening();
183 con
->http
.activity
= time(NULL
);
185 con
->http
.hostaddr
= &(con
->clientaddr
);
188 * Accept the client and get the remote address...
191 addrlen
= sizeof(http_addr_t
);
193 if ((con
->http
.fd
= accept(lis
->fd
, (struct sockaddr
*)con
->http
.hostaddr
,
196 if (errno
== ENFILE
|| errno
== EMFILE
)
197 cupsdPauseListening();
199 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to accept client connection - %s.",
207 if (lis
->address
.addr
.sa_family
== AF_INET6
)
210 * Save the connected port number...
213 con
->http
.hostaddr
->ipv6
.sin6_port
= lis
->address
.ipv6
.sin6_port
;
216 * Convert IPv4 over IPv6 addresses (::ffff:n.n.n.n) to IPv4 forms we
217 * can more easily use...
220 if (con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[0] == 0 &&
221 con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[1] == 0 &&
222 ntohl(con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[2]) == 0xffff)
223 con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[2] = 0;
226 #endif /* AF_INET6 */
227 if (lis
->address
.addr
.sa_family
== AF_INET
)
228 con
->http
.hostaddr
->ipv4
.sin_port
= lis
->address
.ipv4
.sin_port
;
231 * Check the number of clients on the same address...
234 for (count
= 0, tempcon
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
236 tempcon
= (cupsd_client_t
*)cupsArrayNext(Clients
))
237 if (httpAddrEqual(tempcon
->http
.hostaddr
, con
->http
.hostaddr
))
240 if (count
>= MaxClientsPerHost
)
244 if (count
>= MaxClientsPerHost
)
246 if ((time(NULL
) - last_dos
) >= 60)
248 last_dos
= time(NULL
);
249 cupsdLogMessage(CUPSD_LOG_WARN
,
250 "Possible DoS attack - more than %d clients connecting "
253 httpAddrString(con
->http
.hostaddr
, con
->http
.hostname
,
254 sizeof(con
->http
.hostname
)));
258 closesocket(con
->http
.fd
);
268 * Get the hostname or format the IP address as needed...
271 if (httpAddrLocalhost(con
->http
.hostaddr
))
274 * Map accesses from the loopback interface to "localhost"...
277 strlcpy(con
->http
.hostname
, "localhost", sizeof(con
->http
.hostname
));
278 hostname
= con
->http
.hostname
;
283 * Map accesses from the same host to the server name.
286 for (addr
= ServerAddrs
; addr
; addr
= addr
->next
)
287 if (httpAddrEqual(con
->http
.hostaddr
, &(addr
->addr
)))
292 strlcpy(con
->http
.hostname
, ServerName
, sizeof(con
->http
.hostname
));
293 hostname
= con
->http
.hostname
;
295 else if (HostNameLookups
)
296 hostname
= httpAddrLookup(con
->http
.hostaddr
, con
->http
.hostname
,
297 sizeof(con
->http
.hostname
));
301 httpAddrString(con
->http
.hostaddr
, con
->http
.hostname
,
302 sizeof(con
->http
.hostname
));
306 if (hostname
== NULL
&& HostNameLookups
== 2)
309 * Can't have an unresolved IP address with double-lookups enabled...
312 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
313 "cupsdAcceptClient: Closing connection %d...",
317 closesocket(con
->http
.fd
);
322 cupsdLogMessage(CUPSD_LOG_WARN
,
323 "Name lookup failed - connection from %s closed!",
330 if (HostNameLookups
== 2)
333 * Do double lookups as needed...
336 if ((addrlist
= httpAddrGetList(con
->http
.hostname
, AF_UNSPEC
, NULL
))
340 * See if the hostname maps to the same IP address...
343 for (addr
= addrlist
; addr
; addr
= addr
->next
)
344 if (httpAddrEqual(con
->http
.hostaddr
, &(addr
->addr
)))
350 httpAddrFreeList(addrlist
);
355 * Can't have a hostname that doesn't resolve to the same IP address
356 * with double-lookups enabled...
359 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
360 "cupsdAcceptClient: Closing connection %d...",
364 closesocket(con
->http
.fd
);
369 cupsdLogMessage(CUPSD_LOG_WARN
,
370 "IP lookup failed - connection from %s closed!",
379 * See if the connection is denied by TCP wrappers...
382 request_init(&wrap_req
, RQ_DAEMON
, "cupsd", RQ_FILE
, con
->http
.fd
, NULL
);
385 if (!hosts_access(&wrap_req
))
387 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
388 "cupsdAcceptClient: Closing connection %d...",
392 closesocket(con
->http
.fd
);
397 cupsdLogMessage(CUPSD_LOG_WARN
,
398 "Connection from %s refused by /etc/hosts.allow and "
399 "/etc/hosts.deny rules.", con
->http
.hostname
);
403 #endif /* HAVE_TCPD_H */
406 if (con
->http
.hostaddr
->addr
.sa_family
== AF_INET6
)
407 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdAcceptClient: %d from %s:%d (IPv6)",
408 con
->http
.fd
, con
->http
.hostname
,
409 ntohs(con
->http
.hostaddr
->ipv6
.sin6_port
));
411 #endif /* AF_INET6 */
413 if (con
->http
.hostaddr
->addr
.sa_family
== AF_LOCAL
)
414 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdAcceptClient: %d from %s (Domain)",
415 con
->http
.fd
, con
->http
.hostname
);
417 #endif /* AF_LOCAL */
418 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdAcceptClient: %d from %s:%d (IPv4)",
419 con
->http
.fd
, con
->http
.hostname
,
420 ntohs(con
->http
.hostaddr
->ipv4
.sin_port
));
423 * Get the local address the client connected to...
426 addrlen
= sizeof(temp
);
427 if (getsockname(con
->http
.fd
, (struct sockaddr
*)&temp
, &addrlen
))
429 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to get local address - %s",
432 strcpy(con
->servername
, "localhost");
433 con
->serverport
= LocalPort
;
438 if (temp
.addr
.sa_family
== AF_INET6
)
440 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
441 con
->serverport
= ntohs(lis
->address
.ipv6
.sin6_port
);
444 #endif /* AF_INET6 */
445 if (temp
.addr
.sa_family
== AF_INET
)
447 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
448 con
->serverport
= ntohs(lis
->address
.ipv4
.sin_port
);
452 strcpy(con
->servername
, "localhost");
453 con
->serverport
= LocalPort
;
457 cupsArrayAdd(Clients
, con
);
459 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
460 "cupsdAcceptClient: %d connected to server on %s:%d",
461 con
->http
.fd
, con
->servername
, con
->serverport
);
464 * Using TCP_NODELAY improves responsiveness, especially on systems
465 * with a slow loopback interface... Since we write large buffers
466 * when sending print files and requests, there shouldn't be any
467 * performance penalty for this...
471 setsockopt(con
->http
.fd
, IPPROTO_TCP
, TCP_NODELAY
, &val
, sizeof(val
));
474 * Close this file on all execs...
477 fcntl(con
->http
.fd
, F_SETFD
, fcntl(con
->http
.fd
, F_GETFD
) | FD_CLOEXEC
);
480 * Add the socket to the select() input mask.
483 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
486 * Temporarily suspend accept()'s until we lose a client...
489 if (cupsArrayCount(Clients
) == MaxClients
)
490 cupsdPauseListening();
494 * See if we are connecting on a secure port...
497 if (lis
->encryption
== HTTP_ENCRYPT_ALWAYS
)
500 * https connection; go secure...
503 con
->http
.encryption
= HTTP_ENCRYPT_ALWAYS
;
505 if (!encrypt_client(con
))
506 cupsdCloseClient(con
);
510 #endif /* HAVE_SSL */
515 * 'cupsdCloseAllClients()' - Close all remote clients immediately.
519 cupsdCloseAllClients(void)
521 cupsd_client_t
*con
; /* Current client */
524 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
526 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
527 if (cupsdCloseClient(con
))
528 cupsdCloseClient(con
);
533 * 'cupsdCloseClient()' - Close a remote client.
536 int /* O - 1 if partial close, 0 if fully closed */
537 cupsdCloseClient(cupsd_client_t
*con
) /* I - Client to close */
539 int partial
; /* Do partial close for SSL? */
541 SSL_CTX
*context
; /* Context for encryption */
542 SSL
*conn
; /* Connection for encryption */
543 unsigned long error
; /* Error code */
544 #elif defined(HAVE_GNUTLS)
545 http_tls_t
*conn
; /* TLS connection information */
546 int error
; /* Error code */
547 gnutls_certificate_server_credentials
*credentials
;
548 /* TLS credentials */
549 # elif defined(HAVE_CDSASSL)
550 http_tls_t
*conn
; /* CDSA connection information */
551 #endif /* HAVE_LIBSSL */
554 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdCloseClient: %d", con
->http
.fd
);
557 * Flush pending writes before closing...
560 httpFlushWrite(HTTP(con
));
566 * Shutdown encryption as needed...
574 conn
= (SSL
*)(con
->http
.tls
);
575 context
= SSL_get_SSL_CTX(conn
);
577 switch (SSL_shutdown(conn
))
580 cupsdLogMessage(CUPSD_LOG_DEBUG
,
581 "SSL shutdown successful!");
584 cupsdLogMessage(CUPSD_LOG_ERROR
,
585 "Fatal error during SSL shutdown!");
587 while ((error
= ERR_get_error()) != 0)
588 cupsdLogMessage(CUPSD_LOG_ERROR
, "SSL shutdown failed: %s",
589 ERR_error_string(error
, NULL
));
593 SSL_CTX_free(context
);
596 # elif defined(HAVE_GNUTLS)
597 conn
= (http_tls_t
*)(con
->http
.tls
);
598 credentials
= (gnutls_certificate_server_credentials
*)(conn
->credentials
);
600 error
= gnutls_bye(conn
->session
, GNUTLS_SHUT_WR
);
603 case GNUTLS_E_SUCCESS
:
604 cupsdLogMessage(CUPSD_LOG_DEBUG
,
605 "SSL shutdown successful!");
608 cupsdLogMessage(CUPSD_LOG_ERROR
,
609 "SSL shutdown failed: %s", gnutls_strerror(error
));
613 gnutls_deinit(conn
->session
);
614 gnutls_certificate_free_credentials(*credentials
);
618 # elif defined(HAVE_CDSASSL)
619 conn
= (http_tls_t
*)(con
->http
.tls
);
621 while (SSLClose(conn
->session
) == errSSLWouldBlock
)
624 SSLDisposeContext(conn
->session
);
626 if (conn
->certsArray
)
627 CFRelease(conn
->certsArray
);
630 # endif /* HAVE_LIBSSL */
632 con
->http
.tls
= NULL
;
634 #endif /* HAVE_SSL */
636 if (con
->pipe_pid
!= 0)
639 * Stop any CGI process...
642 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
643 "cupsdCloseClient: %d Killing process ID %d...",
644 con
->http
.fd
, con
->pipe_pid
);
645 cupsdEndProcess(con
->pipe_pid
, 1);
651 cupsdRemoveSelect(con
->file
);
653 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
654 "cupsdCloseClient: %d Closing data file %d.",
655 con
->http
.fd
, con
->file
);
662 * Close the socket and clear the file from the input set for select()...
665 if (con
->http
.fd
>= 0)
667 cupsArrayRemove(ActiveClients
, con
);
673 * Only do a partial close so that the encrypted client gets everything.
676 shutdown(con
->http
.fd
, 0);
677 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
682 * Shut the socket down fully...
685 cupsdRemoveSelect(con
->http
.fd
);
697 if (con
->http
.input_set
)
698 free(con
->http
.input_set
);
700 httpClearCookie(HTTP(con
));
701 httpClearFields(HTTP(con
));
703 cupsdClearString(&con
->filename
);
704 cupsdClearString(&con
->command
);
705 cupsdClearString(&con
->options
);
706 cupsdClearString(&con
->query_string
);
710 ippDelete(con
->request
);
716 ippDelete(con
->response
);
717 con
->response
= NULL
;
722 cupsLangFree(con
->language
);
723 con
->language
= NULL
;
726 #ifdef HAVE_AUTHORIZATION_H
729 AuthorizationFree(con
->authref
, kAuthorizationFlagDefaults
);
732 #endif /* HAVE_AUTHORIZATION_H */
735 * Re-enable new client connections if we are going back under the
739 if (cupsArrayCount(Clients
) == MaxClients
)
740 cupsdResumeListening();
743 * Compact the list of clients as necessary...
746 cupsArrayRemove(Clients
, con
);
756 * 'cupsdFlushHeader()' - Flush the header fields to the client.
759 int /* I - Bytes written or -1 on error */
760 cupsdFlushHeader(cupsd_client_t
*con
) /* I - Client to flush to */
762 int bytes
= httpFlushWrite(HTTP(con
));
764 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
771 * 'cupsdReadClient()' - Read data from a client.
775 cupsdReadClient(cupsd_client_t
*con
) /* I - Client to read from */
777 char line
[32768], /* Line from client... */
778 operation
[64], /* Operation code from socket */
779 version
[64], /* HTTP version number string */
780 locale
[64], /* Locale */
781 *ptr
; /* Pointer into strings */
782 int major
, minor
; /* HTTP version numbers */
783 http_status_t status
; /* Transfer status */
784 ipp_state_t ipp_state
; /* State of IPP transfer */
785 int bytes
; /* Number of bytes to POST */
786 char *filename
; /* Name of file for GET/HEAD */
787 char buf
[1024]; /* Buffer for real filename */
788 struct stat filestats
; /* File information */
789 mime_type_t
*type
; /* MIME type of file */
790 cupsd_printer_t
*p
; /* Printer */
791 static unsigned request_id
= 0; /* Request ID for temp files */
794 status
= HTTP_CONTINUE
;
796 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
797 "cupsdReadClient: %d, used=%d, file=%d state=%d",
798 con
->http
.fd
, con
->http
.used
, con
->file
, con
->http
.state
);
802 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdReadClient: http error seen...");
803 cupsdCloseClient(con
);
811 * Automatically check for a SSL/TLS handshake...
816 if (recv(con
->http
.fd
, buf
, 1, MSG_PEEK
) == 1 &&
817 (!buf
[0] || !strchr("DGHOPT", buf
[0])))
820 * Encrypt this connection...
823 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
824 "cupsdReadClient: Saw first byte %02X, auto-negotiating SSL/TLS session...",
827 if (!encrypt_client(con
))
828 cupsdCloseClient(con
);
833 #endif /* HAVE_SSL */
835 switch (con
->http
.state
)
839 * See if we've received a request line...
842 if (httpGets(line
, sizeof(line
) - 1, HTTP(con
)) == NULL
)
844 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
845 "cupsdReadClient: httpGets returned EOF...");
846 cupsdCloseClient(con
);
851 * Ignore blank request lines...
858 * Clear other state variables...
861 httpClearFields(HTTP(con
));
863 con
->http
.activity
= time(NULL
);
864 con
->http
.version
= HTTP_1_0
;
865 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
866 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
867 con
->http
.data_remaining
= 0;
868 con
->http
._data_remaining
= 0;
869 con
->operation
= HTTP_WAITING
;
874 con
->username
[0] = '\0';
875 con
->password
[0] = '\0';
878 cupsdClearString(&con
->command
);
879 cupsdClearString(&con
->options
);
880 cupsdClearString(&con
->query_string
);
884 ippDelete(con
->request
);
890 ippDelete(con
->response
);
891 con
->response
= NULL
;
896 cupsLangFree(con
->language
);
897 con
->language
= NULL
;
901 con
->gss_have_creds
= 0;
902 #endif /* HAVE_GSSAPI */
905 * Grab the request line...
908 switch (sscanf(line
, "%63s%1023s%63s", operation
, con
->uri
, version
))
913 cupsdLogMessage(CUPSD_LOG_ERROR
,
914 "Bad request line \"%s\" from %s!", line
,
916 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
917 cupsdCloseClient(con
);
921 con
->http
.version
= HTTP_0_9
;
924 if (sscanf(version
, "HTTP/%d.%d", &major
, &minor
) != 2)
926 cupsdLogMessage(CUPSD_LOG_ERROR
,
927 "Bad request line \"%s\" from %s!", line
,
929 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
930 cupsdCloseClient(con
);
936 con
->http
.version
= (http_version_t
)(major
* 100 + minor
);
937 if (con
->http
.version
== HTTP_1_1
&& KeepAlive
)
938 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
940 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
944 cupsdSendError(con
, HTTP_NOT_SUPPORTED
, CUPSD_AUTH_NONE
);
945 cupsdCloseClient(con
);
952 * Handle full URLs in the request line...
955 if (strcmp(con
->uri
, "*"))
957 char method
[HTTP_MAX_URI
], /* Method/scheme */
958 userpass
[HTTP_MAX_URI
], /* Username:password */
959 hostname
[HTTP_MAX_URI
], /* Hostname */
960 resource
[HTTP_MAX_URI
]; /* Resource path */
961 int port
; /* Port number */
965 * Separate the URI into its components...
968 httpSeparateURI(HTTP_URI_CODING_MOST
, con
->uri
,
969 method
, sizeof(method
),
970 userpass
, sizeof(userpass
),
971 hostname
, sizeof(hostname
), &port
,
972 resource
, sizeof(resource
));
975 * Only allow URIs with the servername, localhost, or an IP
979 if (strcmp(method
, "file") &&
980 strcasecmp(hostname
, ServerName
) &&
981 strcasecmp(hostname
, "localhost") &&
982 !isdigit(hostname
[0]))
985 * Nope, we don't do proxies...
988 cupsdLogMessage(CUPSD_LOG_ERROR
, "Bad URI \"%s\" in request!",
990 cupsdSendError(con
, HTTP_METHOD_NOT_ALLOWED
, CUPSD_AUTH_NONE
);
991 cupsdCloseClient(con
);
996 * Copy the resource portion back into the URI; both resource and
997 * con->uri are HTTP_MAX_URI bytes in size...
1000 strcpy(con
->uri
, resource
);
1004 * Process the request...
1007 if (!strcmp(operation
, "GET"))
1008 con
->http
.state
= HTTP_GET
;
1009 else if (!strcmp(operation
, "PUT"))
1010 con
->http
.state
= HTTP_PUT
;
1011 else if (!strcmp(operation
, "POST"))
1012 con
->http
.state
= HTTP_POST
;
1013 else if (!strcmp(operation
, "DELETE"))
1014 con
->http
.state
= HTTP_DELETE
;
1015 else if (!strcmp(operation
, "TRACE"))
1016 con
->http
.state
= HTTP_TRACE
;
1017 else if (!strcmp(operation
, "OPTIONS"))
1018 con
->http
.state
= HTTP_OPTIONS
;
1019 else if (!strcmp(operation
, "HEAD"))
1020 con
->http
.state
= HTTP_HEAD
;
1023 cupsdLogMessage(CUPSD_LOG_ERROR
, "Bad operation \"%s\"!", operation
);
1024 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
1025 cupsdCloseClient(con
);
1029 con
->start
= time(NULL
);
1030 con
->operation
= con
->http
.state
;
1032 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdReadClient: %d %s %s HTTP/%d.%d",
1033 con
->http
.fd
, operation
, con
->uri
,
1034 con
->http
.version
/ 100, con
->http
.version
% 100);
1036 con
->http
.status
= HTTP_OK
;
1038 if (!cupsArrayFind(ActiveClients
, con
))
1040 cupsArrayAdd(ActiveClients
, con
);
1041 cupsdSetBusyState();
1052 * Parse incoming parameters until the status changes...
1055 while ((status
= httpUpdate(HTTP(con
))) == HTTP_CONTINUE
)
1056 if (!data_ready(con
))
1059 if (status
!= HTTP_OK
&& status
!= HTTP_CONTINUE
)
1061 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
1062 cupsdCloseClient(con
);
1068 break; /* Anti-compiler-warning-code */
1072 * Handle new transfers...
1075 if (status
== HTTP_OK
)
1077 if (con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
][0])
1080 * Figure out the locale from the Accept-Language and Content-Type
1084 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ',')) != NULL
)
1087 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ';')) != NULL
)
1090 if ((ptr
= strstr(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
], "charset=")) != NULL
)
1093 * Combine language and charset, and trim any extra params in the
1097 snprintf(locale
, sizeof(locale
), "%s.%s",
1098 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ptr
+ 8);
1100 if ((ptr
= strchr(locale
, ',')) != NULL
)
1104 snprintf(locale
, sizeof(locale
), "%s.%s",
1105 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], DefaultCharset
);
1107 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1108 "cupsdReadClient: %d Browser asked for language \"%s\"...",
1109 con
->http
.fd
, locale
);
1111 con
->language
= cupsLangGet(locale
);
1114 con
->language
= cupsLangGet(DefaultLocale
);
1116 cupsdAuthorize(con
);
1118 if (!strncmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Keep-Alive", 10) &&
1120 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
1122 if (!con
->http
.fields
[HTTP_FIELD_HOST
][0] &&
1123 con
->http
.version
>= HTTP_1_1
)
1126 * HTTP/1.1 and higher require the "Host:" field...
1129 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1131 cupsdCloseClient(con
);
1135 else if (con
->operation
== HTTP_OPTIONS
)
1138 * Do OPTIONS command...
1141 if (con
->best
&& con
->best
->type
!= CUPSD_AUTH_NONE
)
1143 if (!cupsdSendHeader(con
, HTTP_UNAUTHORIZED
, NULL
, CUPSD_AUTH_NONE
))
1145 cupsdCloseClient(con
);
1150 if (!strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") &&
1151 con
->http
.tls
== NULL
)
1155 * Do encryption stuff...
1158 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
, CUPSD_AUTH_NONE
))
1160 cupsdCloseClient(con
);
1164 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1165 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1166 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1167 httpPrintf(HTTP(con
), "\r\n");
1169 if (cupsdFlushHeader(con
) < 0)
1171 cupsdCloseClient(con
);
1175 if (!encrypt_client(con
))
1177 cupsdCloseClient(con
);
1181 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
1183 cupsdCloseClient(con
);
1186 #endif /* HAVE_SSL */
1189 if (!cupsdSendHeader(con
, HTTP_OK
, NULL
, CUPSD_AUTH_NONE
))
1191 cupsdCloseClient(con
);
1195 httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n");
1196 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1197 httpPrintf(HTTP(con
), "\r\n");
1199 if (cupsdFlushHeader(con
) < 0)
1201 cupsdCloseClient(con
);
1205 else if (!is_path_absolute(con
->uri
))
1208 * Protect against malicious users!
1211 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1213 cupsdCloseClient(con
);
1219 if (!strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") &&
1220 con
->http
.tls
== NULL
)
1224 * Do encryption stuff...
1227 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
, CUPSD_AUTH_NONE
))
1229 cupsdCloseClient(con
);
1233 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1234 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1235 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1236 httpPrintf(HTTP(con
), "\r\n");
1238 if (cupsdFlushHeader(con
) < 0)
1240 cupsdCloseClient(con
);
1244 if (!encrypt_client(con
))
1246 cupsdCloseClient(con
);
1250 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
1252 cupsdCloseClient(con
);
1255 #endif /* HAVE_SSL */
1258 if ((status
= cupsdIsAuthorized(con
, NULL
)) != HTTP_OK
)
1260 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1261 "cupsdReadClient: Unauthorized request for %s...",
1263 cupsdSendError(con
, status
, CUPSD_AUTH_NONE
);
1264 cupsdCloseClient(con
);
1268 if (con
->http
.expect
&&
1269 (con
->operation
== HTTP_POST
|| con
->operation
== HTTP_PUT
))
1271 if (con
->http
.expect
== HTTP_CONTINUE
)
1274 * Send 100-continue header...
1277 if (!cupsdSendHeader(con
, HTTP_CONTINUE
, NULL
, CUPSD_AUTH_NONE
))
1279 cupsdCloseClient(con
);
1286 * Send 417-expectation-failed header...
1289 if (!cupsdSendHeader(con
, HTTP_EXPECTATION_FAILED
, NULL
, CUPSD_AUTH_NONE
))
1291 cupsdCloseClient(con
);
1295 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1296 httpPrintf(HTTP(con
), "\r\n");
1298 if (cupsdFlushHeader(con
) < 0)
1300 cupsdCloseClient(con
);
1306 switch (con
->http
.state
)
1308 case HTTP_GET_SEND
:
1309 if (!strncmp(con
->uri
, "/printers/", 10) &&
1310 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1313 * Send PPD file - get the real printer name since printer
1314 * names are not case sensitive but filenames can be...
1317 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1319 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1320 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1323 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1325 cupsdCloseClient(con
);
1333 if ((!strncmp(con
->uri
, "/admin", 6) &&
1334 strncmp(con
->uri
, "/admin/conf/", 12) &&
1335 strncmp(con
->uri
, "/admin/log/", 11)) ||
1336 !strncmp(con
->uri
, "/printers", 9) ||
1337 !strncmp(con
->uri
, "/classes", 8) ||
1338 !strncmp(con
->uri
, "/help", 5) ||
1339 !strncmp(con
->uri
, "/jobs", 5))
1342 * Send CGI output...
1345 if (!strncmp(con
->uri
, "/admin", 6))
1347 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1350 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1352 else if (!strncmp(con
->uri
, "/printers", 9))
1354 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1357 if (con
->uri
[9] && con
->uri
[10])
1358 cupsdSetString(&con
->options
, con
->uri
+ 9);
1360 cupsdSetString(&con
->options
, NULL
);
1362 else if (!strncmp(con
->uri
, "/classes", 8))
1364 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1367 if (con
->uri
[8] && con
->uri
[9])
1368 cupsdSetString(&con
->options
, con
->uri
+ 8);
1370 cupsdSetString(&con
->options
, NULL
);
1372 else if (!strncmp(con
->uri
, "/jobs", 5))
1374 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1377 if (con
->uri
[5] && con
->uri
[6])
1378 cupsdSetString(&con
->options
, con
->uri
+ 5);
1380 cupsdSetString(&con
->options
, NULL
);
1384 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1387 if (con
->uri
[5] && con
->uri
[6])
1388 cupsdSetString(&con
->options
, con
->uri
+ 5);
1390 cupsdSetString(&con
->options
, NULL
);
1393 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1395 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1397 cupsdCloseClient(con
);
1402 cupsdLogRequest(con
, HTTP_OK
);
1404 if (con
->http
.version
<= HTTP_1_0
)
1405 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1407 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1408 (strchr(con
->uri
+ 12, '/') ||
1409 strlen(con
->uri
) == 12)) ||
1410 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1411 (strchr(con
->uri
+ 11, '/') ||
1412 strlen(con
->uri
) == 11)))
1415 * GET can only be done to configuration files under
1419 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1421 cupsdCloseClient(con
);
1433 if ((filename
= get_file(con
, &filestats
, buf
,
1434 sizeof(buf
))) == NULL
)
1436 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1438 cupsdCloseClient(con
);
1445 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1447 if (is_cgi(con
, filename
, &filestats
, type
))
1450 * Note: con->command and con->options were set by
1454 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1456 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1458 cupsdCloseClient(con
);
1463 cupsdLogRequest(con
, HTTP_OK
);
1465 if (con
->http
.version
<= HTTP_1_0
)
1466 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1470 if (!check_if_modified(con
, &filestats
))
1472 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1474 cupsdCloseClient(con
);
1481 strcpy(line
, "text/plain");
1483 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1485 if (!write_file(con
, HTTP_OK
, filename
, line
, &filestats
))
1487 cupsdCloseClient(con
);
1494 case HTTP_POST_RECV
:
1496 * See if the POST request includes a Content-Length field, and if
1497 * so check the length against any limits that are set...
1500 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "POST %s", con
->uri
);
1501 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "CONTENT_TYPE = %s",
1502 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
1504 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1505 MaxRequestSize
> 0 &&
1506 con
->http
.data_remaining
> MaxRequestSize
)
1509 * Request too large...
1512 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1514 cupsdCloseClient(con
);
1520 else if (con
->http
.data_remaining
< 0 ||
1521 (!con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1522 con
->http
.data_encoding
== HTTP_ENCODE_LENGTH
))
1525 * Negative content lengths are invalid!
1528 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1530 cupsdCloseClient(con
);
1538 * See what kind of POST request this is; for IPP requests the
1539 * content-type field will be "application/ipp"...
1542 if (!strcmp(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
],
1544 con
->request
= ippNew();
1545 else if ((!strncmp(con
->uri
, "/admin", 6) &&
1546 strncmp(con
->uri
, "/admin/conf/", 12) &&
1547 strncmp(con
->uri
, "/admin/log/", 11)) ||
1548 !strncmp(con
->uri
, "/printers", 9) ||
1549 !strncmp(con
->uri
, "/classes", 8) ||
1550 !strncmp(con
->uri
, "/help", 5) ||
1551 !strncmp(con
->uri
, "/jobs", 5))
1557 if (!strncmp(con
->uri
, "/admin", 6))
1559 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1562 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1564 else if (!strncmp(con
->uri
, "/printers", 9))
1566 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1569 if (con
->uri
[9] && con
->uri
[10])
1570 cupsdSetString(&con
->options
, con
->uri
+ 9);
1572 cupsdSetString(&con
->options
, NULL
);
1574 else if (!strncmp(con
->uri
, "/classes", 8))
1576 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1579 if (con
->uri
[8] && con
->uri
[9])
1580 cupsdSetString(&con
->options
, con
->uri
+ 8);
1582 cupsdSetString(&con
->options
, NULL
);
1584 else if (!strncmp(con
->uri
, "/jobs", 5))
1586 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1589 if (con
->uri
[5] && con
->uri
[6])
1590 cupsdSetString(&con
->options
, con
->uri
+ 5);
1592 cupsdSetString(&con
->options
, NULL
);
1596 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1599 if (con
->uri
[5] && con
->uri
[6])
1600 cupsdSetString(&con
->options
, con
->uri
+ 5);
1602 cupsdSetString(&con
->options
, NULL
);
1605 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1606 "cupsdReadClient: %d command=\"%s\", "
1608 con
->http
.fd
, con
->command
,
1609 con
->options
? con
->options
: "(null)");
1611 if (con
->http
.version
<= HTTP_1_0
)
1612 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1620 if ((filename
= get_file(con
, &filestats
, buf
,
1621 sizeof(buf
))) == NULL
)
1623 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1625 cupsdCloseClient(con
);
1632 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1634 if (!is_cgi(con
, filename
, &filestats
, type
))
1637 * Only POST to CGI's...
1640 if (!cupsdSendError(con
, HTTP_UNAUTHORIZED
, CUPSD_AUTH_NONE
))
1642 cupsdCloseClient(con
);
1649 case HTTP_PUT_RECV
:
1651 * Validate the resource name...
1654 if (strncmp(con
->uri
, "/admin/conf/", 12) ||
1655 strchr(con
->uri
+ 12, '/') ||
1656 strlen(con
->uri
) == 12)
1659 * PUT can only be done to configuration files under
1663 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1665 cupsdCloseClient(con
);
1673 * See if the PUT request includes a Content-Length field, and if
1674 * so check the length against any limits that are set...
1677 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "PUT %s", con
->uri
);
1678 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "CONTENT_TYPE = %s",
1679 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
1681 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1682 MaxRequestSize
> 0 &&
1683 con
->http
.data_remaining
> MaxRequestSize
)
1686 * Request too large...
1689 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1691 cupsdCloseClient(con
);
1697 else if (con
->http
.data_remaining
< 0)
1700 * Negative content lengths are invalid!
1703 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1705 cupsdCloseClient(con
);
1713 * Open a temporary file to hold the request...
1716 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
1718 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1722 cupsdLogMessage(CUPSD_LOG_ERROR
,
1723 "Unable to create request file %s: %s",
1724 con
->filename
, strerror(errno
));
1726 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1728 cupsdCloseClient(con
);
1733 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1734 "cupsdReadClient: %d REQUEST %s=%d", con
->http
.fd
,
1735 con
->filename
, con
->file
);
1737 fchmod(con
->file
, 0640);
1738 fchown(con
->file
, RunUser
, Group
);
1739 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1744 cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
);
1745 cupsdCloseClient(con
);
1749 if (!strncmp(con
->uri
, "/printers/", 10) &&
1750 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1753 * Send PPD file - get the real printer name since printer
1754 * names are not case sensitive but filenames can be...
1757 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1759 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1760 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1763 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1765 cupsdCloseClient(con
);
1773 if ((!strncmp(con
->uri
, "/admin", 6) &&
1774 strncmp(con
->uri
, "/admin/conf/", 12) &&
1775 strncmp(con
->uri
, "/admin/log/", 11)) ||
1776 !strncmp(con
->uri
, "/printers", 9) ||
1777 !strncmp(con
->uri
, "/classes", 8) ||
1778 !strncmp(con
->uri
, "/help", 5) ||
1779 !strncmp(con
->uri
, "/jobs", 5))
1785 if (!cupsdSendHeader(con
, HTTP_OK
, "text/html", CUPSD_AUTH_NONE
))
1787 cupsdCloseClient(con
);
1791 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1793 cupsdCloseClient(con
);
1797 if (cupsdFlushHeader(con
) < 0)
1799 cupsdCloseClient(con
);
1803 cupsdLogRequest(con
, HTTP_OK
);
1805 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1806 (strchr(con
->uri
+ 12, '/') ||
1807 strlen(con
->uri
) == 12)) ||
1808 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1809 (strchr(con
->uri
+ 11, '/') ||
1810 strlen(con
->uri
) == 11)))
1813 * HEAD can only be done to configuration files under
1817 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1819 cupsdCloseClient(con
);
1825 else if ((filename
= get_file(con
, &filestats
, buf
,
1826 sizeof(buf
))) == NULL
)
1828 if (!cupsdSendHeader(con
, HTTP_NOT_FOUND
, "text/html", CUPSD_AUTH_NONE
))
1830 cupsdCloseClient(con
);
1834 cupsdLogRequest(con
, HTTP_NOT_FOUND
);
1836 else if (!check_if_modified(con
, &filestats
))
1838 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1840 cupsdCloseClient(con
);
1844 cupsdLogRequest(con
, HTTP_NOT_MODIFIED
);
1852 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1854 strcpy(line
, "text/plain");
1856 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1858 if (!cupsdSendHeader(con
, HTTP_OK
, line
, CUPSD_AUTH_NONE
))
1860 cupsdCloseClient(con
);
1864 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
1865 httpGetDateString(filestats
.st_mtime
)) < 0)
1867 cupsdCloseClient(con
);
1871 if (httpPrintf(HTTP(con
), "Content-Length: %lu\r\n",
1872 (unsigned long)filestats
.st_size
) < 0)
1874 cupsdCloseClient(con
);
1878 cupsdLogRequest(con
, HTTP_OK
);
1881 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1883 cupsdCloseClient(con
);
1887 if (cupsdFlushHeader(con
) < 0)
1889 cupsdCloseClient(con
);
1893 con
->http
.state
= HTTP_WAITING
;
1897 break; /* Anti-compiler-warning-code */
1903 * Handle any incoming data...
1906 switch (con
->http
.state
)
1908 case HTTP_PUT_RECV
:
1909 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1910 "cupsdReadClient: %d con->data_encoding=HTTP_ENCODE_%s, "
1911 "con->data_remaining=" CUPS_LLFMT
", con->file=%d",
1913 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
?
1914 "CHUNKED" : "LENGTH",
1915 CUPS_LLCAST con
->http
.data_remaining
, con
->file
);
1919 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
1921 cupsdCloseClient(con
);
1926 con
->bytes
+= bytes
;
1928 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1929 "cupsdReadClient: %d writing %d bytes to %d",
1930 con
->http
.fd
, bytes
, con
->file
);
1932 if (write(con
->file
, line
, bytes
) < bytes
)
1934 cupsdLogMessage(CUPSD_LOG_ERROR
,
1935 "cupsdReadClient: Unable to write %d bytes to %s: %s",
1936 bytes
, con
->filename
, strerror(errno
));
1938 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1939 "cupsdReadClient: Closing data file %d...",
1944 unlink(con
->filename
);
1945 cupsdClearString(&con
->filename
);
1947 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1949 cupsdCloseClient(con
);
1955 while (con
->http
.state
== HTTP_PUT_RECV
&& data_ready(con
));
1957 if (con
->http
.state
== HTTP_WAITING
)
1960 * End of file, see how big it is...
1963 fstat(con
->file
, &filestats
);
1965 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1966 "cupsdReadClient: %d Closing data file %d, size="
1968 con
->http
.fd
, con
->file
,
1969 CUPS_LLCAST filestats
.st_size
);
1974 if (filestats
.st_size
> MaxRequestSize
&&
1978 * Request is too big; remove it and send an error...
1981 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1982 "cupsdReadClient: %d Removing temp file %s",
1983 con
->http
.fd
, con
->filename
);
1984 unlink(con
->filename
);
1985 cupsdClearString(&con
->filename
);
1987 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1989 cupsdCloseClient(con
);
1995 * Install the configuration file...
1998 status
= install_conf_file(con
);
2001 * Return the status to the client...
2004 if (!cupsdSendError(con
, status
, CUPSD_AUTH_NONE
))
2006 cupsdCloseClient(con
);
2012 case HTTP_POST_RECV
:
2013 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2014 "cupsdReadClient: %d con->data_encoding=HTTP_ENCODE_"
2015 "%s, con->data_remaining=" CUPS_LLFMT
", con->file=%d",
2017 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
?
2018 "CHUNKED" : "LENGTH",
2019 CUPS_LLCAST con
->http
.data_remaining
, con
->file
);
2026 * Grab any request data from the connection...
2029 if ((ipp_state
= ippRead(&(con
->http
), con
->request
)) == IPP_ERROR
)
2031 cupsdLogMessage(CUPSD_LOG_ERROR
,
2032 "cupsdReadClient: %d IPP Read Error!",
2035 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
2036 cupsdCloseClient(con
);
2039 else if (ipp_state
!= IPP_DATA
)
2041 if (con
->http
.state
== HTTP_POST_SEND
)
2043 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
2044 cupsdCloseClient(con
);
2051 con
->bytes
+= ippLength(con
->request
);
2054 if (con
->file
< 0 && con
->http
.state
!= HTTP_POST_SEND
)
2057 * Create a file as needed for the request data...
2060 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
, request_id
++);
2061 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
2065 cupsdLogMessage(CUPSD_LOG_ERROR
,
2066 "Unable to create request file %s: %s",
2067 con
->filename
, strerror(errno
));
2069 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2071 cupsdCloseClient(con
);
2076 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdReadClient: %d REQUEST %s=%d", con
->http
.fd
,
2077 con
->filename
, con
->file
);
2079 fchmod(con
->file
, 0640);
2080 fchown(con
->file
, RunUser
, Group
);
2081 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2084 if (con
->http
.state
!= HTTP_POST_SEND
)
2086 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
2088 cupsdCloseClient(con
);
2093 con
->bytes
+= bytes
;
2095 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2096 "cupsdReadClient: %d writing %d bytes to %d",
2097 con
->http
.fd
, bytes
, con
->file
);
2099 if (write(con
->file
, line
, bytes
) < bytes
)
2101 cupsdLogMessage(CUPSD_LOG_ERROR
,
2102 "cupsdReadClient: Unable to write %d bytes to %s: %s",
2103 bytes
, con
->filename
, strerror(errno
));
2105 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2106 "cupsdReadClient: Closing file %d...",
2111 unlink(con
->filename
);
2112 cupsdClearString(&con
->filename
);
2114 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2116 cupsdCloseClient(con
);
2121 else if (con
->http
.state
== HTTP_POST_RECV
)
2123 else if (con
->http
.state
!= HTTP_POST_SEND
)
2125 cupsdCloseClient(con
);
2130 while (con
->http
.state
== HTTP_POST_RECV
&& data_ready(con
));
2132 if (con
->http
.state
== HTTP_POST_SEND
)
2136 fstat(con
->file
, &filestats
);
2138 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2139 "cupsdReadClient: %d Closing data file %d, "
2140 "size=" CUPS_LLFMT
".",
2141 con
->http
.fd
, con
->file
,
2142 CUPS_LLCAST filestats
.st_size
);
2147 if (filestats
.st_size
> MaxRequestSize
&&
2151 * Request is too big; remove it and send an error...
2154 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2155 "cupsdReadClient: %d Removing temp file %s",
2156 con
->http
.fd
, con
->filename
);
2157 unlink(con
->filename
);
2158 cupsdClearString(&con
->filename
);
2163 * Delete any IPP request data...
2166 ippDelete(con
->request
);
2167 con
->request
= NULL
;
2170 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2172 cupsdCloseClient(con
);
2179 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
2181 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
2183 cupsdCloseClient(con
);
2188 cupsdLogRequest(con
, HTTP_OK
);
2194 cupsdProcessIPPRequest(con
);
2198 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2199 "cupsdReadClient: %d Removing temp file %s",
2200 con
->http
.fd
, con
->filename
);
2201 unlink(con
->filename
);
2202 cupsdClearString(&con
->filename
);
2211 break; /* Anti-compiler-warning-code */
2214 if (con
->http
.state
== HTTP_WAITING
)
2216 if (!con
->http
.keep_alive
)
2217 cupsdCloseClient(con
);
2220 cupsArrayRemove(ActiveClients
, con
);
2221 cupsdSetBusyState();
2228 * 'cupsdSendCommand()' - Send output from a command via HTTP.
2231 int /* O - 1 on success, 0 on failure */
2233 cupsd_client_t
*con
, /* I - Client connection */
2234 char *command
, /* I - Command to run */
2235 char *options
, /* I - Command-line options */
2236 int root
) /* I - Run as root? */
2238 int fd
; /* Standard input file descriptor */
2243 fd
= open(con
->filename
, O_RDONLY
);
2247 cupsdLogMessage(CUPSD_LOG_ERROR
,
2248 "cupsdSendCommand: %d Unable to open \"%s\" for reading: %s",
2249 con
->http
.fd
, con
->filename
? con
->filename
: "/dev/null",
2254 fcntl(fd
, F_SETFD
, fcntl(fd
, F_GETFD
) | FD_CLOEXEC
);
2259 con
->pipe_pid
= pipe_command(con
, fd
, &(con
->file
), command
, options
, root
);
2264 cupsdLogMessage(CUPSD_LOG_INFO
, "Started \"%s\" (pid=%d)", command
,
2267 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendCommand: %d file=%d",
2268 con
->http
.fd
, con
->file
);
2270 if (con
->pipe_pid
== 0)
2273 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2275 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2277 con
->sent_header
= 0;
2278 con
->file_ready
= 0;
2279 con
->got_fields
= 0;
2287 * 'cupsdSendError()' - Send an error message via HTTP.
2290 int /* O - 1 if successful, 0 otherwise */
2291 cupsdSendError(cupsd_client_t
*con
, /* I - Connection */
2292 http_status_t code
, /* I - Error code */
2293 int auth_type
)/* I - Authentication type */
2297 * Force client to upgrade for authentication if that is how the
2298 * server is configured...
2301 if (code
== HTTP_UNAUTHORIZED
&&
2302 DefaultEncryption
== HTTP_ENCRYPT_REQUIRED
&&
2303 strcasecmp(con
->http
.hostname
, "localhost") &&
2306 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2307 "cupsdSendError: Encryption before authentication!");
2308 code
= HTTP_UPGRADE_REQUIRED
;
2310 #endif /* HAVE_SSL */
2313 * Put the request in the access_log file...
2316 cupsdLogRequest(con
, code
);
2318 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendError: %d code=%d (%s)",
2319 con
->http
.fd
, code
, httpStatus(code
));
2322 * To work around bugs in some proxies, don't use Keep-Alive for some
2325 * Kerberos authentication doesn't work without Keep-Alive, so
2326 * never disable it in that case.
2329 if (code
>= HTTP_BAD_REQUEST
&& con
->http
.auth_type
!= CUPSD_AUTH_NEGOTIATE
)
2330 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
2333 * Send an error message back to the client. If the error code is a
2334 * 400 or 500 series, make sure the message contains some text, too!
2337 if (!cupsdSendHeader(con
, code
, NULL
, auth_type
))
2341 if (code
== HTTP_UPGRADE_REQUIRED
)
2342 if (httpPrintf(HTTP(con
), "Connection: Upgrade\r\n") < 0)
2345 if (httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n") < 0)
2347 #endif /* HAVE_SSL */
2349 if (con
->http
.version
>= HTTP_1_1
&&
2350 con
->http
.keep_alive
== HTTP_KEEPALIVE_OFF
)
2352 if (httpPrintf(HTTP(con
), "Connection: close\r\n") < 0)
2356 if (code
>= HTTP_BAD_REQUEST
)
2359 * Send a human-readable error message.
2362 char message
[4096], /* Message for user */
2363 urltext
[1024], /* URL redirection text */
2364 redirect
[1024]; /* Redirection link */
2365 const char *text
; /* Status-specific text */
2370 if (code
== HTTP_UNAUTHORIZED
)
2371 text
= _cupsLangString(con
->language
,
2372 _("Enter your username and password or the "
2373 "root username and password to access this "
2374 "page. If you are using Kerberos authentication, "
2375 "make sure you have a valid Kerberos ticket."));
2376 else if (code
== HTTP_UPGRADE_REQUIRED
)
2380 snprintf(urltext
, sizeof(urltext
),
2381 _cupsLangString(con
->language
,
2382 _("You must access this page using the URL "
2383 "<A HREF=\"https://%s:%d%s\">"
2384 "https://%s:%d%s</A>.")),
2385 con
->servername
, con
->serverport
, con
->uri
,
2386 con
->servername
, con
->serverport
, con
->uri
);
2388 snprintf(redirect
, sizeof(redirect
),
2389 "<META HTTP-EQUIV=\"Refresh\" "
2390 "CONTENT=\"3;URL=https://%s:%d%s\">\n",
2391 con
->servername
, con
->serverport
, con
->uri
);
2396 snprintf(message
, sizeof(message
),
2397 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" "
2398 "\"http://www.w3.org/TR/REC-html40/loose.dtd\">\n"
2401 "\t<META HTTP-EQUIV=\"Content-Type\" "
2402 "CONTENT=\"text/html; charset=utf-8\">\n"
2403 "\t<TITLE>%d %s</TITLE>\n"
2404 "\t<LINK REL=\"STYLESHEET\" TYPE=\"text/css\" "
2405 "HREF=\"/cups.css\">\n"
2413 code
, httpStatus(code
), redirect
, code
, httpStatus(code
), text
);
2415 if (httpPrintf(HTTP(con
), "Content-Type: text/html; charset=utf-8\r\n") < 0)
2417 if (httpPrintf(HTTP(con
), "Content-Length: %d\r\n",
2418 (int)strlen(message
)) < 0)
2420 if (httpPrintf(HTTP(con
), "\r\n") < 0)
2422 if (httpPrintf(HTTP(con
), "%s", message
) < 0)
2425 else if (httpPrintf(HTTP(con
), "\r\n") < 0)
2428 if (cupsdFlushHeader(con
) < 0)
2431 con
->http
.state
= HTTP_WAITING
;
2438 * 'cupsdSendHeader()' - Send an HTTP request.
2441 int /* O - 1 on success, 0 on failure */
2443 cupsd_client_t
*con
, /* I - Client to send to */
2444 http_status_t code
, /* I - HTTP status code */
2445 char *type
, /* I - MIME type of document */
2446 int auth_type
) /* I - Type of authentication */
2448 char auth_str
[1024]; /* Authorization string */
2450 static char *gss_buf
= NULL
; /* Kerberos auth data buffer */
2451 static int gss_bufsize
= 0; /* Size of Kerberos auth data buffer */
2452 #endif /* HAVE_GSSAPI */
2456 * Send the HTTP status header...
2459 if (code
== HTTP_CONTINUE
)
2462 * 100-continue doesn't send any headers...
2465 return (httpPrintf(HTTP(con
), "HTTP/%d.%d 100 Continue\r\n\r\n",
2466 con
->http
.version
/ 100, con
->http
.version
% 100) > 0);
2469 httpFlushWrite(HTTP(con
));
2471 con
->http
.data_encoding
= HTTP_ENCODE_FIELDS
;
2473 if (httpPrintf(HTTP(con
), "HTTP/%d.%d %d %s\r\n", con
->http
.version
/ 100,
2474 con
->http
.version
% 100, code
, httpStatus(code
)) < 0)
2476 if (httpPrintf(HTTP(con
), "Date: %s\r\n", httpGetDateString(time(NULL
))) < 0)
2479 if (httpPrintf(HTTP(con
), "Server: %s\r\n", ServerHeader
) < 0)
2481 if (con
->http
.keep_alive
&& con
->http
.version
>= HTTP_1_0
)
2483 if (httpPrintf(HTTP(con
), "Connection: Keep-Alive\r\n") < 0)
2485 if (httpPrintf(HTTP(con
), "Keep-Alive: timeout=%d\r\n",
2486 KeepAliveTimeout
) < 0)
2489 if (code
== HTTP_METHOD_NOT_ALLOWED
)
2490 if (httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST\r\n") < 0)
2493 if (code
== HTTP_UNAUTHORIZED
)
2495 if (auth_type
== CUPSD_AUTH_NONE
)
2497 if (!con
->best
|| con
->best
->type
<= CUPSD_AUTH_NONE
)
2498 auth_type
= DefaultAuthType
;
2500 auth_type
= con
->best
->type
;
2505 if (auth_type
== CUPSD_AUTH_BASIC
|| auth_type
== CUPSD_AUTH_BASICDIGEST
)
2506 strlcpy(auth_str
, "Basic realm=\"CUPS\"", sizeof(auth_str
));
2507 else if (auth_type
== CUPSD_AUTH_DIGEST
)
2508 snprintf(auth_str
, sizeof(auth_str
), "Digest realm=\"CUPS\", nonce=\"%s\"",
2509 con
->http
.hostname
);
2511 else if (auth_type
== CUPSD_AUTH_NEGOTIATE
&& con
->gss_output_token
.length
== 0)
2512 strlcpy(auth_str
, "Negotiate", sizeof(auth_str
));
2513 #endif /* HAVE_GSSAPI */
2515 #ifdef HAVE_AUTHORIZATION_H
2516 if (con
->best
&& auth_type
!= CUPSD_AUTH_NEGOTIATE
)
2518 int i
; /* Looping var */
2519 char *auth_key
; /* Auth key buffer */
2520 size_t auth_size
; /* Size of remaining buffer */
2523 auth_key
= auth_str
+ strlen(auth_str
);
2524 auth_size
= sizeof(auth_str
) - (auth_key
- auth_str
);
2526 for (i
= 0; i
< con
->best
->num_names
; i
++)
2528 if (!strncasecmp(con
->best
->names
[i
], "@AUTHKEY(", 9))
2530 snprintf(auth_key
, auth_size
, ", authkey=\"%s\"",
2531 con
->best
->names
[i
] + 9);
2532 /* end parenthesis is stripped in conf.c */
2535 else if (!strcasecmp(con
->best
->names
[i
], "@SYSTEM") &&
2538 snprintf(auth_key
, auth_size
, ", authkey=\"%s\"", SystemGroupAuthKey
);
2543 #endif /* HAVE_AUTHORIZATION_H */
2547 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendHeader: WWW-Authenticate: %s",
2550 if (httpPrintf(HTTP(con
), "WWW-Authenticate: %s\r\n", auth_str
) < 0)
2557 * WWW-Authenticate: Negotiate can be included even for
2558 * non-401 replies...
2561 if (con
->gss_output_token
.length
> 0 && con
->gss_output_token
.length
<= 65536)
2563 OM_uint32 minor_status
; /* Minor status code */
2564 int bufsize
; /* Size of output token buffer */
2567 bufsize
= con
->gss_output_token
.length
* 4 / 3 + 2;
2569 if (bufsize
> gss_bufsize
)
2571 char *buf
; /* New buffer */
2574 bufsize
= (bufsize
+ 1023) & 1023;/* Round up */
2577 buf
= realloc(gss_buf
, bufsize
);
2579 buf
= malloc(bufsize
);
2583 cupsdLogMessage(CUPSD_LOG_ERROR
,
2584 "Unable to allocate %d bytes for Kerberos credentials!",
2590 gss_bufsize
= bufsize
;
2593 httpEncode64_2(gss_buf
, gss_bufsize
,
2594 con
->gss_output_token
.value
,
2595 con
->gss_output_token
.length
);
2596 gss_release_buffer(&minor_status
, &con
->gss_output_token
);
2598 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2599 "cupsdSendHeader: WWW-Authenticate: Negotiate %s", gss_buf
);
2601 if (httpPrintf(HTTP(con
), "WWW-Authenticate: Negotiate %s\r\n",
2605 else if (con
->gss_output_token
.length
> 65536)
2607 cupsdLogMessage(CUPSD_LOG_ERROR
,
2608 "Kerberos credentials larger than 64k (%d)!",
2609 (int)con
->gss_output_token
.length
);
2612 #endif /* HAVE_GSSAPI */
2614 if (con
->language
&& strcmp(con
->language
->language
, "C"))
2616 if (httpPrintf(HTTP(con
), "Content-Language: %s\r\n",
2617 con
->language
->language
) < 0)
2623 if (!strcmp(type
, "text/html"))
2625 if (httpPrintf(HTTP(con
),
2626 "Content-Type: text/html; charset=utf-8\r\n") < 0)
2629 else if (httpPrintf(HTTP(con
), "Content-Type: %s\r\n", type
) < 0)
2638 * 'cupsdUpdateCGI()' - Read status messages from CGI scripts and programs.
2642 cupsdUpdateCGI(void)
2644 char *ptr
, /* Pointer to end of line in buffer */
2645 message
[1024]; /* Pointer to message text */
2646 int loglevel
; /* Log level for message */
2649 while ((ptr
= cupsdStatBufUpdate(CGIStatusBuffer
, &loglevel
,
2650 message
, sizeof(message
))) != NULL
)
2651 if (!strchr(CGIStatusBuffer
->buffer
, '\n'))
2654 if (ptr
== NULL
&& !CGIStatusBuffer
->bufused
)
2657 * Fatal error on pipe - should never happen!
2660 cupsdLogMessage(CUPSD_LOG_CRIT
,
2661 "cupsdUpdateCGI: error reading from CGI error pipe - %s",
2668 * 'cupsdWriteClient()' - Write data to a client as needed.
2672 cupsdWriteClient(cupsd_client_t
*con
) /* I - Client connection */
2674 int bytes
; /* Number of bytes written */
2675 char buf
[16385]; /* Data buffer */
2676 char *bufptr
; /* Pointer into buffer */
2677 ipp_state_t ipp_state
; /* IPP state value */
2681 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2682 "cupsdWriteClient(con=%p) %d response=%p(%d), file=%d "
2683 "pipe_pid=%d state=%d",
2684 con
, con
->http
.fd
, con
->response
,
2685 con
->response
? con
->response
->state
: -1,
2686 con
->file
, con
->pipe_pid
, con
->http
.state
);
2689 if (con
->http
.state
!= HTTP_GET_SEND
&&
2690 con
->http
.state
!= HTTP_POST_SEND
)
2696 * Make sure we select on the CGI output...
2699 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2701 if (!con
->file_ready
)
2704 * Try again later when there is CGI output available...
2707 cupsdRemoveSelect(con
->http
.fd
);
2711 con
->file_ready
= 0;
2714 if (con
->response
&& con
->response
->state
!= IPP_DATA
)
2716 ipp_state
= ippWrite(HTTP(con
), con
->response
);
2717 bytes
= ipp_state
!= IPP_ERROR
&&
2718 (con
->file
>= 0 || ipp_state
!= IPP_DATA
);
2720 else if ((bytes
= read(con
->file
, buf
, sizeof(buf
) - 1)) > 0)
2722 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2723 "cupsdWriteClient: Read %d bytes from file %d...",
2726 if (con
->pipe_pid
&& !con
->got_fields
)
2729 * Inspect the data for Content-Type and other fields.
2734 for (bufptr
= buf
; !con
->got_fields
&& *bufptr
; bufptr
++)
2735 if (*bufptr
== '\n')
2738 * Send line to client...
2741 if (bufptr
> buf
&& bufptr
[-1] == '\r')
2745 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "Script header: %s", buf
);
2747 if (!con
->sent_header
)
2750 * Handle redirection and CGI status codes...
2753 if (!strncasecmp(buf
, "Location:", 9))
2755 cupsdSendHeader(con
, HTTP_SEE_OTHER
, NULL
, CUPSD_AUTH_NONE
);
2756 con
->sent_header
= 2;
2758 if (httpPrintf(HTTP(con
), "Content-Length: 0\r\n") < 0)
2761 else if (!strncasecmp(buf
, "Status:", 7))
2763 cupsdSendError(con
, (http_status_t
)atoi(buf
+ 7), CUPSD_AUTH_NONE
);
2764 con
->sent_header
= 2;
2768 cupsdSendHeader(con
, HTTP_OK
, NULL
, CUPSD_AUTH_NONE
);
2769 con
->sent_header
= 1;
2771 if (con
->http
.version
== HTTP_1_1
)
2773 if (httpPrintf(HTTP(con
), "Transfer-Encoding: chunked\r\n") < 0)
2779 if (strncasecmp(buf
, "Status:", 7))
2780 httpPrintf(HTTP(con
), "%s\r\n", buf
);
2782 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdWriteClient: %d %s",
2789 bytes
-= (bufptr
- buf
);
2790 memmove(buf
, bufptr
, bytes
+ 1);
2794 * See if the line was empty...
2797 if (con
->field_col
== 0)
2799 con
->got_fields
= 1;
2801 if (cupsdFlushHeader(con
) < 0)
2803 cupsdCloseClient(con
);
2807 if (con
->http
.version
== HTTP_1_1
)
2808 con
->http
.data_encoding
= HTTP_ENCODE_CHUNKED
;
2813 else if (*bufptr
!= '\r')
2816 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2817 "cupsdWriteClient: %d bytes=%d, got_fields=%d",
2818 con
->http
.fd
, bytes
, con
->got_fields
);
2820 if (bytes
> 0 && !con
->got_fields
)
2823 * Remaining text needs to go out...
2826 httpPrintf(HTTP(con
), "%s", buf
);
2828 con
->http
.activity
= time(NULL
);
2831 else if (bytes
== 0)
2833 con
->http
.activity
= time(NULL
);
2840 if (httpWrite2(HTTP(con
), buf
, bytes
) < 0)
2842 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2843 "cupsdWriteClient: %d Write of %d bytes failed!",
2844 con
->http
.fd
, bytes
);
2846 cupsdCloseClient(con
);
2850 if (con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
)
2851 httpFlushWrite(HTTP(con
));
2853 con
->bytes
+= bytes
;
2855 if (con
->http
.state
== HTTP_WAITING
)
2862 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdWriteClient: %d bytes < 0",
2865 cupsdLogRequest(con
, HTTP_OK
);
2867 httpFlushWrite(HTTP(con
));
2869 if (con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
&& con
->sent_header
== 1)
2871 if (httpWrite2(HTTP(con
), "", 0) < 0)
2873 cupsdCloseClient(con
);
2878 con
->http
.state
= HTTP_WAITING
;
2880 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
2884 cupsdRemoveSelect(con
->file
);
2887 cupsdEndProcess(con
->pipe_pid
, 0);
2889 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2890 "cupsdWriteClient: %d Closing data file %d.",
2891 con
->http
.fd
, con
->file
);
2900 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2901 "cupsdWriteClient: %d Removing temp file %s",
2902 con
->http
.fd
, con
->filename
);
2903 unlink(con
->filename
);
2904 cupsdClearString(&con
->filename
);
2909 ippDelete(con
->request
);
2910 con
->request
= NULL
;
2915 ippDelete(con
->response
);
2916 con
->response
= NULL
;
2919 cupsdClearString(&con
->command
);
2920 cupsdClearString(&con
->options
);
2921 cupsdClearString(&con
->query_string
);
2923 if (!con
->http
.keep_alive
)
2925 cupsdCloseClient(con
);
2930 con
->http
.activity
= time(NULL
);
2935 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
2938 static int /* O - 1 if modified since */
2940 cupsd_client_t
*con
, /* I - Client connection */
2941 struct stat
*filestats
) /* I - File information */
2943 char *ptr
; /* Pointer into field */
2944 time_t date
; /* Time/date value */
2945 off_t size
; /* Size/length value */
2950 ptr
= con
->http
.fields
[HTTP_FIELD_IF_MODIFIED_SINCE
];
2955 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2956 "check_if_modified: %d If-Modified-Since=\"%s\"",
2959 while (*ptr
!= '\0')
2961 while (isspace(*ptr
) || *ptr
== ';')
2964 if (strncasecmp(ptr
, "length=", 7) == 0)
2967 size
= strtoll(ptr
, NULL
, 10);
2969 while (isdigit(*ptr
))
2972 else if (isalpha(*ptr
))
2974 date
= httpGetDateTime(ptr
);
2975 while (*ptr
!= '\0' && *ptr
!= ';')
2982 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2983 "check_if_modified: %d sizes=" CUPS_LLFMT
","
2984 CUPS_LLFMT
" dates=%d,%d",
2985 con
->http
.fd
, CUPS_LLCAST size
,
2986 CUPS_LLCAST filestats
->st_size
, (int)date
,
2987 (int)filestats
->st_mtime
);
2989 return ((size
!= filestats
->st_size
&& size
!= 0) ||
2990 (date
< filestats
->st_mtime
&& date
!= 0) ||
2991 (size
== 0 && date
== 0));
2996 * 'compare_clients()' - Compare two client connections.
2999 static int /* O - Result of comparison */
3000 compare_clients(cupsd_client_t
*a
, /* I - First client */
3001 cupsd_client_t
*b
, /* I - Second client */
3002 void *data
) /* I - User data (not used) */
3016 * 'data_ready()' - Check whether data is available from a client.
3019 static int /* O - 1 if data is ready, 0 otherwise */
3020 data_ready(cupsd_client_t
*con
) /* I - Client */
3022 if (con
->http
.used
> 0)
3025 else if (con
->http
.tls
)
3028 if (SSL_pending((SSL
*)(con
->http
.tls
)))
3030 # elif defined(HAVE_GNUTLS)
3031 if (gnutls_record_check_pending(((http_tls_t
*)(con
->http
.tls
))->session
))
3033 # elif defined(HAVE_CDSASSL)
3034 size_t bytes
; /* Bytes that are available */
3036 if (!SSLGetBufferedReadSize(((http_tls_t
*)(con
->http
.tls
))->session
,
3037 &bytes
) && bytes
> 0)
3039 # endif /* HAVE_LIBSSL */
3041 #endif /* HAVE_SSL */
3049 * 'encrypt_client()' - Enable encryption for the client...
3052 static int /* O - 1 on success, 0 on error */
3053 encrypt_client(cupsd_client_t
*con
) /* I - Client to encrypt */
3056 SSL_CTX
*context
; /* Context for encryption */
3057 SSL
*conn
; /* Connection for encryption */
3058 BIO
*bio
; /* BIO data */
3059 unsigned long error
; /* Error code */
3063 * Verify that we have a certificate...
3066 if (access(ServerKey
, 0) || access(ServerCertificate
, 0))
3069 * Nope, make a self-signed certificate...
3072 if (!make_certificate(con
))
3077 * Create the SSL context and accept the connection...
3080 context
= SSL_CTX_new(SSLv23_server_method());
3082 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
3083 SSL_CTX_use_PrivateKey_file(context
, ServerKey
, SSL_FILETYPE_PEM
);
3084 SSL_CTX_use_certificate_chain_file(context
, ServerCertificate
,
3087 bio
= BIO_new(_httpBIOMethods());
3088 BIO_ctrl(bio
, BIO_C_SET_FILE_PTR
, 0, (char *)HTTP(con
));
3090 conn
= SSL_new(context
);
3091 SSL_set_bio(conn
, bio
, bio
);
3093 if (SSL_accept(conn
) != 1)
3095 cupsdLogMessage(CUPSD_LOG_ERROR
,
3096 "encrypt_client: Unable to encrypt connection from %s!",
3097 con
->http
.hostname
);
3099 while ((error
= ERR_get_error()) != 0)
3100 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s",
3101 ERR_error_string(error
, NULL
));
3103 SSL_CTX_free(context
);
3108 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3109 "encrypt_client: %d Connection from %s now encrypted.",
3110 con
->http
.fd
, con
->http
.hostname
);
3112 con
->http
.tls
= conn
;
3115 # elif defined(HAVE_GNUTLS)
3116 http_tls_t
*conn
; /* TLS session object */
3117 int error
; /* Error code */
3118 gnutls_certificate_server_credentials
*credentials
;
3119 /* TLS credentials */
3123 * Verify that we have a certificate...
3126 if (access(ServerKey
, 0) || access(ServerCertificate
, 0))
3129 * Nope, make a self-signed certificate...
3132 if (!make_certificate(con
))
3137 * Create the SSL object and perform the SSL handshake...
3140 conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
));
3145 credentials
= (gnutls_certificate_server_credentials
*)
3146 malloc(sizeof(gnutls_certificate_server_credentials
));
3147 if (credentials
== NULL
)
3149 cupsdLogMessage(CUPSD_LOG_ERROR
,
3150 "encrypt_client: Unable to encrypt connection from %s!",
3151 con
->http
.hostname
);
3152 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s", strerror(errno
));
3158 gnutls_certificate_allocate_credentials(credentials
);
3159 gnutls_certificate_set_x509_key_file(*credentials
, ServerCertificate
,
3160 ServerKey
, GNUTLS_X509_FMT_PEM
);
3162 gnutls_init(&(conn
->session
), GNUTLS_SERVER
);
3163 gnutls_set_default_priority(conn
->session
);
3164 gnutls_credentials_set(conn
->session
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
3165 gnutls_transport_set_ptr(conn
->session
, (gnutls_transport_ptr
)HTTP(con
));
3166 gnutls_transport_set_pull_function(conn
->session
, _httpReadGNUTLS
);
3167 gnutls_transport_set_push_function(conn
->session
, _httpWriteGNUTLS
);
3169 error
= gnutls_handshake(conn
->session
);
3171 if (error
!= GNUTLS_E_SUCCESS
)
3173 cupsdLogMessage(CUPSD_LOG_ERROR
,
3174 "encrypt_client: Unable to encrypt connection from %s!",
3175 con
->http
.hostname
);
3176 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s",
3177 gnutls_strerror(error
));
3179 gnutls_deinit(conn
->session
);
3180 gnutls_certificate_free_credentials(*credentials
);
3186 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3187 "encrypt_client: %d Connection from %s now encrypted.",
3188 con
->http
.fd
, con
->http
.hostname
);
3190 conn
->credentials
= credentials
;
3191 con
->http
.tls
= conn
;
3194 # elif defined(HAVE_CDSASSL)
3195 OSStatus error
; /* Error code */
3196 http_tls_t
*conn
; /* CDSA connection information */
3199 if ((conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
))) == NULL
)
3203 conn
->session
= NULL
;
3204 conn
->certsArray
= get_cdsa_certificate(con
);
3206 if (!conn
->certsArray
)
3209 * No keychain (yet), make a self-signed certificate...
3212 if (make_certificate(con
))
3213 conn
->certsArray
= get_cdsa_certificate(con
);
3216 if (!conn
->certsArray
)
3218 cupsdLogMessage(CUPSD_LOG_ERROR
,
3219 "encrypt_client: Could not find signing key in keychain "
3220 "\"%s\"", ServerCertificate
);
3221 error
= errSSLBadCert
; /* errSSLBadConfiguration is a better choice, but not available on 10.2.x */
3225 error
= SSLNewContext(true, &conn
->session
);
3228 error
= SSLSetIOFuncs(conn
->session
, _httpReadCDSA
, _httpWriteCDSA
);
3231 error
= SSLSetProtocolVersionEnabled(conn
->session
, kSSLProtocol2
, false);
3234 error
= SSLSetConnection(conn
->session
, HTTP(con
));
3237 error
= SSLSetAllowsExpiredCerts(conn
->session
, true);
3240 error
= SSLSetAllowsAnyRoot(conn
->session
, true);
3243 error
= SSLSetCertificate(conn
->session
, conn
->certsArray
);
3248 * Perform SSL/TLS handshake
3251 while ((error
= SSLHandshake(conn
->session
)) == errSSLWouldBlock
)
3257 cupsdLogMessage(CUPSD_LOG_ERROR
,
3258 "encrypt_client: Unable to encrypt connection from %s!",
3259 con
->http
.hostname
);
3261 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s (%d)",
3262 cssmErrorString(error
), (int)error
);
3264 con
->http
.error
= error
;
3265 con
->http
.status
= HTTP_ERROR
;
3268 SSLDisposeContext(conn
->session
);
3270 if (conn
->certsArray
)
3271 CFRelease(conn
->certsArray
);
3278 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3279 "encrypt_client: %d Connection from %s now encrypted.",
3280 con
->http
.fd
, con
->http
.hostname
);
3282 con
->http
.tls
= conn
;
3285 # endif /* HAVE_LIBSSL */
3287 #endif /* HAVE_SSL */
3292 * 'get_cdsa_certificate()' - Get a SSL/TLS certificate from the System keychain.
3295 static CFArrayRef
/* O - Array of certificates */
3296 get_cdsa_certificate(cupsd_client_t
*con
) /* I - Client connection */
3298 OSStatus err
; /* Error info */
3299 SecKeychainRef keychain
; /* Keychain reference */
3300 SecIdentitySearchRef search
; /* Search reference */
3301 SecIdentityRef identity
; /* Identity */
3302 CFArrayRef certificates
= NULL
;
3303 /* Certificate array */
3306 if ((err
= SecKeychainOpen(ServerCertificate
, &keychain
)))
3308 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot open keychain \"%s\", %s",
3309 ServerCertificate
, cssmErrorString(err
));
3313 # if HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY
3315 * Use a policy to search for valid certificates who's common name matches the
3319 SecPolicySearchRef policy_search
; /* Policy search ref */
3320 SecPolicyRef policy
; /* Policy ref */
3321 CSSM_DATA options
; /* Policy options */
3322 CSSM_APPLE_TP_SSL_OPTIONS
3323 ssl_options
; /* SSL Option for hostname */
3326 if (SecPolicySearchCreate(CSSM_CERT_X_509v3
, &CSSMOID_APPLE_TP_SSL
,
3327 NULL
, &policy_search
))
3329 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot create a policy search reference");
3330 CFRelease(keychain
);
3334 if (SecPolicySearchCopyNext(policy_search
, &policy
))
3336 cupsdLogMessage(CUPSD_LOG_ERROR
,
3337 "Cannot find a policy to use for searching");
3338 CFRelease(keychain
);
3339 CFRelease(policy_search
);
3343 memset(&ssl_options
, 0, sizeof(ssl_options
));
3344 ssl_options
.Version
= CSSM_APPLE_TP_SSL_OPTS_VERSION
;
3345 ssl_options
.ServerName
= con
->servername
;
3346 ssl_options
.ServerNameLen
= strlen(con
->servername
);
3348 options
.Data
= (uint8
*)&ssl_options
;
3349 options
.Length
= sizeof(ssl_options
);
3351 if (SecPolicySetValue(policy
, &options
))
3353 cupsdLogMessage(CUPSD_LOG_ERROR
,
3354 "Cannot set policy value to use for searching");
3355 CFRelease(keychain
);
3356 CFRelease(policy_search
);
3360 err
= SecIdentitySearchCreateWithPolicy(policy
, NULL
, CSSM_KEYUSE_SIGN
,
3361 keychain
, FALSE
, &search
);
3364 * Assume there is exactly one SecIdentity in the keychain...
3367 err
= SecIdentitySearchCreate(keychain
, CSSM_KEYUSE_SIGN
, &search
);
3368 # endif /* HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY */
3371 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3372 "Cannot create keychain search reference: %s",
3373 cssmErrorString(err
));
3376 if ((err
= SecIdentitySearchCopyNext(search
, &identity
)))
3378 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3379 "Cannot find signing key in keychain \"%s\", error %d",
3380 ServerCertificate
, (int)err
);
3384 if (CFGetTypeID(identity
) != SecIdentityGetTypeID())
3385 cupsdLogMessage(CUPSD_LOG_ERROR
,
3386 "SecIdentitySearchCopyNext CFTypeID failure!");
3389 if ((certificates
= CFArrayCreate(NULL
, (const void **)&identity
,
3390 1, &kCFTypeArrayCallBacks
)) == NULL
)
3391 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot create certificate array");
3394 CFRelease(identity
);
3400 # if HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY
3402 CFRelease(policy_search
);
3403 # endif /* HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY */
3405 return (certificates
);
3407 #endif /* HAVE_CDSASSL */
3411 * 'get_file()' - Get a filename and state info.
3414 static char * /* O - Real filename */
3415 get_file(cupsd_client_t
*con
, /* I - Client connection */
3416 struct stat
*filestats
, /* O - File information */
3417 char *filename
, /* IO - Filename buffer */
3418 int len
) /* I - Buffer length */
3420 int status
; /* Status of filesystem calls */
3421 char *ptr
; /* Pointer info filename */
3422 int plen
; /* Remaining length after pointer */
3423 char language
[7]; /* Language subdirectory, if any */
3427 * Figure out the real filename...
3432 if (!strncmp(con
->uri
, "/ppd/", 5))
3433 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
);
3434 else if (!strncmp(con
->uri
, "/rss/", 5) && !strchr(con
->uri
+ 5, '/'))
3435 snprintf(filename
, len
, "%s/rss/%s", CacheDir
, con
->uri
+ 5);
3436 else if (!strncmp(con
->uri
, "/admin/conf/", 12))
3437 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
+ 11);
3438 else if (!strncmp(con
->uri
, "/admin/log/", 11))
3440 if (!strncmp(con
->uri
+ 11, "access_log", 10) && AccessLog
[0] == '/')
3441 strlcpy(filename
, AccessLog
, len
);
3442 else if (!strncmp(con
->uri
+ 11, "error_log", 9) && ErrorLog
[0] == '/')
3443 strlcpy(filename
, ErrorLog
, len
);
3444 else if (!strncmp(con
->uri
+ 11, "page_log", 8) && PageLog
[0] == '/')
3445 strlcpy(filename
, PageLog
, len
);
3449 else if (con
->language
)
3451 snprintf(language
, sizeof(language
), "/%s", con
->language
->language
);
3452 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3455 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3457 if ((ptr
= strchr(filename
, '?')) != NULL
)
3461 * Grab the status for this language; if there isn't a language-specific file
3462 * then fallback to the default one...
3465 if ((status
= stat(filename
, filestats
)) != 0 && language
[0] &&
3466 strncmp(con
->uri
, "/ppd/", 5) &&
3467 strncmp(con
->uri
, "/admin/conf/", 12) &&
3468 strncmp(con
->uri
, "/admin/log/", 11))
3471 * Drop the country code...
3475 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3477 if ((ptr
= strchr(filename
, '?')) != NULL
)
3480 if ((status
= stat(filename
, filestats
)) != 0)
3483 * Drop the language prefix and try the root directory...
3487 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3489 if ((ptr
= strchr(filename
, '?')) != NULL
)
3492 status
= stat(filename
, filestats
);
3497 * If we're found a directory, get the index.html file instead...
3500 if (!status
&& S_ISDIR(filestats
->st_mode
))
3503 * Make sure the URI ends with a slash...
3506 if (con
->uri
[strlen(con
->uri
) - 1] != '/')
3507 strlcat(con
->uri
, "/", sizeof(con
->uri
));
3510 * Find the directory index file, trying every language...
3515 if (status
&& language
[0])
3518 * Try a different language subset...
3522 language
[0] = '\0'; /* Strip country code */
3524 language
[0] = '\0'; /* Strip language */
3528 * Look for the index file...
3531 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3533 if ((ptr
= strchr(filename
, '?')) != NULL
)
3536 ptr
= filename
+ strlen(filename
);
3537 plen
= len
- (ptr
- filename
);
3539 strlcpy(ptr
, "index.html", plen
);
3540 status
= stat(filename
, filestats
);
3545 strlcpy(ptr
, "index.class", plen
);
3546 status
= stat(filename
, filestats
);
3548 #endif /* HAVE_JAVA */
3553 strlcpy(ptr
, "index.pl", plen
);
3554 status
= stat(filename
, filestats
);
3556 #endif /* HAVE_PERL */
3561 strlcpy(ptr
, "index.php", plen
);
3562 status
= stat(filename
, filestats
);
3564 #endif /* HAVE_PHP */
3569 strlcpy(ptr
, "index.pyc", plen
);
3570 status
= stat(filename
, filestats
);
3575 strlcpy(ptr
, "index.py", plen
);
3576 status
= stat(filename
, filestats
);
3578 #endif /* HAVE_PYTHON */
3581 while (status
&& language
[0]);
3584 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "get_file: %d filename=%s size=%d",
3585 con
->http
.fd
, filename
,
3586 status
? -1 : (int)filestats
->st_size
);
3589 con
->http
.data_remaining
= (int)filestats
->st_size
;
3599 * 'install_conf_file()' - Install a configuration file.
3602 static http_status_t
/* O - Status */
3603 install_conf_file(cupsd_client_t
*con
) /* I - Connection */
3605 cups_file_t
*in
, /* Input file */
3606 *out
; /* Output file */
3607 char buffer
[1024]; /* Copy buffer */
3608 int bytes
; /* Number of bytes */
3609 char conffile
[1024], /* Configuration filename */
3610 newfile
[1024], /* New config filename */
3611 oldfile
[1024]; /* Old config filename */
3612 struct stat confinfo
; /* Config file info */
3616 * First construct the filenames...
3619 snprintf(conffile
, sizeof(conffile
), "%s%s", ServerRoot
, con
->uri
+ 11);
3620 snprintf(newfile
, sizeof(newfile
), "%s%s.N", ServerRoot
, con
->uri
+ 11);
3621 snprintf(oldfile
, sizeof(oldfile
), "%s%s.O", ServerRoot
, con
->uri
+ 11);
3623 cupsdLogMessage(CUPSD_LOG_INFO
, "Installing config file \"%s\"...", conffile
);
3626 * Get the owner, group, and permissions of the configuration file.
3627 * If it doesn't exist, assign it to the User and Group in the
3628 * cupsd.conf file with mode 0640 permissions.
3631 if (stat(conffile
, &confinfo
))
3633 confinfo
.st_uid
= User
;
3634 confinfo
.st_gid
= Group
;
3635 confinfo
.st_mode
= ConfigFilePerm
;
3639 * Open the request file and new config file...
3642 if ((in
= cupsFileOpen(con
->filename
, "rb")) == NULL
)
3644 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open request file \"%s\" - %s",
3645 con
->filename
, strerror(errno
));
3646 return (HTTP_SERVER_ERROR
);
3649 if ((out
= cupsFileOpen(newfile
, "wb")) == NULL
)
3652 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open config file \"%s\" - %s",
3653 newfile
, strerror(errno
));
3654 return (HTTP_SERVER_ERROR
);
3657 fchmod(cupsFileNumber(out
), confinfo
.st_mode
);
3658 fchown(cupsFileNumber(out
), confinfo
.st_uid
, confinfo
.st_gid
);
3661 * Copy from the request to the new config file...
3664 while ((bytes
= cupsFileRead(in
, buffer
, sizeof(buffer
))) > 0)
3665 if (cupsFileWrite(out
, buffer
, bytes
) < bytes
)
3667 cupsdLogMessage(CUPSD_LOG_ERROR
,
3668 "Unable to copy to config file \"%s\" - %s",
3669 newfile
, strerror(errno
));
3675 return (HTTP_SERVER_ERROR
);
3679 * Close the files...
3683 if (cupsFileClose(out
))
3685 cupsdLogMessage(CUPSD_LOG_ERROR
,
3686 "Error file closing config file \"%s\" - %s",
3687 newfile
, strerror(errno
));
3691 return (HTTP_SERVER_ERROR
);
3695 * Remove the request file...
3698 unlink(con
->filename
);
3699 cupsdClearString(&con
->filename
);
3702 * Unlink the old backup, rename the current config file to the backup
3703 * filename, and rename the new config file to the config file name...
3706 if (unlink(oldfile
))
3707 if (errno
!= ENOENT
)
3709 cupsdLogMessage(CUPSD_LOG_ERROR
,
3710 "Unable to remove backup config file \"%s\" - %s",
3711 oldfile
, strerror(errno
));
3715 return (HTTP_SERVER_ERROR
);
3718 if (rename(conffile
, oldfile
))
3719 if (errno
!= ENOENT
)
3721 cupsdLogMessage(CUPSD_LOG_ERROR
,
3722 "Unable to rename old config file \"%s\" - %s",
3723 conffile
, strerror(errno
));
3727 return (HTTP_SERVER_ERROR
);
3730 if (rename(newfile
, conffile
))
3732 cupsdLogMessage(CUPSD_LOG_ERROR
,
3733 "Unable to rename new config file \"%s\" - %s",
3734 newfile
, strerror(errno
));
3736 rename(oldfile
, conffile
);
3739 return (HTTP_SERVER_ERROR
);
3743 * If the cupsd.conf file was updated, set the NeedReload flag...
3746 if (!strcmp(con
->uri
, "/admin/conf/cupsd.conf"))
3747 NeedReload
= RELOAD_CUPSD
;
3749 NeedReload
= RELOAD_ALL
;
3751 ReloadTime
= time(NULL
);
3754 * Return that the file was created successfully...
3757 return (HTTP_CREATED
);
3762 * 'is_cgi()' - Is the resource a CGI script/program?
3765 static int /* O - 1 = CGI, 0 = file */
3766 is_cgi(cupsd_client_t
*con
, /* I - Client connection */
3767 const char *filename
, /* I - Real filename */
3768 struct stat
*filestats
, /* I - File information */
3769 mime_type_t
*type
) /* I - MIME type */
3771 const char *options
; /* Options on URL */
3774 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3775 "is_cgi(con=%p, filename=\"%s\", filestats=%p, type=%s/%s)",
3776 con
, filename
, filestats
, type
? type
->super
: "unknown",
3777 type
? type
->type
: "unknown");
3780 * Get the options, if any...
3783 if ((options
= strchr(con
->uri
, '?')) != NULL
)
3786 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", options
);
3790 * Check for known types...
3793 if (!type
|| strcasecmp(type
->super
, "application"))
3795 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "is_cgi: Returning 0...");
3799 if (!strcasecmp(type
->type
, "x-httpd-cgi") &&
3800 (filestats
->st_mode
& 0111))
3803 * "application/x-httpd-cgi" is a CGI script.
3806 cupsdSetString(&con
->command
, filename
);
3809 cupsdSetStringf(&con
->options
, " %s", options
);
3811 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3812 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3813 con
->command
, con
->options
);
3818 else if (!strcasecmp(type
->type
, "x-httpd-java"))
3821 * "application/x-httpd-java" is a Java servlet.
3824 cupsdSetString(&con
->command
, CUPS_JAVA
);
3827 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3829 cupsdSetStringf(&con
->options
, " %s", filename
);
3831 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3832 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3833 con
->command
, con
->options
);
3837 #endif /* HAVE_JAVA */
3839 else if (!strcasecmp(type
->type
, "x-httpd-perl"))
3842 * "application/x-httpd-perl" is a Perl page.
3845 cupsdSetString(&con
->command
, CUPS_PERL
);
3848 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3850 cupsdSetStringf(&con
->options
, " %s", filename
);
3852 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3853 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3854 con
->command
, con
->options
);
3858 #endif /* HAVE_PERL */
3860 else if (!strcasecmp(type
->type
, "x-httpd-php"))
3863 * "application/x-httpd-php" is a PHP page.
3866 cupsdSetString(&con
->command
, CUPS_PHP
);
3869 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3871 cupsdSetStringf(&con
->options
, " %s", filename
);
3873 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3874 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3875 con
->command
, con
->options
);
3879 #endif /* HAVE_PHP */
3881 else if (!strcasecmp(type
->type
, "x-httpd-python"))
3884 * "application/x-httpd-python" is a Python page.
3887 cupsdSetString(&con
->command
, CUPS_PYTHON
);
3890 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3892 cupsdSetStringf(&con
->options
, " %s", filename
);
3894 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3895 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3896 con
->command
, con
->options
);
3900 #endif /* HAVE_PYTHON */
3902 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "is_cgi: Returning 0...");
3909 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
3912 static int /* O - 0 if relative, 1 if absolute */
3913 is_path_absolute(const char *path
) /* I - Input path */
3916 * Check for a leading slash...
3923 * Check for "/.." in the path...
3926 while ((path
= strstr(path
, "/..")) != NULL
)
3928 if (!path
[3] || path
[3] == '/')
3935 * If we haven't found any relative paths, return 1 indicating an
3945 * 'make_certificate()' - Make a self-signed SSL/TLS certificate.
3948 static int /* O - 1 on success, 0 on failure */
3949 make_certificate(cupsd_client_t
*con
) /* I - Client connection */
3951 #if defined(HAVE_LIBSSL) && defined(HAVE_WAITPID)
3952 int pid
, /* Process ID of command */
3953 status
; /* Status of command */
3954 char command
[1024], /* Command */
3955 *argv
[12], /* Command-line arguments */
3956 *envp
[MAX_ENV
+ 1], /* Environment variables */
3957 home
[1024], /* HOME environment variable */
3958 infofile
[1024], /* Type-in information for cert */
3959 seedfile
[1024]; /* Random number seed file */
3960 int envc
, /* Number of environment variables */
3961 bytes
; /* Bytes written */
3962 cups_file_t
*fp
; /* Seed/info file */
3963 int infofd
; /* Info file descriptor */
3967 * Run the "openssl" command to seed the random number generator and
3968 * generate a self-signed certificate that is good for 10 years:
3970 * openssl rand -rand seedfile 1
3972 * openssl req -new -x509 -keyout ServerKey \
3973 * -out ServerCertificate -days 3650 -nodes
3975 * The seeding step is crucial in ensuring that the openssl command
3976 * does not block on systems without sufficient entropy...
3979 if (!cupsFileFind("openssl", getenv("PATH"), 1, command
, sizeof(command
)))
3981 cupsdLogMessage(CUPSD_LOG_ERROR
,
3982 "No SSL certificate and openssl command not found!");
3986 if (access("/dev/urandom", 0))
3989 * If the system doesn't provide /dev/urandom, then any random source
3990 * will probably be blocking-style, so generate some random data to
3991 * use as a seed for the certificate. Note that we have already
3992 * seeded the random number generator in cupsdInitCerts()...
3995 cupsdLogMessage(CUPSD_LOG_INFO
,
3996 "Seeding the random number generator...");
3998 snprintf(home
, sizeof(home
), "HOME=%s", TempDir
);
4001 * Write the seed file...
4004 if ((fp
= cupsTempFile2(seedfile
, sizeof(seedfile
))) == NULL
)
4006 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to create seed file %s - %s",
4007 seedfile
, strerror(errno
));
4011 for (bytes
= 0; bytes
< 262144; bytes
++)
4012 cupsFilePutChar(fp
, random());
4017 * Run the openssl command to seed its random number generator...
4020 argv
[0] = "openssl";
4027 envc
= cupsdLoadEnv(envp
, MAX_ENV
);
4028 envp
[envc
++] = home
;
4031 if (!cupsdStartProcess(command
, argv
, envp
, -1, -1, -1, -1, -1, 1, NULL
,
4038 while (waitpid(pid
, &status
, 0) < 0)
4045 cupsdFinishProcess(pid
, command
, sizeof(command
));
4048 * Remove the seed file, as it is no longer needed...
4055 if (WIFEXITED(status
))
4056 cupsdLogMessage(CUPSD_LOG_ERROR
,
4057 "Unable to seed random number generator - "
4058 "the openssl command stopped with status %d!",
4059 WEXITSTATUS(status
));
4061 cupsdLogMessage(CUPSD_LOG_ERROR
,
4062 "Unable to seed random number generator - "
4063 "the openssl command crashed on signal %d!",
4071 * Create a file with the certificate information fields...
4073 * Note: This assumes that the default questions are asked by the openssl
4077 if ((fp
= cupsTempFile2(infofile
, sizeof(infofile
))) == NULL
)
4079 cupsdLogMessage(CUPSD_LOG_ERROR
,
4080 "Unable to create certificate information file %s - %s",
4081 infofile
, strerror(errno
));
4085 cupsFilePrintf(fp
, ".\n.\n.\n%s\n.\n%s\n%s\n",
4086 ServerName
, ServerName
, ServerAdmin
);
4089 cupsdLogMessage(CUPSD_LOG_INFO
,
4090 "Generating SSL server key and certificate...");
4092 argv
[0] = "openssl";
4096 argv
[4] = "-keyout";
4097 argv
[5] = ServerKey
;
4099 argv
[7] = ServerCertificate
;
4102 argv
[10] = "-nodes";
4105 cupsdLoadEnv(envp
, MAX_ENV
);
4107 infofd
= open(infofile
, O_RDONLY
);
4109 if (!cupsdStartProcess(command
, argv
, envp
, infofd
, -1, -1, -1, -1, 1, NULL
,
4120 while (waitpid(pid
, &status
, 0) < 0)
4127 cupsdFinishProcess(pid
, command
, sizeof(command
));
4131 if (WIFEXITED(status
))
4132 cupsdLogMessage(CUPSD_LOG_ERROR
,
4133 "Unable to create SSL server key and certificate - "
4134 "the openssl command stopped with status %d!",
4135 WEXITSTATUS(status
));
4137 cupsdLogMessage(CUPSD_LOG_ERROR
,
4138 "Unable to create SSL server key and certificate - "
4139 "the openssl command crashed on signal %d!",
4144 cupsdLogMessage(CUPSD_LOG_INFO
, "Created SSL server key file \"%s\"...",
4146 cupsdLogMessage(CUPSD_LOG_INFO
,
4147 "Created SSL server certificate file \"%s\"...",
4153 #elif defined(HAVE_GNUTLS)
4154 gnutls_x509_crt crt
; /* Self-signed certificate */
4155 gnutls_x509_privkey key
; /* Encryption key */
4156 cups_lang_t
*language
; /* Default language info */
4157 cups_file_t
*fp
; /* Key/cert file */
4158 unsigned char buffer
[8192]; /* Buffer for x509 data */
4159 size_t bytes
; /* Number of bytes of data */
4160 unsigned char serial
[4]; /* Serial number buffer */
4161 time_t curtime
; /* Current time */
4162 int result
; /* Result of GNU TLS calls */
4166 * Create the encryption key...
4169 cupsdLogMessage(CUPSD_LOG_INFO
, "Generating SSL server key...");
4171 gnutls_x509_privkey_init(&key
);
4172 gnutls_x509_privkey_generate(key
, GNUTLS_PK_RSA
, 2048, 0);
4178 bytes
= sizeof(buffer
);
4180 if ((result
= gnutls_x509_privkey_export(key
, GNUTLS_X509_FMT_PEM
,
4181 buffer
, &bytes
)) < 0)
4183 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to export SSL server key - %s",
4184 gnutls_strerror(result
));
4185 gnutls_x509_privkey_deinit(key
);
4188 else if ((fp
= cupsFileOpen(ServerKey
, "w")) != NULL
)
4190 cupsFileWrite(fp
, (char *)buffer
, bytes
);
4193 cupsdLogMessage(CUPSD_LOG_INFO
, "Created SSL server key file \"%s\"...",
4198 cupsdLogMessage(CUPSD_LOG_ERROR
,
4199 "Unable to create SSL server key file \"%s\" - %s",
4200 ServerKey
, strerror(errno
));
4201 gnutls_x509_privkey_deinit(key
);
4206 * Create the self-signed certificate...
4209 cupsdLogMessage(CUPSD_LOG_INFO
, "Generating self-signed SSL certificate...");
4211 language
= cupsLangDefault();
4212 curtime
= time(NULL
);
4213 serial
[0] = curtime
>> 24;
4214 serial
[1] = curtime
>> 16;
4215 serial
[2] = curtime
>> 8;
4216 serial
[3] = curtime
;
4218 gnutls_x509_crt_init(&crt
);
4219 if (strlen(language
->language
) == 5)
4220 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
4221 language
->language
+ 3, 2);
4223 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
4225 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COMMON_NAME
, 0,
4226 ServerName
, strlen(ServerName
));
4227 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATION_NAME
, 0,
4228 ServerName
, strlen(ServerName
));
4229 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATIONAL_UNIT_NAME
,
4231 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_STATE_OR_PROVINCE_NAME
, 0,
4233 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_LOCALITY_NAME
, 0,
4235 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_PKCS9_EMAIL
, 0,
4236 ServerAdmin
, strlen(ServerAdmin
));
4237 gnutls_x509_crt_set_key(crt
, key
);
4238 gnutls_x509_crt_set_serial(crt
, serial
, sizeof(serial
));
4239 gnutls_x509_crt_set_activation_time(crt
, curtime
);
4240 gnutls_x509_crt_set_expiration_time(crt
, curtime
+ 10 * 365 * 86400);
4241 gnutls_x509_crt_set_ca_status(crt
, 0);
4242 gnutls_x509_crt_set_subject_alternative_name(crt
, GNUTLS_SAN_DNSNAME
,
4244 gnutls_x509_crt_set_key_purpose_oid(crt
, GNUTLS_KP_TLS_WWW_SERVER
, 0);
4245 gnutls_x509_crt_set_key_usage(crt
, GNUTLS_KEY_KEY_ENCIPHERMENT
);
4246 gnutls_x509_crt_set_version(crt
, 3);
4248 bytes
= sizeof(buffer
);
4249 if (gnutls_x509_crt_get_key_id(crt
, 0, buffer
, &bytes
) >= 0)
4250 gnutls_x509_crt_set_subject_key_id(crt
, buffer
, bytes
);
4252 gnutls_x509_crt_sign(crt
, crt
, key
);
4258 bytes
= sizeof(buffer
);
4259 if ((result
= gnutls_x509_crt_export(crt
, GNUTLS_X509_FMT_PEM
,
4260 buffer
, &bytes
)) < 0)
4261 cupsdLogMessage(CUPSD_LOG_ERROR
,
4262 "Unable to export SSL server certificate - %s",
4263 gnutls_strerror(result
));
4264 else if ((fp
= cupsFileOpen(ServerCertificate
, "w")) != NULL
)
4266 cupsFileWrite(fp
, (char *)buffer
, bytes
);
4269 cupsdLogMessage(CUPSD_LOG_INFO
,
4270 "Created SSL server certificate file \"%s\"...",
4274 cupsdLogMessage(CUPSD_LOG_ERROR
,
4275 "Unable to create SSL server certificate file \"%s\" - %s",
4276 ServerCertificate
, strerror(errno
));
4282 gnutls_x509_crt_deinit(crt
);
4283 gnutls_x509_privkey_deinit(key
);
4287 #elif defined(HAVE_CDSASSL) && defined(HAVE_WAITPID)
4288 int pid
, /* Process ID of command */
4289 status
; /* Status of command */
4290 char command
[1024], /* Command */
4291 *argv
[4], /* Command-line arguments */
4292 *envp
[MAX_ENV
+ 1], /* Environment variables */
4293 keychain
[1024], /* Keychain argument */
4294 infofile
[1024]; /* Type-in information for cert */
4295 cups_file_t
*fp
; /* Seed/info file */
4296 int infofd
; /* Info file descriptor */
4300 * Run the "certtool" command to generate a self-signed certificate...
4303 if (!cupsFileFind("certtool", getenv("PATH"), 1, command
, sizeof(command
)))
4305 cupsdLogMessage(CUPSD_LOG_ERROR
,
4306 "No SSL certificate and certtool command not found!");
4311 * Create a file with the certificate information fields...
4313 * Note: This assumes that the default questions are asked by the certtool
4317 if ((fp
= cupsTempFile2(infofile
, sizeof(infofile
))) == NULL
)
4319 cupsdLogMessage(CUPSD_LOG_ERROR
,
4320 "Unable to create certificate information file %s - %s",
4321 infofile
, strerror(errno
));
4325 cupsFilePrintf(fp
, "%s\nr\n\ny\nb\ns\ny\n%s\n\n\n\n\n%s\ny\n",
4326 con
->servername
, con
->servername
, ServerAdmin
);
4329 cupsdLogMessage(CUPSD_LOG_INFO
,
4330 "Generating SSL server key and certificate...");
4332 snprintf(keychain
, sizeof(keychain
), "k=%s", ServerCertificate
);
4334 argv
[0] = "certtool";
4339 cupsdLoadEnv(envp
, MAX_ENV
);
4341 infofd
= open(infofile
, O_RDONLY
);
4343 if (!cupsdStartProcess(command
, argv
, envp
, infofd
, -1, -1, -1, -1, 1, NULL
,
4354 while (waitpid(pid
, &status
, 0) < 0)
4361 cupsdFinishProcess(pid
, command
, sizeof(command
));
4365 if (WIFEXITED(status
))
4366 cupsdLogMessage(CUPSD_LOG_ERROR
,
4367 "Unable to create SSL server key and certificate - "
4368 "the certtool command stopped with status %d!",
4369 WEXITSTATUS(status
));
4371 cupsdLogMessage(CUPSD_LOG_ERROR
,
4372 "Unable to create SSL server key and certificate - "
4373 "the certtool command crashed on signal %d!",
4378 cupsdLogMessage(CUPSD_LOG_INFO
,
4379 "Created SSL server certificate file \"%s\"...",
4387 #endif /* HAVE_LIBSSL && HAVE_WAITPID */
4389 #endif /* HAVE_SSL */
4393 * 'pipe_command()' - Pipe the output of a command to the remote client.
4396 static int /* O - Process ID */
4397 pipe_command(cupsd_client_t
*con
, /* I - Client connection */
4398 int infile
, /* I - Standard input for command */
4399 int *outfile
, /* O - Standard output for command */
4400 char *command
, /* I - Command to run */
4401 char *options
, /* I - Options for command */
4402 int root
) /* I - Run as root? */
4404 int i
; /* Looping var */
4405 int pid
; /* Process ID */
4406 char *commptr
, /* Command string pointer */
4407 commch
; /* Command string character */
4408 char *uriptr
; /* URI string pointer */
4409 int fds
[2]; /* Pipe FDs */
4410 int argc
; /* Number of arguments */
4411 int envc
; /* Number of environment variables */
4412 char argbuf
[10240], /* Argument buffer */
4413 *argv
[100], /* Argument strings */
4414 *envp
[MAX_ENV
+ 20]; /* Environment variables */
4415 char auth_type
[256], /* CUPSD_AUTH_TYPE environment variable */
4416 content_length
[1024], /* CONTENT_LENGTH environment variable */
4417 content_type
[1024], /* CONTENT_TYPE environment variable */
4418 http_cookie
[32768], /* HTTP_COOKIE environment variable */
4419 http_referer
[1024], /* HTTP_REFERER environment variable */
4420 http_user_agent
[1024], /* HTTP_USER_AGENT environment variable */
4421 lang
[1024], /* LANG environment variable */
4422 path_info
[1024], /* PATH_INFO environment variable */
4423 remote_addr
[1024], /* REMOTE_ADDR environment variable */
4424 remote_host
[1024], /* REMOTE_HOST environment variable */
4425 remote_user
[1024], /* REMOTE_USER environment variable */
4426 script_filename
[1024], /* SCRIPT_FILENAME environment variable */
4427 script_name
[1024], /* SCRIPT_NAME environment variable */
4428 server_name
[1024], /* SERVER_NAME environment variable */
4429 server_port
[1024]; /* SERVER_PORT environment variable */
4430 ipp_attribute_t
*attr
; /* attributes-natural-language attribute */
4432 krb5_ccache ccache
= NULL
; /* Kerberos credentials */
4433 char krb5ccname
[1024]; /* KRB5CCNAME environment variable */
4434 #endif /* HAVE_GSSAPI */
4438 * Parse a copy of the options string, which is of the form:
4440 * argument+argument+argument
4441 * ?argument+argument+argument
4442 * param=value¶m=value
4443 * ?param=value¶m=value
4444 * /name?argument+argument+argument
4445 * /name?param=value¶m=value
4447 * If the string contains an "=" character after the initial name,
4448 * then we treat it as a HTTP GET form request and make a copy of
4449 * the remaining string for the environment variable.
4451 * The string is always parsed out as command-line arguments, to
4452 * be consistent with Apache...
4455 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4456 "pipe_command: command=\"%s\", options=\"%s\"",
4457 command
, options
? options
: "(null)");
4462 strlcpy(argbuf
, options
, sizeof(argbuf
));
4466 if (argbuf
[0] == '/')
4469 * Found some trailing path information, set PATH_INFO...
4472 if ((commptr
= strchr(argbuf
, '?')) == NULL
)
4473 commptr
= argbuf
+ strlen(argbuf
);
4477 snprintf(path_info
, sizeof(path_info
), "PATH_INFO=%s", argbuf
);
4483 path_info
[0] = '\0';
4485 if (*commptr
== ' ')
4489 if (*commptr
== '?' && con
->operation
== HTTP_GET
&& !con
->query_string
)
4492 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", commptr
);
4499 argv
[argc
++] = commptr
;
4501 for (; *commptr
&& argc
< 99; commptr
++)
4504 * Break arguments whenever we see a + or space...
4507 if (*commptr
== ' ' || *commptr
== '+')
4509 while (*commptr
== ' ' || *commptr
== '+')
4513 * If we don't have a blank string, save it as another argument...
4518 argv
[argc
] = commptr
;
4524 else if (*commptr
== '%' && isxdigit(commptr
[1] & 255) &&
4525 isxdigit(commptr
[2] & 255))
4528 * Convert the %xx notation to the individual character.
4531 if (commptr
[1] >= '0' && commptr
[1] <= '9')
4532 *commptr
= (commptr
[1] - '0') << 4;
4534 *commptr
= (tolower(commptr
[1]) - 'a' + 10) << 4;
4536 if (commptr
[2] >= '0' && commptr
[2] <= '9')
4537 *commptr
|= commptr
[2] - '0';
4539 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
4541 _cups_strcpy(commptr
+ 1, commptr
+ 3);
4544 * Check for a %00 and break if that is the case...
4556 * Setup the environment variables as needed...
4559 if (con
->username
[0])
4561 snprintf(auth_type
, sizeof(auth_type
), "CUPSD_AUTH_TYPE=%s",
4562 httpGetField(HTTP(con
), HTTP_FIELD_AUTHORIZATION
));
4564 if ((uriptr
= strchr(auth_type
+ 10, ' ')) != NULL
)
4568 auth_type
[0] = '\0';
4571 (attr
= ippFindAttribute(con
->request
, "attributes-natural-language",
4572 IPP_TAG_LANGUAGE
)) != NULL
)
4574 switch (strlen(attr
->values
[0].string
.text
))
4578 * This is an unknown or badly formatted language code; use
4579 * the POSIX locale...
4582 strcpy(lang
, "LANG=C");
4587 * Just the language code (ll)...
4590 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8",
4591 attr
->values
[0].string
.text
);
4596 * Language and country code (ll-cc)...
4599 snprintf(lang
, sizeof(lang
), "LANG=%c%c_%c%c.UTF8",
4600 attr
->values
[0].string
.text
[0],
4601 attr
->values
[0].string
.text
[1],
4602 toupper(attr
->values
[0].string
.text
[3] & 255),
4603 toupper(attr
->values
[0].string
.text
[4] & 255));
4607 else if (con
->language
)
4608 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8", con
->language
->language
);
4610 strcpy(lang
, "LANG=C");
4612 strcpy(remote_addr
, "REMOTE_ADDR=");
4613 httpAddrString(con
->http
.hostaddr
, remote_addr
+ 12,
4614 sizeof(remote_addr
) - 12);
4616 snprintf(remote_host
, sizeof(remote_host
), "REMOTE_HOST=%s",
4617 con
->http
.hostname
);
4619 snprintf(script_name
, sizeof(script_name
), "SCRIPT_NAME=%s", con
->uri
);
4620 if ((uriptr
= strchr(script_name
, '?')) != NULL
)
4623 snprintf(script_filename
, sizeof(script_filename
), "SCRIPT_FILENAME=%s%s",
4624 DocumentRoot
, script_name
+ 12);
4626 sprintf(server_port
, "SERVER_PORT=%d", con
->serverport
);
4628 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
4631 envc
= cupsdLoadEnv(envp
, (int)(sizeof(envp
) / sizeof(envp
[0])));
4634 envp
[envc
++] = auth_type
;
4636 envp
[envc
++] = lang
;
4637 envp
[envc
++] = "REDIRECT_STATUS=1";
4638 envp
[envc
++] = "GATEWAY_INTERFACE=CGI/1.1";
4639 envp
[envc
++] = server_name
;
4640 envp
[envc
++] = server_port
;
4641 envp
[envc
++] = remote_addr
;
4642 envp
[envc
++] = remote_host
;
4643 envp
[envc
++] = script_name
;
4644 envp
[envc
++] = script_filename
;
4647 envp
[envc
++] = path_info
;
4649 if (con
->username
[0])
4651 snprintf(remote_user
, sizeof(remote_user
), "REMOTE_USER=%s", con
->username
);
4653 envp
[envc
++] = remote_user
;
4656 * Save Kerberos credentials, if any...
4660 if (con
->gss_have_creds
)
4662 # if !defined(HAVE_KRB5_CC_NEW_UNIQUE) && !defined(HAVE_HEIMDAL)
4663 cupsdLogMessage(CUPSD_LOG_INFO
,
4664 "Sorry, your version of Kerberos does not support "
4665 "delegated credentials!");
4668 krb5_error_code error
; /* Kerberos error code */
4669 OM_uint32 major_status
, /* Major status code */
4670 minor_status
; /* Minor status code */
4671 krb5_principal principal
; /* Kerberos principal */
4676 * If the weak-linked GSSAPI/Kerberos library is not present, don't try
4680 if (krb5_init_context
!= NULL
)
4682 # endif /* __APPLE__ */
4685 * We MUST create a file-based cache because memory-based caches are
4686 * only valid for the current process/address space.
4688 * Due to various bugs/features in different versions of Kerberos, we
4689 * need either the krb5_cc_new_unique() function or Heimdal's version
4690 * of krb5_cc_gen_new() to create a new FILE: credential cache that
4691 * can be passed to the backend. These functions create a temporary
4692 * file (typically in /tmp) containing the cached credentials, which
4693 * are removed when we have successfully printed a job.
4696 # ifdef HAVE_KRB5_CC_NEW_UNIQUE
4697 if ((error
= krb5_cc_new_unique(KerberosContext
, "FILE", NULL
,
4699 # else /* HAVE_HEIMDAL */
4700 if ((error
= krb5_cc_gen_new(KerberosContext
, &krb5_fcc_ops
,
4702 # endif /* HAVE_KRB5_CC_NEW_UNIQUE */
4704 cupsdLogMessage(CUPSD_LOG_ERROR
,
4705 "Unable to create new credentials cache (%d/%s)",
4706 error
, strerror(errno
));
4709 else if ((error
= krb5_parse_name(KerberosContext
, con
->username
,
4712 cupsdLogMessage(CUPSD_LOG_ERROR
,
4713 "Unable to parse kerberos username (%d/%s)", error
,
4715 krb5_cc_destroy(KerberosContext
, ccache
);
4718 else if ((error
= krb5_cc_initialize(KerberosContext
, ccache
,
4721 cupsdLogMessage(CUPSD_LOG_ERROR
,
4722 "Unable to initialize credentials cache (%d/%s)", error
,
4724 krb5_cc_destroy(KerberosContext
, ccache
);
4725 krb5_free_principal(KerberosContext
, principal
);
4730 krb5_free_principal(KerberosContext
, principal
);
4733 * Copy the user's credentials to the new cache file...
4736 major_status
= gss_krb5_copy_ccache(&minor_status
,
4737 con
->gss_delegated_cred
, ccache
);
4739 if (GSS_ERROR(major_status
))
4741 cupsdLogGSSMessage(CUPSD_LOG_ERROR
, major_status
, minor_status
,
4742 "Unable to import client credentials cache");
4743 krb5_cc_destroy(KerberosContext
, ccache
);
4749 * Add the KRB5CCNAME environment variable to the job so that the
4750 * backend can use the credentials when printing.
4753 snprintf(krb5ccname
, sizeof(krb5ccname
), "KRB5CCNAME=FILE:%s",
4754 krb5_cc_get_name(KerberosContext
, ccache
));
4755 envp
[envc
++] = krb5ccname
;
4758 chown(krb5_cc_get_name(KerberosContext
, ccache
), User
, Group
);
4763 # endif /* __APPLE__ */
4764 # endif /* HAVE_KRB5_CC_NEW_UNIQUE || HAVE_HEIMDAL */
4766 #endif /* HAVE_GSSAPI */
4770 if (con
->http
.version
== HTTP_1_1
)
4771 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.1";
4772 else if (con
->http
.version
== HTTP_1_0
)
4773 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.0";
4775 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/0.9";
4777 if (con
->http
.cookie
)
4779 snprintf(http_cookie
, sizeof(http_cookie
), "HTTP_COOKIE=%s",
4781 envp
[envc
++] = http_cookie
;
4784 if (con
->http
.fields
[HTTP_FIELD_USER_AGENT
][0])
4786 snprintf(http_user_agent
, sizeof(http_user_agent
), "HTTP_USER_AGENT=%s",
4787 con
->http
.fields
[HTTP_FIELD_USER_AGENT
]);
4788 envp
[envc
++] = http_user_agent
;
4791 if (con
->http
.fields
[HTTP_FIELD_REFERER
][0])
4793 snprintf(http_referer
, sizeof(http_referer
), "HTTP_REFERER=%s",
4794 con
->http
.fields
[HTTP_FIELD_REFERER
]);
4795 envp
[envc
++] = http_referer
;
4798 if (con
->operation
== HTTP_GET
)
4800 envp
[envc
++] = "REQUEST_METHOD=GET";
4802 if (con
->query_string
)
4805 * Add GET form variables after ?...
4808 envp
[envc
++] = con
->query_string
;
4811 envp
[envc
++] = "QUERY_STRING=";
4815 sprintf(content_length
, "CONTENT_LENGTH=" CUPS_LLFMT
,
4816 CUPS_LLCAST con
->bytes
);
4817 snprintf(content_type
, sizeof(content_type
), "CONTENT_TYPE=%s",
4818 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
4820 envp
[envc
++] = "REQUEST_METHOD=POST";
4821 envp
[envc
++] = content_length
;
4822 envp
[envc
++] = content_type
;
4826 * Tell the CGI if we are using encryption...
4830 envp
[envc
++] = "HTTPS=ON";
4833 * Terminate the environment array...
4838 if (LogLevel
== CUPSD_LOG_DEBUG2
)
4840 for (i
= 0; i
< argc
; i
++)
4841 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4842 "pipe_command: argv[%d] = \"%s\"", i
, argv
[i
]);
4843 for (i
= 0; i
< envc
; i
++)
4844 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4845 "pipe_command: envp[%d] = \"%s\"", i
, envp
[i
]);
4849 * Create a pipe for the output...
4852 if (cupsdOpenPipe(fds
))
4854 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to create pipes for CGI %s - %s",
4855 argv
[0], strerror(errno
));
4860 * Then execute the command...
4863 if (cupsdStartProcess(command
, argv
, envp
, infile
, fds
[1], CGIPipes
[1],
4864 -1, -1, root
, DefaultProfile
, &pid
) < 0)
4867 * Error - can't fork!
4870 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to fork for CGI %s - %s", argv
[0],
4873 cupsdClosePipe(fds
);
4879 * Fork successful - return the PID...
4882 if (con
->username
[0])
4884 cupsdAddCert(pid
, con
->username
, ccache
);
4886 cupsdAddCert(pid
, con
->username
, NULL
);
4887 #endif /* HAVE_GSSAPI */
4889 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[CGI] %s started - PID = %d",
4901 * 'write_file()' - Send a file via HTTP.
4904 static int /* O - 0 on failure, 1 on success */
4905 write_file(cupsd_client_t
*con
, /* I - Client connection */
4906 http_status_t code
, /* I - HTTP status */
4907 char *filename
, /* I - Filename */
4908 char *type
, /* I - File type */
4909 struct stat
*filestats
) /* O - File information */
4911 con
->file
= open(filename
, O_RDONLY
);
4913 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "write_file: %d file=%d", con
->http
.fd
,
4919 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
4923 if (!cupsdSendHeader(con
, code
, type
, CUPSD_AUTH_NONE
))
4926 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
4927 httpGetDateString(filestats
->st_mtime
)) < 0)
4929 if (httpPrintf(HTTP(con
), "Content-Length: " CUPS_LLFMT
"\r\n",
4930 CUPS_LLCAST filestats
->st_size
) < 0)
4932 if (httpPrintf(HTTP(con
), "\r\n") < 0)
4935 if (cupsdFlushHeader(con
) < 0)
4938 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
4939 con
->http
.data_remaining
= filestats
->st_size
;
4941 if (con
->http
.data_remaining
<= INT_MAX
)
4942 con
->http
._data_remaining
= con
->http
.data_remaining
;
4944 con
->http
._data_remaining
= INT_MAX
;
4946 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
,
4947 (cupsd_selfunc_t
)cupsdWriteClient
, con
);
4954 * 'write_pipe()' - Flag that data is available on the CGI pipe.
4958 write_pipe(cupsd_client_t
*con
) /* I - Client connection */
4960 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "write_pipe: CGI output on fd %d...",
4963 con
->file_ready
= 1;
4965 cupsdRemoveSelect(con
->file
);
4966 cupsdAddSelect(con
->http
.fd
, NULL
, (cupsd_selfunc_t
)cupsdWriteClient
, con
);
4971 * End of "$Id: client.c 7673 2008-06-18 22:31:26Z mike $".