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 scheme
[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 scheme
, sizeof(scheme
),
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(scheme
, "file") &&
992 strcasecmp(hostname
, ServerName
) &&
993 strcasecmp(hostname
, "localhost") &&
994 !isdigit(hostname
[0]) && 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 if (!data_ready(con
) && recv(con
->http
.fd
, buf
, 1, MSG_PEEK
) < 1)
1083 * Connection closed...
1086 cupsdCloseClient(con
);
1089 break; /* Anti-compiler-warning-code */
1093 * Handle new transfers...
1096 if (status
== HTTP_OK
)
1098 if (con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
][0])
1101 * Figure out the locale from the Accept-Language and Content-Type
1105 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ',')) != NULL
)
1108 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ';')) != NULL
)
1111 if ((ptr
= strstr(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
], "charset=")) != NULL
)
1114 * Combine language and charset, and trim any extra params in the
1118 snprintf(locale
, sizeof(locale
), "%s.%s",
1119 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ptr
+ 8);
1121 if ((ptr
= strchr(locale
, ',')) != NULL
)
1125 snprintf(locale
, sizeof(locale
), "%s.%s",
1126 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], DefaultCharset
);
1128 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1129 "cupsdReadClient: %d Browser asked for language \"%s\"...",
1130 con
->http
.fd
, locale
);
1132 con
->language
= cupsLangGet(locale
);
1135 con
->language
= cupsLangGet(DefaultLocale
);
1137 cupsdAuthorize(con
);
1139 if (!strncasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Keep-Alive", 10) &&
1141 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
1142 else if (!strncasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "close", 5))
1143 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1145 if (!con
->http
.fields
[HTTP_FIELD_HOST
][0] &&
1146 con
->http
.version
>= HTTP_1_1
)
1149 * HTTP/1.1 and higher require the "Host:" field...
1152 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1154 cupsdCloseClient(con
);
1158 else if (httpAddrLocalhost(con
->http
.hostaddr
) &&
1159 strcasecmp(con
->http
.fields
[HTTP_FIELD_HOST
], "localhost") &&
1160 strncasecmp(con
->http
.fields
[HTTP_FIELD_HOST
], "localhost:", 10) &&
1161 strcmp(con
->http
.fields
[HTTP_FIELD_HOST
], "127.0.0.1") &&
1162 strncmp(con
->http
.fields
[HTTP_FIELD_HOST
], "127.0.0.1:", 10) &&
1163 strcmp(con
->http
.fields
[HTTP_FIELD_HOST
], "[::1]") &&
1164 strncmp(con
->http
.fields
[HTTP_FIELD_HOST
], "[::1]:", 6))
1167 * Access to localhost must use "localhost" or the corresponding IPv4
1168 * or IPv6 values in the Host: field.
1171 cupsdLogMessage(CUPSD_LOG_WARN
,
1172 "Request from \"%s\" using invalid Host: field \"%s\"",
1173 con
->http
.hostname
, con
->http
.fields
[HTTP_FIELD_HOST
]);
1175 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1177 cupsdCloseClient(con
);
1181 else if (con
->operation
== HTTP_OPTIONS
)
1184 * Do OPTIONS command...
1187 if (con
->best
&& con
->best
->type
!= CUPSD_AUTH_NONE
)
1189 if (!cupsdSendHeader(con
, HTTP_UNAUTHORIZED
, NULL
, CUPSD_AUTH_NONE
))
1191 cupsdCloseClient(con
);
1196 if (!strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") &&
1197 con
->http
.tls
== NULL
)
1201 * Do encryption stuff...
1204 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
, CUPSD_AUTH_NONE
))
1206 cupsdCloseClient(con
);
1210 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1211 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1212 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1213 httpPrintf(HTTP(con
), "\r\n");
1215 if (cupsdFlushHeader(con
) < 0)
1217 cupsdCloseClient(con
);
1221 if (!encrypt_client(con
))
1223 cupsdCloseClient(con
);
1227 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
1229 cupsdCloseClient(con
);
1232 #endif /* HAVE_SSL */
1235 if (!cupsdSendHeader(con
, HTTP_OK
, NULL
, CUPSD_AUTH_NONE
))
1237 cupsdCloseClient(con
);
1241 httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n");
1242 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1243 httpPrintf(HTTP(con
), "\r\n");
1245 if (cupsdFlushHeader(con
) < 0)
1247 cupsdCloseClient(con
);
1251 else if (!is_path_absolute(con
->uri
))
1254 * Protect against malicious users!
1257 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1259 cupsdCloseClient(con
);
1265 if (!strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") &&
1266 con
->http
.tls
== NULL
)
1270 * Do encryption stuff...
1273 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
, CUPSD_AUTH_NONE
))
1275 cupsdCloseClient(con
);
1279 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1280 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1281 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1282 httpPrintf(HTTP(con
), "\r\n");
1284 if (cupsdFlushHeader(con
) < 0)
1286 cupsdCloseClient(con
);
1290 if (!encrypt_client(con
))
1292 cupsdCloseClient(con
);
1296 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
1298 cupsdCloseClient(con
);
1301 #endif /* HAVE_SSL */
1304 if ((status
= cupsdIsAuthorized(con
, NULL
)) != HTTP_OK
)
1306 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1307 "cupsdReadClient: Unauthorized request for %s...",
1309 cupsdSendError(con
, status
, CUPSD_AUTH_NONE
);
1310 cupsdCloseClient(con
);
1314 if (con
->http
.expect
&&
1315 (con
->operation
== HTTP_POST
|| con
->operation
== HTTP_PUT
))
1317 if (con
->http
.expect
== HTTP_CONTINUE
)
1320 * Send 100-continue header...
1323 if (!cupsdSendHeader(con
, HTTP_CONTINUE
, NULL
, CUPSD_AUTH_NONE
))
1325 cupsdCloseClient(con
);
1332 * Send 417-expectation-failed header...
1335 if (!cupsdSendHeader(con
, HTTP_EXPECTATION_FAILED
, NULL
, CUPSD_AUTH_NONE
))
1337 cupsdCloseClient(con
);
1341 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1342 httpPrintf(HTTP(con
), "\r\n");
1344 if (cupsdFlushHeader(con
) < 0)
1346 cupsdCloseClient(con
);
1352 switch (con
->http
.state
)
1354 case HTTP_GET_SEND
:
1355 if (!strncmp(con
->uri
, "/printers/", 10) &&
1356 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1359 * Send PPD file - get the real printer name since printer
1360 * names are not case sensitive but filenames can be...
1363 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1365 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1366 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1369 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1371 cupsdCloseClient(con
);
1379 if ((!strncmp(con
->uri
, "/admin", 6) &&
1380 strncmp(con
->uri
, "/admin/conf/", 12) &&
1381 strncmp(con
->uri
, "/admin/log/", 11)) ||
1382 !strncmp(con
->uri
, "/printers", 9) ||
1383 !strncmp(con
->uri
, "/classes", 8) ||
1384 !strncmp(con
->uri
, "/help", 5) ||
1385 !strncmp(con
->uri
, "/jobs", 5))
1388 * Send CGI output...
1391 if (!strncmp(con
->uri
, "/admin", 6))
1393 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1396 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1398 else if (!strncmp(con
->uri
, "/printers", 9))
1400 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1403 if (con
->uri
[9] && con
->uri
[10])
1404 cupsdSetString(&con
->options
, con
->uri
+ 9);
1406 cupsdSetString(&con
->options
, NULL
);
1408 else if (!strncmp(con
->uri
, "/classes", 8))
1410 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1413 if (con
->uri
[8] && con
->uri
[9])
1414 cupsdSetString(&con
->options
, con
->uri
+ 8);
1416 cupsdSetString(&con
->options
, NULL
);
1418 else if (!strncmp(con
->uri
, "/jobs", 5))
1420 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1423 if (con
->uri
[5] && con
->uri
[6])
1424 cupsdSetString(&con
->options
, con
->uri
+ 5);
1426 cupsdSetString(&con
->options
, NULL
);
1430 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1433 if (con
->uri
[5] && con
->uri
[6])
1434 cupsdSetString(&con
->options
, con
->uri
+ 5);
1436 cupsdSetString(&con
->options
, NULL
);
1439 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1441 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1443 cupsdCloseClient(con
);
1448 cupsdLogRequest(con
, HTTP_OK
);
1450 if (con
->http
.version
<= HTTP_1_0
)
1451 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1453 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1454 (strchr(con
->uri
+ 12, '/') ||
1455 strlen(con
->uri
) == 12)) ||
1456 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1457 (strchr(con
->uri
+ 11, '/') ||
1458 strlen(con
->uri
) == 11)))
1461 * GET can only be done to configuration files under
1465 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1467 cupsdCloseClient(con
);
1479 if ((filename
= get_file(con
, &filestats
, buf
,
1480 sizeof(buf
))) == NULL
)
1482 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1484 cupsdCloseClient(con
);
1491 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1493 if (is_cgi(con
, filename
, &filestats
, type
))
1496 * Note: con->command and con->options were set by
1500 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1502 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1504 cupsdCloseClient(con
);
1509 cupsdLogRequest(con
, HTTP_OK
);
1511 if (con
->http
.version
<= HTTP_1_0
)
1512 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1516 if (!check_if_modified(con
, &filestats
))
1518 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1520 cupsdCloseClient(con
);
1527 strcpy(line
, "text/plain");
1529 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1531 if (!write_file(con
, HTTP_OK
, filename
, line
, &filestats
))
1533 cupsdCloseClient(con
);
1540 case HTTP_POST_RECV
:
1542 * See if the POST request includes a Content-Length field, and if
1543 * so check the length against any limits that are set...
1546 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "POST %s", con
->uri
);
1547 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "CONTENT_TYPE = %s",
1548 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
1550 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1551 MaxRequestSize
> 0 &&
1552 con
->http
.data_remaining
> MaxRequestSize
)
1555 * Request too large...
1558 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1560 cupsdCloseClient(con
);
1566 else if (con
->http
.data_remaining
< 0 ||
1567 (!con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1568 con
->http
.data_encoding
== HTTP_ENCODE_LENGTH
))
1571 * Negative content lengths are invalid!
1574 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1576 cupsdCloseClient(con
);
1584 * See what kind of POST request this is; for IPP requests the
1585 * content-type field will be "application/ipp"...
1588 if (!strcmp(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
],
1590 con
->request
= ippNew();
1591 else if ((!strncmp(con
->uri
, "/admin", 6) &&
1592 strncmp(con
->uri
, "/admin/conf/", 12) &&
1593 strncmp(con
->uri
, "/admin/log/", 11)) ||
1594 !strncmp(con
->uri
, "/printers", 9) ||
1595 !strncmp(con
->uri
, "/classes", 8) ||
1596 !strncmp(con
->uri
, "/help", 5) ||
1597 !strncmp(con
->uri
, "/jobs", 5))
1603 if (!strncmp(con
->uri
, "/admin", 6))
1605 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1608 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1610 else if (!strncmp(con
->uri
, "/printers", 9))
1612 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1615 if (con
->uri
[9] && con
->uri
[10])
1616 cupsdSetString(&con
->options
, con
->uri
+ 9);
1618 cupsdSetString(&con
->options
, NULL
);
1620 else if (!strncmp(con
->uri
, "/classes", 8))
1622 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1625 if (con
->uri
[8] && con
->uri
[9])
1626 cupsdSetString(&con
->options
, con
->uri
+ 8);
1628 cupsdSetString(&con
->options
, NULL
);
1630 else if (!strncmp(con
->uri
, "/jobs", 5))
1632 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1635 if (con
->uri
[5] && con
->uri
[6])
1636 cupsdSetString(&con
->options
, con
->uri
+ 5);
1638 cupsdSetString(&con
->options
, NULL
);
1642 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1645 if (con
->uri
[5] && con
->uri
[6])
1646 cupsdSetString(&con
->options
, con
->uri
+ 5);
1648 cupsdSetString(&con
->options
, NULL
);
1651 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1652 "cupsdReadClient: %d command=\"%s\", "
1654 con
->http
.fd
, con
->command
,
1655 con
->options
? con
->options
: "(null)");
1657 if (con
->http
.version
<= HTTP_1_0
)
1658 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1666 if ((filename
= get_file(con
, &filestats
, buf
,
1667 sizeof(buf
))) == NULL
)
1669 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1671 cupsdCloseClient(con
);
1678 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1680 if (!is_cgi(con
, filename
, &filestats
, type
))
1683 * Only POST to CGI's...
1686 if (!cupsdSendError(con
, HTTP_UNAUTHORIZED
, CUPSD_AUTH_NONE
))
1688 cupsdCloseClient(con
);
1695 case HTTP_PUT_RECV
:
1697 * Validate the resource name...
1700 if (strncmp(con
->uri
, "/admin/conf/", 12) ||
1701 strchr(con
->uri
+ 12, '/') ||
1702 strlen(con
->uri
) == 12)
1705 * PUT can only be done to configuration files under
1709 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1711 cupsdCloseClient(con
);
1719 * See if the PUT request includes a Content-Length field, and if
1720 * so check the length against any limits that are set...
1723 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "PUT %s", con
->uri
);
1724 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "CONTENT_TYPE = %s",
1725 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
1727 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1728 MaxRequestSize
> 0 &&
1729 con
->http
.data_remaining
> MaxRequestSize
)
1732 * Request too large...
1735 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1737 cupsdCloseClient(con
);
1743 else if (con
->http
.data_remaining
< 0)
1746 * Negative content lengths are invalid!
1749 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1751 cupsdCloseClient(con
);
1759 * Open a temporary file to hold the request...
1762 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
1764 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1768 cupsdLogMessage(CUPSD_LOG_ERROR
,
1769 "Unable to create request file %s: %s",
1770 con
->filename
, strerror(errno
));
1772 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1774 cupsdCloseClient(con
);
1779 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1780 "cupsdReadClient: %d REQUEST %s=%d", con
->http
.fd
,
1781 con
->filename
, con
->file
);
1783 fchmod(con
->file
, 0640);
1784 fchown(con
->file
, RunUser
, Group
);
1785 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1790 cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
);
1791 cupsdCloseClient(con
);
1795 if (!strncmp(con
->uri
, "/printers/", 10) &&
1796 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1799 * Send PPD file - get the real printer name since printer
1800 * names are not case sensitive but filenames can be...
1803 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1805 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1806 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1809 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1811 cupsdCloseClient(con
);
1819 if ((!strncmp(con
->uri
, "/admin", 6) &&
1820 strncmp(con
->uri
, "/admin/conf/", 12) &&
1821 strncmp(con
->uri
, "/admin/log/", 11)) ||
1822 !strncmp(con
->uri
, "/printers", 9) ||
1823 !strncmp(con
->uri
, "/classes", 8) ||
1824 !strncmp(con
->uri
, "/help", 5) ||
1825 !strncmp(con
->uri
, "/jobs", 5))
1831 if (!cupsdSendHeader(con
, HTTP_OK
, "text/html", CUPSD_AUTH_NONE
))
1833 cupsdCloseClient(con
);
1837 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1839 cupsdCloseClient(con
);
1843 if (cupsdFlushHeader(con
) < 0)
1845 cupsdCloseClient(con
);
1849 cupsdLogRequest(con
, HTTP_OK
);
1851 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1852 (strchr(con
->uri
+ 12, '/') ||
1853 strlen(con
->uri
) == 12)) ||
1854 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1855 (strchr(con
->uri
+ 11, '/') ||
1856 strlen(con
->uri
) == 11)))
1859 * HEAD can only be done to configuration files under
1863 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1865 cupsdCloseClient(con
);
1871 else if ((filename
= get_file(con
, &filestats
, buf
,
1872 sizeof(buf
))) == NULL
)
1874 if (!cupsdSendHeader(con
, HTTP_NOT_FOUND
, "text/html", CUPSD_AUTH_NONE
))
1876 cupsdCloseClient(con
);
1880 cupsdLogRequest(con
, HTTP_NOT_FOUND
);
1882 else if (!check_if_modified(con
, &filestats
))
1884 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1886 cupsdCloseClient(con
);
1890 cupsdLogRequest(con
, HTTP_NOT_MODIFIED
);
1898 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1900 strcpy(line
, "text/plain");
1902 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1904 if (!cupsdSendHeader(con
, HTTP_OK
, line
, CUPSD_AUTH_NONE
))
1906 cupsdCloseClient(con
);
1910 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
1911 httpGetDateString(filestats
.st_mtime
)) < 0)
1913 cupsdCloseClient(con
);
1917 if (httpPrintf(HTTP(con
), "Content-Length: %lu\r\n",
1918 (unsigned long)filestats
.st_size
) < 0)
1920 cupsdCloseClient(con
);
1924 cupsdLogRequest(con
, HTTP_OK
);
1927 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1929 cupsdCloseClient(con
);
1933 if (cupsdFlushHeader(con
) < 0)
1935 cupsdCloseClient(con
);
1939 con
->http
.state
= HTTP_WAITING
;
1943 break; /* Anti-compiler-warning-code */
1949 * Handle any incoming data...
1952 switch (con
->http
.state
)
1954 case HTTP_PUT_RECV
:
1955 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1956 "cupsdReadClient: %d con->data_encoding=HTTP_ENCODE_%s, "
1957 "con->data_remaining=" CUPS_LLFMT
", con->file=%d",
1959 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
?
1960 "CHUNKED" : "LENGTH",
1961 CUPS_LLCAST con
->http
.data_remaining
, con
->file
);
1965 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
1967 cupsdCloseClient(con
);
1972 con
->bytes
+= bytes
;
1974 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1975 "cupsdReadClient: %d writing %d bytes to %d",
1976 con
->http
.fd
, bytes
, con
->file
);
1978 if (write(con
->file
, line
, bytes
) < bytes
)
1980 cupsdLogMessage(CUPSD_LOG_ERROR
,
1981 "cupsdReadClient: Unable to write %d bytes to %s: %s",
1982 bytes
, con
->filename
, strerror(errno
));
1984 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1985 "cupsdReadClient: Closing data file %d...",
1990 unlink(con
->filename
);
1991 cupsdClearString(&con
->filename
);
1993 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1995 cupsdCloseClient(con
);
2001 while (con
->http
.state
== HTTP_PUT_RECV
&& data_ready(con
));
2003 if (con
->http
.state
== HTTP_WAITING
)
2006 * End of file, see how big it is...
2009 fstat(con
->file
, &filestats
);
2011 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2012 "cupsdReadClient: %d Closing data file %d, size="
2014 con
->http
.fd
, con
->file
,
2015 CUPS_LLCAST filestats
.st_size
);
2020 if (filestats
.st_size
> MaxRequestSize
&&
2024 * Request is too big; remove it and send an error...
2027 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2028 "cupsdReadClient: %d Removing temp file %s",
2029 con
->http
.fd
, con
->filename
);
2030 unlink(con
->filename
);
2031 cupsdClearString(&con
->filename
);
2033 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2035 cupsdCloseClient(con
);
2041 * Install the configuration file...
2044 status
= install_conf_file(con
);
2047 * Return the status to the client...
2050 if (!cupsdSendError(con
, status
, CUPSD_AUTH_NONE
))
2052 cupsdCloseClient(con
);
2058 case HTTP_POST_RECV
:
2059 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2060 "cupsdReadClient: %d con->data_encoding=HTTP_ENCODE_"
2061 "%s, con->data_remaining=" CUPS_LLFMT
", con->file=%d",
2063 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
?
2064 "CHUNKED" : "LENGTH",
2065 CUPS_LLCAST con
->http
.data_remaining
, con
->file
);
2072 * Grab any request data from the connection...
2075 if ((ipp_state
= ippRead(&(con
->http
), con
->request
)) == IPP_ERROR
)
2077 cupsdLogMessage(CUPSD_LOG_ERROR
,
2078 "cupsdReadClient: %d IPP Read Error!",
2081 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
2082 cupsdCloseClient(con
);
2085 else if (ipp_state
!= IPP_DATA
)
2087 if (con
->http
.state
== HTTP_POST_SEND
)
2089 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
2090 cupsdCloseClient(con
);
2097 con
->bytes
+= ippLength(con
->request
);
2100 if (con
->file
< 0 && con
->http
.state
!= HTTP_POST_SEND
)
2103 * Create a file as needed for the request data...
2106 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
, request_id
++);
2107 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
2111 cupsdLogMessage(CUPSD_LOG_ERROR
,
2112 "Unable to create request file %s: %s",
2113 con
->filename
, strerror(errno
));
2115 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2117 cupsdCloseClient(con
);
2122 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdReadClient: %d REQUEST %s=%d", con
->http
.fd
,
2123 con
->filename
, con
->file
);
2125 fchmod(con
->file
, 0640);
2126 fchown(con
->file
, RunUser
, Group
);
2127 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2130 if (con
->http
.state
!= HTTP_POST_SEND
)
2132 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
2134 cupsdCloseClient(con
);
2139 con
->bytes
+= bytes
;
2141 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2142 "cupsdReadClient: %d writing %d bytes to %d",
2143 con
->http
.fd
, bytes
, con
->file
);
2145 if (write(con
->file
, line
, bytes
) < bytes
)
2147 cupsdLogMessage(CUPSD_LOG_ERROR
,
2148 "cupsdReadClient: Unable to write %d bytes to %s: %s",
2149 bytes
, con
->filename
, strerror(errno
));
2151 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2152 "cupsdReadClient: Closing file %d...",
2157 unlink(con
->filename
);
2158 cupsdClearString(&con
->filename
);
2160 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2162 cupsdCloseClient(con
);
2167 else if (con
->http
.state
== HTTP_POST_RECV
)
2169 else if (con
->http
.state
!= HTTP_POST_SEND
)
2171 cupsdCloseClient(con
);
2176 while (con
->http
.state
== HTTP_POST_RECV
&& data_ready(con
));
2178 if (con
->http
.state
== HTTP_POST_SEND
)
2182 fstat(con
->file
, &filestats
);
2184 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2185 "cupsdReadClient: %d Closing data file %d, "
2186 "size=" CUPS_LLFMT
".",
2187 con
->http
.fd
, con
->file
,
2188 CUPS_LLCAST filestats
.st_size
);
2193 if (filestats
.st_size
> MaxRequestSize
&&
2197 * Request is too big; remove it and send an error...
2200 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2201 "cupsdReadClient: %d Removing temp file %s",
2202 con
->http
.fd
, con
->filename
);
2203 unlink(con
->filename
);
2204 cupsdClearString(&con
->filename
);
2209 * Delete any IPP request data...
2212 ippDelete(con
->request
);
2213 con
->request
= NULL
;
2216 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2218 cupsdCloseClient(con
);
2225 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
2227 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
2229 cupsdCloseClient(con
);
2234 cupsdLogRequest(con
, HTTP_OK
);
2240 cupsdProcessIPPRequest(con
);
2244 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2245 "cupsdReadClient: %d Removing temp file %s",
2246 con
->http
.fd
, con
->filename
);
2247 unlink(con
->filename
);
2248 cupsdClearString(&con
->filename
);
2257 break; /* Anti-compiler-warning-code */
2260 if (con
->http
.state
== HTTP_WAITING
)
2262 if (!con
->http
.keep_alive
)
2263 cupsdCloseClient(con
);
2266 cupsArrayRemove(ActiveClients
, con
);
2267 cupsdSetBusyState();
2274 * 'cupsdSendCommand()' - Send output from a command via HTTP.
2277 int /* O - 1 on success, 0 on failure */
2279 cupsd_client_t
*con
, /* I - Client connection */
2280 char *command
, /* I - Command to run */
2281 char *options
, /* I - Command-line options */
2282 int root
) /* I - Run as root? */
2284 int fd
; /* Standard input file descriptor */
2289 fd
= open(con
->filename
, O_RDONLY
);
2293 cupsdLogMessage(CUPSD_LOG_ERROR
,
2294 "cupsdSendCommand: %d Unable to open \"%s\" for reading: %s",
2295 con
->http
.fd
, con
->filename
? con
->filename
: "/dev/null",
2300 fcntl(fd
, F_SETFD
, fcntl(fd
, F_GETFD
) | FD_CLOEXEC
);
2305 con
->pipe_pid
= pipe_command(con
, fd
, &(con
->file
), command
, options
, root
);
2310 cupsdLogMessage(CUPSD_LOG_INFO
, "Started \"%s\" (pid=%d)", command
,
2313 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendCommand: %d file=%d",
2314 con
->http
.fd
, con
->file
);
2316 if (con
->pipe_pid
== 0)
2319 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2321 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2323 con
->sent_header
= 0;
2324 con
->file_ready
= 0;
2325 con
->got_fields
= 0;
2333 * 'cupsdSendError()' - Send an error message via HTTP.
2336 int /* O - 1 if successful, 0 otherwise */
2337 cupsdSendError(cupsd_client_t
*con
, /* I - Connection */
2338 http_status_t code
, /* I - Error code */
2339 int auth_type
)/* I - Authentication type */
2343 * Force client to upgrade for authentication if that is how the
2344 * server is configured...
2347 if (code
== HTTP_UNAUTHORIZED
&&
2348 DefaultEncryption
== HTTP_ENCRYPT_REQUIRED
&&
2349 strcasecmp(con
->http
.hostname
, "localhost") &&
2352 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2353 "cupsdSendError: Encryption before authentication!");
2354 code
= HTTP_UPGRADE_REQUIRED
;
2356 #endif /* HAVE_SSL */
2359 * Put the request in the access_log file...
2362 cupsdLogRequest(con
, code
);
2364 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendError: %d code=%d (%s)",
2365 con
->http
.fd
, code
, httpStatus(code
));
2368 * To work around bugs in some proxies, don't use Keep-Alive for some
2371 * Kerberos authentication doesn't work without Keep-Alive, so
2372 * never disable it in that case.
2375 if (code
>= HTTP_BAD_REQUEST
&& con
->http
.auth_type
!= CUPSD_AUTH_NEGOTIATE
)
2376 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
2379 * Send an error message back to the client. If the error code is a
2380 * 400 or 500 series, make sure the message contains some text, too!
2383 if (!cupsdSendHeader(con
, code
, NULL
, auth_type
))
2387 if (code
== HTTP_UPGRADE_REQUIRED
)
2388 if (httpPrintf(HTTP(con
), "Connection: Upgrade\r\n") < 0)
2391 if (httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n") < 0)
2393 #endif /* HAVE_SSL */
2395 if (con
->http
.version
>= HTTP_1_1
&&
2396 con
->http
.keep_alive
== HTTP_KEEPALIVE_OFF
)
2398 if (httpPrintf(HTTP(con
), "Connection: close\r\n") < 0)
2402 if (code
>= HTTP_BAD_REQUEST
)
2405 * Send a human-readable error message.
2408 char message
[4096], /* Message for user */
2409 urltext
[1024], /* URL redirection text */
2410 redirect
[1024]; /* Redirection link */
2411 const char *text
; /* Status-specific text */
2416 if (code
== HTTP_UNAUTHORIZED
)
2417 text
= _cupsLangString(con
->language
,
2418 _("Enter your username and password or the "
2419 "root username and password to access this "
2420 "page. If you are using Kerberos authentication, "
2421 "make sure you have a valid Kerberos ticket."));
2422 else if (code
== HTTP_UPGRADE_REQUIRED
)
2426 snprintf(urltext
, sizeof(urltext
),
2427 _cupsLangString(con
->language
,
2428 _("You must access this page using the URL "
2429 "<A HREF=\"https://%s:%d%s\">"
2430 "https://%s:%d%s</A>.")),
2431 con
->servername
, con
->serverport
, con
->uri
,
2432 con
->servername
, con
->serverport
, con
->uri
);
2434 snprintf(redirect
, sizeof(redirect
),
2435 "<META HTTP-EQUIV=\"Refresh\" "
2436 "CONTENT=\"3;URL=https://%s:%d%s\">\n",
2437 con
->servername
, con
->serverport
, con
->uri
);
2442 snprintf(message
, sizeof(message
),
2443 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" "
2444 "\"http://www.w3.org/TR/REC-html40/loose.dtd\">\n"
2447 "\t<META HTTP-EQUIV=\"Content-Type\" "
2448 "CONTENT=\"text/html; charset=utf-8\">\n"
2449 "\t<TITLE>%d %s</TITLE>\n"
2450 "\t<LINK REL=\"STYLESHEET\" TYPE=\"text/css\" "
2451 "HREF=\"/cups.css\">\n"
2459 code
, httpStatus(code
), redirect
, code
, httpStatus(code
), text
);
2461 if (httpPrintf(HTTP(con
), "Content-Type: text/html; charset=utf-8\r\n") < 0)
2463 if (httpPrintf(HTTP(con
), "Content-Length: %d\r\n",
2464 (int)strlen(message
)) < 0)
2466 if (httpPrintf(HTTP(con
), "\r\n") < 0)
2468 if (httpPrintf(HTTP(con
), "%s", message
) < 0)
2471 else if (httpPrintf(HTTP(con
), "\r\n") < 0)
2474 if (cupsdFlushHeader(con
) < 0)
2477 con
->http
.state
= HTTP_WAITING
;
2484 * 'cupsdSendHeader()' - Send an HTTP request.
2487 int /* O - 1 on success, 0 on failure */
2489 cupsd_client_t
*con
, /* I - Client to send to */
2490 http_status_t code
, /* I - HTTP status code */
2491 char *type
, /* I - MIME type of document */
2492 int auth_type
) /* I - Type of authentication */
2494 char auth_str
[1024]; /* Authorization string */
2496 static char *gss_buf
= NULL
; /* Kerberos auth data buffer */
2497 static int gss_bufsize
= 0; /* Size of Kerberos auth data buffer */
2498 #endif /* HAVE_GSSAPI */
2502 * Send the HTTP status header...
2505 if (code
== HTTP_CONTINUE
)
2508 * 100-continue doesn't send any headers...
2511 return (httpPrintf(HTTP(con
), "HTTP/%d.%d 100 Continue\r\n\r\n",
2512 con
->http
.version
/ 100, con
->http
.version
% 100) > 0);
2515 httpFlushWrite(HTTP(con
));
2517 con
->http
.data_encoding
= HTTP_ENCODE_FIELDS
;
2519 if (httpPrintf(HTTP(con
), "HTTP/%d.%d %d %s\r\n", con
->http
.version
/ 100,
2520 con
->http
.version
% 100, code
, httpStatus(code
)) < 0)
2522 if (httpPrintf(HTTP(con
), "Date: %s\r\n", httpGetDateString(time(NULL
))) < 0)
2525 if (httpPrintf(HTTP(con
), "Server: %s\r\n", ServerHeader
) < 0)
2527 if (con
->http
.keep_alive
&& con
->http
.version
>= HTTP_1_0
)
2529 if (httpPrintf(HTTP(con
), "Connection: Keep-Alive\r\n") < 0)
2531 if (httpPrintf(HTTP(con
), "Keep-Alive: timeout=%d\r\n",
2532 KeepAliveTimeout
) < 0)
2535 if (code
== HTTP_METHOD_NOT_ALLOWED
)
2536 if (httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n") < 0)
2539 if (code
== HTTP_UNAUTHORIZED
)
2541 if (auth_type
== CUPSD_AUTH_NONE
)
2543 if (!con
->best
|| con
->best
->type
<= CUPSD_AUTH_NONE
)
2544 auth_type
= DefaultAuthType
;
2546 auth_type
= con
->best
->type
;
2551 if (auth_type
== CUPSD_AUTH_BASIC
|| auth_type
== CUPSD_AUTH_BASICDIGEST
)
2552 strlcpy(auth_str
, "Basic realm=\"CUPS\"", sizeof(auth_str
));
2553 else if (auth_type
== CUPSD_AUTH_DIGEST
)
2554 snprintf(auth_str
, sizeof(auth_str
), "Digest realm=\"CUPS\", nonce=\"%s\"",
2555 con
->http
.hostname
);
2557 else if (auth_type
== CUPSD_AUTH_NEGOTIATE
&& con
->gss_output_token
.length
== 0)
2558 strlcpy(auth_str
, "Negotiate", sizeof(auth_str
));
2559 #endif /* HAVE_GSSAPI */
2561 #ifdef HAVE_AUTHORIZATION_H
2562 if (con
->best
&& auth_type
!= CUPSD_AUTH_NEGOTIATE
)
2564 int i
; /* Looping var */
2565 char *auth_key
; /* Auth key buffer */
2566 size_t auth_size
; /* Size of remaining buffer */
2569 auth_key
= auth_str
+ strlen(auth_str
);
2570 auth_size
= sizeof(auth_str
) - (auth_key
- auth_str
);
2572 for (i
= 0; i
< con
->best
->num_names
; i
++)
2574 if (!strncasecmp(con
->best
->names
[i
], "@AUTHKEY(", 9))
2576 snprintf(auth_key
, auth_size
, ", authkey=\"%s\"",
2577 con
->best
->names
[i
] + 9);
2578 /* end parenthesis is stripped in conf.c */
2581 else if (!strcasecmp(con
->best
->names
[i
], "@SYSTEM") &&
2584 snprintf(auth_key
, auth_size
, ", authkey=\"%s\"", SystemGroupAuthKey
);
2589 #endif /* HAVE_AUTHORIZATION_H */
2593 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendHeader: WWW-Authenticate: %s",
2596 if (httpPrintf(HTTP(con
), "WWW-Authenticate: %s\r\n", auth_str
) < 0)
2603 * WWW-Authenticate: Negotiate can be included even for
2604 * non-401 replies...
2607 if (con
->gss_output_token
.length
> 0 && con
->gss_output_token
.length
<= 65536)
2609 OM_uint32 minor_status
; /* Minor status code */
2610 int bufsize
; /* Size of output token buffer */
2613 bufsize
= con
->gss_output_token
.length
* 4 / 3 + 2;
2615 if (bufsize
> gss_bufsize
)
2617 char *buf
; /* New buffer */
2620 bufsize
= (bufsize
+ 1023) & 1023;/* Round up */
2623 buf
= realloc(gss_buf
, bufsize
);
2625 buf
= malloc(bufsize
);
2629 cupsdLogMessage(CUPSD_LOG_ERROR
,
2630 "Unable to allocate %d bytes for Kerberos credentials!",
2636 gss_bufsize
= bufsize
;
2639 httpEncode64_2(gss_buf
, gss_bufsize
,
2640 con
->gss_output_token
.value
,
2641 con
->gss_output_token
.length
);
2642 gss_release_buffer(&minor_status
, &con
->gss_output_token
);
2644 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2645 "cupsdSendHeader: WWW-Authenticate: Negotiate %s", gss_buf
);
2647 if (httpPrintf(HTTP(con
), "WWW-Authenticate: Negotiate %s\r\n",
2651 else if (con
->gss_output_token
.length
> 65536)
2653 cupsdLogMessage(CUPSD_LOG_ERROR
,
2654 "Kerberos credentials larger than 64k (%d)!",
2655 (int)con
->gss_output_token
.length
);
2658 #endif /* HAVE_GSSAPI */
2660 if (con
->language
&& strcmp(con
->language
->language
, "C"))
2662 if (httpPrintf(HTTP(con
), "Content-Language: %s\r\n",
2663 con
->language
->language
) < 0)
2669 if (!strcmp(type
, "text/html"))
2671 if (httpPrintf(HTTP(con
),
2672 "Content-Type: text/html; charset=utf-8\r\n") < 0)
2675 else if (httpPrintf(HTTP(con
), "Content-Type: %s\r\n", type
) < 0)
2684 * 'cupsdUpdateCGI()' - Read status messages from CGI scripts and programs.
2688 cupsdUpdateCGI(void)
2690 char *ptr
, /* Pointer to end of line in buffer */
2691 message
[1024]; /* Pointer to message text */
2692 int loglevel
; /* Log level for message */
2695 while ((ptr
= cupsdStatBufUpdate(CGIStatusBuffer
, &loglevel
,
2696 message
, sizeof(message
))) != NULL
)
2697 if (!strchr(CGIStatusBuffer
->buffer
, '\n'))
2700 if (ptr
== NULL
&& !CGIStatusBuffer
->bufused
)
2703 * Fatal error on pipe - should never happen!
2706 cupsdLogMessage(CUPSD_LOG_CRIT
,
2707 "cupsdUpdateCGI: error reading from CGI error pipe - %s",
2714 * 'cupsdWriteClient()' - Write data to a client as needed.
2718 cupsdWriteClient(cupsd_client_t
*con
) /* I - Client connection */
2720 int bytes
; /* Number of bytes written */
2721 char buf
[16385]; /* Data buffer */
2722 char *bufptr
; /* Pointer into buffer */
2723 ipp_state_t ipp_state
; /* IPP state value */
2727 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2728 "cupsdWriteClient(con=%p) %d response=%p(%d), file=%d "
2729 "pipe_pid=%d state=%d",
2730 con
, con
->http
.fd
, con
->response
,
2731 con
->response
? con
->response
->state
: -1,
2732 con
->file
, con
->pipe_pid
, con
->http
.state
);
2735 if (con
->http
.state
!= HTTP_GET_SEND
&&
2736 con
->http
.state
!= HTTP_POST_SEND
)
2742 * Make sure we select on the CGI output...
2745 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2747 if (!con
->file_ready
)
2750 * Try again later when there is CGI output available...
2753 cupsdRemoveSelect(con
->http
.fd
);
2757 con
->file_ready
= 0;
2760 if (con
->response
&& con
->response
->state
!= IPP_DATA
)
2762 ipp_state
= ippWrite(HTTP(con
), con
->response
);
2763 bytes
= ipp_state
!= IPP_ERROR
&&
2764 (con
->file
>= 0 || ipp_state
!= IPP_DATA
);
2766 else if ((bytes
= read(con
->file
, buf
, sizeof(buf
) - 1)) > 0)
2768 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2769 "cupsdWriteClient: Read %d bytes from file %d...",
2772 if (con
->pipe_pid
&& !con
->got_fields
)
2775 * Inspect the data for Content-Type and other fields.
2780 for (bufptr
= buf
; !con
->got_fields
&& *bufptr
; bufptr
++)
2781 if (*bufptr
== '\n')
2784 * Send line to client...
2787 if (bufptr
> buf
&& bufptr
[-1] == '\r')
2791 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "Script header: %s", buf
);
2793 if (!con
->sent_header
)
2796 * Handle redirection and CGI status codes...
2799 if (!strncasecmp(buf
, "Location:", 9))
2801 cupsdSendHeader(con
, HTTP_SEE_OTHER
, NULL
, CUPSD_AUTH_NONE
);
2802 con
->sent_header
= 2;
2804 if (httpPrintf(HTTP(con
), "Content-Length: 0\r\n") < 0)
2807 else if (!strncasecmp(buf
, "Status:", 7))
2809 cupsdSendError(con
, (http_status_t
)atoi(buf
+ 7), CUPSD_AUTH_NONE
);
2810 con
->sent_header
= 2;
2814 cupsdSendHeader(con
, HTTP_OK
, NULL
, CUPSD_AUTH_NONE
);
2815 con
->sent_header
= 1;
2817 if (con
->http
.version
== HTTP_1_1
)
2819 if (httpPrintf(HTTP(con
), "Transfer-Encoding: chunked\r\n") < 0)
2825 if (strncasecmp(buf
, "Status:", 7))
2826 httpPrintf(HTTP(con
), "%s\r\n", buf
);
2828 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdWriteClient: %d %s",
2835 bytes
-= (bufptr
- buf
);
2836 memmove(buf
, bufptr
, bytes
+ 1);
2840 * See if the line was empty...
2843 if (con
->field_col
== 0)
2845 con
->got_fields
= 1;
2847 if (cupsdFlushHeader(con
) < 0)
2849 cupsdCloseClient(con
);
2853 if (con
->http
.version
== HTTP_1_1
)
2854 con
->http
.data_encoding
= HTTP_ENCODE_CHUNKED
;
2859 else if (*bufptr
!= '\r')
2862 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2863 "cupsdWriteClient: %d bytes=%d, got_fields=%d",
2864 con
->http
.fd
, bytes
, con
->got_fields
);
2866 if (bytes
> 0 && !con
->got_fields
)
2869 * Remaining text needs to go out...
2872 httpPrintf(HTTP(con
), "%s", buf
);
2874 con
->http
.activity
= time(NULL
);
2877 else if (bytes
== 0)
2879 con
->http
.activity
= time(NULL
);
2886 if (httpWrite2(HTTP(con
), buf
, bytes
) < 0)
2888 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2889 "cupsdWriteClient: %d Write of %d bytes failed!",
2890 con
->http
.fd
, bytes
);
2892 cupsdCloseClient(con
);
2896 if (con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
)
2897 httpFlushWrite(HTTP(con
));
2899 con
->bytes
+= bytes
;
2901 if (con
->http
.state
== HTTP_WAITING
)
2908 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdWriteClient: %d bytes < 0",
2911 cupsdLogRequest(con
, HTTP_OK
);
2913 httpFlushWrite(HTTP(con
));
2915 if (con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
&& con
->sent_header
== 1)
2917 if (httpWrite2(HTTP(con
), "", 0) < 0)
2919 cupsdCloseClient(con
);
2924 con
->http
.state
= HTTP_WAITING
;
2926 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
2930 cupsdRemoveSelect(con
->file
);
2933 cupsdEndProcess(con
->pipe_pid
, 0);
2935 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2936 "cupsdWriteClient: %d Closing data file %d.",
2937 con
->http
.fd
, con
->file
);
2946 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2947 "cupsdWriteClient: %d Removing temp file %s",
2948 con
->http
.fd
, con
->filename
);
2949 unlink(con
->filename
);
2950 cupsdClearString(&con
->filename
);
2955 ippDelete(con
->request
);
2956 con
->request
= NULL
;
2961 ippDelete(con
->response
);
2962 con
->response
= NULL
;
2965 cupsdClearString(&con
->command
);
2966 cupsdClearString(&con
->options
);
2967 cupsdClearString(&con
->query_string
);
2969 if (!con
->http
.keep_alive
)
2971 cupsdCloseClient(con
);
2976 con
->http
.activity
= time(NULL
);
2981 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
2984 static int /* O - 1 if modified since */
2986 cupsd_client_t
*con
, /* I - Client connection */
2987 struct stat
*filestats
) /* I - File information */
2989 char *ptr
; /* Pointer into field */
2990 time_t date
; /* Time/date value */
2991 off_t size
; /* Size/length value */
2996 ptr
= con
->http
.fields
[HTTP_FIELD_IF_MODIFIED_SINCE
];
3001 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3002 "check_if_modified: %d If-Modified-Since=\"%s\"",
3005 while (*ptr
!= '\0')
3007 while (isspace(*ptr
) || *ptr
== ';')
3010 if (strncasecmp(ptr
, "length=", 7) == 0)
3013 size
= strtoll(ptr
, NULL
, 10);
3015 while (isdigit(*ptr
))
3018 else if (isalpha(*ptr
))
3020 date
= httpGetDateTime(ptr
);
3021 while (*ptr
!= '\0' && *ptr
!= ';')
3028 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3029 "check_if_modified: %d sizes=" CUPS_LLFMT
","
3030 CUPS_LLFMT
" dates=%d,%d",
3031 con
->http
.fd
, CUPS_LLCAST size
,
3032 CUPS_LLCAST filestats
->st_size
, (int)date
,
3033 (int)filestats
->st_mtime
);
3035 return ((size
!= filestats
->st_size
&& size
!= 0) ||
3036 (date
< filestats
->st_mtime
&& date
!= 0) ||
3037 (size
== 0 && date
== 0));
3042 * 'compare_clients()' - Compare two client connections.
3045 static int /* O - Result of comparison */
3046 compare_clients(cupsd_client_t
*a
, /* I - First client */
3047 cupsd_client_t
*b
, /* I - Second client */
3048 void *data
) /* I - User data (not used) */
3062 * 'data_ready()' - Check whether data is available from a client.
3065 static int /* O - 1 if data is ready, 0 otherwise */
3066 data_ready(cupsd_client_t
*con
) /* I - Client */
3068 if (con
->http
.used
> 0)
3071 else if (con
->http
.tls
)
3074 if (SSL_pending((SSL
*)(con
->http
.tls
)))
3076 # elif defined(HAVE_GNUTLS)
3077 if (gnutls_record_check_pending(((http_tls_t
*)(con
->http
.tls
))->session
))
3079 # elif defined(HAVE_CDSASSL)
3080 size_t bytes
; /* Bytes that are available */
3082 if (!SSLGetBufferedReadSize(((http_tls_t
*)(con
->http
.tls
))->session
,
3083 &bytes
) && bytes
> 0)
3085 # endif /* HAVE_LIBSSL */
3087 #endif /* HAVE_SSL */
3095 * 'encrypt_client()' - Enable encryption for the client...
3098 static int /* O - 1 on success, 0 on error */
3099 encrypt_client(cupsd_client_t
*con
) /* I - Client to encrypt */
3102 SSL_CTX
*context
; /* Context for encryption */
3103 SSL
*conn
; /* Connection for encryption */
3104 BIO
*bio
; /* BIO data */
3105 unsigned long error
; /* Error code */
3109 * Verify that we have a certificate...
3112 if (access(ServerKey
, 0) || access(ServerCertificate
, 0))
3115 * Nope, make a self-signed certificate...
3118 if (!make_certificate(con
))
3123 * Create the SSL context and accept the connection...
3126 context
= SSL_CTX_new(SSLv23_server_method());
3128 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
3129 if (SSLOptions
& CUPSD_SSL_NOEMPTY
)
3130 SSL_CTX_set_options(context
, SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
);
3131 SSL_CTX_use_PrivateKey_file(context
, ServerKey
, SSL_FILETYPE_PEM
);
3132 SSL_CTX_use_certificate_chain_file(context
, ServerCertificate
);
3134 bio
= BIO_new(_httpBIOMethods());
3135 BIO_ctrl(bio
, BIO_C_SET_FILE_PTR
, 0, (char *)HTTP(con
));
3137 conn
= SSL_new(context
);
3138 SSL_set_bio(conn
, bio
, bio
);
3140 if (SSL_accept(conn
) != 1)
3142 cupsdLogMessage(CUPSD_LOG_ERROR
,
3143 "encrypt_client: Unable to encrypt connection from %s!",
3144 con
->http
.hostname
);
3146 while ((error
= ERR_get_error()) != 0)
3147 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s",
3148 ERR_error_string(error
, NULL
));
3150 SSL_CTX_free(context
);
3155 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3156 "encrypt_client: %d Connection from %s now encrypted.",
3157 con
->http
.fd
, con
->http
.hostname
);
3159 con
->http
.tls
= conn
;
3162 # elif defined(HAVE_GNUTLS)
3163 http_tls_t
*conn
; /* TLS session object */
3164 int error
; /* Error code */
3165 gnutls_certificate_server_credentials
*credentials
;
3166 /* TLS credentials */
3170 * Verify that we have a certificate...
3173 if (access(ServerKey
, 0) || access(ServerCertificate
, 0))
3176 * Nope, make a self-signed certificate...
3179 if (!make_certificate(con
))
3184 * Create the SSL object and perform the SSL handshake...
3187 conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
));
3192 credentials
= (gnutls_certificate_server_credentials
*)
3193 malloc(sizeof(gnutls_certificate_server_credentials
));
3194 if (credentials
== NULL
)
3196 cupsdLogMessage(CUPSD_LOG_ERROR
,
3197 "encrypt_client: Unable to encrypt connection from %s!",
3198 con
->http
.hostname
);
3199 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s", strerror(errno
));
3205 gnutls_certificate_allocate_credentials(credentials
);
3206 gnutls_certificate_set_x509_key_file(*credentials
, ServerCertificate
,
3207 ServerKey
, GNUTLS_X509_FMT_PEM
);
3209 gnutls_init(&(conn
->session
), GNUTLS_SERVER
);
3210 gnutls_set_default_priority(conn
->session
);
3211 gnutls_credentials_set(conn
->session
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
3212 gnutls_transport_set_ptr(conn
->session
, (gnutls_transport_ptr
)HTTP(con
));
3213 gnutls_transport_set_pull_function(conn
->session
, _httpReadGNUTLS
);
3214 gnutls_transport_set_push_function(conn
->session
, _httpWriteGNUTLS
);
3216 error
= gnutls_handshake(conn
->session
);
3218 if (error
!= GNUTLS_E_SUCCESS
)
3220 cupsdLogMessage(CUPSD_LOG_ERROR
,
3221 "encrypt_client: Unable to encrypt connection from %s!",
3222 con
->http
.hostname
);
3223 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s",
3224 gnutls_strerror(error
));
3226 gnutls_deinit(conn
->session
);
3227 gnutls_certificate_free_credentials(*credentials
);
3233 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3234 "encrypt_client: %d Connection from %s now encrypted.",
3235 con
->http
.fd
, con
->http
.hostname
);
3237 conn
->credentials
= credentials
;
3238 con
->http
.tls
= conn
;
3241 # elif defined(HAVE_CDSASSL)
3242 OSStatus error
; /* Error code */
3243 http_tls_t
*conn
; /* CDSA connection information */
3246 if ((conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
))) == NULL
)
3250 conn
->session
= NULL
;
3251 conn
->certsArray
= get_cdsa_certificate(con
);
3253 if (!conn
->certsArray
)
3256 * No keychain (yet), make a self-signed certificate...
3259 if (make_certificate(con
))
3260 conn
->certsArray
= get_cdsa_certificate(con
);
3263 if (!conn
->certsArray
)
3265 cupsdLogMessage(CUPSD_LOG_ERROR
,
3266 "encrypt_client: Could not find signing key in keychain "
3267 "\"%s\"", ServerCertificate
);
3268 error
= errSSLBadCert
; /* errSSLBadConfiguration is a better choice, but not available on 10.2.x */
3272 error
= SSLNewContext(true, &conn
->session
);
3275 error
= SSLSetIOFuncs(conn
->session
, _httpReadCDSA
, _httpWriteCDSA
);
3278 error
= SSLSetProtocolVersionEnabled(conn
->session
, kSSLProtocol2
, false);
3281 error
= SSLSetConnection(conn
->session
, HTTP(con
));
3284 error
= SSLSetAllowsExpiredCerts(conn
->session
, true);
3287 error
= SSLSetAllowsAnyRoot(conn
->session
, true);
3290 error
= SSLSetCertificate(conn
->session
, conn
->certsArray
);
3295 * Perform SSL/TLS handshake
3298 while ((error
= SSLHandshake(conn
->session
)) == errSSLWouldBlock
)
3304 cupsdLogMessage(CUPSD_LOG_ERROR
,
3305 "encrypt_client: Unable to encrypt connection from %s!",
3306 con
->http
.hostname
);
3308 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s (%d)",
3309 cssmErrorString(error
), (int)error
);
3311 con
->http
.error
= error
;
3312 con
->http
.status
= HTTP_ERROR
;
3315 SSLDisposeContext(conn
->session
);
3317 if (conn
->certsArray
)
3318 CFRelease(conn
->certsArray
);
3325 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3326 "encrypt_client: %d Connection from %s now encrypted.",
3327 con
->http
.fd
, con
->http
.hostname
);
3329 con
->http
.tls
= conn
;
3332 # endif /* HAVE_LIBSSL */
3334 #endif /* HAVE_SSL */
3339 * 'get_cdsa_certificate()' - Get a SSL/TLS certificate from the System keychain.
3342 static CFArrayRef
/* O - Array of certificates */
3343 get_cdsa_certificate(cupsd_client_t
*con
) /* I - Client connection */
3345 OSStatus err
; /* Error info */
3346 SecKeychainRef keychain
; /* Keychain reference */
3347 SecIdentitySearchRef search
; /* Search reference */
3348 SecIdentityRef identity
; /* Identity */
3349 CFArrayRef certificates
= NULL
;
3350 /* Certificate array */
3353 if ((err
= SecKeychainOpen(ServerCertificate
, &keychain
)))
3355 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot open keychain \"%s\", %s",
3356 ServerCertificate
, cssmErrorString(err
));
3360 # if HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY
3362 * Use a policy to search for valid certificates who's common name matches the
3366 SecPolicySearchRef policy_search
; /* Policy search ref */
3367 SecPolicyRef policy
; /* Policy ref */
3368 CSSM_DATA options
; /* Policy options */
3369 CSSM_APPLE_TP_SSL_OPTIONS
3370 ssl_options
; /* SSL Option for hostname */
3373 if (SecPolicySearchCreate(CSSM_CERT_X_509v3
, &CSSMOID_APPLE_TP_SSL
,
3374 NULL
, &policy_search
))
3376 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot create a policy search reference");
3377 CFRelease(keychain
);
3381 if (SecPolicySearchCopyNext(policy_search
, &policy
))
3383 cupsdLogMessage(CUPSD_LOG_ERROR
,
3384 "Cannot find a policy to use for searching");
3385 CFRelease(keychain
);
3386 CFRelease(policy_search
);
3390 memset(&ssl_options
, 0, sizeof(ssl_options
));
3391 ssl_options
.Version
= CSSM_APPLE_TP_SSL_OPTS_VERSION
;
3392 ssl_options
.ServerName
= con
->servername
;
3393 ssl_options
.ServerNameLen
= strlen(con
->servername
);
3395 options
.Data
= (uint8
*)&ssl_options
;
3396 options
.Length
= sizeof(ssl_options
);
3398 if (SecPolicySetValue(policy
, &options
))
3400 cupsdLogMessage(CUPSD_LOG_ERROR
,
3401 "Cannot set policy value to use for searching");
3402 CFRelease(keychain
);
3403 CFRelease(policy_search
);
3407 err
= SecIdentitySearchCreateWithPolicy(policy
, NULL
, CSSM_KEYUSE_SIGN
,
3408 keychain
, FALSE
, &search
);
3411 * Assume there is exactly one SecIdentity in the keychain...
3414 err
= SecIdentitySearchCreate(keychain
, CSSM_KEYUSE_SIGN
, &search
);
3415 # endif /* HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY */
3418 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3419 "Cannot create keychain search reference: %s",
3420 cssmErrorString(err
));
3423 if ((err
= SecIdentitySearchCopyNext(search
, &identity
)))
3425 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3426 "Cannot find signing key in keychain \"%s\", error %d",
3427 ServerCertificate
, (int)err
);
3431 if (CFGetTypeID(identity
) != SecIdentityGetTypeID())
3432 cupsdLogMessage(CUPSD_LOG_ERROR
,
3433 "SecIdentitySearchCopyNext CFTypeID failure!");
3436 if ((certificates
= CFArrayCreate(NULL
, (const void **)&identity
,
3437 1, &kCFTypeArrayCallBacks
)) == NULL
)
3438 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot create certificate array");
3441 CFRelease(identity
);
3447 # if HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY
3449 CFRelease(policy_search
);
3450 # endif /* HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY */
3452 return (certificates
);
3454 #endif /* HAVE_CDSASSL */
3458 * 'get_file()' - Get a filename and state info.
3461 static char * /* O - Real filename */
3462 get_file(cupsd_client_t
*con
, /* I - Client connection */
3463 struct stat
*filestats
, /* O - File information */
3464 char *filename
, /* IO - Filename buffer */
3465 int len
) /* I - Buffer length */
3467 int status
; /* Status of filesystem calls */
3468 char *ptr
; /* Pointer info filename */
3469 int plen
; /* Remaining length after pointer */
3470 char language
[7]; /* Language subdirectory, if any */
3474 * Figure out the real filename...
3479 if (!strncmp(con
->uri
, "/ppd/", 5))
3480 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
);
3481 else if (!strncmp(con
->uri
, "/rss/", 5) && !strchr(con
->uri
+ 5, '/'))
3482 snprintf(filename
, len
, "%s/rss/%s", CacheDir
, con
->uri
+ 5);
3483 else if (!strncmp(con
->uri
, "/admin/conf/", 12))
3484 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
+ 11);
3485 else if (!strncmp(con
->uri
, "/admin/log/", 11))
3487 if (!strncmp(con
->uri
+ 11, "access_log", 10) && AccessLog
[0] == '/')
3488 strlcpy(filename
, AccessLog
, len
);
3489 else if (!strncmp(con
->uri
+ 11, "error_log", 9) && ErrorLog
[0] == '/')
3490 strlcpy(filename
, ErrorLog
, len
);
3491 else if (!strncmp(con
->uri
+ 11, "page_log", 8) && PageLog
[0] == '/')
3492 strlcpy(filename
, PageLog
, len
);
3496 else if (con
->language
)
3498 snprintf(language
, sizeof(language
), "/%s", con
->language
->language
);
3499 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3502 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3504 if ((ptr
= strchr(filename
, '?')) != NULL
)
3508 * Grab the status for this language; if there isn't a language-specific file
3509 * then fallback to the default one...
3512 if ((status
= stat(filename
, filestats
)) != 0 && language
[0] &&
3513 strncmp(con
->uri
, "/ppd/", 5) &&
3514 strncmp(con
->uri
, "/admin/conf/", 12) &&
3515 strncmp(con
->uri
, "/admin/log/", 11))
3518 * Drop the country code...
3522 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3524 if ((ptr
= strchr(filename
, '?')) != NULL
)
3527 if ((status
= stat(filename
, filestats
)) != 0)
3530 * Drop the language prefix and try the root directory...
3534 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3536 if ((ptr
= strchr(filename
, '?')) != NULL
)
3539 status
= stat(filename
, filestats
);
3544 * If we're found a directory, get the index.html file instead...
3547 if (!status
&& S_ISDIR(filestats
->st_mode
))
3550 * Make sure the URI ends with a slash...
3553 if (con
->uri
[strlen(con
->uri
) - 1] != '/')
3554 strlcat(con
->uri
, "/", sizeof(con
->uri
));
3557 * Find the directory index file, trying every language...
3562 if (status
&& language
[0])
3565 * Try a different language subset...
3569 language
[0] = '\0'; /* Strip country code */
3571 language
[0] = '\0'; /* Strip language */
3575 * Look for the index file...
3578 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3580 if ((ptr
= strchr(filename
, '?')) != NULL
)
3583 ptr
= filename
+ strlen(filename
);
3584 plen
= len
- (ptr
- filename
);
3586 strlcpy(ptr
, "index.html", plen
);
3587 status
= stat(filename
, filestats
);
3592 strlcpy(ptr
, "index.class", plen
);
3593 status
= stat(filename
, filestats
);
3595 #endif /* HAVE_JAVA */
3600 strlcpy(ptr
, "index.pl", plen
);
3601 status
= stat(filename
, filestats
);
3603 #endif /* HAVE_PERL */
3608 strlcpy(ptr
, "index.php", plen
);
3609 status
= stat(filename
, filestats
);
3611 #endif /* HAVE_PHP */
3616 strlcpy(ptr
, "index.pyc", plen
);
3617 status
= stat(filename
, filestats
);
3622 strlcpy(ptr
, "index.py", plen
);
3623 status
= stat(filename
, filestats
);
3625 #endif /* HAVE_PYTHON */
3628 while (status
&& language
[0]);
3631 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "get_file: %d filename=%s size=%d",
3632 con
->http
.fd
, filename
,
3633 status
? -1 : (int)filestats
->st_size
);
3636 con
->http
.data_remaining
= (int)filestats
->st_size
;
3646 * 'install_conf_file()' - Install a configuration file.
3649 static http_status_t
/* O - Status */
3650 install_conf_file(cupsd_client_t
*con
) /* I - Connection */
3652 cups_file_t
*in
, /* Input file */
3653 *out
; /* Output file */
3654 char buffer
[1024]; /* Copy buffer */
3655 int bytes
; /* Number of bytes */
3656 char conffile
[1024], /* Configuration filename */
3657 newfile
[1024], /* New config filename */
3658 oldfile
[1024]; /* Old config filename */
3659 struct stat confinfo
; /* Config file info */
3663 * First construct the filenames...
3666 snprintf(conffile
, sizeof(conffile
), "%s%s", ServerRoot
, con
->uri
+ 11);
3667 snprintf(newfile
, sizeof(newfile
), "%s%s.N", ServerRoot
, con
->uri
+ 11);
3668 snprintf(oldfile
, sizeof(oldfile
), "%s%s.O", ServerRoot
, con
->uri
+ 11);
3670 cupsdLogMessage(CUPSD_LOG_INFO
, "Installing config file \"%s\"...", conffile
);
3673 * Get the owner, group, and permissions of the configuration file.
3674 * If it doesn't exist, assign it to the User and Group in the
3675 * cupsd.conf file with mode 0640 permissions.
3678 if (stat(conffile
, &confinfo
))
3680 confinfo
.st_uid
= User
;
3681 confinfo
.st_gid
= Group
;
3682 confinfo
.st_mode
= ConfigFilePerm
;
3686 * Open the request file and new config file...
3689 if ((in
= cupsFileOpen(con
->filename
, "rb")) == NULL
)
3691 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open request file \"%s\" - %s",
3692 con
->filename
, strerror(errno
));
3693 return (HTTP_SERVER_ERROR
);
3696 if ((out
= cupsFileOpen(newfile
, "wb")) == NULL
)
3699 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open config file \"%s\" - %s",
3700 newfile
, strerror(errno
));
3701 return (HTTP_SERVER_ERROR
);
3704 fchmod(cupsFileNumber(out
), confinfo
.st_mode
);
3705 fchown(cupsFileNumber(out
), confinfo
.st_uid
, confinfo
.st_gid
);
3708 * Copy from the request to the new config file...
3711 while ((bytes
= cupsFileRead(in
, buffer
, sizeof(buffer
))) > 0)
3712 if (cupsFileWrite(out
, buffer
, bytes
) < bytes
)
3714 cupsdLogMessage(CUPSD_LOG_ERROR
,
3715 "Unable to copy to config file \"%s\" - %s",
3716 newfile
, strerror(errno
));
3722 return (HTTP_SERVER_ERROR
);
3726 * Close the files...
3730 if (cupsFileClose(out
))
3732 cupsdLogMessage(CUPSD_LOG_ERROR
,
3733 "Error file closing config file \"%s\" - %s",
3734 newfile
, strerror(errno
));
3738 return (HTTP_SERVER_ERROR
);
3742 * Remove the request file...
3745 unlink(con
->filename
);
3746 cupsdClearString(&con
->filename
);
3749 * Unlink the old backup, rename the current config file to the backup
3750 * filename, and rename the new config file to the config file name...
3753 if (unlink(oldfile
))
3754 if (errno
!= ENOENT
)
3756 cupsdLogMessage(CUPSD_LOG_ERROR
,
3757 "Unable to remove backup config file \"%s\" - %s",
3758 oldfile
, strerror(errno
));
3762 return (HTTP_SERVER_ERROR
);
3765 if (rename(conffile
, oldfile
))
3766 if (errno
!= ENOENT
)
3768 cupsdLogMessage(CUPSD_LOG_ERROR
,
3769 "Unable to rename old config file \"%s\" - %s",
3770 conffile
, strerror(errno
));
3774 return (HTTP_SERVER_ERROR
);
3777 if (rename(newfile
, conffile
))
3779 cupsdLogMessage(CUPSD_LOG_ERROR
,
3780 "Unable to rename new config file \"%s\" - %s",
3781 newfile
, strerror(errno
));
3783 rename(oldfile
, conffile
);
3786 return (HTTP_SERVER_ERROR
);
3790 * If the cupsd.conf file was updated, set the NeedReload flag...
3793 if (!strcmp(con
->uri
, "/admin/conf/cupsd.conf"))
3794 NeedReload
= RELOAD_CUPSD
;
3796 NeedReload
= RELOAD_ALL
;
3798 ReloadTime
= time(NULL
);
3801 * Return that the file was created successfully...
3804 return (HTTP_CREATED
);
3809 * 'is_cgi()' - Is the resource a CGI script/program?
3812 static int /* O - 1 = CGI, 0 = file */
3813 is_cgi(cupsd_client_t
*con
, /* I - Client connection */
3814 const char *filename
, /* I - Real filename */
3815 struct stat
*filestats
, /* I - File information */
3816 mime_type_t
*type
) /* I - MIME type */
3818 const char *options
; /* Options on URL */
3821 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3822 "is_cgi(con=%p, filename=\"%s\", filestats=%p, type=%s/%s)",
3823 con
, filename
, filestats
, type
? type
->super
: "unknown",
3824 type
? type
->type
: "unknown");
3827 * Get the options, if any...
3830 if ((options
= strchr(con
->uri
, '?')) != NULL
)
3833 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", options
);
3837 * Check for known types...
3840 if (!type
|| strcasecmp(type
->super
, "application"))
3842 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "is_cgi: Returning 0...");
3846 if (!strcasecmp(type
->type
, "x-httpd-cgi") &&
3847 (filestats
->st_mode
& 0111))
3850 * "application/x-httpd-cgi" is a CGI script.
3853 cupsdSetString(&con
->command
, filename
);
3856 cupsdSetStringf(&con
->options
, " %s", options
);
3858 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3859 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3860 con
->command
, con
->options
);
3865 else if (!strcasecmp(type
->type
, "x-httpd-java"))
3868 * "application/x-httpd-java" is a Java servlet.
3871 cupsdSetString(&con
->command
, CUPS_JAVA
);
3874 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3876 cupsdSetStringf(&con
->options
, " %s", filename
);
3878 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3879 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3880 con
->command
, con
->options
);
3884 #endif /* HAVE_JAVA */
3886 else if (!strcasecmp(type
->type
, "x-httpd-perl"))
3889 * "application/x-httpd-perl" is a Perl page.
3892 cupsdSetString(&con
->command
, CUPS_PERL
);
3895 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3897 cupsdSetStringf(&con
->options
, " %s", filename
);
3899 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3900 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3901 con
->command
, con
->options
);
3905 #endif /* HAVE_PERL */
3907 else if (!strcasecmp(type
->type
, "x-httpd-php"))
3910 * "application/x-httpd-php" is a PHP page.
3913 cupsdSetString(&con
->command
, CUPS_PHP
);
3916 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3918 cupsdSetStringf(&con
->options
, " %s", filename
);
3920 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3921 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3922 con
->command
, con
->options
);
3926 #endif /* HAVE_PHP */
3928 else if (!strcasecmp(type
->type
, "x-httpd-python"))
3931 * "application/x-httpd-python" is a Python page.
3934 cupsdSetString(&con
->command
, CUPS_PYTHON
);
3937 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3939 cupsdSetStringf(&con
->options
, " %s", filename
);
3941 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3942 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3943 con
->command
, con
->options
);
3947 #endif /* HAVE_PYTHON */
3949 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "is_cgi: Returning 0...");
3956 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
3959 static int /* O - 0 if relative, 1 if absolute */
3960 is_path_absolute(const char *path
) /* I - Input path */
3963 * Check for a leading slash...
3970 * Check for "/.." in the path...
3973 while ((path
= strstr(path
, "/..")) != NULL
)
3975 if (!path
[3] || path
[3] == '/')
3982 * If we haven't found any relative paths, return 1 indicating an
3992 * 'make_certificate()' - Make a self-signed SSL/TLS certificate.
3995 static int /* O - 1 on success, 0 on failure */
3996 make_certificate(cupsd_client_t
*con
) /* I - Client connection */
3998 #if defined(HAVE_LIBSSL) && defined(HAVE_WAITPID)
3999 int pid
, /* Process ID of command */
4000 status
; /* Status of command */
4001 char command
[1024], /* Command */
4002 *argv
[12], /* Command-line arguments */
4003 *envp
[MAX_ENV
+ 1], /* Environment variables */
4004 home
[1024], /* HOME environment variable */
4005 infofile
[1024], /* Type-in information for cert */
4006 seedfile
[1024]; /* Random number seed file */
4007 int envc
, /* Number of environment variables */
4008 bytes
; /* Bytes written */
4009 cups_file_t
*fp
; /* Seed/info file */
4010 int infofd
; /* Info file descriptor */
4014 * Run the "openssl" command to seed the random number generator and
4015 * generate a self-signed certificate that is good for 10 years:
4017 * openssl rand -rand seedfile 1
4019 * openssl req -new -x509 -keyout ServerKey \
4020 * -out ServerCertificate -days 3650 -nodes
4022 * The seeding step is crucial in ensuring that the openssl command
4023 * does not block on systems without sufficient entropy...
4026 if (!cupsFileFind("openssl", getenv("PATH"), 1, command
, sizeof(command
)))
4028 cupsdLogMessage(CUPSD_LOG_ERROR
,
4029 "No SSL certificate and openssl command not found!");
4033 if (access("/dev/urandom", 0))
4036 * If the system doesn't provide /dev/urandom, then any random source
4037 * will probably be blocking-style, so generate some random data to
4038 * use as a seed for the certificate. Note that we have already
4039 * seeded the random number generator in cupsdInitCerts()...
4042 cupsdLogMessage(CUPSD_LOG_INFO
,
4043 "Seeding the random number generator...");
4045 snprintf(home
, sizeof(home
), "HOME=%s", TempDir
);
4048 * Write the seed file...
4051 if ((fp
= cupsTempFile2(seedfile
, sizeof(seedfile
))) == NULL
)
4053 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to create seed file %s - %s",
4054 seedfile
, strerror(errno
));
4058 for (bytes
= 0; bytes
< 262144; bytes
++)
4059 cupsFilePutChar(fp
, random());
4064 * Run the openssl command to seed its random number generator...
4067 argv
[0] = "openssl";
4074 envc
= cupsdLoadEnv(envp
, MAX_ENV
);
4075 envp
[envc
++] = home
;
4078 if (!cupsdStartProcess(command
, argv
, envp
, -1, -1, -1, -1, -1, 1, NULL
,
4085 while (waitpid(pid
, &status
, 0) < 0)
4092 cupsdFinishProcess(pid
, command
, sizeof(command
));
4095 * Remove the seed file, as it is no longer needed...
4102 if (WIFEXITED(status
))
4103 cupsdLogMessage(CUPSD_LOG_ERROR
,
4104 "Unable to seed random number generator - "
4105 "the openssl command stopped with status %d!",
4106 WEXITSTATUS(status
));
4108 cupsdLogMessage(CUPSD_LOG_ERROR
,
4109 "Unable to seed random number generator - "
4110 "the openssl command crashed on signal %d!",
4118 * Create a file with the certificate information fields...
4120 * Note: This assumes that the default questions are asked by the openssl
4124 if ((fp
= cupsTempFile2(infofile
, sizeof(infofile
))) == NULL
)
4126 cupsdLogMessage(CUPSD_LOG_ERROR
,
4127 "Unable to create certificate information file %s - %s",
4128 infofile
, strerror(errno
));
4132 cupsFilePrintf(fp
, ".\n.\n.\n%s\n.\n%s\n%s\n",
4133 ServerName
, ServerName
, ServerAdmin
);
4136 cupsdLogMessage(CUPSD_LOG_INFO
,
4137 "Generating SSL server key and certificate...");
4139 argv
[0] = "openssl";
4143 argv
[4] = "-keyout";
4144 argv
[5] = ServerKey
;
4146 argv
[7] = ServerCertificate
;
4149 argv
[10] = "-nodes";
4152 cupsdLoadEnv(envp
, MAX_ENV
);
4154 infofd
= open(infofile
, O_RDONLY
);
4156 if (!cupsdStartProcess(command
, argv
, envp
, infofd
, -1, -1, -1, -1, 1, NULL
,
4167 while (waitpid(pid
, &status
, 0) < 0)
4174 cupsdFinishProcess(pid
, command
, sizeof(command
));
4178 if (WIFEXITED(status
))
4179 cupsdLogMessage(CUPSD_LOG_ERROR
,
4180 "Unable to create SSL server key and certificate - "
4181 "the openssl command stopped with status %d!",
4182 WEXITSTATUS(status
));
4184 cupsdLogMessage(CUPSD_LOG_ERROR
,
4185 "Unable to create SSL server key and certificate - "
4186 "the openssl command crashed on signal %d!",
4191 cupsdLogMessage(CUPSD_LOG_INFO
, "Created SSL server key file \"%s\"...",
4193 cupsdLogMessage(CUPSD_LOG_INFO
,
4194 "Created SSL server certificate file \"%s\"...",
4200 #elif defined(HAVE_GNUTLS)
4201 gnutls_x509_crt crt
; /* Self-signed certificate */
4202 gnutls_x509_privkey key
; /* Encryption key */
4203 cups_lang_t
*language
; /* Default language info */
4204 cups_file_t
*fp
; /* Key/cert file */
4205 unsigned char buffer
[8192]; /* Buffer for x509 data */
4206 size_t bytes
; /* Number of bytes of data */
4207 unsigned char serial
[4]; /* Serial number buffer */
4208 time_t curtime
; /* Current time */
4209 int result
; /* Result of GNU TLS calls */
4213 * Create the encryption key...
4216 cupsdLogMessage(CUPSD_LOG_INFO
, "Generating SSL server key...");
4218 gnutls_x509_privkey_init(&key
);
4219 gnutls_x509_privkey_generate(key
, GNUTLS_PK_RSA
, 2048, 0);
4225 bytes
= sizeof(buffer
);
4227 if ((result
= gnutls_x509_privkey_export(key
, GNUTLS_X509_FMT_PEM
,
4228 buffer
, &bytes
)) < 0)
4230 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to export SSL server key - %s",
4231 gnutls_strerror(result
));
4232 gnutls_x509_privkey_deinit(key
);
4235 else if ((fp
= cupsFileOpen(ServerKey
, "w")) != NULL
)
4237 cupsFileWrite(fp
, (char *)buffer
, bytes
);
4240 cupsdLogMessage(CUPSD_LOG_INFO
, "Created SSL server key file \"%s\"...",
4245 cupsdLogMessage(CUPSD_LOG_ERROR
,
4246 "Unable to create SSL server key file \"%s\" - %s",
4247 ServerKey
, strerror(errno
));
4248 gnutls_x509_privkey_deinit(key
);
4253 * Create the self-signed certificate...
4256 cupsdLogMessage(CUPSD_LOG_INFO
, "Generating self-signed SSL certificate...");
4258 language
= cupsLangDefault();
4259 curtime
= time(NULL
);
4260 serial
[0] = curtime
>> 24;
4261 serial
[1] = curtime
>> 16;
4262 serial
[2] = curtime
>> 8;
4263 serial
[3] = curtime
;
4265 gnutls_x509_crt_init(&crt
);
4266 if (strlen(language
->language
) == 5)
4267 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
4268 language
->language
+ 3, 2);
4270 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
4272 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COMMON_NAME
, 0,
4273 ServerName
, strlen(ServerName
));
4274 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATION_NAME
, 0,
4275 ServerName
, strlen(ServerName
));
4276 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATIONAL_UNIT_NAME
,
4278 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_STATE_OR_PROVINCE_NAME
, 0,
4280 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_LOCALITY_NAME
, 0,
4282 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_PKCS9_EMAIL
, 0,
4283 ServerAdmin
, strlen(ServerAdmin
));
4284 gnutls_x509_crt_set_key(crt
, key
);
4285 gnutls_x509_crt_set_serial(crt
, serial
, sizeof(serial
));
4286 gnutls_x509_crt_set_activation_time(crt
, curtime
);
4287 gnutls_x509_crt_set_expiration_time(crt
, curtime
+ 10 * 365 * 86400);
4288 gnutls_x509_crt_set_ca_status(crt
, 0);
4289 gnutls_x509_crt_set_subject_alternative_name(crt
, GNUTLS_SAN_DNSNAME
,
4291 gnutls_x509_crt_set_key_purpose_oid(crt
, GNUTLS_KP_TLS_WWW_SERVER
, 0);
4292 gnutls_x509_crt_set_key_usage(crt
, GNUTLS_KEY_KEY_ENCIPHERMENT
);
4293 gnutls_x509_crt_set_version(crt
, 3);
4295 bytes
= sizeof(buffer
);
4296 if (gnutls_x509_crt_get_key_id(crt
, 0, buffer
, &bytes
) >= 0)
4297 gnutls_x509_crt_set_subject_key_id(crt
, buffer
, bytes
);
4299 gnutls_x509_crt_sign(crt
, crt
, key
);
4305 bytes
= sizeof(buffer
);
4306 if ((result
= gnutls_x509_crt_export(crt
, GNUTLS_X509_FMT_PEM
,
4307 buffer
, &bytes
)) < 0)
4308 cupsdLogMessage(CUPSD_LOG_ERROR
,
4309 "Unable to export SSL server certificate - %s",
4310 gnutls_strerror(result
));
4311 else if ((fp
= cupsFileOpen(ServerCertificate
, "w")) != NULL
)
4313 cupsFileWrite(fp
, (char *)buffer
, bytes
);
4316 cupsdLogMessage(CUPSD_LOG_INFO
,
4317 "Created SSL server certificate file \"%s\"...",
4321 cupsdLogMessage(CUPSD_LOG_ERROR
,
4322 "Unable to create SSL server certificate file \"%s\" - %s",
4323 ServerCertificate
, strerror(errno
));
4329 gnutls_x509_crt_deinit(crt
);
4330 gnutls_x509_privkey_deinit(key
);
4334 #elif defined(HAVE_CDSASSL) && defined(HAVE_WAITPID)
4335 int pid
, /* Process ID of command */
4336 status
; /* Status of command */
4337 char command
[1024], /* Command */
4338 *argv
[4], /* Command-line arguments */
4339 *envp
[MAX_ENV
+ 1], /* Environment variables */
4340 keychain
[1024], /* Keychain argument */
4341 infofile
[1024]; /* Type-in information for cert */
4342 cups_file_t
*fp
; /* Seed/info file */
4343 int infofd
; /* Info file descriptor */
4347 * Run the "certtool" command to generate a self-signed certificate...
4350 if (!cupsFileFind("certtool", getenv("PATH"), 1, command
, sizeof(command
)))
4352 cupsdLogMessage(CUPSD_LOG_ERROR
,
4353 "No SSL certificate and certtool command not found!");
4358 * Create a file with the certificate information fields...
4360 * Note: This assumes that the default questions are asked by the certtool
4364 if ((fp
= cupsTempFile2(infofile
, sizeof(infofile
))) == NULL
)
4366 cupsdLogMessage(CUPSD_LOG_ERROR
,
4367 "Unable to create certificate information file %s - %s",
4368 infofile
, strerror(errno
));
4372 cupsFilePrintf(fp
, "%s\nr\n\ny\nb\ns\ny\n%s\n\n\n\n\n%s\ny\n",
4373 con
->servername
, con
->servername
, ServerAdmin
);
4376 cupsdLogMessage(CUPSD_LOG_INFO
,
4377 "Generating SSL server key and certificate...");
4379 snprintf(keychain
, sizeof(keychain
), "k=%s", ServerCertificate
);
4381 argv
[0] = "certtool";
4386 cupsdLoadEnv(envp
, MAX_ENV
);
4388 infofd
= open(infofile
, O_RDONLY
);
4390 if (!cupsdStartProcess(command
, argv
, envp
, infofd
, -1, -1, -1, -1, 1, NULL
,
4401 while (waitpid(pid
, &status
, 0) < 0)
4408 cupsdFinishProcess(pid
, command
, sizeof(command
));
4412 if (WIFEXITED(status
))
4413 cupsdLogMessage(CUPSD_LOG_ERROR
,
4414 "Unable to create SSL server key and certificate - "
4415 "the certtool command stopped with status %d!",
4416 WEXITSTATUS(status
));
4418 cupsdLogMessage(CUPSD_LOG_ERROR
,
4419 "Unable to create SSL server key and certificate - "
4420 "the certtool command crashed on signal %d!",
4425 cupsdLogMessage(CUPSD_LOG_INFO
,
4426 "Created SSL server certificate file \"%s\"...",
4434 #endif /* HAVE_LIBSSL && HAVE_WAITPID */
4436 #endif /* HAVE_SSL */
4440 * 'pipe_command()' - Pipe the output of a command to the remote client.
4443 static int /* O - Process ID */
4444 pipe_command(cupsd_client_t
*con
, /* I - Client connection */
4445 int infile
, /* I - Standard input for command */
4446 int *outfile
, /* O - Standard output for command */
4447 char *command
, /* I - Command to run */
4448 char *options
, /* I - Options for command */
4449 int root
) /* I - Run as root? */
4451 int i
; /* Looping var */
4452 int pid
; /* Process ID */
4453 char *commptr
, /* Command string pointer */
4454 commch
; /* Command string character */
4455 char *uriptr
; /* URI string pointer */
4456 int fds
[2]; /* Pipe FDs */
4457 int argc
; /* Number of arguments */
4458 int envc
; /* Number of environment variables */
4459 char argbuf
[10240], /* Argument buffer */
4460 *argv
[100], /* Argument strings */
4461 *envp
[MAX_ENV
+ 20]; /* Environment variables */
4462 char auth_type
[256], /* CUPSD_AUTH_TYPE environment variable */
4463 content_length
[1024], /* CONTENT_LENGTH environment variable */
4464 content_type
[1024], /* CONTENT_TYPE environment variable */
4465 http_cookie
[32768], /* HTTP_COOKIE environment variable */
4466 http_referer
[1024], /* HTTP_REFERER environment variable */
4467 http_user_agent
[1024], /* HTTP_USER_AGENT environment variable */
4468 lang
[1024], /* LANG environment variable */
4469 path_info
[1024], /* PATH_INFO environment variable */
4470 remote_addr
[1024], /* REMOTE_ADDR environment variable */
4471 remote_host
[1024], /* REMOTE_HOST environment variable */
4472 remote_user
[1024], /* REMOTE_USER environment variable */
4473 script_filename
[1024], /* SCRIPT_FILENAME environment variable */
4474 script_name
[1024], /* SCRIPT_NAME environment variable */
4475 server_name
[1024], /* SERVER_NAME environment variable */
4476 server_port
[1024]; /* SERVER_PORT environment variable */
4477 ipp_attribute_t
*attr
; /* attributes-natural-language attribute */
4479 krb5_ccache ccache
= NULL
; /* Kerberos credentials */
4480 # if defined(HAVE_KRB5_CC_NEW_UNIQUE) || defined(HAVE_HEIMDAL)
4481 char krb5ccname
[1024]; /* KRB5CCNAME environment variable */
4482 # endif /* HAVE_KRB5_CC_NEW_UNIQUE || HAVE_HEIMDAL */
4483 #endif /* HAVE_GSSAPI */
4487 * Parse a copy of the options string, which is of the form:
4489 * argument+argument+argument
4490 * ?argument+argument+argument
4491 * param=value¶m=value
4492 * ?param=value¶m=value
4493 * /name?argument+argument+argument
4494 * /name?param=value¶m=value
4496 * If the string contains an "=" character after the initial name,
4497 * then we treat it as a HTTP GET form request and make a copy of
4498 * the remaining string for the environment variable.
4500 * The string is always parsed out as command-line arguments, to
4501 * be consistent with Apache...
4504 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4505 "pipe_command: command=\"%s\", options=\"%s\"",
4506 command
, options
? options
: "(null)");
4511 strlcpy(argbuf
, options
, sizeof(argbuf
));
4515 if (argbuf
[0] == '/')
4518 * Found some trailing path information, set PATH_INFO...
4521 if ((commptr
= strchr(argbuf
, '?')) == NULL
)
4522 commptr
= argbuf
+ strlen(argbuf
);
4526 snprintf(path_info
, sizeof(path_info
), "PATH_INFO=%s", argbuf
);
4532 path_info
[0] = '\0';
4534 if (*commptr
== ' ')
4538 if (*commptr
== '?' && con
->operation
== HTTP_GET
&& !con
->query_string
)
4541 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", commptr
);
4548 argv
[argc
++] = commptr
;
4550 for (; *commptr
&& argc
< 99; commptr
++)
4553 * Break arguments whenever we see a + or space...
4556 if (*commptr
== ' ' || *commptr
== '+')
4558 while (*commptr
== ' ' || *commptr
== '+')
4562 * If we don't have a blank string, save it as another argument...
4567 argv
[argc
] = commptr
;
4573 else if (*commptr
== '%' && isxdigit(commptr
[1] & 255) &&
4574 isxdigit(commptr
[2] & 255))
4577 * Convert the %xx notation to the individual character.
4580 if (commptr
[1] >= '0' && commptr
[1] <= '9')
4581 *commptr
= (commptr
[1] - '0') << 4;
4583 *commptr
= (tolower(commptr
[1]) - 'a' + 10) << 4;
4585 if (commptr
[2] >= '0' && commptr
[2] <= '9')
4586 *commptr
|= commptr
[2] - '0';
4588 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
4590 _cups_strcpy(commptr
+ 1, commptr
+ 3);
4593 * Check for a %00 and break if that is the case...
4605 * Setup the environment variables as needed...
4608 if (con
->username
[0])
4610 snprintf(auth_type
, sizeof(auth_type
), "CUPSD_AUTH_TYPE=%s",
4611 httpGetField(HTTP(con
), HTTP_FIELD_AUTHORIZATION
));
4613 if ((uriptr
= strchr(auth_type
+ 10, ' ')) != NULL
)
4617 auth_type
[0] = '\0';
4620 (attr
= ippFindAttribute(con
->request
, "attributes-natural-language",
4621 IPP_TAG_LANGUAGE
)) != NULL
)
4623 switch (strlen(attr
->values
[0].string
.text
))
4627 * This is an unknown or badly formatted language code; use
4628 * the POSIX locale...
4631 strcpy(lang
, "LANG=C");
4636 * Just the language code (ll)...
4639 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8",
4640 attr
->values
[0].string
.text
);
4645 * Language and country code (ll-cc)...
4648 snprintf(lang
, sizeof(lang
), "LANG=%c%c_%c%c.UTF8",
4649 attr
->values
[0].string
.text
[0],
4650 attr
->values
[0].string
.text
[1],
4651 toupper(attr
->values
[0].string
.text
[3] & 255),
4652 toupper(attr
->values
[0].string
.text
[4] & 255));
4656 else if (con
->language
)
4657 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8", con
->language
->language
);
4659 strcpy(lang
, "LANG=C");
4661 strcpy(remote_addr
, "REMOTE_ADDR=");
4662 httpAddrString(con
->http
.hostaddr
, remote_addr
+ 12,
4663 sizeof(remote_addr
) - 12);
4665 snprintf(remote_host
, sizeof(remote_host
), "REMOTE_HOST=%s",
4666 con
->http
.hostname
);
4668 snprintf(script_name
, sizeof(script_name
), "SCRIPT_NAME=%s", con
->uri
);
4669 if ((uriptr
= strchr(script_name
, '?')) != NULL
)
4672 snprintf(script_filename
, sizeof(script_filename
), "SCRIPT_FILENAME=%s%s",
4673 DocumentRoot
, script_name
+ 12);
4675 sprintf(server_port
, "SERVER_PORT=%d", con
->serverport
);
4677 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
4680 envc
= cupsdLoadEnv(envp
, (int)(sizeof(envp
) / sizeof(envp
[0])));
4683 envp
[envc
++] = auth_type
;
4685 envp
[envc
++] = lang
;
4686 envp
[envc
++] = "REDIRECT_STATUS=1";
4687 envp
[envc
++] = "GATEWAY_INTERFACE=CGI/1.1";
4688 envp
[envc
++] = server_name
;
4689 envp
[envc
++] = server_port
;
4690 envp
[envc
++] = remote_addr
;
4691 envp
[envc
++] = remote_host
;
4692 envp
[envc
++] = script_name
;
4693 envp
[envc
++] = script_filename
;
4696 envp
[envc
++] = path_info
;
4698 if (con
->username
[0])
4700 snprintf(remote_user
, sizeof(remote_user
), "REMOTE_USER=%s", con
->username
);
4702 envp
[envc
++] = remote_user
;
4705 * Save Kerberos credentials, if any...
4709 if (con
->gss_have_creds
)
4711 # if !defined(HAVE_KRB5_CC_NEW_UNIQUE) && !defined(HAVE_HEIMDAL)
4712 cupsdLogMessage(CUPSD_LOG_INFO
,
4713 "Sorry, your version of Kerberos does not support "
4714 "delegated credentials!");
4717 krb5_error_code error
; /* Kerberos error code */
4718 OM_uint32 major_status
, /* Major status code */
4719 minor_status
; /* Minor status code */
4720 krb5_principal principal
; /* Kerberos principal */
4725 * If the weak-linked GSSAPI/Kerberos library is not present, don't try
4729 if (krb5_init_context
!= NULL
)
4731 # endif /* __APPLE__ */
4733 if (!KerberosInitialized
)
4736 * Setup a Kerberos context for the scheduler to use...
4739 KerberosInitialized
= 1;
4741 if (krb5_init_context(&KerberosContext
))
4743 KerberosContext
= NULL
;
4745 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to initialize Kerberos context");
4750 * We MUST create a file-based cache because memory-based caches are
4751 * only valid for the current process/address space.
4753 * Due to various bugs/features in different versions of Kerberos, we
4754 * need either the krb5_cc_new_unique() function or Heimdal's version
4755 * of krb5_cc_gen_new() to create a new FILE: credential cache that
4756 * can be passed to the backend. These functions create a temporary
4757 * file (typically in /tmp) containing the cached credentials, which
4758 * are removed when we have successfully printed a job.
4761 if (KerberosContext
)
4763 # ifdef HAVE_KRB5_CC_NEW_UNIQUE
4764 if ((error
= krb5_cc_new_unique(KerberosContext
, "FILE", NULL
,
4766 # else /* HAVE_HEIMDAL */
4767 if ((error
= krb5_cc_gen_new(KerberosContext
, &krb5_fcc_ops
,
4769 # endif /* HAVE_KRB5_CC_NEW_UNIQUE */
4771 cupsdLogMessage(CUPSD_LOG_ERROR
,
4772 "Unable to create new credentials cache (%d/%s)",
4773 error
, strerror(errno
));
4776 else if ((error
= krb5_parse_name(KerberosContext
, con
->username
,
4779 cupsdLogMessage(CUPSD_LOG_ERROR
,
4780 "Unable to parse kerberos username (%d/%s)", error
,
4782 krb5_cc_destroy(KerberosContext
, ccache
);
4785 else if ((error
= krb5_cc_initialize(KerberosContext
, ccache
,
4788 cupsdLogMessage(CUPSD_LOG_ERROR
,
4789 "Unable to initialize credentials cache (%d/%s)", error
,
4791 krb5_cc_destroy(KerberosContext
, ccache
);
4792 krb5_free_principal(KerberosContext
, principal
);
4797 krb5_free_principal(KerberosContext
, principal
);
4800 * Copy the user's credentials to the new cache file...
4803 major_status
= gss_krb5_copy_ccache(&minor_status
,
4804 con
->gss_delegated_cred
, ccache
);
4806 if (GSS_ERROR(major_status
))
4808 cupsdLogGSSMessage(CUPSD_LOG_ERROR
, major_status
, minor_status
,
4809 "Unable to import client credentials cache");
4810 krb5_cc_destroy(KerberosContext
, ccache
);
4816 * Add the KRB5CCNAME environment variable to the job so that the
4817 * backend can use the credentials when printing.
4820 snprintf(krb5ccname
, sizeof(krb5ccname
), "KRB5CCNAME=FILE:%s",
4821 krb5_cc_get_name(KerberosContext
, ccache
));
4822 envp
[envc
++] = krb5ccname
;
4825 chown(krb5_cc_get_name(KerberosContext
, ccache
), User
, Group
);
4831 # endif /* __APPLE__ */
4832 # endif /* HAVE_KRB5_CC_NEW_UNIQUE || HAVE_HEIMDAL */
4834 #endif /* HAVE_GSSAPI */
4837 if (con
->http
.version
== HTTP_1_1
)
4838 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.1";
4839 else if (con
->http
.version
== HTTP_1_0
)
4840 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.0";
4842 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/0.9";
4844 if (con
->http
.cookie
)
4846 snprintf(http_cookie
, sizeof(http_cookie
), "HTTP_COOKIE=%s",
4848 envp
[envc
++] = http_cookie
;
4851 if (con
->http
.fields
[HTTP_FIELD_USER_AGENT
][0])
4853 snprintf(http_user_agent
, sizeof(http_user_agent
), "HTTP_USER_AGENT=%s",
4854 con
->http
.fields
[HTTP_FIELD_USER_AGENT
]);
4855 envp
[envc
++] = http_user_agent
;
4858 if (con
->http
.fields
[HTTP_FIELD_REFERER
][0])
4860 snprintf(http_referer
, sizeof(http_referer
), "HTTP_REFERER=%s",
4861 con
->http
.fields
[HTTP_FIELD_REFERER
]);
4862 envp
[envc
++] = http_referer
;
4865 if (con
->operation
== HTTP_GET
)
4867 envp
[envc
++] = "REQUEST_METHOD=GET";
4869 if (con
->query_string
)
4872 * Add GET form variables after ?...
4875 envp
[envc
++] = con
->query_string
;
4878 envp
[envc
++] = "QUERY_STRING=";
4882 sprintf(content_length
, "CONTENT_LENGTH=" CUPS_LLFMT
,
4883 CUPS_LLCAST con
->bytes
);
4884 snprintf(content_type
, sizeof(content_type
), "CONTENT_TYPE=%s",
4885 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
4887 envp
[envc
++] = "REQUEST_METHOD=POST";
4888 envp
[envc
++] = content_length
;
4889 envp
[envc
++] = content_type
;
4893 * Tell the CGI if we are using encryption...
4897 envp
[envc
++] = "HTTPS=ON";
4900 * Terminate the environment array...
4905 if (LogLevel
== CUPSD_LOG_DEBUG2
)
4907 for (i
= 0; i
< argc
; i
++)
4908 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4909 "pipe_command: argv[%d] = \"%s\"", i
, argv
[i
]);
4910 for (i
= 0; i
< envc
; i
++)
4911 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4912 "pipe_command: envp[%d] = \"%s\"", i
, envp
[i
]);
4916 * Create a pipe for the output...
4919 if (cupsdOpenPipe(fds
))
4921 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to create pipes for CGI %s - %s",
4922 argv
[0], strerror(errno
));
4927 * Then execute the command...
4930 if (cupsdStartProcess(command
, argv
, envp
, infile
, fds
[1], CGIPipes
[1],
4931 -1, -1, root
, DefaultProfile
, &pid
) < 0)
4934 * Error - can't fork!
4937 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to fork for CGI %s - %s", argv
[0],
4940 cupsdClosePipe(fds
);
4946 * Fork successful - return the PID...
4949 if (con
->username
[0])
4951 cupsdAddCert(pid
, con
->username
, ccache
);
4953 cupsdAddCert(pid
, con
->username
, NULL
);
4954 #endif /* HAVE_GSSAPI */
4956 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[CGI] %s started - PID = %d",
4968 * 'write_file()' - Send a file via HTTP.
4971 static int /* O - 0 on failure, 1 on success */
4972 write_file(cupsd_client_t
*con
, /* I - Client connection */
4973 http_status_t code
, /* I - HTTP status */
4974 char *filename
, /* I - Filename */
4975 char *type
, /* I - File type */
4976 struct stat
*filestats
) /* O - File information */
4978 con
->file
= open(filename
, O_RDONLY
);
4980 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "write_file: %d file=%d", con
->http
.fd
,
4986 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
4990 if (!cupsdSendHeader(con
, code
, type
, CUPSD_AUTH_NONE
))
4993 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
4994 httpGetDateString(filestats
->st_mtime
)) < 0)
4996 if (httpPrintf(HTTP(con
), "Content-Length: " CUPS_LLFMT
"\r\n",
4997 CUPS_LLCAST filestats
->st_size
) < 0)
4999 if (httpPrintf(HTTP(con
), "\r\n") < 0)
5002 if (cupsdFlushHeader(con
) < 0)
5005 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
5006 con
->http
.data_remaining
= filestats
->st_size
;
5008 if (con
->http
.data_remaining
<= INT_MAX
)
5009 con
->http
._data_remaining
= con
->http
.data_remaining
;
5011 con
->http
._data_remaining
= INT_MAX
;
5013 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
,
5014 (cupsd_selfunc_t
)cupsdWriteClient
, con
);
5021 * 'write_pipe()' - Flag that data is available on the CGI pipe.
5025 write_pipe(cupsd_client_t
*con
) /* I - Client connection */
5027 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "write_pipe: CGI output on fd %d...",
5030 con
->file_ready
= 1;
5032 cupsdRemoveSelect(con
->file
);
5033 cupsdAddSelect(con
->http
.fd
, NULL
, (cupsd_selfunc_t
)cupsdWriteClient
, con
);
5038 * End of "$Id: client.c 7950 2008-09-17 00:21:59Z mike $".