2 * "$Id: client.c 7950 2008-09-17 00:21:59Z mike $"
4 * Client routines for the Common UNIX Printing System (CUPS) scheduler.
6 * Copyright 2007-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
)
441 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
442 else if (httpAddrLocalhost(&temp
))
443 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
445 httpAddrString(&temp
, con
->servername
, sizeof(con
->servername
));
447 con
->serverport
= ntohs(lis
->address
.ipv6
.sin6_port
);
450 #endif /* AF_INET6 */
451 if (temp
.addr
.sa_family
== AF_INET
)
454 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
455 else if (httpAddrLocalhost(&temp
))
456 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
458 httpAddrString(&temp
, con
->servername
, sizeof(con
->servername
));
460 con
->serverport
= ntohs(lis
->address
.ipv4
.sin_port
);
464 strcpy(con
->servername
, "localhost");
465 con
->serverport
= LocalPort
;
469 cupsArrayAdd(Clients
, con
);
471 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
472 "cupsdAcceptClient: %d connected to server on %s:%d",
473 con
->http
.fd
, con
->servername
, con
->serverport
);
476 * Using TCP_NODELAY improves responsiveness, especially on systems
477 * with a slow loopback interface... Since we write large buffers
478 * when sending print files and requests, there shouldn't be any
479 * performance penalty for this...
483 setsockopt(con
->http
.fd
, IPPROTO_TCP
, TCP_NODELAY
, &val
, sizeof(val
));
486 * Close this file on all execs...
489 fcntl(con
->http
.fd
, F_SETFD
, fcntl(con
->http
.fd
, F_GETFD
) | FD_CLOEXEC
);
492 * Add the socket to the select() input mask.
495 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
498 * Temporarily suspend accept()'s until we lose a client...
501 if (cupsArrayCount(Clients
) == MaxClients
)
502 cupsdPauseListening();
506 * See if we are connecting on a secure port...
509 if (lis
->encryption
== HTTP_ENCRYPT_ALWAYS
)
512 * https connection; go secure...
515 con
->http
.encryption
= HTTP_ENCRYPT_ALWAYS
;
517 if (!encrypt_client(con
))
518 cupsdCloseClient(con
);
522 #endif /* HAVE_SSL */
527 * 'cupsdCloseAllClients()' - Close all remote clients immediately.
531 cupsdCloseAllClients(void)
533 cupsd_client_t
*con
; /* Current client */
536 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
538 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
539 if (cupsdCloseClient(con
))
540 cupsdCloseClient(con
);
545 * 'cupsdCloseClient()' - Close a remote client.
548 int /* O - 1 if partial close, 0 if fully closed */
549 cupsdCloseClient(cupsd_client_t
*con
) /* I - Client to close */
551 int partial
; /* Do partial close for SSL? */
553 SSL_CTX
*context
; /* Context for encryption */
554 SSL
*conn
; /* Connection for encryption */
555 unsigned long error
; /* Error code */
556 #elif defined(HAVE_GNUTLS)
557 http_tls_t
*conn
; /* TLS connection information */
558 int error
; /* Error code */
559 gnutls_certificate_server_credentials
*credentials
;
560 /* TLS credentials */
561 # elif defined(HAVE_CDSASSL)
562 http_tls_t
*conn
; /* CDSA connection information */
563 #endif /* HAVE_LIBSSL */
566 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdCloseClient: %d", con
->http
.fd
);
569 * Flush pending writes before closing...
572 httpFlushWrite(HTTP(con
));
578 * Shutdown encryption as needed...
586 conn
= (SSL
*)(con
->http
.tls
);
587 context
= SSL_get_SSL_CTX(conn
);
589 switch (SSL_shutdown(conn
))
592 cupsdLogMessage(CUPSD_LOG_DEBUG
,
593 "SSL shutdown successful!");
596 cupsdLogMessage(CUPSD_LOG_ERROR
,
597 "Fatal error during SSL shutdown!");
599 while ((error
= ERR_get_error()) != 0)
600 cupsdLogMessage(CUPSD_LOG_ERROR
, "SSL shutdown failed: %s",
601 ERR_error_string(error
, NULL
));
605 SSL_CTX_free(context
);
608 # elif defined(HAVE_GNUTLS)
609 conn
= (http_tls_t
*)(con
->http
.tls
);
610 credentials
= (gnutls_certificate_server_credentials
*)(conn
->credentials
);
612 error
= gnutls_bye(conn
->session
, GNUTLS_SHUT_WR
);
615 case GNUTLS_E_SUCCESS
:
616 cupsdLogMessage(CUPSD_LOG_DEBUG
,
617 "SSL shutdown successful!");
620 cupsdLogMessage(CUPSD_LOG_ERROR
,
621 "SSL shutdown failed: %s", gnutls_strerror(error
));
625 gnutls_deinit(conn
->session
);
626 gnutls_certificate_free_credentials(*credentials
);
630 # elif defined(HAVE_CDSASSL)
631 conn
= (http_tls_t
*)(con
->http
.tls
);
633 while (SSLClose(conn
->session
) == errSSLWouldBlock
)
636 SSLDisposeContext(conn
->session
);
638 if (conn
->certsArray
)
639 CFRelease(conn
->certsArray
);
642 # endif /* HAVE_LIBSSL */
644 con
->http
.tls
= NULL
;
646 #endif /* HAVE_SSL */
648 if (con
->pipe_pid
!= 0)
651 * Stop any CGI process...
654 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
655 "cupsdCloseClient: %d Killing process ID %d...",
656 con
->http
.fd
, con
->pipe_pid
);
657 cupsdEndProcess(con
->pipe_pid
, 1);
663 cupsdRemoveSelect(con
->file
);
665 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
666 "cupsdCloseClient: %d Closing data file %d.",
667 con
->http
.fd
, con
->file
);
674 * Close the socket and clear the file from the input set for select()...
677 if (con
->http
.fd
>= 0)
679 cupsArrayRemove(ActiveClients
, con
);
685 * Only do a partial close so that the encrypted client gets everything.
688 shutdown(con
->http
.fd
, 0);
689 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
694 * Shut the socket down fully...
697 cupsdRemoveSelect(con
->http
.fd
);
709 if (con
->http
.input_set
)
710 free(con
->http
.input_set
);
712 httpClearCookie(HTTP(con
));
713 httpClearFields(HTTP(con
));
715 cupsdClearString(&con
->filename
);
716 cupsdClearString(&con
->command
);
717 cupsdClearString(&con
->options
);
718 cupsdClearString(&con
->query_string
);
722 ippDelete(con
->request
);
728 ippDelete(con
->response
);
729 con
->response
= NULL
;
734 cupsLangFree(con
->language
);
735 con
->language
= NULL
;
738 #ifdef HAVE_AUTHORIZATION_H
741 AuthorizationFree(con
->authref
, kAuthorizationFlagDefaults
);
744 #endif /* HAVE_AUTHORIZATION_H */
747 * Re-enable new client connections if we are going back under the
751 if (cupsArrayCount(Clients
) == MaxClients
)
752 cupsdResumeListening();
755 * Compact the list of clients as necessary...
758 cupsArrayRemove(Clients
, con
);
768 * 'cupsdFlushHeader()' - Flush the header fields to the client.
771 int /* I - Bytes written or -1 on error */
772 cupsdFlushHeader(cupsd_client_t
*con
) /* I - Client to flush to */
774 int bytes
= httpFlushWrite(HTTP(con
));
776 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
783 * 'cupsdReadClient()' - Read data from a client.
787 cupsdReadClient(cupsd_client_t
*con
) /* I - Client to read from */
789 char line
[32768], /* Line from client... */
790 operation
[64], /* Operation code from socket */
791 version
[64], /* HTTP version number string */
792 locale
[64], /* Locale */
793 *ptr
; /* Pointer into strings */
794 int major
, minor
; /* HTTP version numbers */
795 http_status_t status
; /* Transfer status */
796 ipp_state_t ipp_state
; /* State of IPP transfer */
797 int bytes
; /* Number of bytes to POST */
798 char *filename
; /* Name of file for GET/HEAD */
799 char buf
[1024]; /* Buffer for real filename */
800 struct stat filestats
; /* File information */
801 mime_type_t
*type
; /* MIME type of file */
802 cupsd_printer_t
*p
; /* Printer */
803 static unsigned request_id
= 0; /* Request ID for temp files */
806 status
= HTTP_CONTINUE
;
808 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
809 "cupsdReadClient: %d, used=%d, file=%d state=%d",
810 con
->http
.fd
, con
->http
.used
, con
->file
, con
->http
.state
);
814 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdReadClient: http error seen...");
815 cupsdCloseClient(con
);
823 * Automatically check for a SSL/TLS handshake...
828 if (recv(con
->http
.fd
, buf
, 1, MSG_PEEK
) == 1 &&
829 (!buf
[0] || !strchr("DGHOPT", buf
[0])))
832 * Encrypt this connection...
835 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
836 "cupsdReadClient: Saw first byte %02X, auto-negotiating SSL/TLS session...",
839 if (!encrypt_client(con
))
840 cupsdCloseClient(con
);
845 #endif /* HAVE_SSL */
847 switch (con
->http
.state
)
851 * See if we've received a request line...
854 if (httpGets(line
, sizeof(line
) - 1, HTTP(con
)) == NULL
)
856 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
857 "cupsdReadClient: httpGets returned EOF...");
858 cupsdCloseClient(con
);
863 * Ignore blank request lines...
870 * Clear other state variables...
873 httpClearFields(HTTP(con
));
875 con
->http
.activity
= time(NULL
);
876 con
->http
.version
= HTTP_1_0
;
877 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
878 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
879 con
->http
.data_remaining
= 0;
880 con
->http
._data_remaining
= 0;
881 con
->operation
= HTTP_WAITING
;
886 con
->username
[0] = '\0';
887 con
->password
[0] = '\0';
890 cupsdClearString(&con
->command
);
891 cupsdClearString(&con
->options
);
892 cupsdClearString(&con
->query_string
);
896 ippDelete(con
->request
);
902 ippDelete(con
->response
);
903 con
->response
= NULL
;
908 cupsLangFree(con
->language
);
909 con
->language
= NULL
;
913 con
->gss_have_creds
= 0;
914 #endif /* HAVE_GSSAPI */
917 * Grab the request line...
920 switch (sscanf(line
, "%63s%1023s%63s", operation
, con
->uri
, version
))
925 cupsdLogMessage(CUPSD_LOG_ERROR
,
926 "Bad request line \"%s\" from %s!", line
,
928 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
929 cupsdCloseClient(con
);
933 con
->http
.version
= HTTP_0_9
;
936 if (sscanf(version
, "HTTP/%d.%d", &major
, &minor
) != 2)
938 cupsdLogMessage(CUPSD_LOG_ERROR
,
939 "Bad request line \"%s\" from %s!", line
,
941 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
942 cupsdCloseClient(con
);
948 con
->http
.version
= (http_version_t
)(major
* 100 + minor
);
949 if (con
->http
.version
== HTTP_1_1
&& KeepAlive
)
950 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
952 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
956 cupsdSendError(con
, HTTP_NOT_SUPPORTED
, CUPSD_AUTH_NONE
);
957 cupsdCloseClient(con
);
964 * Handle full URLs in the request line...
967 if (strcmp(con
->uri
, "*"))
969 char method
[HTTP_MAX_URI
], /* Method/scheme */
970 userpass
[HTTP_MAX_URI
], /* Username:password */
971 hostname
[HTTP_MAX_URI
], /* Hostname */
972 resource
[HTTP_MAX_URI
]; /* Resource path */
973 int port
; /* Port number */
977 * Separate the URI into its components...
980 httpSeparateURI(HTTP_URI_CODING_MOST
, con
->uri
,
981 method
, sizeof(method
),
982 userpass
, sizeof(userpass
),
983 hostname
, sizeof(hostname
), &port
,
984 resource
, sizeof(resource
));
987 * Only allow URIs with the servername, localhost, or an IP
991 if (strcmp(method
, "file") &&
992 strcasecmp(hostname
, ServerName
) &&
993 strcasecmp(hostname
, "localhost") &&
994 !isdigit(hostname
[0]))
997 * Nope, we don't do proxies...
1000 cupsdLogMessage(CUPSD_LOG_ERROR
, "Bad URI \"%s\" in request!",
1002 cupsdSendError(con
, HTTP_METHOD_NOT_ALLOWED
, CUPSD_AUTH_NONE
);
1003 cupsdCloseClient(con
);
1008 * Copy the resource portion back into the URI; both resource and
1009 * con->uri are HTTP_MAX_URI bytes in size...
1012 strcpy(con
->uri
, resource
);
1016 * Process the request...
1019 if (!strcmp(operation
, "GET"))
1020 con
->http
.state
= HTTP_GET
;
1021 else if (!strcmp(operation
, "PUT"))
1022 con
->http
.state
= HTTP_PUT
;
1023 else if (!strcmp(operation
, "POST"))
1024 con
->http
.state
= HTTP_POST
;
1025 else if (!strcmp(operation
, "DELETE"))
1026 con
->http
.state
= HTTP_DELETE
;
1027 else if (!strcmp(operation
, "TRACE"))
1028 con
->http
.state
= HTTP_TRACE
;
1029 else if (!strcmp(operation
, "OPTIONS"))
1030 con
->http
.state
= HTTP_OPTIONS
;
1031 else if (!strcmp(operation
, "HEAD"))
1032 con
->http
.state
= HTTP_HEAD
;
1035 cupsdLogMessage(CUPSD_LOG_ERROR
, "Bad operation \"%s\"!", operation
);
1036 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
1037 cupsdCloseClient(con
);
1041 con
->start
= time(NULL
);
1042 con
->operation
= con
->http
.state
;
1044 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdReadClient: %d %s %s HTTP/%d.%d",
1045 con
->http
.fd
, operation
, con
->uri
,
1046 con
->http
.version
/ 100, con
->http
.version
% 100);
1048 con
->http
.status
= HTTP_OK
;
1050 if (!cupsArrayFind(ActiveClients
, con
))
1052 cupsArrayAdd(ActiveClients
, con
);
1053 cupsdSetBusyState();
1064 * Parse incoming parameters until the status changes...
1067 while ((status
= httpUpdate(HTTP(con
))) == HTTP_CONTINUE
)
1068 if (!data_ready(con
))
1071 if (status
!= HTTP_OK
&& status
!= HTTP_CONTINUE
)
1073 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
1074 cupsdCloseClient(con
);
1080 break; /* Anti-compiler-warning-code */
1084 * Handle new transfers...
1087 if (status
== HTTP_OK
)
1089 if (con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
][0])
1092 * Figure out the locale from the Accept-Language and Content-Type
1096 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ',')) != NULL
)
1099 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ';')) != NULL
)
1102 if ((ptr
= strstr(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
], "charset=")) != NULL
)
1105 * Combine language and charset, and trim any extra params in the
1109 snprintf(locale
, sizeof(locale
), "%s.%s",
1110 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ptr
+ 8);
1112 if ((ptr
= strchr(locale
, ',')) != NULL
)
1116 snprintf(locale
, sizeof(locale
), "%s.%s",
1117 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], DefaultCharset
);
1119 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1120 "cupsdReadClient: %d Browser asked for language \"%s\"...",
1121 con
->http
.fd
, locale
);
1123 con
->language
= cupsLangGet(locale
);
1126 con
->language
= cupsLangGet(DefaultLocale
);
1128 cupsdAuthorize(con
);
1130 if (!strncmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Keep-Alive", 10) &&
1132 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
1134 if (!con
->http
.fields
[HTTP_FIELD_HOST
][0] &&
1135 con
->http
.version
>= HTTP_1_1
)
1138 * HTTP/1.1 and higher require the "Host:" field...
1141 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1143 cupsdCloseClient(con
);
1147 else if (con
->operation
== HTTP_OPTIONS
)
1150 * Do OPTIONS command...
1153 if (con
->best
&& con
->best
->type
!= CUPSD_AUTH_NONE
)
1155 if (!cupsdSendHeader(con
, HTTP_UNAUTHORIZED
, NULL
, CUPSD_AUTH_NONE
))
1157 cupsdCloseClient(con
);
1162 if (!strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") &&
1163 con
->http
.tls
== NULL
)
1167 * Do encryption stuff...
1170 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
, CUPSD_AUTH_NONE
))
1172 cupsdCloseClient(con
);
1176 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1177 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1178 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1179 httpPrintf(HTTP(con
), "\r\n");
1181 if (cupsdFlushHeader(con
) < 0)
1183 cupsdCloseClient(con
);
1187 if (!encrypt_client(con
))
1189 cupsdCloseClient(con
);
1193 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
1195 cupsdCloseClient(con
);
1198 #endif /* HAVE_SSL */
1201 if (!cupsdSendHeader(con
, HTTP_OK
, NULL
, CUPSD_AUTH_NONE
))
1203 cupsdCloseClient(con
);
1207 httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n");
1208 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1209 httpPrintf(HTTP(con
), "\r\n");
1211 if (cupsdFlushHeader(con
) < 0)
1213 cupsdCloseClient(con
);
1217 else if (!is_path_absolute(con
->uri
))
1220 * Protect against malicious users!
1223 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1225 cupsdCloseClient(con
);
1231 if (!strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") &&
1232 con
->http
.tls
== NULL
)
1236 * Do encryption stuff...
1239 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
, CUPSD_AUTH_NONE
))
1241 cupsdCloseClient(con
);
1245 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1246 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1247 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1248 httpPrintf(HTTP(con
), "\r\n");
1250 if (cupsdFlushHeader(con
) < 0)
1252 cupsdCloseClient(con
);
1256 if (!encrypt_client(con
))
1258 cupsdCloseClient(con
);
1262 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
1264 cupsdCloseClient(con
);
1267 #endif /* HAVE_SSL */
1270 if ((status
= cupsdIsAuthorized(con
, NULL
)) != HTTP_OK
)
1272 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1273 "cupsdReadClient: Unauthorized request for %s...",
1275 cupsdSendError(con
, status
, CUPSD_AUTH_NONE
);
1276 cupsdCloseClient(con
);
1280 if (con
->http
.expect
&&
1281 (con
->operation
== HTTP_POST
|| con
->operation
== HTTP_PUT
))
1283 if (con
->http
.expect
== HTTP_CONTINUE
)
1286 * Send 100-continue header...
1289 if (!cupsdSendHeader(con
, HTTP_CONTINUE
, NULL
, CUPSD_AUTH_NONE
))
1291 cupsdCloseClient(con
);
1298 * Send 417-expectation-failed header...
1301 if (!cupsdSendHeader(con
, HTTP_EXPECTATION_FAILED
, NULL
, CUPSD_AUTH_NONE
))
1303 cupsdCloseClient(con
);
1307 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1308 httpPrintf(HTTP(con
), "\r\n");
1310 if (cupsdFlushHeader(con
) < 0)
1312 cupsdCloseClient(con
);
1318 switch (con
->http
.state
)
1320 case HTTP_GET_SEND
:
1321 if (!strncmp(con
->uri
, "/printers/", 10) &&
1322 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1325 * Send PPD file - get the real printer name since printer
1326 * names are not case sensitive but filenames can be...
1329 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1331 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1332 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1335 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1337 cupsdCloseClient(con
);
1345 if ((!strncmp(con
->uri
, "/admin", 6) &&
1346 strncmp(con
->uri
, "/admin/conf/", 12) &&
1347 strncmp(con
->uri
, "/admin/log/", 11)) ||
1348 !strncmp(con
->uri
, "/printers", 9) ||
1349 !strncmp(con
->uri
, "/classes", 8) ||
1350 !strncmp(con
->uri
, "/help", 5) ||
1351 !strncmp(con
->uri
, "/jobs", 5))
1354 * Send CGI output...
1357 if (!strncmp(con
->uri
, "/admin", 6))
1359 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1362 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1364 else if (!strncmp(con
->uri
, "/printers", 9))
1366 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1369 if (con
->uri
[9] && con
->uri
[10])
1370 cupsdSetString(&con
->options
, con
->uri
+ 9);
1372 cupsdSetString(&con
->options
, NULL
);
1374 else if (!strncmp(con
->uri
, "/classes", 8))
1376 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1379 if (con
->uri
[8] && con
->uri
[9])
1380 cupsdSetString(&con
->options
, con
->uri
+ 8);
1382 cupsdSetString(&con
->options
, NULL
);
1384 else if (!strncmp(con
->uri
, "/jobs", 5))
1386 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1389 if (con
->uri
[5] && con
->uri
[6])
1390 cupsdSetString(&con
->options
, con
->uri
+ 5);
1392 cupsdSetString(&con
->options
, NULL
);
1396 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1399 if (con
->uri
[5] && con
->uri
[6])
1400 cupsdSetString(&con
->options
, con
->uri
+ 5);
1402 cupsdSetString(&con
->options
, NULL
);
1405 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1407 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1409 cupsdCloseClient(con
);
1414 cupsdLogRequest(con
, HTTP_OK
);
1416 if (con
->http
.version
<= HTTP_1_0
)
1417 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1419 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1420 (strchr(con
->uri
+ 12, '/') ||
1421 strlen(con
->uri
) == 12)) ||
1422 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1423 (strchr(con
->uri
+ 11, '/') ||
1424 strlen(con
->uri
) == 11)))
1427 * GET can only be done to configuration files under
1431 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1433 cupsdCloseClient(con
);
1445 if ((filename
= get_file(con
, &filestats
, buf
,
1446 sizeof(buf
))) == NULL
)
1448 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1450 cupsdCloseClient(con
);
1457 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1459 if (is_cgi(con
, filename
, &filestats
, type
))
1462 * Note: con->command and con->options were set by
1466 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1468 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1470 cupsdCloseClient(con
);
1475 cupsdLogRequest(con
, HTTP_OK
);
1477 if (con
->http
.version
<= HTTP_1_0
)
1478 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1482 if (!check_if_modified(con
, &filestats
))
1484 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1486 cupsdCloseClient(con
);
1493 strcpy(line
, "text/plain");
1495 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1497 if (!write_file(con
, HTTP_OK
, filename
, line
, &filestats
))
1499 cupsdCloseClient(con
);
1506 case HTTP_POST_RECV
:
1508 * See if the POST request includes a Content-Length field, and if
1509 * so check the length against any limits that are set...
1512 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "POST %s", con
->uri
);
1513 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "CONTENT_TYPE = %s",
1514 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
1516 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1517 MaxRequestSize
> 0 &&
1518 con
->http
.data_remaining
> MaxRequestSize
)
1521 * Request too large...
1524 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1526 cupsdCloseClient(con
);
1532 else if (con
->http
.data_remaining
< 0 ||
1533 (!con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1534 con
->http
.data_encoding
== HTTP_ENCODE_LENGTH
))
1537 * Negative content lengths are invalid!
1540 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1542 cupsdCloseClient(con
);
1550 * See what kind of POST request this is; for IPP requests the
1551 * content-type field will be "application/ipp"...
1554 if (!strcmp(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
],
1556 con
->request
= ippNew();
1557 else if ((!strncmp(con
->uri
, "/admin", 6) &&
1558 strncmp(con
->uri
, "/admin/conf/", 12) &&
1559 strncmp(con
->uri
, "/admin/log/", 11)) ||
1560 !strncmp(con
->uri
, "/printers", 9) ||
1561 !strncmp(con
->uri
, "/classes", 8) ||
1562 !strncmp(con
->uri
, "/help", 5) ||
1563 !strncmp(con
->uri
, "/jobs", 5))
1569 if (!strncmp(con
->uri
, "/admin", 6))
1571 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1574 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1576 else if (!strncmp(con
->uri
, "/printers", 9))
1578 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1581 if (con
->uri
[9] && con
->uri
[10])
1582 cupsdSetString(&con
->options
, con
->uri
+ 9);
1584 cupsdSetString(&con
->options
, NULL
);
1586 else if (!strncmp(con
->uri
, "/classes", 8))
1588 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1591 if (con
->uri
[8] && con
->uri
[9])
1592 cupsdSetString(&con
->options
, con
->uri
+ 8);
1594 cupsdSetString(&con
->options
, NULL
);
1596 else if (!strncmp(con
->uri
, "/jobs", 5))
1598 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1601 if (con
->uri
[5] && con
->uri
[6])
1602 cupsdSetString(&con
->options
, con
->uri
+ 5);
1604 cupsdSetString(&con
->options
, NULL
);
1608 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1611 if (con
->uri
[5] && con
->uri
[6])
1612 cupsdSetString(&con
->options
, con
->uri
+ 5);
1614 cupsdSetString(&con
->options
, NULL
);
1617 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1618 "cupsdReadClient: %d command=\"%s\", "
1620 con
->http
.fd
, con
->command
,
1621 con
->options
? con
->options
: "(null)");
1623 if (con
->http
.version
<= HTTP_1_0
)
1624 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1632 if ((filename
= get_file(con
, &filestats
, buf
,
1633 sizeof(buf
))) == NULL
)
1635 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1637 cupsdCloseClient(con
);
1644 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1646 if (!is_cgi(con
, filename
, &filestats
, type
))
1649 * Only POST to CGI's...
1652 if (!cupsdSendError(con
, HTTP_UNAUTHORIZED
, CUPSD_AUTH_NONE
))
1654 cupsdCloseClient(con
);
1661 case HTTP_PUT_RECV
:
1663 * Validate the resource name...
1666 if (strncmp(con
->uri
, "/admin/conf/", 12) ||
1667 strchr(con
->uri
+ 12, '/') ||
1668 strlen(con
->uri
) == 12)
1671 * PUT can only be done to configuration files under
1675 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1677 cupsdCloseClient(con
);
1685 * See if the PUT request includes a Content-Length field, and if
1686 * so check the length against any limits that are set...
1689 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "PUT %s", con
->uri
);
1690 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "CONTENT_TYPE = %s",
1691 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
1693 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1694 MaxRequestSize
> 0 &&
1695 con
->http
.data_remaining
> MaxRequestSize
)
1698 * Request too large...
1701 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1703 cupsdCloseClient(con
);
1709 else if (con
->http
.data_remaining
< 0)
1712 * Negative content lengths are invalid!
1715 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1717 cupsdCloseClient(con
);
1725 * Open a temporary file to hold the request...
1728 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
1730 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1734 cupsdLogMessage(CUPSD_LOG_ERROR
,
1735 "Unable to create request file %s: %s",
1736 con
->filename
, strerror(errno
));
1738 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1740 cupsdCloseClient(con
);
1745 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1746 "cupsdReadClient: %d REQUEST %s=%d", con
->http
.fd
,
1747 con
->filename
, con
->file
);
1749 fchmod(con
->file
, 0640);
1750 fchown(con
->file
, RunUser
, Group
);
1751 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1756 cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
);
1757 cupsdCloseClient(con
);
1761 if (!strncmp(con
->uri
, "/printers/", 10) &&
1762 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1765 * Send PPD file - get the real printer name since printer
1766 * names are not case sensitive but filenames can be...
1769 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1771 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1772 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1775 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1777 cupsdCloseClient(con
);
1785 if ((!strncmp(con
->uri
, "/admin", 6) &&
1786 strncmp(con
->uri
, "/admin/conf/", 12) &&
1787 strncmp(con
->uri
, "/admin/log/", 11)) ||
1788 !strncmp(con
->uri
, "/printers", 9) ||
1789 !strncmp(con
->uri
, "/classes", 8) ||
1790 !strncmp(con
->uri
, "/help", 5) ||
1791 !strncmp(con
->uri
, "/jobs", 5))
1797 if (!cupsdSendHeader(con
, HTTP_OK
, "text/html", CUPSD_AUTH_NONE
))
1799 cupsdCloseClient(con
);
1803 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1805 cupsdCloseClient(con
);
1809 if (cupsdFlushHeader(con
) < 0)
1811 cupsdCloseClient(con
);
1815 cupsdLogRequest(con
, HTTP_OK
);
1817 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1818 (strchr(con
->uri
+ 12, '/') ||
1819 strlen(con
->uri
) == 12)) ||
1820 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1821 (strchr(con
->uri
+ 11, '/') ||
1822 strlen(con
->uri
) == 11)))
1825 * HEAD can only be done to configuration files under
1829 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1831 cupsdCloseClient(con
);
1837 else if ((filename
= get_file(con
, &filestats
, buf
,
1838 sizeof(buf
))) == NULL
)
1840 if (!cupsdSendHeader(con
, HTTP_NOT_FOUND
, "text/html", CUPSD_AUTH_NONE
))
1842 cupsdCloseClient(con
);
1846 cupsdLogRequest(con
, HTTP_NOT_FOUND
);
1848 else if (!check_if_modified(con
, &filestats
))
1850 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1852 cupsdCloseClient(con
);
1856 cupsdLogRequest(con
, HTTP_NOT_MODIFIED
);
1864 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1866 strcpy(line
, "text/plain");
1868 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1870 if (!cupsdSendHeader(con
, HTTP_OK
, line
, CUPSD_AUTH_NONE
))
1872 cupsdCloseClient(con
);
1876 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
1877 httpGetDateString(filestats
.st_mtime
)) < 0)
1879 cupsdCloseClient(con
);
1883 if (httpPrintf(HTTP(con
), "Content-Length: %lu\r\n",
1884 (unsigned long)filestats
.st_size
) < 0)
1886 cupsdCloseClient(con
);
1890 cupsdLogRequest(con
, HTTP_OK
);
1893 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1895 cupsdCloseClient(con
);
1899 if (cupsdFlushHeader(con
) < 0)
1901 cupsdCloseClient(con
);
1905 con
->http
.state
= HTTP_WAITING
;
1909 break; /* Anti-compiler-warning-code */
1915 * Handle any incoming data...
1918 switch (con
->http
.state
)
1920 case HTTP_PUT_RECV
:
1921 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1922 "cupsdReadClient: %d con->data_encoding=HTTP_ENCODE_%s, "
1923 "con->data_remaining=" CUPS_LLFMT
", con->file=%d",
1925 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
?
1926 "CHUNKED" : "LENGTH",
1927 CUPS_LLCAST con
->http
.data_remaining
, con
->file
);
1931 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
1933 cupsdCloseClient(con
);
1938 con
->bytes
+= bytes
;
1940 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1941 "cupsdReadClient: %d writing %d bytes to %d",
1942 con
->http
.fd
, bytes
, con
->file
);
1944 if (write(con
->file
, line
, bytes
) < bytes
)
1946 cupsdLogMessage(CUPSD_LOG_ERROR
,
1947 "cupsdReadClient: Unable to write %d bytes to %s: %s",
1948 bytes
, con
->filename
, strerror(errno
));
1950 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1951 "cupsdReadClient: Closing data file %d...",
1956 unlink(con
->filename
);
1957 cupsdClearString(&con
->filename
);
1959 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1961 cupsdCloseClient(con
);
1967 while (con
->http
.state
== HTTP_PUT_RECV
&& data_ready(con
));
1969 if (con
->http
.state
== HTTP_WAITING
)
1972 * End of file, see how big it is...
1975 fstat(con
->file
, &filestats
);
1977 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1978 "cupsdReadClient: %d Closing data file %d, size="
1980 con
->http
.fd
, con
->file
,
1981 CUPS_LLCAST filestats
.st_size
);
1986 if (filestats
.st_size
> MaxRequestSize
&&
1990 * Request is too big; remove it and send an error...
1993 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1994 "cupsdReadClient: %d Removing temp file %s",
1995 con
->http
.fd
, con
->filename
);
1996 unlink(con
->filename
);
1997 cupsdClearString(&con
->filename
);
1999 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2001 cupsdCloseClient(con
);
2007 * Install the configuration file...
2010 status
= install_conf_file(con
);
2013 * Return the status to the client...
2016 if (!cupsdSendError(con
, status
, CUPSD_AUTH_NONE
))
2018 cupsdCloseClient(con
);
2024 case HTTP_POST_RECV
:
2025 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2026 "cupsdReadClient: %d con->data_encoding=HTTP_ENCODE_"
2027 "%s, con->data_remaining=" CUPS_LLFMT
", con->file=%d",
2029 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
?
2030 "CHUNKED" : "LENGTH",
2031 CUPS_LLCAST con
->http
.data_remaining
, con
->file
);
2038 * Grab any request data from the connection...
2041 if ((ipp_state
= ippRead(&(con
->http
), con
->request
)) == IPP_ERROR
)
2043 cupsdLogMessage(CUPSD_LOG_ERROR
,
2044 "cupsdReadClient: %d IPP Read Error!",
2047 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
2048 cupsdCloseClient(con
);
2051 else if (ipp_state
!= IPP_DATA
)
2053 if (con
->http
.state
== HTTP_POST_SEND
)
2055 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
2056 cupsdCloseClient(con
);
2063 con
->bytes
+= ippLength(con
->request
);
2066 if (con
->file
< 0 && con
->http
.state
!= HTTP_POST_SEND
)
2069 * Create a file as needed for the request data...
2072 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
, request_id
++);
2073 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
2077 cupsdLogMessage(CUPSD_LOG_ERROR
,
2078 "Unable to create request file %s: %s",
2079 con
->filename
, strerror(errno
));
2081 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2083 cupsdCloseClient(con
);
2088 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdReadClient: %d REQUEST %s=%d", con
->http
.fd
,
2089 con
->filename
, con
->file
);
2091 fchmod(con
->file
, 0640);
2092 fchown(con
->file
, RunUser
, Group
);
2093 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2096 if (con
->http
.state
!= HTTP_POST_SEND
)
2098 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
2100 cupsdCloseClient(con
);
2105 con
->bytes
+= bytes
;
2107 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2108 "cupsdReadClient: %d writing %d bytes to %d",
2109 con
->http
.fd
, bytes
, con
->file
);
2111 if (write(con
->file
, line
, bytes
) < bytes
)
2113 cupsdLogMessage(CUPSD_LOG_ERROR
,
2114 "cupsdReadClient: Unable to write %d bytes to %s: %s",
2115 bytes
, con
->filename
, strerror(errno
));
2117 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2118 "cupsdReadClient: Closing file %d...",
2123 unlink(con
->filename
);
2124 cupsdClearString(&con
->filename
);
2126 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2128 cupsdCloseClient(con
);
2133 else if (con
->http
.state
== HTTP_POST_RECV
)
2135 else if (con
->http
.state
!= HTTP_POST_SEND
)
2137 cupsdCloseClient(con
);
2142 while (con
->http
.state
== HTTP_POST_RECV
&& data_ready(con
));
2144 if (con
->http
.state
== HTTP_POST_SEND
)
2148 fstat(con
->file
, &filestats
);
2150 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2151 "cupsdReadClient: %d Closing data file %d, "
2152 "size=" CUPS_LLFMT
".",
2153 con
->http
.fd
, con
->file
,
2154 CUPS_LLCAST filestats
.st_size
);
2159 if (filestats
.st_size
> MaxRequestSize
&&
2163 * Request is too big; remove it and send an error...
2166 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2167 "cupsdReadClient: %d Removing temp file %s",
2168 con
->http
.fd
, con
->filename
);
2169 unlink(con
->filename
);
2170 cupsdClearString(&con
->filename
);
2175 * Delete any IPP request data...
2178 ippDelete(con
->request
);
2179 con
->request
= NULL
;
2182 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2184 cupsdCloseClient(con
);
2191 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
2193 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
2195 cupsdCloseClient(con
);
2200 cupsdLogRequest(con
, HTTP_OK
);
2206 cupsdProcessIPPRequest(con
);
2210 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2211 "cupsdReadClient: %d Removing temp file %s",
2212 con
->http
.fd
, con
->filename
);
2213 unlink(con
->filename
);
2214 cupsdClearString(&con
->filename
);
2223 break; /* Anti-compiler-warning-code */
2226 if (con
->http
.state
== HTTP_WAITING
)
2228 if (!con
->http
.keep_alive
)
2229 cupsdCloseClient(con
);
2232 cupsArrayRemove(ActiveClients
, con
);
2233 cupsdSetBusyState();
2240 * 'cupsdSendCommand()' - Send output from a command via HTTP.
2243 int /* O - 1 on success, 0 on failure */
2245 cupsd_client_t
*con
, /* I - Client connection */
2246 char *command
, /* I - Command to run */
2247 char *options
, /* I - Command-line options */
2248 int root
) /* I - Run as root? */
2250 int fd
; /* Standard input file descriptor */
2255 fd
= open(con
->filename
, O_RDONLY
);
2259 cupsdLogMessage(CUPSD_LOG_ERROR
,
2260 "cupsdSendCommand: %d Unable to open \"%s\" for reading: %s",
2261 con
->http
.fd
, con
->filename
? con
->filename
: "/dev/null",
2266 fcntl(fd
, F_SETFD
, fcntl(fd
, F_GETFD
) | FD_CLOEXEC
);
2271 con
->pipe_pid
= pipe_command(con
, fd
, &(con
->file
), command
, options
, root
);
2276 cupsdLogMessage(CUPSD_LOG_INFO
, "Started \"%s\" (pid=%d)", command
,
2279 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendCommand: %d file=%d",
2280 con
->http
.fd
, con
->file
);
2282 if (con
->pipe_pid
== 0)
2285 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2287 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2289 con
->sent_header
= 0;
2290 con
->file_ready
= 0;
2291 con
->got_fields
= 0;
2299 * 'cupsdSendError()' - Send an error message via HTTP.
2302 int /* O - 1 if successful, 0 otherwise */
2303 cupsdSendError(cupsd_client_t
*con
, /* I - Connection */
2304 http_status_t code
, /* I - Error code */
2305 int auth_type
)/* I - Authentication type */
2309 * Force client to upgrade for authentication if that is how the
2310 * server is configured...
2313 if (code
== HTTP_UNAUTHORIZED
&&
2314 DefaultEncryption
== HTTP_ENCRYPT_REQUIRED
&&
2315 strcasecmp(con
->http
.hostname
, "localhost") &&
2318 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2319 "cupsdSendError: Encryption before authentication!");
2320 code
= HTTP_UPGRADE_REQUIRED
;
2322 #endif /* HAVE_SSL */
2325 * Put the request in the access_log file...
2328 cupsdLogRequest(con
, code
);
2330 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendError: %d code=%d (%s)",
2331 con
->http
.fd
, code
, httpStatus(code
));
2334 * To work around bugs in some proxies, don't use Keep-Alive for some
2337 * Kerberos authentication doesn't work without Keep-Alive, so
2338 * never disable it in that case.
2341 if (code
>= HTTP_BAD_REQUEST
&& con
->http
.auth_type
!= CUPSD_AUTH_NEGOTIATE
)
2342 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
2345 * Send an error message back to the client. If the error code is a
2346 * 400 or 500 series, make sure the message contains some text, too!
2349 if (!cupsdSendHeader(con
, code
, NULL
, auth_type
))
2353 if (code
== HTTP_UPGRADE_REQUIRED
)
2354 if (httpPrintf(HTTP(con
), "Connection: Upgrade\r\n") < 0)
2357 if (httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n") < 0)
2359 #endif /* HAVE_SSL */
2361 if (con
->http
.version
>= HTTP_1_1
&&
2362 con
->http
.keep_alive
== HTTP_KEEPALIVE_OFF
)
2364 if (httpPrintf(HTTP(con
), "Connection: close\r\n") < 0)
2368 if (code
>= HTTP_BAD_REQUEST
)
2371 * Send a human-readable error message.
2374 char message
[4096], /* Message for user */
2375 urltext
[1024], /* URL redirection text */
2376 redirect
[1024]; /* Redirection link */
2377 const char *text
; /* Status-specific text */
2382 if (code
== HTTP_UNAUTHORIZED
)
2383 text
= _cupsLangString(con
->language
,
2384 _("Enter your username and password or the "
2385 "root username and password to access this "
2386 "page. If you are using Kerberos authentication, "
2387 "make sure you have a valid Kerberos ticket."));
2388 else if (code
== HTTP_UPGRADE_REQUIRED
)
2392 snprintf(urltext
, sizeof(urltext
),
2393 _cupsLangString(con
->language
,
2394 _("You must access this page using the URL "
2395 "<A HREF=\"https://%s:%d%s\">"
2396 "https://%s:%d%s</A>.")),
2397 con
->servername
, con
->serverport
, con
->uri
,
2398 con
->servername
, con
->serverport
, con
->uri
);
2400 snprintf(redirect
, sizeof(redirect
),
2401 "<META HTTP-EQUIV=\"Refresh\" "
2402 "CONTENT=\"3;URL=https://%s:%d%s\">\n",
2403 con
->servername
, con
->serverport
, con
->uri
);
2408 snprintf(message
, sizeof(message
),
2409 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" "
2410 "\"http://www.w3.org/TR/REC-html40/loose.dtd\">\n"
2413 "\t<META HTTP-EQUIV=\"Content-Type\" "
2414 "CONTENT=\"text/html; charset=utf-8\">\n"
2415 "\t<TITLE>%d %s</TITLE>\n"
2416 "\t<LINK REL=\"STYLESHEET\" TYPE=\"text/css\" "
2417 "HREF=\"/cups.css\">\n"
2425 code
, httpStatus(code
), redirect
, code
, httpStatus(code
), text
);
2427 if (httpPrintf(HTTP(con
), "Content-Type: text/html; charset=utf-8\r\n") < 0)
2429 if (httpPrintf(HTTP(con
), "Content-Length: %d\r\n",
2430 (int)strlen(message
)) < 0)
2432 if (httpPrintf(HTTP(con
), "\r\n") < 0)
2434 if (httpPrintf(HTTP(con
), "%s", message
) < 0)
2437 else if (httpPrintf(HTTP(con
), "\r\n") < 0)
2440 if (cupsdFlushHeader(con
) < 0)
2443 con
->http
.state
= HTTP_WAITING
;
2450 * 'cupsdSendHeader()' - Send an HTTP request.
2453 int /* O - 1 on success, 0 on failure */
2455 cupsd_client_t
*con
, /* I - Client to send to */
2456 http_status_t code
, /* I - HTTP status code */
2457 char *type
, /* I - MIME type of document */
2458 int auth_type
) /* I - Type of authentication */
2460 char auth_str
[1024]; /* Authorization string */
2462 static char *gss_buf
= NULL
; /* Kerberos auth data buffer */
2463 static int gss_bufsize
= 0; /* Size of Kerberos auth data buffer */
2464 #endif /* HAVE_GSSAPI */
2468 * Send the HTTP status header...
2471 if (code
== HTTP_CONTINUE
)
2474 * 100-continue doesn't send any headers...
2477 return (httpPrintf(HTTP(con
), "HTTP/%d.%d 100 Continue\r\n\r\n",
2478 con
->http
.version
/ 100, con
->http
.version
% 100) > 0);
2481 httpFlushWrite(HTTP(con
));
2483 con
->http
.data_encoding
= HTTP_ENCODE_FIELDS
;
2485 if (httpPrintf(HTTP(con
), "HTTP/%d.%d %d %s\r\n", con
->http
.version
/ 100,
2486 con
->http
.version
% 100, code
, httpStatus(code
)) < 0)
2488 if (httpPrintf(HTTP(con
), "Date: %s\r\n", httpGetDateString(time(NULL
))) < 0)
2491 if (httpPrintf(HTTP(con
), "Server: %s\r\n", ServerHeader
) < 0)
2493 if (con
->http
.keep_alive
&& con
->http
.version
>= HTTP_1_0
)
2495 if (httpPrintf(HTTP(con
), "Connection: Keep-Alive\r\n") < 0)
2497 if (httpPrintf(HTTP(con
), "Keep-Alive: timeout=%d\r\n",
2498 KeepAliveTimeout
) < 0)
2501 if (code
== HTTP_METHOD_NOT_ALLOWED
)
2502 if (httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST\r\n") < 0)
2505 if (code
== HTTP_UNAUTHORIZED
)
2507 if (auth_type
== CUPSD_AUTH_NONE
)
2509 if (!con
->best
|| con
->best
->type
<= CUPSD_AUTH_NONE
)
2510 auth_type
= DefaultAuthType
;
2512 auth_type
= con
->best
->type
;
2517 if (auth_type
== CUPSD_AUTH_BASIC
|| auth_type
== CUPSD_AUTH_BASICDIGEST
)
2518 strlcpy(auth_str
, "Basic realm=\"CUPS\"", sizeof(auth_str
));
2519 else if (auth_type
== CUPSD_AUTH_DIGEST
)
2520 snprintf(auth_str
, sizeof(auth_str
), "Digest realm=\"CUPS\", nonce=\"%s\"",
2521 con
->http
.hostname
);
2523 else if (auth_type
== CUPSD_AUTH_NEGOTIATE
&& con
->gss_output_token
.length
== 0)
2524 strlcpy(auth_str
, "Negotiate", sizeof(auth_str
));
2525 #endif /* HAVE_GSSAPI */
2527 #ifdef HAVE_AUTHORIZATION_H
2528 if (con
->best
&& auth_type
!= CUPSD_AUTH_NEGOTIATE
)
2530 int i
; /* Looping var */
2531 char *auth_key
; /* Auth key buffer */
2532 size_t auth_size
; /* Size of remaining buffer */
2535 auth_key
= auth_str
+ strlen(auth_str
);
2536 auth_size
= sizeof(auth_str
) - (auth_key
- auth_str
);
2538 for (i
= 0; i
< con
->best
->num_names
; i
++)
2540 if (!strncasecmp(con
->best
->names
[i
], "@AUTHKEY(", 9))
2542 snprintf(auth_key
, auth_size
, ", authkey=\"%s\"",
2543 con
->best
->names
[i
] + 9);
2544 /* end parenthesis is stripped in conf.c */
2547 else if (!strcasecmp(con
->best
->names
[i
], "@SYSTEM") &&
2550 snprintf(auth_key
, auth_size
, ", authkey=\"%s\"", SystemGroupAuthKey
);
2555 #endif /* HAVE_AUTHORIZATION_H */
2559 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendHeader: WWW-Authenticate: %s",
2562 if (httpPrintf(HTTP(con
), "WWW-Authenticate: %s\r\n", auth_str
) < 0)
2569 * WWW-Authenticate: Negotiate can be included even for
2570 * non-401 replies...
2573 if (con
->gss_output_token
.length
> 0 && con
->gss_output_token
.length
<= 65536)
2575 OM_uint32 minor_status
; /* Minor status code */
2576 int bufsize
; /* Size of output token buffer */
2579 bufsize
= con
->gss_output_token
.length
* 4 / 3 + 2;
2581 if (bufsize
> gss_bufsize
)
2583 char *buf
; /* New buffer */
2586 bufsize
= (bufsize
+ 1023) & 1023;/* Round up */
2589 buf
= realloc(gss_buf
, bufsize
);
2591 buf
= malloc(bufsize
);
2595 cupsdLogMessage(CUPSD_LOG_ERROR
,
2596 "Unable to allocate %d bytes for Kerberos credentials!",
2602 gss_bufsize
= bufsize
;
2605 httpEncode64_2(gss_buf
, gss_bufsize
,
2606 con
->gss_output_token
.value
,
2607 con
->gss_output_token
.length
);
2608 gss_release_buffer(&minor_status
, &con
->gss_output_token
);
2610 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2611 "cupsdSendHeader: WWW-Authenticate: Negotiate %s", gss_buf
);
2613 if (httpPrintf(HTTP(con
), "WWW-Authenticate: Negotiate %s\r\n",
2617 else if (con
->gss_output_token
.length
> 65536)
2619 cupsdLogMessage(CUPSD_LOG_ERROR
,
2620 "Kerberos credentials larger than 64k (%d)!",
2621 (int)con
->gss_output_token
.length
);
2624 #endif /* HAVE_GSSAPI */
2626 if (con
->language
&& strcmp(con
->language
->language
, "C"))
2628 if (httpPrintf(HTTP(con
), "Content-Language: %s\r\n",
2629 con
->language
->language
) < 0)
2635 if (!strcmp(type
, "text/html"))
2637 if (httpPrintf(HTTP(con
),
2638 "Content-Type: text/html; charset=utf-8\r\n") < 0)
2641 else if (httpPrintf(HTTP(con
), "Content-Type: %s\r\n", type
) < 0)
2650 * 'cupsdUpdateCGI()' - Read status messages from CGI scripts and programs.
2654 cupsdUpdateCGI(void)
2656 char *ptr
, /* Pointer to end of line in buffer */
2657 message
[1024]; /* Pointer to message text */
2658 int loglevel
; /* Log level for message */
2661 while ((ptr
= cupsdStatBufUpdate(CGIStatusBuffer
, &loglevel
,
2662 message
, sizeof(message
))) != NULL
)
2663 if (!strchr(CGIStatusBuffer
->buffer
, '\n'))
2666 if (ptr
== NULL
&& !CGIStatusBuffer
->bufused
)
2669 * Fatal error on pipe - should never happen!
2672 cupsdLogMessage(CUPSD_LOG_CRIT
,
2673 "cupsdUpdateCGI: error reading from CGI error pipe - %s",
2680 * 'cupsdWriteClient()' - Write data to a client as needed.
2684 cupsdWriteClient(cupsd_client_t
*con
) /* I - Client connection */
2686 int bytes
; /* Number of bytes written */
2687 char buf
[16385]; /* Data buffer */
2688 char *bufptr
; /* Pointer into buffer */
2689 ipp_state_t ipp_state
; /* IPP state value */
2693 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2694 "cupsdWriteClient(con=%p) %d response=%p(%d), file=%d "
2695 "pipe_pid=%d state=%d",
2696 con
, con
->http
.fd
, con
->response
,
2697 con
->response
? con
->response
->state
: -1,
2698 con
->file
, con
->pipe_pid
, con
->http
.state
);
2701 if (con
->http
.state
!= HTTP_GET_SEND
&&
2702 con
->http
.state
!= HTTP_POST_SEND
)
2708 * Make sure we select on the CGI output...
2711 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2713 if (!con
->file_ready
)
2716 * Try again later when there is CGI output available...
2719 cupsdRemoveSelect(con
->http
.fd
);
2723 con
->file_ready
= 0;
2726 if (con
->response
&& con
->response
->state
!= IPP_DATA
)
2728 ipp_state
= ippWrite(HTTP(con
), con
->response
);
2729 bytes
= ipp_state
!= IPP_ERROR
&&
2730 (con
->file
>= 0 || ipp_state
!= IPP_DATA
);
2732 else if ((bytes
= read(con
->file
, buf
, sizeof(buf
) - 1)) > 0)
2734 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2735 "cupsdWriteClient: Read %d bytes from file %d...",
2738 if (con
->pipe_pid
&& !con
->got_fields
)
2741 * Inspect the data for Content-Type and other fields.
2746 for (bufptr
= buf
; !con
->got_fields
&& *bufptr
; bufptr
++)
2747 if (*bufptr
== '\n')
2750 * Send line to client...
2753 if (bufptr
> buf
&& bufptr
[-1] == '\r')
2757 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "Script header: %s", buf
);
2759 if (!con
->sent_header
)
2762 * Handle redirection and CGI status codes...
2765 if (!strncasecmp(buf
, "Location:", 9))
2767 cupsdSendHeader(con
, HTTP_SEE_OTHER
, NULL
, CUPSD_AUTH_NONE
);
2768 con
->sent_header
= 2;
2770 if (httpPrintf(HTTP(con
), "Content-Length: 0\r\n") < 0)
2773 else if (!strncasecmp(buf
, "Status:", 7))
2775 cupsdSendError(con
, (http_status_t
)atoi(buf
+ 7), CUPSD_AUTH_NONE
);
2776 con
->sent_header
= 2;
2780 cupsdSendHeader(con
, HTTP_OK
, NULL
, CUPSD_AUTH_NONE
);
2781 con
->sent_header
= 1;
2783 if (con
->http
.version
== HTTP_1_1
)
2785 if (httpPrintf(HTTP(con
), "Transfer-Encoding: chunked\r\n") < 0)
2791 if (strncasecmp(buf
, "Status:", 7))
2792 httpPrintf(HTTP(con
), "%s\r\n", buf
);
2794 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdWriteClient: %d %s",
2801 bytes
-= (bufptr
- buf
);
2802 memmove(buf
, bufptr
, bytes
+ 1);
2806 * See if the line was empty...
2809 if (con
->field_col
== 0)
2811 con
->got_fields
= 1;
2813 if (cupsdFlushHeader(con
) < 0)
2815 cupsdCloseClient(con
);
2819 if (con
->http
.version
== HTTP_1_1
)
2820 con
->http
.data_encoding
= HTTP_ENCODE_CHUNKED
;
2825 else if (*bufptr
!= '\r')
2828 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2829 "cupsdWriteClient: %d bytes=%d, got_fields=%d",
2830 con
->http
.fd
, bytes
, con
->got_fields
);
2832 if (bytes
> 0 && !con
->got_fields
)
2835 * Remaining text needs to go out...
2838 httpPrintf(HTTP(con
), "%s", buf
);
2840 con
->http
.activity
= time(NULL
);
2843 else if (bytes
== 0)
2845 con
->http
.activity
= time(NULL
);
2852 if (httpWrite2(HTTP(con
), buf
, bytes
) < 0)
2854 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2855 "cupsdWriteClient: %d Write of %d bytes failed!",
2856 con
->http
.fd
, bytes
);
2858 cupsdCloseClient(con
);
2862 if (con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
)
2863 httpFlushWrite(HTTP(con
));
2865 con
->bytes
+= bytes
;
2867 if (con
->http
.state
== HTTP_WAITING
)
2874 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdWriteClient: %d bytes < 0",
2877 cupsdLogRequest(con
, HTTP_OK
);
2879 httpFlushWrite(HTTP(con
));
2881 if (con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
&& con
->sent_header
== 1)
2883 if (httpWrite2(HTTP(con
), "", 0) < 0)
2885 cupsdCloseClient(con
);
2890 con
->http
.state
= HTTP_WAITING
;
2892 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
2896 cupsdRemoveSelect(con
->file
);
2899 cupsdEndProcess(con
->pipe_pid
, 0);
2901 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2902 "cupsdWriteClient: %d Closing data file %d.",
2903 con
->http
.fd
, con
->file
);
2912 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2913 "cupsdWriteClient: %d Removing temp file %s",
2914 con
->http
.fd
, con
->filename
);
2915 unlink(con
->filename
);
2916 cupsdClearString(&con
->filename
);
2921 ippDelete(con
->request
);
2922 con
->request
= NULL
;
2927 ippDelete(con
->response
);
2928 con
->response
= NULL
;
2931 cupsdClearString(&con
->command
);
2932 cupsdClearString(&con
->options
);
2933 cupsdClearString(&con
->query_string
);
2935 if (!con
->http
.keep_alive
)
2937 cupsdCloseClient(con
);
2942 con
->http
.activity
= time(NULL
);
2947 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
2950 static int /* O - 1 if modified since */
2952 cupsd_client_t
*con
, /* I - Client connection */
2953 struct stat
*filestats
) /* I - File information */
2955 char *ptr
; /* Pointer into field */
2956 time_t date
; /* Time/date value */
2957 off_t size
; /* Size/length value */
2962 ptr
= con
->http
.fields
[HTTP_FIELD_IF_MODIFIED_SINCE
];
2967 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2968 "check_if_modified: %d If-Modified-Since=\"%s\"",
2971 while (*ptr
!= '\0')
2973 while (isspace(*ptr
) || *ptr
== ';')
2976 if (strncasecmp(ptr
, "length=", 7) == 0)
2979 size
= strtoll(ptr
, NULL
, 10);
2981 while (isdigit(*ptr
))
2984 else if (isalpha(*ptr
))
2986 date
= httpGetDateTime(ptr
);
2987 while (*ptr
!= '\0' && *ptr
!= ';')
2994 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2995 "check_if_modified: %d sizes=" CUPS_LLFMT
","
2996 CUPS_LLFMT
" dates=%d,%d",
2997 con
->http
.fd
, CUPS_LLCAST size
,
2998 CUPS_LLCAST filestats
->st_size
, (int)date
,
2999 (int)filestats
->st_mtime
);
3001 return ((size
!= filestats
->st_size
&& size
!= 0) ||
3002 (date
< filestats
->st_mtime
&& date
!= 0) ||
3003 (size
== 0 && date
== 0));
3008 * 'compare_clients()' - Compare two client connections.
3011 static int /* O - Result of comparison */
3012 compare_clients(cupsd_client_t
*a
, /* I - First client */
3013 cupsd_client_t
*b
, /* I - Second client */
3014 void *data
) /* I - User data (not used) */
3028 * 'data_ready()' - Check whether data is available from a client.
3031 static int /* O - 1 if data is ready, 0 otherwise */
3032 data_ready(cupsd_client_t
*con
) /* I - Client */
3034 if (con
->http
.used
> 0)
3037 else if (con
->http
.tls
)
3040 if (SSL_pending((SSL
*)(con
->http
.tls
)))
3042 # elif defined(HAVE_GNUTLS)
3043 if (gnutls_record_check_pending(((http_tls_t
*)(con
->http
.tls
))->session
))
3045 # elif defined(HAVE_CDSASSL)
3046 size_t bytes
; /* Bytes that are available */
3048 if (!SSLGetBufferedReadSize(((http_tls_t
*)(con
->http
.tls
))->session
,
3049 &bytes
) && bytes
> 0)
3051 # endif /* HAVE_LIBSSL */
3053 #endif /* HAVE_SSL */
3061 * 'encrypt_client()' - Enable encryption for the client...
3064 static int /* O - 1 on success, 0 on error */
3065 encrypt_client(cupsd_client_t
*con
) /* I - Client to encrypt */
3068 SSL_CTX
*context
; /* Context for encryption */
3069 SSL
*conn
; /* Connection for encryption */
3070 BIO
*bio
; /* BIO data */
3071 unsigned long error
; /* Error code */
3075 * Verify that we have a certificate...
3078 if (access(ServerKey
, 0) || access(ServerCertificate
, 0))
3081 * Nope, make a self-signed certificate...
3084 if (!make_certificate(con
))
3089 * Create the SSL context and accept the connection...
3092 context
= SSL_CTX_new(SSLv23_server_method());
3094 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
3095 if (SSLOptions
& CUPSD_SSL_NOEMPTY
)
3096 SSL_CTX_set_options(context
, SSL_OP_DONTS_INSERT_EMPTY_FRAGMENTS
);
3097 SSL_CTX_use_PrivateKey_file(context
, ServerKey
, SSL_FILETYPE_PEM
);
3098 SSL_CTX_use_certificate_chain_file(context
, ServerCertificate
,
3101 bio
= BIO_new(_httpBIOMethods());
3102 BIO_ctrl(bio
, BIO_C_SET_FILE_PTR
, 0, (char *)HTTP(con
));
3104 conn
= SSL_new(context
);
3105 SSL_set_bio(conn
, bio
, bio
);
3107 if (SSL_accept(conn
) != 1)
3109 cupsdLogMessage(CUPSD_LOG_ERROR
,
3110 "encrypt_client: Unable to encrypt connection from %s!",
3111 con
->http
.hostname
);
3113 while ((error
= ERR_get_error()) != 0)
3114 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s",
3115 ERR_error_string(error
, NULL
));
3117 SSL_CTX_free(context
);
3122 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3123 "encrypt_client: %d Connection from %s now encrypted.",
3124 con
->http
.fd
, con
->http
.hostname
);
3126 con
->http
.tls
= conn
;
3129 # elif defined(HAVE_GNUTLS)
3130 http_tls_t
*conn
; /* TLS session object */
3131 int error
; /* Error code */
3132 gnutls_certificate_server_credentials
*credentials
;
3133 /* TLS credentials */
3137 * Verify that we have a certificate...
3140 if (access(ServerKey
, 0) || access(ServerCertificate
, 0))
3143 * Nope, make a self-signed certificate...
3146 if (!make_certificate(con
))
3151 * Create the SSL object and perform the SSL handshake...
3154 conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
));
3159 credentials
= (gnutls_certificate_server_credentials
*)
3160 malloc(sizeof(gnutls_certificate_server_credentials
));
3161 if (credentials
== NULL
)
3163 cupsdLogMessage(CUPSD_LOG_ERROR
,
3164 "encrypt_client: Unable to encrypt connection from %s!",
3165 con
->http
.hostname
);
3166 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s", strerror(errno
));
3172 gnutls_certificate_allocate_credentials(credentials
);
3173 gnutls_certificate_set_x509_key_file(*credentials
, ServerCertificate
,
3174 ServerKey
, GNUTLS_X509_FMT_PEM
);
3176 gnutls_init(&(conn
->session
), GNUTLS_SERVER
);
3177 gnutls_set_default_priority(conn
->session
);
3178 gnutls_credentials_set(conn
->session
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
3179 gnutls_transport_set_ptr(conn
->session
, (gnutls_transport_ptr
)HTTP(con
));
3180 gnutls_transport_set_pull_function(conn
->session
, _httpReadGNUTLS
);
3181 gnutls_transport_set_push_function(conn
->session
, _httpWriteGNUTLS
);
3183 error
= gnutls_handshake(conn
->session
);
3185 if (error
!= GNUTLS_E_SUCCESS
)
3187 cupsdLogMessage(CUPSD_LOG_ERROR
,
3188 "encrypt_client: Unable to encrypt connection from %s!",
3189 con
->http
.hostname
);
3190 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s",
3191 gnutls_strerror(error
));
3193 gnutls_deinit(conn
->session
);
3194 gnutls_certificate_free_credentials(*credentials
);
3200 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3201 "encrypt_client: %d Connection from %s now encrypted.",
3202 con
->http
.fd
, con
->http
.hostname
);
3204 conn
->credentials
= credentials
;
3205 con
->http
.tls
= conn
;
3208 # elif defined(HAVE_CDSASSL)
3209 OSStatus error
; /* Error code */
3210 http_tls_t
*conn
; /* CDSA connection information */
3213 if ((conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
))) == NULL
)
3217 conn
->session
= NULL
;
3218 conn
->certsArray
= get_cdsa_certificate(con
);
3220 if (!conn
->certsArray
)
3223 * No keychain (yet), make a self-signed certificate...
3226 if (make_certificate(con
))
3227 conn
->certsArray
= get_cdsa_certificate(con
);
3230 if (!conn
->certsArray
)
3232 cupsdLogMessage(CUPSD_LOG_ERROR
,
3233 "encrypt_client: Could not find signing key in keychain "
3234 "\"%s\"", ServerCertificate
);
3235 error
= errSSLBadCert
; /* errSSLBadConfiguration is a better choice, but not available on 10.2.x */
3239 error
= SSLNewContext(true, &conn
->session
);
3242 error
= SSLSetIOFuncs(conn
->session
, _httpReadCDSA
, _httpWriteCDSA
);
3245 error
= SSLSetProtocolVersionEnabled(conn
->session
, kSSLProtocol2
, false);
3248 error
= SSLSetConnection(conn
->session
, HTTP(con
));
3251 error
= SSLSetAllowsExpiredCerts(conn
->session
, true);
3254 error
= SSLSetAllowsAnyRoot(conn
->session
, true);
3257 error
= SSLSetCertificate(conn
->session
, conn
->certsArray
);
3262 * Perform SSL/TLS handshake
3265 while ((error
= SSLHandshake(conn
->session
)) == errSSLWouldBlock
)
3271 cupsdLogMessage(CUPSD_LOG_ERROR
,
3272 "encrypt_client: Unable to encrypt connection from %s!",
3273 con
->http
.hostname
);
3275 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s (%d)",
3276 cssmErrorString(error
), (int)error
);
3278 con
->http
.error
= error
;
3279 con
->http
.status
= HTTP_ERROR
;
3282 SSLDisposeContext(conn
->session
);
3284 if (conn
->certsArray
)
3285 CFRelease(conn
->certsArray
);
3292 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3293 "encrypt_client: %d Connection from %s now encrypted.",
3294 con
->http
.fd
, con
->http
.hostname
);
3296 con
->http
.tls
= conn
;
3299 # endif /* HAVE_LIBSSL */
3301 #endif /* HAVE_SSL */
3306 * 'get_cdsa_certificate()' - Get a SSL/TLS certificate from the System keychain.
3309 static CFArrayRef
/* O - Array of certificates */
3310 get_cdsa_certificate(cupsd_client_t
*con
) /* I - Client connection */
3312 OSStatus err
; /* Error info */
3313 SecKeychainRef keychain
; /* Keychain reference */
3314 SecIdentitySearchRef search
; /* Search reference */
3315 SecIdentityRef identity
; /* Identity */
3316 CFArrayRef certificates
= NULL
;
3317 /* Certificate array */
3320 if ((err
= SecKeychainOpen(ServerCertificate
, &keychain
)))
3322 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot open keychain \"%s\", %s",
3323 ServerCertificate
, cssmErrorString(err
));
3327 # if HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY
3329 * Use a policy to search for valid certificates who's common name matches the
3333 SecPolicySearchRef policy_search
; /* Policy search ref */
3334 SecPolicyRef policy
; /* Policy ref */
3335 CSSM_DATA options
; /* Policy options */
3336 CSSM_APPLE_TP_SSL_OPTIONS
3337 ssl_options
; /* SSL Option for hostname */
3340 if (SecPolicySearchCreate(CSSM_CERT_X_509v3
, &CSSMOID_APPLE_TP_SSL
,
3341 NULL
, &policy_search
))
3343 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot create a policy search reference");
3344 CFRelease(keychain
);
3348 if (SecPolicySearchCopyNext(policy_search
, &policy
))
3350 cupsdLogMessage(CUPSD_LOG_ERROR
,
3351 "Cannot find a policy to use for searching");
3352 CFRelease(keychain
);
3353 CFRelease(policy_search
);
3357 memset(&ssl_options
, 0, sizeof(ssl_options
));
3358 ssl_options
.Version
= CSSM_APPLE_TP_SSL_OPTS_VERSION
;
3359 ssl_options
.ServerName
= con
->servername
;
3360 ssl_options
.ServerNameLen
= strlen(con
->servername
);
3362 options
.Data
= (uint8
*)&ssl_options
;
3363 options
.Length
= sizeof(ssl_options
);
3365 if (SecPolicySetValue(policy
, &options
))
3367 cupsdLogMessage(CUPSD_LOG_ERROR
,
3368 "Cannot set policy value to use for searching");
3369 CFRelease(keychain
);
3370 CFRelease(policy_search
);
3374 err
= SecIdentitySearchCreateWithPolicy(policy
, NULL
, CSSM_KEYUSE_SIGN
,
3375 keychain
, FALSE
, &search
);
3378 * Assume there is exactly one SecIdentity in the keychain...
3381 err
= SecIdentitySearchCreate(keychain
, CSSM_KEYUSE_SIGN
, &search
);
3382 # endif /* HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY */
3385 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3386 "Cannot create keychain search reference: %s",
3387 cssmErrorString(err
));
3390 if ((err
= SecIdentitySearchCopyNext(search
, &identity
)))
3392 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3393 "Cannot find signing key in keychain \"%s\", error %d",
3394 ServerCertificate
, (int)err
);
3398 if (CFGetTypeID(identity
) != SecIdentityGetTypeID())
3399 cupsdLogMessage(CUPSD_LOG_ERROR
,
3400 "SecIdentitySearchCopyNext CFTypeID failure!");
3403 if ((certificates
= CFArrayCreate(NULL
, (const void **)&identity
,
3404 1, &kCFTypeArrayCallBacks
)) == NULL
)
3405 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot create certificate array");
3408 CFRelease(identity
);
3414 # if HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY
3416 CFRelease(policy_search
);
3417 # endif /* HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY */
3419 return (certificates
);
3421 #endif /* HAVE_CDSASSL */
3425 * 'get_file()' - Get a filename and state info.
3428 static char * /* O - Real filename */
3429 get_file(cupsd_client_t
*con
, /* I - Client connection */
3430 struct stat
*filestats
, /* O - File information */
3431 char *filename
, /* IO - Filename buffer */
3432 int len
) /* I - Buffer length */
3434 int status
; /* Status of filesystem calls */
3435 char *ptr
; /* Pointer info filename */
3436 int plen
; /* Remaining length after pointer */
3437 char language
[7]; /* Language subdirectory, if any */
3441 * Figure out the real filename...
3446 if (!strncmp(con
->uri
, "/ppd/", 5))
3447 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
);
3448 else if (!strncmp(con
->uri
, "/rss/", 5) && !strchr(con
->uri
+ 5, '/'))
3449 snprintf(filename
, len
, "%s/rss/%s", CacheDir
, con
->uri
+ 5);
3450 else if (!strncmp(con
->uri
, "/admin/conf/", 12))
3451 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
+ 11);
3452 else if (!strncmp(con
->uri
, "/admin/log/", 11))
3454 if (!strncmp(con
->uri
+ 11, "access_log", 10) && AccessLog
[0] == '/')
3455 strlcpy(filename
, AccessLog
, len
);
3456 else if (!strncmp(con
->uri
+ 11, "error_log", 9) && ErrorLog
[0] == '/')
3457 strlcpy(filename
, ErrorLog
, len
);
3458 else if (!strncmp(con
->uri
+ 11, "page_log", 8) && PageLog
[0] == '/')
3459 strlcpy(filename
, PageLog
, len
);
3463 else if (con
->language
)
3465 snprintf(language
, sizeof(language
), "/%s", con
->language
->language
);
3466 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3469 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3471 if ((ptr
= strchr(filename
, '?')) != NULL
)
3475 * Grab the status for this language; if there isn't a language-specific file
3476 * then fallback to the default one...
3479 if ((status
= stat(filename
, filestats
)) != 0 && language
[0] &&
3480 strncmp(con
->uri
, "/ppd/", 5) &&
3481 strncmp(con
->uri
, "/admin/conf/", 12) &&
3482 strncmp(con
->uri
, "/admin/log/", 11))
3485 * Drop the country code...
3489 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3491 if ((ptr
= strchr(filename
, '?')) != NULL
)
3494 if ((status
= stat(filename
, filestats
)) != 0)
3497 * Drop the language prefix and try the root directory...
3501 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3503 if ((ptr
= strchr(filename
, '?')) != NULL
)
3506 status
= stat(filename
, filestats
);
3511 * If we're found a directory, get the index.html file instead...
3514 if (!status
&& S_ISDIR(filestats
->st_mode
))
3517 * Make sure the URI ends with a slash...
3520 if (con
->uri
[strlen(con
->uri
) - 1] != '/')
3521 strlcat(con
->uri
, "/", sizeof(con
->uri
));
3524 * Find the directory index file, trying every language...
3529 if (status
&& language
[0])
3532 * Try a different language subset...
3536 language
[0] = '\0'; /* Strip country code */
3538 language
[0] = '\0'; /* Strip language */
3542 * Look for the index file...
3545 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3547 if ((ptr
= strchr(filename
, '?')) != NULL
)
3550 ptr
= filename
+ strlen(filename
);
3551 plen
= len
- (ptr
- filename
);
3553 strlcpy(ptr
, "index.html", plen
);
3554 status
= stat(filename
, filestats
);
3559 strlcpy(ptr
, "index.class", plen
);
3560 status
= stat(filename
, filestats
);
3562 #endif /* HAVE_JAVA */
3567 strlcpy(ptr
, "index.pl", plen
);
3568 status
= stat(filename
, filestats
);
3570 #endif /* HAVE_PERL */
3575 strlcpy(ptr
, "index.php", plen
);
3576 status
= stat(filename
, filestats
);
3578 #endif /* HAVE_PHP */
3583 strlcpy(ptr
, "index.pyc", plen
);
3584 status
= stat(filename
, filestats
);
3589 strlcpy(ptr
, "index.py", plen
);
3590 status
= stat(filename
, filestats
);
3592 #endif /* HAVE_PYTHON */
3595 while (status
&& language
[0]);
3598 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "get_file: %d filename=%s size=%d",
3599 con
->http
.fd
, filename
,
3600 status
? -1 : (int)filestats
->st_size
);
3603 con
->http
.data_remaining
= (int)filestats
->st_size
;
3613 * 'install_conf_file()' - Install a configuration file.
3616 static http_status_t
/* O - Status */
3617 install_conf_file(cupsd_client_t
*con
) /* I - Connection */
3619 cups_file_t
*in
, /* Input file */
3620 *out
; /* Output file */
3621 char buffer
[1024]; /* Copy buffer */
3622 int bytes
; /* Number of bytes */
3623 char conffile
[1024], /* Configuration filename */
3624 newfile
[1024], /* New config filename */
3625 oldfile
[1024]; /* Old config filename */
3626 struct stat confinfo
; /* Config file info */
3630 * First construct the filenames...
3633 snprintf(conffile
, sizeof(conffile
), "%s%s", ServerRoot
, con
->uri
+ 11);
3634 snprintf(newfile
, sizeof(newfile
), "%s%s.N", ServerRoot
, con
->uri
+ 11);
3635 snprintf(oldfile
, sizeof(oldfile
), "%s%s.O", ServerRoot
, con
->uri
+ 11);
3637 cupsdLogMessage(CUPSD_LOG_INFO
, "Installing config file \"%s\"...", conffile
);
3640 * Get the owner, group, and permissions of the configuration file.
3641 * If it doesn't exist, assign it to the User and Group in the
3642 * cupsd.conf file with mode 0640 permissions.
3645 if (stat(conffile
, &confinfo
))
3647 confinfo
.st_uid
= User
;
3648 confinfo
.st_gid
= Group
;
3649 confinfo
.st_mode
= ConfigFilePerm
;
3653 * Open the request file and new config file...
3656 if ((in
= cupsFileOpen(con
->filename
, "rb")) == NULL
)
3658 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open request file \"%s\" - %s",
3659 con
->filename
, strerror(errno
));
3660 return (HTTP_SERVER_ERROR
);
3663 if ((out
= cupsFileOpen(newfile
, "wb")) == NULL
)
3666 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open config file \"%s\" - %s",
3667 newfile
, strerror(errno
));
3668 return (HTTP_SERVER_ERROR
);
3671 fchmod(cupsFileNumber(out
), confinfo
.st_mode
);
3672 fchown(cupsFileNumber(out
), confinfo
.st_uid
, confinfo
.st_gid
);
3675 * Copy from the request to the new config file...
3678 while ((bytes
= cupsFileRead(in
, buffer
, sizeof(buffer
))) > 0)
3679 if (cupsFileWrite(out
, buffer
, bytes
) < bytes
)
3681 cupsdLogMessage(CUPSD_LOG_ERROR
,
3682 "Unable to copy to config file \"%s\" - %s",
3683 newfile
, strerror(errno
));
3689 return (HTTP_SERVER_ERROR
);
3693 * Close the files...
3697 if (cupsFileClose(out
))
3699 cupsdLogMessage(CUPSD_LOG_ERROR
,
3700 "Error file closing config file \"%s\" - %s",
3701 newfile
, strerror(errno
));
3705 return (HTTP_SERVER_ERROR
);
3709 * Remove the request file...
3712 unlink(con
->filename
);
3713 cupsdClearString(&con
->filename
);
3716 * Unlink the old backup, rename the current config file to the backup
3717 * filename, and rename the new config file to the config file name...
3720 if (unlink(oldfile
))
3721 if (errno
!= ENOENT
)
3723 cupsdLogMessage(CUPSD_LOG_ERROR
,
3724 "Unable to remove backup config file \"%s\" - %s",
3725 oldfile
, strerror(errno
));
3729 return (HTTP_SERVER_ERROR
);
3732 if (rename(conffile
, oldfile
))
3733 if (errno
!= ENOENT
)
3735 cupsdLogMessage(CUPSD_LOG_ERROR
,
3736 "Unable to rename old config file \"%s\" - %s",
3737 conffile
, strerror(errno
));
3741 return (HTTP_SERVER_ERROR
);
3744 if (rename(newfile
, conffile
))
3746 cupsdLogMessage(CUPSD_LOG_ERROR
,
3747 "Unable to rename new config file \"%s\" - %s",
3748 newfile
, strerror(errno
));
3750 rename(oldfile
, conffile
);
3753 return (HTTP_SERVER_ERROR
);
3757 * If the cupsd.conf file was updated, set the NeedReload flag...
3760 if (!strcmp(con
->uri
, "/admin/conf/cupsd.conf"))
3761 NeedReload
= RELOAD_CUPSD
;
3763 NeedReload
= RELOAD_ALL
;
3765 ReloadTime
= time(NULL
);
3768 * Return that the file was created successfully...
3771 return (HTTP_CREATED
);
3776 * 'is_cgi()' - Is the resource a CGI script/program?
3779 static int /* O - 1 = CGI, 0 = file */
3780 is_cgi(cupsd_client_t
*con
, /* I - Client connection */
3781 const char *filename
, /* I - Real filename */
3782 struct stat
*filestats
, /* I - File information */
3783 mime_type_t
*type
) /* I - MIME type */
3785 const char *options
; /* Options on URL */
3788 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3789 "is_cgi(con=%p, filename=\"%s\", filestats=%p, type=%s/%s)",
3790 con
, filename
, filestats
, type
? type
->super
: "unknown",
3791 type
? type
->type
: "unknown");
3794 * Get the options, if any...
3797 if ((options
= strchr(con
->uri
, '?')) != NULL
)
3800 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", options
);
3804 * Check for known types...
3807 if (!type
|| strcasecmp(type
->super
, "application"))
3809 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "is_cgi: Returning 0...");
3813 if (!strcasecmp(type
->type
, "x-httpd-cgi") &&
3814 (filestats
->st_mode
& 0111))
3817 * "application/x-httpd-cgi" is a CGI script.
3820 cupsdSetString(&con
->command
, filename
);
3823 cupsdSetStringf(&con
->options
, " %s", options
);
3825 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3826 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3827 con
->command
, con
->options
);
3832 else if (!strcasecmp(type
->type
, "x-httpd-java"))
3835 * "application/x-httpd-java" is a Java servlet.
3838 cupsdSetString(&con
->command
, CUPS_JAVA
);
3841 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3843 cupsdSetStringf(&con
->options
, " %s", filename
);
3845 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3846 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3847 con
->command
, con
->options
);
3851 #endif /* HAVE_JAVA */
3853 else if (!strcasecmp(type
->type
, "x-httpd-perl"))
3856 * "application/x-httpd-perl" is a Perl page.
3859 cupsdSetString(&con
->command
, CUPS_PERL
);
3862 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3864 cupsdSetStringf(&con
->options
, " %s", filename
);
3866 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3867 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3868 con
->command
, con
->options
);
3872 #endif /* HAVE_PERL */
3874 else if (!strcasecmp(type
->type
, "x-httpd-php"))
3877 * "application/x-httpd-php" is a PHP page.
3880 cupsdSetString(&con
->command
, CUPS_PHP
);
3883 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3885 cupsdSetStringf(&con
->options
, " %s", filename
);
3887 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3888 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3889 con
->command
, con
->options
);
3893 #endif /* HAVE_PHP */
3895 else if (!strcasecmp(type
->type
, "x-httpd-python"))
3898 * "application/x-httpd-python" is a Python page.
3901 cupsdSetString(&con
->command
, CUPS_PYTHON
);
3904 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3906 cupsdSetStringf(&con
->options
, " %s", filename
);
3908 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3909 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3910 con
->command
, con
->options
);
3914 #endif /* HAVE_PYTHON */
3916 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "is_cgi: Returning 0...");
3923 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
3926 static int /* O - 0 if relative, 1 if absolute */
3927 is_path_absolute(const char *path
) /* I - Input path */
3930 * Check for a leading slash...
3937 * Check for "/.." in the path...
3940 while ((path
= strstr(path
, "/..")) != NULL
)
3942 if (!path
[3] || path
[3] == '/')
3949 * If we haven't found any relative paths, return 1 indicating an
3959 * 'make_certificate()' - Make a self-signed SSL/TLS certificate.
3962 static int /* O - 1 on success, 0 on failure */
3963 make_certificate(cupsd_client_t
*con
) /* I - Client connection */
3965 #if defined(HAVE_LIBSSL) && defined(HAVE_WAITPID)
3966 int pid
, /* Process ID of command */
3967 status
; /* Status of command */
3968 char command
[1024], /* Command */
3969 *argv
[12], /* Command-line arguments */
3970 *envp
[MAX_ENV
+ 1], /* Environment variables */
3971 home
[1024], /* HOME environment variable */
3972 infofile
[1024], /* Type-in information for cert */
3973 seedfile
[1024]; /* Random number seed file */
3974 int envc
, /* Number of environment variables */
3975 bytes
; /* Bytes written */
3976 cups_file_t
*fp
; /* Seed/info file */
3977 int infofd
; /* Info file descriptor */
3981 * Run the "openssl" command to seed the random number generator and
3982 * generate a self-signed certificate that is good for 10 years:
3984 * openssl rand -rand seedfile 1
3986 * openssl req -new -x509 -keyout ServerKey \
3987 * -out ServerCertificate -days 3650 -nodes
3989 * The seeding step is crucial in ensuring that the openssl command
3990 * does not block on systems without sufficient entropy...
3993 if (!cupsFileFind("openssl", getenv("PATH"), 1, command
, sizeof(command
)))
3995 cupsdLogMessage(CUPSD_LOG_ERROR
,
3996 "No SSL certificate and openssl command not found!");
4000 if (access("/dev/urandom", 0))
4003 * If the system doesn't provide /dev/urandom, then any random source
4004 * will probably be blocking-style, so generate some random data to
4005 * use as a seed for the certificate. Note that we have already
4006 * seeded the random number generator in cupsdInitCerts()...
4009 cupsdLogMessage(CUPSD_LOG_INFO
,
4010 "Seeding the random number generator...");
4012 snprintf(home
, sizeof(home
), "HOME=%s", TempDir
);
4015 * Write the seed file...
4018 if ((fp
= cupsTempFile2(seedfile
, sizeof(seedfile
))) == NULL
)
4020 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to create seed file %s - %s",
4021 seedfile
, strerror(errno
));
4025 for (bytes
= 0; bytes
< 262144; bytes
++)
4026 cupsFilePutChar(fp
, random());
4031 * Run the openssl command to seed its random number generator...
4034 argv
[0] = "openssl";
4041 envc
= cupsdLoadEnv(envp
, MAX_ENV
);
4042 envp
[envc
++] = home
;
4045 if (!cupsdStartProcess(command
, argv
, envp
, -1, -1, -1, -1, -1, 1, NULL
,
4052 while (waitpid(pid
, &status
, 0) < 0)
4059 cupsdFinishProcess(pid
, command
, sizeof(command
));
4062 * Remove the seed file, as it is no longer needed...
4069 if (WIFEXITED(status
))
4070 cupsdLogMessage(CUPSD_LOG_ERROR
,
4071 "Unable to seed random number generator - "
4072 "the openssl command stopped with status %d!",
4073 WEXITSTATUS(status
));
4075 cupsdLogMessage(CUPSD_LOG_ERROR
,
4076 "Unable to seed random number generator - "
4077 "the openssl command crashed on signal %d!",
4085 * Create a file with the certificate information fields...
4087 * Note: This assumes that the default questions are asked by the openssl
4091 if ((fp
= cupsTempFile2(infofile
, sizeof(infofile
))) == NULL
)
4093 cupsdLogMessage(CUPSD_LOG_ERROR
,
4094 "Unable to create certificate information file %s - %s",
4095 infofile
, strerror(errno
));
4099 cupsFilePrintf(fp
, ".\n.\n.\n%s\n.\n%s\n%s\n",
4100 ServerName
, ServerName
, ServerAdmin
);
4103 cupsdLogMessage(CUPSD_LOG_INFO
,
4104 "Generating SSL server key and certificate...");
4106 argv
[0] = "openssl";
4110 argv
[4] = "-keyout";
4111 argv
[5] = ServerKey
;
4113 argv
[7] = ServerCertificate
;
4116 argv
[10] = "-nodes";
4119 cupsdLoadEnv(envp
, MAX_ENV
);
4121 infofd
= open(infofile
, O_RDONLY
);
4123 if (!cupsdStartProcess(command
, argv
, envp
, infofd
, -1, -1, -1, -1, 1, NULL
,
4134 while (waitpid(pid
, &status
, 0) < 0)
4141 cupsdFinishProcess(pid
, command
, sizeof(command
));
4145 if (WIFEXITED(status
))
4146 cupsdLogMessage(CUPSD_LOG_ERROR
,
4147 "Unable to create SSL server key and certificate - "
4148 "the openssl command stopped with status %d!",
4149 WEXITSTATUS(status
));
4151 cupsdLogMessage(CUPSD_LOG_ERROR
,
4152 "Unable to create SSL server key and certificate - "
4153 "the openssl command crashed on signal %d!",
4158 cupsdLogMessage(CUPSD_LOG_INFO
, "Created SSL server key file \"%s\"...",
4160 cupsdLogMessage(CUPSD_LOG_INFO
,
4161 "Created SSL server certificate file \"%s\"...",
4167 #elif defined(HAVE_GNUTLS)
4168 gnutls_x509_crt crt
; /* Self-signed certificate */
4169 gnutls_x509_privkey key
; /* Encryption key */
4170 cups_lang_t
*language
; /* Default language info */
4171 cups_file_t
*fp
; /* Key/cert file */
4172 unsigned char buffer
[8192]; /* Buffer for x509 data */
4173 size_t bytes
; /* Number of bytes of data */
4174 unsigned char serial
[4]; /* Serial number buffer */
4175 time_t curtime
; /* Current time */
4176 int result
; /* Result of GNU TLS calls */
4180 * Create the encryption key...
4183 cupsdLogMessage(CUPSD_LOG_INFO
, "Generating SSL server key...");
4185 gnutls_x509_privkey_init(&key
);
4186 gnutls_x509_privkey_generate(key
, GNUTLS_PK_RSA
, 2048, 0);
4192 bytes
= sizeof(buffer
);
4194 if ((result
= gnutls_x509_privkey_export(key
, GNUTLS_X509_FMT_PEM
,
4195 buffer
, &bytes
)) < 0)
4197 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to export SSL server key - %s",
4198 gnutls_strerror(result
));
4199 gnutls_x509_privkey_deinit(key
);
4202 else if ((fp
= cupsFileOpen(ServerKey
, "w")) != NULL
)
4204 cupsFileWrite(fp
, (char *)buffer
, bytes
);
4207 cupsdLogMessage(CUPSD_LOG_INFO
, "Created SSL server key file \"%s\"...",
4212 cupsdLogMessage(CUPSD_LOG_ERROR
,
4213 "Unable to create SSL server key file \"%s\" - %s",
4214 ServerKey
, strerror(errno
));
4215 gnutls_x509_privkey_deinit(key
);
4220 * Create the self-signed certificate...
4223 cupsdLogMessage(CUPSD_LOG_INFO
, "Generating self-signed SSL certificate...");
4225 language
= cupsLangDefault();
4226 curtime
= time(NULL
);
4227 serial
[0] = curtime
>> 24;
4228 serial
[1] = curtime
>> 16;
4229 serial
[2] = curtime
>> 8;
4230 serial
[3] = curtime
;
4232 gnutls_x509_crt_init(&crt
);
4233 if (strlen(language
->language
) == 5)
4234 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
4235 language
->language
+ 3, 2);
4237 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
4239 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COMMON_NAME
, 0,
4240 ServerName
, strlen(ServerName
));
4241 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATION_NAME
, 0,
4242 ServerName
, strlen(ServerName
));
4243 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATIONAL_UNIT_NAME
,
4245 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_STATE_OR_PROVINCE_NAME
, 0,
4247 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_LOCALITY_NAME
, 0,
4249 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_PKCS9_EMAIL
, 0,
4250 ServerAdmin
, strlen(ServerAdmin
));
4251 gnutls_x509_crt_set_key(crt
, key
);
4252 gnutls_x509_crt_set_serial(crt
, serial
, sizeof(serial
));
4253 gnutls_x509_crt_set_activation_time(crt
, curtime
);
4254 gnutls_x509_crt_set_expiration_time(crt
, curtime
+ 10 * 365 * 86400);
4255 gnutls_x509_crt_set_ca_status(crt
, 0);
4256 gnutls_x509_crt_set_subject_alternative_name(crt
, GNUTLS_SAN_DNSNAME
,
4258 gnutls_x509_crt_set_key_purpose_oid(crt
, GNUTLS_KP_TLS_WWW_SERVER
, 0);
4259 gnutls_x509_crt_set_key_usage(crt
, GNUTLS_KEY_KEY_ENCIPHERMENT
);
4260 gnutls_x509_crt_set_version(crt
, 3);
4262 bytes
= sizeof(buffer
);
4263 if (gnutls_x509_crt_get_key_id(crt
, 0, buffer
, &bytes
) >= 0)
4264 gnutls_x509_crt_set_subject_key_id(crt
, buffer
, bytes
);
4266 gnutls_x509_crt_sign(crt
, crt
, key
);
4272 bytes
= sizeof(buffer
);
4273 if ((result
= gnutls_x509_crt_export(crt
, GNUTLS_X509_FMT_PEM
,
4274 buffer
, &bytes
)) < 0)
4275 cupsdLogMessage(CUPSD_LOG_ERROR
,
4276 "Unable to export SSL server certificate - %s",
4277 gnutls_strerror(result
));
4278 else if ((fp
= cupsFileOpen(ServerCertificate
, "w")) != NULL
)
4280 cupsFileWrite(fp
, (char *)buffer
, bytes
);
4283 cupsdLogMessage(CUPSD_LOG_INFO
,
4284 "Created SSL server certificate file \"%s\"...",
4288 cupsdLogMessage(CUPSD_LOG_ERROR
,
4289 "Unable to create SSL server certificate file \"%s\" - %s",
4290 ServerCertificate
, strerror(errno
));
4296 gnutls_x509_crt_deinit(crt
);
4297 gnutls_x509_privkey_deinit(key
);
4301 #elif defined(HAVE_CDSASSL) && defined(HAVE_WAITPID)
4302 int pid
, /* Process ID of command */
4303 status
; /* Status of command */
4304 char command
[1024], /* Command */
4305 *argv
[4], /* Command-line arguments */
4306 *envp
[MAX_ENV
+ 1], /* Environment variables */
4307 keychain
[1024], /* Keychain argument */
4308 infofile
[1024]; /* Type-in information for cert */
4309 cups_file_t
*fp
; /* Seed/info file */
4310 int infofd
; /* Info file descriptor */
4314 * Run the "certtool" command to generate a self-signed certificate...
4317 if (!cupsFileFind("certtool", getenv("PATH"), 1, command
, sizeof(command
)))
4319 cupsdLogMessage(CUPSD_LOG_ERROR
,
4320 "No SSL certificate and certtool command not found!");
4325 * Create a file with the certificate information fields...
4327 * Note: This assumes that the default questions are asked by the certtool
4331 if ((fp
= cupsTempFile2(infofile
, sizeof(infofile
))) == NULL
)
4333 cupsdLogMessage(CUPSD_LOG_ERROR
,
4334 "Unable to create certificate information file %s - %s",
4335 infofile
, strerror(errno
));
4339 cupsFilePrintf(fp
, "%s\nr\n\ny\nb\ns\ny\n%s\n\n\n\n\n%s\ny\n",
4340 con
->servername
, con
->servername
, ServerAdmin
);
4343 cupsdLogMessage(CUPSD_LOG_INFO
,
4344 "Generating SSL server key and certificate...");
4346 snprintf(keychain
, sizeof(keychain
), "k=%s", ServerCertificate
);
4348 argv
[0] = "certtool";
4353 cupsdLoadEnv(envp
, MAX_ENV
);
4355 infofd
= open(infofile
, O_RDONLY
);
4357 if (!cupsdStartProcess(command
, argv
, envp
, infofd
, -1, -1, -1, -1, 1, NULL
,
4368 while (waitpid(pid
, &status
, 0) < 0)
4375 cupsdFinishProcess(pid
, command
, sizeof(command
));
4379 if (WIFEXITED(status
))
4380 cupsdLogMessage(CUPSD_LOG_ERROR
,
4381 "Unable to create SSL server key and certificate - "
4382 "the certtool command stopped with status %d!",
4383 WEXITSTATUS(status
));
4385 cupsdLogMessage(CUPSD_LOG_ERROR
,
4386 "Unable to create SSL server key and certificate - "
4387 "the certtool command crashed on signal %d!",
4392 cupsdLogMessage(CUPSD_LOG_INFO
,
4393 "Created SSL server certificate file \"%s\"...",
4401 #endif /* HAVE_LIBSSL && HAVE_WAITPID */
4403 #endif /* HAVE_SSL */
4407 * 'pipe_command()' - Pipe the output of a command to the remote client.
4410 static int /* O - Process ID */
4411 pipe_command(cupsd_client_t
*con
, /* I - Client connection */
4412 int infile
, /* I - Standard input for command */
4413 int *outfile
, /* O - Standard output for command */
4414 char *command
, /* I - Command to run */
4415 char *options
, /* I - Options for command */
4416 int root
) /* I - Run as root? */
4418 int i
; /* Looping var */
4419 int pid
; /* Process ID */
4420 char *commptr
, /* Command string pointer */
4421 commch
; /* Command string character */
4422 char *uriptr
; /* URI string pointer */
4423 int fds
[2]; /* Pipe FDs */
4424 int argc
; /* Number of arguments */
4425 int envc
; /* Number of environment variables */
4426 char argbuf
[10240], /* Argument buffer */
4427 *argv
[100], /* Argument strings */
4428 *envp
[MAX_ENV
+ 20]; /* Environment variables */
4429 char auth_type
[256], /* CUPSD_AUTH_TYPE environment variable */
4430 content_length
[1024], /* CONTENT_LENGTH environment variable */
4431 content_type
[1024], /* CONTENT_TYPE environment variable */
4432 http_cookie
[32768], /* HTTP_COOKIE environment variable */
4433 http_referer
[1024], /* HTTP_REFERER environment variable */
4434 http_user_agent
[1024], /* HTTP_USER_AGENT environment variable */
4435 lang
[1024], /* LANG environment variable */
4436 path_info
[1024], /* PATH_INFO environment variable */
4437 remote_addr
[1024], /* REMOTE_ADDR environment variable */
4438 remote_host
[1024], /* REMOTE_HOST environment variable */
4439 remote_user
[1024], /* REMOTE_USER environment variable */
4440 script_filename
[1024], /* SCRIPT_FILENAME environment variable */
4441 script_name
[1024], /* SCRIPT_NAME environment variable */
4442 server_name
[1024], /* SERVER_NAME environment variable */
4443 server_port
[1024]; /* SERVER_PORT environment variable */
4444 ipp_attribute_t
*attr
; /* attributes-natural-language attribute */
4446 krb5_ccache ccache
= NULL
; /* Kerberos credentials */
4447 char krb5ccname
[1024]; /* KRB5CCNAME environment variable */
4448 #endif /* HAVE_GSSAPI */
4452 * Parse a copy of the options string, which is of the form:
4454 * argument+argument+argument
4455 * ?argument+argument+argument
4456 * param=value¶m=value
4457 * ?param=value¶m=value
4458 * /name?argument+argument+argument
4459 * /name?param=value¶m=value
4461 * If the string contains an "=" character after the initial name,
4462 * then we treat it as a HTTP GET form request and make a copy of
4463 * the remaining string for the environment variable.
4465 * The string is always parsed out as command-line arguments, to
4466 * be consistent with Apache...
4469 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4470 "pipe_command: command=\"%s\", options=\"%s\"",
4471 command
, options
? options
: "(null)");
4476 strlcpy(argbuf
, options
, sizeof(argbuf
));
4480 if (argbuf
[0] == '/')
4483 * Found some trailing path information, set PATH_INFO...
4486 if ((commptr
= strchr(argbuf
, '?')) == NULL
)
4487 commptr
= argbuf
+ strlen(argbuf
);
4491 snprintf(path_info
, sizeof(path_info
), "PATH_INFO=%s", argbuf
);
4497 path_info
[0] = '\0';
4499 if (*commptr
== ' ')
4503 if (*commptr
== '?' && con
->operation
== HTTP_GET
&& !con
->query_string
)
4506 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", commptr
);
4513 argv
[argc
++] = commptr
;
4515 for (; *commptr
&& argc
< 99; commptr
++)
4518 * Break arguments whenever we see a + or space...
4521 if (*commptr
== ' ' || *commptr
== '+')
4523 while (*commptr
== ' ' || *commptr
== '+')
4527 * If we don't have a blank string, save it as another argument...
4532 argv
[argc
] = commptr
;
4538 else if (*commptr
== '%' && isxdigit(commptr
[1] & 255) &&
4539 isxdigit(commptr
[2] & 255))
4542 * Convert the %xx notation to the individual character.
4545 if (commptr
[1] >= '0' && commptr
[1] <= '9')
4546 *commptr
= (commptr
[1] - '0') << 4;
4548 *commptr
= (tolower(commptr
[1]) - 'a' + 10) << 4;
4550 if (commptr
[2] >= '0' && commptr
[2] <= '9')
4551 *commptr
|= commptr
[2] - '0';
4553 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
4555 _cups_strcpy(commptr
+ 1, commptr
+ 3);
4558 * Check for a %00 and break if that is the case...
4570 * Setup the environment variables as needed...
4573 if (con
->username
[0])
4575 snprintf(auth_type
, sizeof(auth_type
), "CUPSD_AUTH_TYPE=%s",
4576 httpGetField(HTTP(con
), HTTP_FIELD_AUTHORIZATION
));
4578 if ((uriptr
= strchr(auth_type
+ 10, ' ')) != NULL
)
4582 auth_type
[0] = '\0';
4585 (attr
= ippFindAttribute(con
->request
, "attributes-natural-language",
4586 IPP_TAG_LANGUAGE
)) != NULL
)
4588 switch (strlen(attr
->values
[0].string
.text
))
4592 * This is an unknown or badly formatted language code; use
4593 * the POSIX locale...
4596 strcpy(lang
, "LANG=C");
4601 * Just the language code (ll)...
4604 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8",
4605 attr
->values
[0].string
.text
);
4610 * Language and country code (ll-cc)...
4613 snprintf(lang
, sizeof(lang
), "LANG=%c%c_%c%c.UTF8",
4614 attr
->values
[0].string
.text
[0],
4615 attr
->values
[0].string
.text
[1],
4616 toupper(attr
->values
[0].string
.text
[3] & 255),
4617 toupper(attr
->values
[0].string
.text
[4] & 255));
4621 else if (con
->language
)
4622 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8", con
->language
->language
);
4624 strcpy(lang
, "LANG=C");
4626 strcpy(remote_addr
, "REMOTE_ADDR=");
4627 httpAddrString(con
->http
.hostaddr
, remote_addr
+ 12,
4628 sizeof(remote_addr
) - 12);
4630 snprintf(remote_host
, sizeof(remote_host
), "REMOTE_HOST=%s",
4631 con
->http
.hostname
);
4633 snprintf(script_name
, sizeof(script_name
), "SCRIPT_NAME=%s", con
->uri
);
4634 if ((uriptr
= strchr(script_name
, '?')) != NULL
)
4637 snprintf(script_filename
, sizeof(script_filename
), "SCRIPT_FILENAME=%s%s",
4638 DocumentRoot
, script_name
+ 12);
4640 sprintf(server_port
, "SERVER_PORT=%d", con
->serverport
);
4642 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
4645 envc
= cupsdLoadEnv(envp
, (int)(sizeof(envp
) / sizeof(envp
[0])));
4648 envp
[envc
++] = auth_type
;
4650 envp
[envc
++] = lang
;
4651 envp
[envc
++] = "REDIRECT_STATUS=1";
4652 envp
[envc
++] = "GATEWAY_INTERFACE=CGI/1.1";
4653 envp
[envc
++] = server_name
;
4654 envp
[envc
++] = server_port
;
4655 envp
[envc
++] = remote_addr
;
4656 envp
[envc
++] = remote_host
;
4657 envp
[envc
++] = script_name
;
4658 envp
[envc
++] = script_filename
;
4661 envp
[envc
++] = path_info
;
4663 if (con
->username
[0])
4665 snprintf(remote_user
, sizeof(remote_user
), "REMOTE_USER=%s", con
->username
);
4667 envp
[envc
++] = remote_user
;
4670 * Save Kerberos credentials, if any...
4674 if (con
->gss_have_creds
)
4676 # if !defined(HAVE_KRB5_CC_NEW_UNIQUE) && !defined(HAVE_HEIMDAL)
4677 cupsdLogMessage(CUPSD_LOG_INFO
,
4678 "Sorry, your version of Kerberos does not support "
4679 "delegated credentials!");
4682 krb5_error_code error
; /* Kerberos error code */
4683 OM_uint32 major_status
, /* Major status code */
4684 minor_status
; /* Minor status code */
4685 krb5_principal principal
; /* Kerberos principal */
4690 * If the weak-linked GSSAPI/Kerberos library is not present, don't try
4694 if (krb5_init_context
!= NULL
)
4696 # endif /* __APPLE__ */
4698 if (!KerberosInitialized
)
4701 * Setup a Kerberos context for the scheduler to use...
4704 KerberosInitialized
= 1;
4706 if (krb5_init_context(&KerberosContext
))
4708 KerberosContext
= NULL
;
4710 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to initialize Kerberos context");
4715 * We MUST create a file-based cache because memory-based caches are
4716 * only valid for the current process/address space.
4718 * Due to various bugs/features in different versions of Kerberos, we
4719 * need either the krb5_cc_new_unique() function or Heimdal's version
4720 * of krb5_cc_gen_new() to create a new FILE: credential cache that
4721 * can be passed to the backend. These functions create a temporary
4722 * file (typically in /tmp) containing the cached credentials, which
4723 * are removed when we have successfully printed a job.
4726 if (KerberosContext
)
4728 # ifdef HAVE_KRB5_CC_NEW_UNIQUE
4729 if ((error
= krb5_cc_new_unique(KerberosContext
, "FILE", NULL
,
4731 # else /* HAVE_HEIMDAL */
4732 if ((error
= krb5_cc_gen_new(KerberosContext
, &krb5_fcc_ops
,
4734 # endif /* HAVE_KRB5_CC_NEW_UNIQUE */
4736 cupsdLogMessage(CUPSD_LOG_ERROR
,
4737 "Unable to create new credentials cache (%d/%s)",
4738 error
, strerror(errno
));
4741 else if ((error
= krb5_parse_name(KerberosContext
, con
->username
,
4744 cupsdLogMessage(CUPSD_LOG_ERROR
,
4745 "Unable to parse kerberos username (%d/%s)", error
,
4747 krb5_cc_destroy(KerberosContext
, ccache
);
4750 else if ((error
= krb5_cc_initialize(KerberosContext
, ccache
,
4753 cupsdLogMessage(CUPSD_LOG_ERROR
,
4754 "Unable to initialize credentials cache (%d/%s)", error
,
4756 krb5_cc_destroy(KerberosContext
, ccache
);
4757 krb5_free_principal(KerberosContext
, principal
);
4762 krb5_free_principal(KerberosContext
, principal
);
4765 * Copy the user's credentials to the new cache file...
4768 major_status
= gss_krb5_copy_ccache(&minor_status
,
4769 con
->gss_delegated_cred
, ccache
);
4771 if (GSS_ERROR(major_status
))
4773 cupsdLogGSSMessage(CUPSD_LOG_ERROR
, major_status
, minor_status
,
4774 "Unable to import client credentials cache");
4775 krb5_cc_destroy(KerberosContext
, ccache
);
4781 * Add the KRB5CCNAME environment variable to the job so that the
4782 * backend can use the credentials when printing.
4785 snprintf(krb5ccname
, sizeof(krb5ccname
), "KRB5CCNAME=FILE:%s",
4786 krb5_cc_get_name(KerberosContext
, ccache
));
4787 envp
[envc
++] = krb5ccname
;
4790 chown(krb5_cc_get_name(KerberosContext
, ccache
), User
, Group
);
4796 # endif /* __APPLE__ */
4797 # endif /* HAVE_KRB5_CC_NEW_UNIQUE || HAVE_HEIMDAL */
4799 #endif /* HAVE_GSSAPI */
4802 if (con
->http
.version
== HTTP_1_1
)
4803 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.1";
4804 else if (con
->http
.version
== HTTP_1_0
)
4805 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.0";
4807 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/0.9";
4809 if (con
->http
.cookie
)
4811 snprintf(http_cookie
, sizeof(http_cookie
), "HTTP_COOKIE=%s",
4813 envp
[envc
++] = http_cookie
;
4816 if (con
->http
.fields
[HTTP_FIELD_USER_AGENT
][0])
4818 snprintf(http_user_agent
, sizeof(http_user_agent
), "HTTP_USER_AGENT=%s",
4819 con
->http
.fields
[HTTP_FIELD_USER_AGENT
]);
4820 envp
[envc
++] = http_user_agent
;
4823 if (con
->http
.fields
[HTTP_FIELD_REFERER
][0])
4825 snprintf(http_referer
, sizeof(http_referer
), "HTTP_REFERER=%s",
4826 con
->http
.fields
[HTTP_FIELD_REFERER
]);
4827 envp
[envc
++] = http_referer
;
4830 if (con
->operation
== HTTP_GET
)
4832 envp
[envc
++] = "REQUEST_METHOD=GET";
4834 if (con
->query_string
)
4837 * Add GET form variables after ?...
4840 envp
[envc
++] = con
->query_string
;
4843 envp
[envc
++] = "QUERY_STRING=";
4847 sprintf(content_length
, "CONTENT_LENGTH=" CUPS_LLFMT
,
4848 CUPS_LLCAST con
->bytes
);
4849 snprintf(content_type
, sizeof(content_type
), "CONTENT_TYPE=%s",
4850 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
4852 envp
[envc
++] = "REQUEST_METHOD=POST";
4853 envp
[envc
++] = content_length
;
4854 envp
[envc
++] = content_type
;
4858 * Tell the CGI if we are using encryption...
4862 envp
[envc
++] = "HTTPS=ON";
4865 * Terminate the environment array...
4870 if (LogLevel
== CUPSD_LOG_DEBUG2
)
4872 for (i
= 0; i
< argc
; i
++)
4873 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4874 "pipe_command: argv[%d] = \"%s\"", i
, argv
[i
]);
4875 for (i
= 0; i
< envc
; i
++)
4876 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4877 "pipe_command: envp[%d] = \"%s\"", i
, envp
[i
]);
4881 * Create a pipe for the output...
4884 if (cupsdOpenPipe(fds
))
4886 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to create pipes for CGI %s - %s",
4887 argv
[0], strerror(errno
));
4892 * Then execute the command...
4895 if (cupsdStartProcess(command
, argv
, envp
, infile
, fds
[1], CGIPipes
[1],
4896 -1, -1, root
, DefaultProfile
, &pid
) < 0)
4899 * Error - can't fork!
4902 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to fork for CGI %s - %s", argv
[0],
4905 cupsdClosePipe(fds
);
4911 * Fork successful - return the PID...
4914 if (con
->username
[0])
4916 cupsdAddCert(pid
, con
->username
, ccache
);
4918 cupsdAddCert(pid
, con
->username
, NULL
);
4919 #endif /* HAVE_GSSAPI */
4921 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[CGI] %s started - PID = %d",
4933 * 'write_file()' - Send a file via HTTP.
4936 static int /* O - 0 on failure, 1 on success */
4937 write_file(cupsd_client_t
*con
, /* I - Client connection */
4938 http_status_t code
, /* I - HTTP status */
4939 char *filename
, /* I - Filename */
4940 char *type
, /* I - File type */
4941 struct stat
*filestats
) /* O - File information */
4943 con
->file
= open(filename
, O_RDONLY
);
4945 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "write_file: %d file=%d", con
->http
.fd
,
4951 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
4955 if (!cupsdSendHeader(con
, code
, type
, CUPSD_AUTH_NONE
))
4958 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
4959 httpGetDateString(filestats
->st_mtime
)) < 0)
4961 if (httpPrintf(HTTP(con
), "Content-Length: " CUPS_LLFMT
"\r\n",
4962 CUPS_LLCAST filestats
->st_size
) < 0)
4964 if (httpPrintf(HTTP(con
), "\r\n") < 0)
4967 if (cupsdFlushHeader(con
) < 0)
4970 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
4971 con
->http
.data_remaining
= filestats
->st_size
;
4973 if (con
->http
.data_remaining
<= INT_MAX
)
4974 con
->http
._data_remaining
= con
->http
.data_remaining
;
4976 con
->http
._data_remaining
= INT_MAX
;
4978 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
,
4979 (cupsd_selfunc_t
)cupsdWriteClient
, con
);
4986 * 'write_pipe()' - Flag that data is available on the CGI pipe.
4990 write_pipe(cupsd_client_t
*con
) /* I - Client connection */
4992 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "write_pipe: CGI output on fd %d...",
4995 con
->file_ready
= 1;
4997 cupsdRemoveSelect(con
->file
);
4998 cupsdAddSelect(con
->http
.fd
, NULL
, (cupsd_selfunc_t
)cupsdWriteClient
, con
);
5003 * End of "$Id: client.c 7950 2008-09-17 00:21:59Z mike $".