2 * "$Id: client.c 7950 2008-09-17 00:21:59Z mike $"
4 * Client routines for the Common UNIX Printing System (CUPS) scheduler.
6 * Copyright 2007-2009 by Apple Inc.
7 * Copyright 1997-2007 by Easy Software Products, all rights reserved.
9 * This file contains Kerberos support code, copyright 2006 by
12 * These coded instructions, statements, and computer programs are the
13 * property of Apple Inc. and are protected by Federal copyright
14 * law. Distribution and use rights are outlined in the file "LICENSE.txt"
15 * which should have been included with this file. If this file is
16 * file is missing or damaged, see the license at "http://www.cups.org/".
20 * cupsdAcceptClient() - Accept a new client.
21 * cupsdCloseAllClients() - Close all remote clients immediately.
22 * cupsdCloseClient() - Close a remote client.
23 * cupsdFlushHeader() - Flush the header fields to the client.
24 * cupsdReadClient() - Read data from a client.
25 * cupsdSendCommand() - Send output from a command via HTTP.
26 * cupsdSendError() - Send an error message via HTTP.
27 * cupsdSendHeader() - Send an HTTP request.
28 * cupsdUpdateCGI() - Read status messages from CGI scripts and 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.
287 hostname
= httpAddrLookup(con
->http
.hostaddr
, con
->http
.hostname
,
288 sizeof(con
->http
.hostname
));
292 httpAddrString(con
->http
.hostaddr
, con
->http
.hostname
,
293 sizeof(con
->http
.hostname
));
297 if (hostname
== NULL
&& HostNameLookups
== 2)
300 * Can't have an unresolved IP address with double-lookups enabled...
303 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
304 "cupsdAcceptClient: Closing connection %d...",
308 closesocket(con
->http
.fd
);
313 cupsdLogMessage(CUPSD_LOG_WARN
,
314 "Name lookup failed - connection from %s closed!",
321 if (HostNameLookups
== 2)
324 * Do double lookups as needed...
327 if ((addrlist
= httpAddrGetList(con
->http
.hostname
, AF_UNSPEC
, NULL
))
331 * See if the hostname maps to the same IP address...
334 for (addr
= addrlist
; addr
; addr
= addr
->next
)
335 if (httpAddrEqual(con
->http
.hostaddr
, &(addr
->addr
)))
341 httpAddrFreeList(addrlist
);
346 * Can't have a hostname that doesn't resolve to the same IP address
347 * with double-lookups enabled...
350 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
351 "cupsdAcceptClient: Closing connection %d...",
355 closesocket(con
->http
.fd
);
360 cupsdLogMessage(CUPSD_LOG_WARN
,
361 "IP lookup failed - connection from %s closed!",
370 * See if the connection is denied by TCP wrappers...
373 request_init(&wrap_req
, RQ_DAEMON
, "cupsd", RQ_FILE
, con
->http
.fd
, NULL
);
376 if (!hosts_access(&wrap_req
))
378 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
379 "cupsdAcceptClient: Closing connection %d...",
383 closesocket(con
->http
.fd
);
388 cupsdLogMessage(CUPSD_LOG_WARN
,
389 "Connection from %s refused by /etc/hosts.allow and "
390 "/etc/hosts.deny rules.", con
->http
.hostname
);
394 #endif /* HAVE_TCPD_H */
397 if (con
->http
.hostaddr
->addr
.sa_family
== AF_INET6
)
398 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdAcceptClient: %d from %s:%d (IPv6)",
399 con
->http
.fd
, con
->http
.hostname
,
400 ntohs(con
->http
.hostaddr
->ipv6
.sin6_port
));
402 #endif /* AF_INET6 */
404 if (con
->http
.hostaddr
->addr
.sa_family
== AF_LOCAL
)
405 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdAcceptClient: %d from %s (Domain)",
406 con
->http
.fd
, con
->http
.hostname
);
408 #endif /* AF_LOCAL */
409 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdAcceptClient: %d from %s:%d (IPv4)",
410 con
->http
.fd
, con
->http
.hostname
,
411 ntohs(con
->http
.hostaddr
->ipv4
.sin_port
));
414 * Get the local address the client connected to...
417 addrlen
= sizeof(temp
);
418 if (getsockname(con
->http
.fd
, (struct sockaddr
*)&temp
, &addrlen
))
420 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to get local address - %s",
423 strcpy(con
->servername
, "localhost");
424 con
->serverport
= LocalPort
;
429 if (temp
.addr
.sa_family
== AF_INET6
)
432 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
433 else if (httpAddrLocalhost(&temp
))
434 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
436 httpAddrString(&temp
, con
->servername
, sizeof(con
->servername
));
438 con
->serverport
= ntohs(lis
->address
.ipv6
.sin6_port
);
441 #endif /* AF_INET6 */
442 if (temp
.addr
.sa_family
== AF_INET
)
445 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
446 else if (httpAddrLocalhost(&temp
))
447 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
449 httpAddrString(&temp
, con
->servername
, sizeof(con
->servername
));
451 con
->serverport
= ntohs(lis
->address
.ipv4
.sin_port
);
455 strcpy(con
->servername
, "localhost");
456 con
->serverport
= LocalPort
;
460 cupsArrayAdd(Clients
, con
);
462 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
463 "cupsdAcceptClient: %d connected to server on %s:%d",
464 con
->http
.fd
, con
->servername
, con
->serverport
);
467 * Using TCP_NODELAY improves responsiveness, especially on systems
468 * with a slow loopback interface... Since we write large buffers
469 * when sending print files and requests, there shouldn't be any
470 * performance penalty for this...
474 setsockopt(con
->http
.fd
, IPPROTO_TCP
, TCP_NODELAY
, &val
, sizeof(val
));
477 * Close this file on all execs...
480 fcntl(con
->http
.fd
, F_SETFD
, fcntl(con
->http
.fd
, F_GETFD
) | FD_CLOEXEC
);
483 * Add the socket to the select() input mask.
486 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
489 * Temporarily suspend accept()'s until we lose a client...
492 if (cupsArrayCount(Clients
) == MaxClients
)
493 cupsdPauseListening();
497 * See if we are connecting on a secure port...
500 if (lis
->encryption
== HTTP_ENCRYPT_ALWAYS
)
503 * https connection; go secure...
506 con
->http
.encryption
= HTTP_ENCRYPT_ALWAYS
;
508 if (!encrypt_client(con
))
509 cupsdCloseClient(con
);
513 #endif /* HAVE_SSL */
518 * 'cupsdCloseAllClients()' - Close all remote clients immediately.
522 cupsdCloseAllClients(void)
524 cupsd_client_t
*con
; /* Current client */
527 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
529 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
530 if (cupsdCloseClient(con
))
531 cupsdCloseClient(con
);
536 * 'cupsdCloseClient()' - Close a remote client.
539 int /* O - 1 if partial close, 0 if fully closed */
540 cupsdCloseClient(cupsd_client_t
*con
) /* I - Client to close */
542 int partial
; /* Do partial close for SSL? */
544 SSL_CTX
*context
; /* Context for encryption */
545 SSL
*conn
; /* Connection for encryption */
546 unsigned long error
; /* Error code */
547 #elif defined(HAVE_GNUTLS)
548 http_tls_t
*conn
; /* TLS connection information */
549 int error
; /* Error code */
550 gnutls_certificate_server_credentials
*credentials
;
551 /* TLS credentials */
552 # elif defined(HAVE_CDSASSL)
553 http_tls_t
*conn
; /* CDSA connection information */
554 #endif /* HAVE_LIBSSL */
557 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdCloseClient: %d", con
->http
.fd
);
560 * Flush pending writes before closing...
563 httpFlushWrite(HTTP(con
));
569 * Shutdown encryption as needed...
577 conn
= (SSL
*)(con
->http
.tls
);
578 context
= SSL_get_SSL_CTX(conn
);
580 switch (SSL_shutdown(conn
))
583 cupsdLogMessage(CUPSD_LOG_DEBUG
,
584 "SSL shutdown successful!");
587 cupsdLogMessage(CUPSD_LOG_ERROR
,
588 "Fatal error during SSL shutdown!");
590 while ((error
= ERR_get_error()) != 0)
591 cupsdLogMessage(CUPSD_LOG_ERROR
, "SSL shutdown failed: %s",
592 ERR_error_string(error
, NULL
));
596 SSL_CTX_free(context
);
599 # elif defined(HAVE_GNUTLS)
600 conn
= (http_tls_t
*)(con
->http
.tls
);
601 credentials
= (gnutls_certificate_server_credentials
*)(conn
->credentials
);
603 error
= gnutls_bye(conn
->session
, GNUTLS_SHUT_WR
);
606 case GNUTLS_E_SUCCESS
:
607 cupsdLogMessage(CUPSD_LOG_DEBUG
,
608 "SSL shutdown successful!");
611 cupsdLogMessage(CUPSD_LOG_ERROR
,
612 "SSL shutdown failed: %s", gnutls_strerror(error
));
616 gnutls_deinit(conn
->session
);
617 gnutls_certificate_free_credentials(*credentials
);
621 # elif defined(HAVE_CDSASSL)
622 conn
= (http_tls_t
*)(con
->http
.tls
);
624 while (SSLClose(conn
->session
) == errSSLWouldBlock
)
627 SSLDisposeContext(conn
->session
);
629 if (conn
->certsArray
)
630 CFRelease(conn
->certsArray
);
633 # endif /* HAVE_LIBSSL */
635 con
->http
.tls
= NULL
;
637 #endif /* HAVE_SSL */
639 if (con
->pipe_pid
!= 0)
642 * Stop any CGI process...
645 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
646 "cupsdCloseClient: %d Killing process ID %d...",
647 con
->http
.fd
, con
->pipe_pid
);
648 cupsdEndProcess(con
->pipe_pid
, 1);
654 cupsdRemoveSelect(con
->file
);
656 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
657 "cupsdCloseClient: %d Closing data file %d.",
658 con
->http
.fd
, con
->file
);
665 * Close the socket and clear the file from the input set for select()...
668 if (con
->http
.fd
>= 0)
670 cupsArrayRemove(ActiveClients
, con
);
676 * Only do a partial close so that the encrypted client gets everything.
679 shutdown(con
->http
.fd
, 0);
680 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
685 * Shut the socket down fully...
688 cupsdRemoveSelect(con
->http
.fd
);
700 if (con
->http
.input_set
)
701 free(con
->http
.input_set
);
703 httpClearCookie(HTTP(con
));
704 httpClearFields(HTTP(con
));
706 cupsdClearString(&con
->filename
);
707 cupsdClearString(&con
->command
);
708 cupsdClearString(&con
->options
);
709 cupsdClearString(&con
->query_string
);
713 ippDelete(con
->request
);
719 ippDelete(con
->response
);
720 con
->response
= NULL
;
725 cupsLangFree(con
->language
);
726 con
->language
= NULL
;
729 #ifdef HAVE_AUTHORIZATION_H
732 AuthorizationFree(con
->authref
, kAuthorizationFlagDefaults
);
735 #endif /* HAVE_AUTHORIZATION_H */
738 * Re-enable new client connections if we are going back under the
742 if (cupsArrayCount(Clients
) == MaxClients
)
743 cupsdResumeListening();
746 * Compact the list of clients as necessary...
749 cupsArrayRemove(Clients
, con
);
759 * 'cupsdFlushHeader()' - Flush the header fields to the client.
762 int /* I - Bytes written or -1 on error */
763 cupsdFlushHeader(cupsd_client_t
*con
) /* I - Client to flush to */
765 int bytes
= httpFlushWrite(HTTP(con
));
767 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
774 * 'cupsdReadClient()' - Read data from a client.
778 cupsdReadClient(cupsd_client_t
*con
) /* I - Client to read from */
780 char line
[32768], /* Line from client... */
781 operation
[64], /* Operation code from socket */
782 version
[64], /* HTTP version number string */
783 locale
[64], /* Locale */
784 *ptr
; /* Pointer into strings */
785 int major
, minor
; /* HTTP version numbers */
786 http_status_t status
; /* Transfer status */
787 ipp_state_t ipp_state
; /* State of IPP transfer */
788 int bytes
; /* Number of bytes to POST */
789 char *filename
; /* Name of file for GET/HEAD */
790 char buf
[1024]; /* Buffer for real filename */
791 struct stat filestats
; /* File information */
792 mime_type_t
*type
; /* MIME type of file */
793 cupsd_printer_t
*p
; /* Printer */
794 static unsigned request_id
= 0; /* Request ID for temp files */
797 status
= HTTP_CONTINUE
;
799 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
800 "cupsdReadClient: %d, used=%d, file=%d state=%d",
801 con
->http
.fd
, con
->http
.used
, con
->file
, con
->http
.state
);
805 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdReadClient: http error seen...");
806 cupsdCloseClient(con
);
814 * Automatically check for a SSL/TLS handshake...
819 if (recv(con
->http
.fd
, buf
, 1, MSG_PEEK
) == 1 &&
820 (!buf
[0] || !strchr("DGHOPT", buf
[0])))
823 * Encrypt this connection...
826 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
827 "cupsdReadClient: Saw first byte %02X, auto-negotiating SSL/TLS session...",
830 if (!encrypt_client(con
))
831 cupsdCloseClient(con
);
836 #endif /* HAVE_SSL */
838 switch (con
->http
.state
)
842 * See if we've received a request line...
845 if (httpGets(line
, sizeof(line
) - 1, HTTP(con
)) == NULL
)
847 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
848 "cupsdReadClient: httpGets returned EOF...");
849 cupsdCloseClient(con
);
854 * Ignore blank request lines...
861 * Clear other state variables...
864 httpClearFields(HTTP(con
));
866 con
->http
.activity
= time(NULL
);
867 con
->http
.version
= HTTP_1_0
;
868 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
869 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
870 con
->http
.data_remaining
= 0;
871 con
->http
._data_remaining
= 0;
872 con
->operation
= HTTP_WAITING
;
877 con
->username
[0] = '\0';
878 con
->password
[0] = '\0';
881 cupsdClearString(&con
->command
);
882 cupsdClearString(&con
->options
);
883 cupsdClearString(&con
->query_string
);
887 ippDelete(con
->request
);
893 ippDelete(con
->response
);
894 con
->response
= NULL
;
899 cupsLangFree(con
->language
);
900 con
->language
= NULL
;
904 con
->gss_have_creds
= 0;
905 #endif /* HAVE_GSSAPI */
908 * Grab the request line...
911 switch (sscanf(line
, "%63s%1023s%63s", operation
, con
->uri
, version
))
916 cupsdLogMessage(CUPSD_LOG_ERROR
,
917 "Bad request line \"%s\" from %s!", line
,
919 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
920 cupsdCloseClient(con
);
924 con
->http
.version
= HTTP_0_9
;
927 if (sscanf(version
, "HTTP/%d.%d", &major
, &minor
) != 2)
929 cupsdLogMessage(CUPSD_LOG_ERROR
,
930 "Bad request line \"%s\" from %s!", line
,
932 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
933 cupsdCloseClient(con
);
939 con
->http
.version
= (http_version_t
)(major
* 100 + minor
);
940 if (con
->http
.version
== HTTP_1_1
&& KeepAlive
)
941 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
943 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
947 cupsdSendError(con
, HTTP_NOT_SUPPORTED
, CUPSD_AUTH_NONE
);
948 cupsdCloseClient(con
);
955 * Handle full URLs in the request line...
958 if (strcmp(con
->uri
, "*"))
960 char scheme
[HTTP_MAX_URI
], /* Method/scheme */
961 userpass
[HTTP_MAX_URI
], /* Username:password */
962 hostname
[HTTP_MAX_URI
], /* Hostname */
963 resource
[HTTP_MAX_URI
]; /* Resource path */
964 int port
; /* Port number */
968 * Separate the URI into its components...
971 httpSeparateURI(HTTP_URI_CODING_MOST
, con
->uri
,
972 scheme
, sizeof(scheme
),
973 userpass
, sizeof(userpass
),
974 hostname
, sizeof(hostname
), &port
,
975 resource
, sizeof(resource
));
978 * Only allow URIs with the servername, localhost, or an IP
982 if (strcmp(scheme
, "file") &&
983 strcasecmp(hostname
, ServerName
) &&
984 strcasecmp(hostname
, "localhost") &&
985 !isdigit(hostname
[0]) && hostname
[0] != '[')
988 * Nope, we don't do proxies...
991 cupsdLogMessage(CUPSD_LOG_ERROR
, "Bad URI \"%s\" in request!",
993 cupsdSendError(con
, HTTP_METHOD_NOT_ALLOWED
, CUPSD_AUTH_NONE
);
994 cupsdCloseClient(con
);
999 * Copy the resource portion back into the URI; both resource and
1000 * con->uri are HTTP_MAX_URI bytes in size...
1003 strcpy(con
->uri
, resource
);
1007 * Process the request...
1010 if (!strcmp(operation
, "GET"))
1011 con
->http
.state
= HTTP_GET
;
1012 else if (!strcmp(operation
, "PUT"))
1013 con
->http
.state
= HTTP_PUT
;
1014 else if (!strcmp(operation
, "POST"))
1015 con
->http
.state
= HTTP_POST
;
1016 else if (!strcmp(operation
, "DELETE"))
1017 con
->http
.state
= HTTP_DELETE
;
1018 else if (!strcmp(operation
, "TRACE"))
1019 con
->http
.state
= HTTP_TRACE
;
1020 else if (!strcmp(operation
, "OPTIONS"))
1021 con
->http
.state
= HTTP_OPTIONS
;
1022 else if (!strcmp(operation
, "HEAD"))
1023 con
->http
.state
= HTTP_HEAD
;
1026 cupsdLogMessage(CUPSD_LOG_ERROR
, "Bad operation \"%s\"!", operation
);
1027 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
1028 cupsdCloseClient(con
);
1032 gettimeofday(&(con
->start
), NULL
);
1033 con
->operation
= con
->http
.state
;
1035 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdReadClient: %d %s %s HTTP/%d.%d",
1036 con
->http
.fd
, operation
, con
->uri
,
1037 con
->http
.version
/ 100, con
->http
.version
% 100);
1039 con
->http
.status
= HTTP_OK
;
1041 if (!cupsArrayFind(ActiveClients
, con
))
1043 cupsArrayAdd(ActiveClients
, con
);
1044 cupsdSetBusyState();
1055 * Parse incoming parameters until the status changes...
1058 while ((status
= httpUpdate(HTTP(con
))) == HTTP_CONTINUE
)
1059 if (!data_ready(con
))
1062 if (status
!= HTTP_OK
&& status
!= HTTP_CONTINUE
)
1064 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
1065 cupsdCloseClient(con
);
1071 if (!data_ready(con
) && recv(con
->http
.fd
, buf
, 1, MSG_PEEK
) < 1)
1074 * Connection closed...
1077 cupsdCloseClient(con
);
1080 break; /* Anti-compiler-warning-code */
1084 * Handle new transfers...
1087 if (status
== HTTP_OK
)
1089 if (con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
][0])
1092 * Figure out the locale from the Accept-Language and Content-Type
1096 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ',')) != NULL
)
1099 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ';')) != NULL
)
1102 if ((ptr
= strstr(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
], "charset=")) != NULL
)
1105 * Combine language and charset, and trim any extra params in the
1109 snprintf(locale
, sizeof(locale
), "%s.%s",
1110 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ptr
+ 8);
1112 if ((ptr
= strchr(locale
, ',')) != NULL
)
1116 snprintf(locale
, sizeof(locale
), "%s.%s",
1117 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], DefaultCharset
);
1119 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1120 "cupsdReadClient: %d Browser asked for language \"%s\"...",
1121 con
->http
.fd
, locale
);
1123 con
->language
= cupsLangGet(locale
);
1126 con
->language
= cupsLangGet(DefaultLocale
);
1128 cupsdAuthorize(con
);
1130 if (!strncasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Keep-Alive", 10) &&
1132 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
1133 else if (!strncasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "close", 5))
1134 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1136 if (!con
->http
.fields
[HTTP_FIELD_HOST
][0] &&
1137 con
->http
.version
>= HTTP_1_1
)
1140 * HTTP/1.1 and higher require the "Host:" field...
1143 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1145 cupsdCloseClient(con
);
1149 else if (httpAddrLocalhost(con
->http
.hostaddr
) &&
1150 strcasecmp(con
->http
.fields
[HTTP_FIELD_HOST
], "localhost") &&
1151 strncasecmp(con
->http
.fields
[HTTP_FIELD_HOST
], "localhost:", 10) &&
1152 strcmp(con
->http
.fields
[HTTP_FIELD_HOST
], "127.0.0.1") &&
1153 strncmp(con
->http
.fields
[HTTP_FIELD_HOST
], "127.0.0.1:", 10) &&
1154 strcmp(con
->http
.fields
[HTTP_FIELD_HOST
], "[::1]") &&
1155 strncmp(con
->http
.fields
[HTTP_FIELD_HOST
], "[::1]:", 6))
1158 * Access to localhost must use "localhost" or the corresponding IPv4
1159 * or IPv6 values in the Host: field.
1162 cupsdLogMessage(CUPSD_LOG_WARN
,
1163 "Request from \"%s\" using invalid Host: field \"%s\"",
1164 con
->http
.hostname
, con
->http
.fields
[HTTP_FIELD_HOST
]);
1166 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1168 cupsdCloseClient(con
);
1172 else if (con
->operation
== HTTP_OPTIONS
)
1175 * Do OPTIONS command...
1178 if (con
->best
&& con
->best
->type
!= CUPSD_AUTH_NONE
)
1180 if (!cupsdSendHeader(con
, HTTP_UNAUTHORIZED
, NULL
, CUPSD_AUTH_NONE
))
1182 cupsdCloseClient(con
);
1187 if (!strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") &&
1188 con
->http
.tls
== NULL
)
1192 * Do encryption stuff...
1195 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
, CUPSD_AUTH_NONE
))
1197 cupsdCloseClient(con
);
1201 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1202 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1203 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1204 httpPrintf(HTTP(con
), "\r\n");
1206 if (cupsdFlushHeader(con
) < 0)
1208 cupsdCloseClient(con
);
1212 if (!encrypt_client(con
))
1214 cupsdCloseClient(con
);
1218 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
1220 cupsdCloseClient(con
);
1223 #endif /* HAVE_SSL */
1226 if (!cupsdSendHeader(con
, HTTP_OK
, NULL
, CUPSD_AUTH_NONE
))
1228 cupsdCloseClient(con
);
1232 httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n");
1233 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1234 httpPrintf(HTTP(con
), "\r\n");
1236 if (cupsdFlushHeader(con
) < 0)
1238 cupsdCloseClient(con
);
1242 else if (!is_path_absolute(con
->uri
))
1245 * Protect against malicious users!
1248 cupsdLogMessage(CUPSD_LOG_ERROR
,
1249 "Request for non-absolute resource \"%s\"!", con
->uri
);
1251 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1253 cupsdCloseClient(con
);
1259 if (!strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") &&
1260 con
->http
.tls
== NULL
)
1264 * Do encryption stuff...
1267 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
, CUPSD_AUTH_NONE
))
1269 cupsdCloseClient(con
);
1273 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1274 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1275 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1276 httpPrintf(HTTP(con
), "\r\n");
1278 if (cupsdFlushHeader(con
) < 0)
1280 cupsdCloseClient(con
);
1284 if (!encrypt_client(con
))
1286 cupsdCloseClient(con
);
1290 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
1292 cupsdCloseClient(con
);
1295 #endif /* HAVE_SSL */
1298 if ((status
= cupsdIsAuthorized(con
, NULL
)) != HTTP_OK
)
1300 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1301 "cupsdReadClient: Unauthorized request for %s...",
1303 cupsdSendError(con
, status
, CUPSD_AUTH_NONE
);
1304 cupsdCloseClient(con
);
1308 if (con
->http
.expect
&&
1309 (con
->operation
== HTTP_POST
|| con
->operation
== HTTP_PUT
))
1311 if (con
->http
.expect
== HTTP_CONTINUE
)
1314 * Send 100-continue header...
1317 if (!cupsdSendHeader(con
, HTTP_CONTINUE
, NULL
, CUPSD_AUTH_NONE
))
1319 cupsdCloseClient(con
);
1326 * Send 417-expectation-failed header...
1329 if (!cupsdSendHeader(con
, HTTP_EXPECTATION_FAILED
, NULL
, CUPSD_AUTH_NONE
))
1331 cupsdCloseClient(con
);
1335 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1336 httpPrintf(HTTP(con
), "\r\n");
1338 if (cupsdFlushHeader(con
) < 0)
1340 cupsdCloseClient(con
);
1346 switch (con
->http
.state
)
1348 case HTTP_GET_SEND
:
1349 if (!strncmp(con
->uri
, "/printers/", 10) &&
1350 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1353 * Send PPD file - get the real printer name since printer
1354 * names are not case sensitive but filenames can be...
1357 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1359 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1360 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1363 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1365 cupsdCloseClient(con
);
1373 if ((!strncmp(con
->uri
, "/admin", 6) &&
1374 strncmp(con
->uri
, "/admin/conf/", 12) &&
1375 strncmp(con
->uri
, "/admin/log/", 11)) ||
1376 !strncmp(con
->uri
, "/printers", 9) ||
1377 !strncmp(con
->uri
, "/classes", 8) ||
1378 !strncmp(con
->uri
, "/help", 5) ||
1379 !strncmp(con
->uri
, "/jobs", 5))
1382 * Send CGI output...
1385 if (!strncmp(con
->uri
, "/admin", 6))
1387 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1390 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1392 else if (!strncmp(con
->uri
, "/printers", 9))
1394 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1397 if (con
->uri
[9] && con
->uri
[10])
1398 cupsdSetString(&con
->options
, con
->uri
+ 9);
1400 cupsdSetString(&con
->options
, NULL
);
1402 else if (!strncmp(con
->uri
, "/classes", 8))
1404 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1407 if (con
->uri
[8] && con
->uri
[9])
1408 cupsdSetString(&con
->options
, con
->uri
+ 8);
1410 cupsdSetString(&con
->options
, NULL
);
1412 else if (!strncmp(con
->uri
, "/jobs", 5))
1414 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1417 if (con
->uri
[5] && con
->uri
[6])
1418 cupsdSetString(&con
->options
, con
->uri
+ 5);
1420 cupsdSetString(&con
->options
, NULL
);
1424 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1427 if (con
->uri
[5] && con
->uri
[6])
1428 cupsdSetString(&con
->options
, con
->uri
+ 5);
1430 cupsdSetString(&con
->options
, NULL
);
1433 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1435 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1437 cupsdCloseClient(con
);
1442 cupsdLogRequest(con
, HTTP_OK
);
1444 if (con
->http
.version
<= HTTP_1_0
)
1445 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1447 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1448 (strchr(con
->uri
+ 12, '/') ||
1449 strlen(con
->uri
) == 12)) ||
1450 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1451 (strchr(con
->uri
+ 11, '/') ||
1452 strlen(con
->uri
) == 11)))
1455 * GET can only be done to configuration files directly under
1459 cupsdLogMessage(CUPSD_LOG_ERROR
,
1460 "Request for subdirectory \"%s\"!", con
->uri
);
1462 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1464 cupsdCloseClient(con
);
1476 if ((filename
= get_file(con
, &filestats
, buf
,
1477 sizeof(buf
))) == NULL
)
1479 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1481 cupsdCloseClient(con
);
1488 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1490 if (is_cgi(con
, filename
, &filestats
, type
))
1493 * Note: con->command and con->options were set by
1497 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1499 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1501 cupsdCloseClient(con
);
1506 cupsdLogRequest(con
, HTTP_OK
);
1508 if (con
->http
.version
<= HTTP_1_0
)
1509 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1513 if (!check_if_modified(con
, &filestats
))
1515 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1517 cupsdCloseClient(con
);
1524 strcpy(line
, "text/plain");
1526 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1528 if (!write_file(con
, HTTP_OK
, filename
, line
, &filestats
))
1530 cupsdCloseClient(con
);
1537 case HTTP_POST_RECV
:
1539 * See if the POST request includes a Content-Length field, and if
1540 * so check the length against any limits that are set...
1543 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "POST %s", con
->uri
);
1544 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "CONTENT_TYPE = %s",
1545 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
1547 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1548 MaxRequestSize
> 0 &&
1549 con
->http
.data_remaining
> MaxRequestSize
)
1552 * Request too large...
1555 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1557 cupsdCloseClient(con
);
1563 else if (con
->http
.data_remaining
< 0 ||
1564 (!con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1565 con
->http
.data_encoding
== HTTP_ENCODE_LENGTH
))
1568 * Negative content lengths are invalid!
1571 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1573 cupsdCloseClient(con
);
1581 * See what kind of POST request this is; for IPP requests the
1582 * content-type field will be "application/ipp"...
1585 if (!strcmp(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
],
1587 con
->request
= ippNew();
1588 else if ((!strncmp(con
->uri
, "/admin", 6) &&
1589 strncmp(con
->uri
, "/admin/conf/", 12) &&
1590 strncmp(con
->uri
, "/admin/log/", 11)) ||
1591 !strncmp(con
->uri
, "/printers", 9) ||
1592 !strncmp(con
->uri
, "/classes", 8) ||
1593 !strncmp(con
->uri
, "/help", 5) ||
1594 !strncmp(con
->uri
, "/jobs", 5))
1600 if (!strncmp(con
->uri
, "/admin", 6))
1602 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1605 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1607 else if (!strncmp(con
->uri
, "/printers", 9))
1609 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1612 if (con
->uri
[9] && con
->uri
[10])
1613 cupsdSetString(&con
->options
, con
->uri
+ 9);
1615 cupsdSetString(&con
->options
, NULL
);
1617 else if (!strncmp(con
->uri
, "/classes", 8))
1619 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1622 if (con
->uri
[8] && con
->uri
[9])
1623 cupsdSetString(&con
->options
, con
->uri
+ 8);
1625 cupsdSetString(&con
->options
, NULL
);
1627 else if (!strncmp(con
->uri
, "/jobs", 5))
1629 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1632 if (con
->uri
[5] && con
->uri
[6])
1633 cupsdSetString(&con
->options
, con
->uri
+ 5);
1635 cupsdSetString(&con
->options
, NULL
);
1639 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1642 if (con
->uri
[5] && con
->uri
[6])
1643 cupsdSetString(&con
->options
, con
->uri
+ 5);
1645 cupsdSetString(&con
->options
, NULL
);
1648 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1649 "cupsdReadClient: %d command=\"%s\", "
1651 con
->http
.fd
, con
->command
,
1652 con
->options
? con
->options
: "(null)");
1654 if (con
->http
.version
<= HTTP_1_0
)
1655 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1663 if ((filename
= get_file(con
, &filestats
, buf
,
1664 sizeof(buf
))) == NULL
)
1666 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1668 cupsdCloseClient(con
);
1675 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1677 if (!is_cgi(con
, filename
, &filestats
, type
))
1680 * Only POST to CGI's...
1683 if (!cupsdSendError(con
, HTTP_UNAUTHORIZED
, CUPSD_AUTH_NONE
))
1685 cupsdCloseClient(con
);
1692 case HTTP_PUT_RECV
:
1694 * Validate the resource name...
1697 if (strncmp(con
->uri
, "/admin/conf/", 12) ||
1698 strchr(con
->uri
+ 12, '/') ||
1699 strlen(con
->uri
) == 12)
1702 * PUT can only be done to configuration files under
1706 cupsdLogMessage(CUPSD_LOG_ERROR
,
1707 "Request for subdirectory \"%s\"!", con
->uri
);
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 cupsdLogMessage(CUPSD_LOG_ERROR
,
1864 "Request for subdirectory \"%s\"!", con
->uri
);
1866 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1868 cupsdCloseClient(con
);
1874 else if ((filename
= get_file(con
, &filestats
, buf
,
1875 sizeof(buf
))) == NULL
)
1877 if (!cupsdSendHeader(con
, HTTP_NOT_FOUND
, "text/html", CUPSD_AUTH_NONE
))
1879 cupsdCloseClient(con
);
1883 cupsdLogRequest(con
, HTTP_NOT_FOUND
);
1885 else if (!check_if_modified(con
, &filestats
))
1887 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1889 cupsdCloseClient(con
);
1893 cupsdLogRequest(con
, HTTP_NOT_MODIFIED
);
1901 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1903 strcpy(line
, "text/plain");
1905 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1907 if (!cupsdSendHeader(con
, HTTP_OK
, line
, CUPSD_AUTH_NONE
))
1909 cupsdCloseClient(con
);
1913 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
1914 httpGetDateString(filestats
.st_mtime
)) < 0)
1916 cupsdCloseClient(con
);
1920 if (httpPrintf(HTTP(con
), "Content-Length: %lu\r\n",
1921 (unsigned long)filestats
.st_size
) < 0)
1923 cupsdCloseClient(con
);
1927 cupsdLogRequest(con
, HTTP_OK
);
1930 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1932 cupsdCloseClient(con
);
1936 if (cupsdFlushHeader(con
) < 0)
1938 cupsdCloseClient(con
);
1942 con
->http
.state
= HTTP_WAITING
;
1946 break; /* Anti-compiler-warning-code */
1952 * Handle any incoming data...
1955 switch (con
->http
.state
)
1957 case HTTP_PUT_RECV
:
1958 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1959 "cupsdReadClient: %d con->data_encoding=HTTP_ENCODE_%s, "
1960 "con->data_remaining=" CUPS_LLFMT
", con->file=%d",
1962 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
?
1963 "CHUNKED" : "LENGTH",
1964 CUPS_LLCAST con
->http
.data_remaining
, con
->file
);
1968 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
1970 cupsdCloseClient(con
);
1975 con
->bytes
+= bytes
;
1977 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1978 "cupsdReadClient: %d writing %d bytes to %d",
1979 con
->http
.fd
, bytes
, con
->file
);
1981 if (write(con
->file
, line
, bytes
) < bytes
)
1983 cupsdLogMessage(CUPSD_LOG_ERROR
,
1984 "cupsdReadClient: Unable to write %d bytes to %s: %s",
1985 bytes
, con
->filename
, strerror(errno
));
1987 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1988 "cupsdReadClient: Closing data file %d...",
1993 unlink(con
->filename
);
1994 cupsdClearString(&con
->filename
);
1996 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1998 cupsdCloseClient(con
);
2004 while (con
->http
.state
== HTTP_PUT_RECV
&& data_ready(con
));
2006 if (con
->http
.state
== HTTP_WAITING
)
2009 * End of file, see how big it is...
2012 fstat(con
->file
, &filestats
);
2014 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2015 "cupsdReadClient: %d Closing data file %d, size="
2017 con
->http
.fd
, con
->file
,
2018 CUPS_LLCAST filestats
.st_size
);
2023 if (filestats
.st_size
> MaxRequestSize
&&
2027 * Request is too big; remove it and send an error...
2030 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2031 "cupsdReadClient: %d Removing temp file %s",
2032 con
->http
.fd
, con
->filename
);
2033 unlink(con
->filename
);
2034 cupsdClearString(&con
->filename
);
2036 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2038 cupsdCloseClient(con
);
2044 * Install the configuration file...
2047 status
= install_conf_file(con
);
2050 * Return the status to the client...
2053 if (!cupsdSendError(con
, status
, CUPSD_AUTH_NONE
))
2055 cupsdCloseClient(con
);
2061 case HTTP_POST_RECV
:
2062 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2063 "cupsdReadClient: %d con->data_encoding=HTTP_ENCODE_"
2064 "%s, con->data_remaining=" CUPS_LLFMT
", con->file=%d",
2066 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
?
2067 "CHUNKED" : "LENGTH",
2068 CUPS_LLCAST con
->http
.data_remaining
, con
->file
);
2075 * Grab any request data from the connection...
2078 if ((ipp_state
= ippRead(&(con
->http
), con
->request
)) == IPP_ERROR
)
2080 cupsdLogMessage(CUPSD_LOG_ERROR
,
2081 "cupsdReadClient: %d IPP Read Error!",
2084 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
2085 cupsdCloseClient(con
);
2088 else if (ipp_state
!= IPP_DATA
)
2090 if (con
->http
.state
== HTTP_POST_SEND
)
2092 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
2093 cupsdCloseClient(con
);
2100 con
->bytes
+= ippLength(con
->request
);
2103 if (con
->file
< 0 && con
->http
.state
!= HTTP_POST_SEND
)
2106 * Create a file as needed for the request data...
2109 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
, request_id
++);
2110 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
2114 cupsdLogMessage(CUPSD_LOG_ERROR
,
2115 "Unable to create request file %s: %s",
2116 con
->filename
, strerror(errno
));
2118 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2120 cupsdCloseClient(con
);
2125 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdReadClient: %d REQUEST %s=%d", con
->http
.fd
,
2126 con
->filename
, con
->file
);
2128 fchmod(con
->file
, 0640);
2129 fchown(con
->file
, RunUser
, Group
);
2130 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2133 if (con
->http
.state
!= HTTP_POST_SEND
)
2135 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
2137 cupsdCloseClient(con
);
2142 con
->bytes
+= bytes
;
2144 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2145 "cupsdReadClient: %d writing %d bytes to %d",
2146 con
->http
.fd
, bytes
, con
->file
);
2148 if (write(con
->file
, line
, bytes
) < bytes
)
2150 cupsdLogMessage(CUPSD_LOG_ERROR
,
2151 "cupsdReadClient: Unable to write %d bytes to %s: %s",
2152 bytes
, con
->filename
, strerror(errno
));
2154 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2155 "cupsdReadClient: Closing file %d...",
2160 unlink(con
->filename
);
2161 cupsdClearString(&con
->filename
);
2163 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2165 cupsdCloseClient(con
);
2170 else if (con
->http
.state
== HTTP_POST_RECV
)
2172 else if (con
->http
.state
!= HTTP_POST_SEND
)
2174 cupsdCloseClient(con
);
2179 while (con
->http
.state
== HTTP_POST_RECV
&& data_ready(con
));
2181 if (con
->http
.state
== HTTP_POST_SEND
)
2185 fstat(con
->file
, &filestats
);
2187 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2188 "cupsdReadClient: %d Closing data file %d, "
2189 "size=" CUPS_LLFMT
".",
2190 con
->http
.fd
, con
->file
,
2191 CUPS_LLCAST filestats
.st_size
);
2196 if (filestats
.st_size
> MaxRequestSize
&&
2200 * Request is too big; remove it and send an error...
2203 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2204 "cupsdReadClient: %d Removing temp file %s",
2205 con
->http
.fd
, con
->filename
);
2206 unlink(con
->filename
);
2207 cupsdClearString(&con
->filename
);
2212 * Delete any IPP request data...
2215 ippDelete(con
->request
);
2216 con
->request
= NULL
;
2219 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2221 cupsdCloseClient(con
);
2228 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
2230 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
2232 cupsdCloseClient(con
);
2237 cupsdLogRequest(con
, HTTP_OK
);
2243 cupsdProcessIPPRequest(con
);
2247 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2248 "cupsdReadClient: %d Removing temp file %s",
2249 con
->http
.fd
, con
->filename
);
2250 unlink(con
->filename
);
2251 cupsdClearString(&con
->filename
);
2260 break; /* Anti-compiler-warning-code */
2263 if (con
->http
.state
== HTTP_WAITING
)
2265 if (!con
->http
.keep_alive
)
2266 cupsdCloseClient(con
);
2269 cupsArrayRemove(ActiveClients
, con
);
2270 cupsdSetBusyState();
2277 * 'cupsdSendCommand()' - Send output from a command via HTTP.
2280 int /* O - 1 on success, 0 on failure */
2282 cupsd_client_t
*con
, /* I - Client connection */
2283 char *command
, /* I - Command to run */
2284 char *options
, /* I - Command-line options */
2285 int root
) /* I - Run as root? */
2287 int fd
; /* Standard input file descriptor */
2292 fd
= open(con
->filename
, O_RDONLY
);
2296 cupsdLogMessage(CUPSD_LOG_ERROR
,
2297 "cupsdSendCommand: %d Unable to open \"%s\" for reading: %s",
2298 con
->http
.fd
, con
->filename
? con
->filename
: "/dev/null",
2303 fcntl(fd
, F_SETFD
, fcntl(fd
, F_GETFD
) | FD_CLOEXEC
);
2308 con
->pipe_pid
= pipe_command(con
, fd
, &(con
->file
), command
, options
, root
);
2313 cupsdLogMessage(CUPSD_LOG_INFO
, "Started \"%s\" (pid=%d)", command
,
2316 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendCommand: %d file=%d",
2317 con
->http
.fd
, con
->file
);
2319 if (con
->pipe_pid
== 0)
2322 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2324 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2326 con
->sent_header
= 0;
2327 con
->file_ready
= 0;
2328 con
->got_fields
= 0;
2336 * 'cupsdSendError()' - Send an error message via HTTP.
2339 int /* O - 1 if successful, 0 otherwise */
2340 cupsdSendError(cupsd_client_t
*con
, /* I - Connection */
2341 http_status_t code
, /* I - Error code */
2342 int auth_type
)/* I - Authentication type */
2346 * Force client to upgrade for authentication if that is how the
2347 * server is configured...
2350 if (code
== HTTP_UNAUTHORIZED
&&
2351 DefaultEncryption
== HTTP_ENCRYPT_REQUIRED
&&
2352 strcasecmp(con
->http
.hostname
, "localhost") &&
2355 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2356 "cupsdSendError: Encryption before authentication!");
2357 code
= HTTP_UPGRADE_REQUIRED
;
2359 #endif /* HAVE_SSL */
2362 * Put the request in the access_log file...
2365 cupsdLogRequest(con
, code
);
2367 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendError: %d code=%d (%s)",
2368 con
->http
.fd
, code
, httpStatus(code
));
2371 * To work around bugs in some proxies, don't use Keep-Alive for some
2374 * Kerberos authentication doesn't work without Keep-Alive, so
2375 * never disable it in that case.
2378 if (code
>= HTTP_BAD_REQUEST
&& con
->http
.auth_type
!= CUPSD_AUTH_NEGOTIATE
)
2379 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
2382 * Send an error message back to the client. If the error code is a
2383 * 400 or 500 series, make sure the message contains some text, too!
2386 if (!cupsdSendHeader(con
, code
, NULL
, auth_type
))
2390 if (code
== HTTP_UPGRADE_REQUIRED
)
2391 if (httpPrintf(HTTP(con
), "Connection: Upgrade\r\n") < 0)
2394 if (httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n") < 0)
2396 #endif /* HAVE_SSL */
2398 if (con
->http
.version
>= HTTP_1_1
&&
2399 con
->http
.keep_alive
== HTTP_KEEPALIVE_OFF
)
2401 if (httpPrintf(HTTP(con
), "Connection: close\r\n") < 0)
2405 if (code
>= HTTP_BAD_REQUEST
)
2408 * Send a human-readable error message.
2411 char message
[4096], /* Message for user */
2412 urltext
[1024], /* URL redirection text */
2413 redirect
[1024]; /* Redirection link */
2414 const char *text
; /* Status-specific text */
2419 if (code
== HTTP_UNAUTHORIZED
)
2420 text
= _cupsLangString(con
->language
,
2421 _("Enter your username and password or the "
2422 "root username and password to access this "
2423 "page. If you are using Kerberos authentication, "
2424 "make sure you have a valid Kerberos ticket."));
2425 else if (code
== HTTP_UPGRADE_REQUIRED
)
2429 snprintf(urltext
, sizeof(urltext
),
2430 _cupsLangString(con
->language
,
2431 _("You must access this page using the URL "
2432 "<A HREF=\"https://%s:%d%s\">"
2433 "https://%s:%d%s</A>.")),
2434 con
->servername
, con
->serverport
, con
->uri
,
2435 con
->servername
, con
->serverport
, con
->uri
);
2437 snprintf(redirect
, sizeof(redirect
),
2438 "<META HTTP-EQUIV=\"Refresh\" "
2439 "CONTENT=\"3;URL=https://%s:%d%s\">\n",
2440 con
->servername
, con
->serverport
, con
->uri
);
2445 snprintf(message
, sizeof(message
),
2446 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" "
2447 "\"http://www.w3.org/TR/html4/loose.dtd\">\n"
2450 "\t<META HTTP-EQUIV=\"Content-Type\" "
2451 "CONTENT=\"text/html; charset=utf-8\">\n"
2452 "\t<TITLE>%d %s</TITLE>\n"
2453 "\t<LINK REL=\"STYLESHEET\" TYPE=\"text/css\" "
2454 "HREF=\"/cups.css\">\n"
2462 code
, httpStatus(code
), redirect
, code
, httpStatus(code
), text
);
2464 if (httpPrintf(HTTP(con
), "Content-Type: text/html; charset=utf-8\r\n") < 0)
2466 if (httpPrintf(HTTP(con
), "Content-Length: %d\r\n",
2467 (int)strlen(message
)) < 0)
2469 if (httpPrintf(HTTP(con
), "\r\n") < 0)
2471 if (httpPrintf(HTTP(con
), "%s", message
) < 0)
2474 else if (httpPrintf(HTTP(con
), "\r\n") < 0)
2477 if (cupsdFlushHeader(con
) < 0)
2480 con
->http
.state
= HTTP_WAITING
;
2487 * 'cupsdSendHeader()' - Send an HTTP request.
2490 int /* O - 1 on success, 0 on failure */
2492 cupsd_client_t
*con
, /* I - Client to send to */
2493 http_status_t code
, /* I - HTTP status code */
2494 char *type
, /* I - MIME type of document */
2495 int auth_type
) /* I - Type of authentication */
2497 char auth_str
[1024]; /* Authorization string */
2499 static char *gss_buf
= NULL
; /* Kerberos auth data buffer */
2500 static int gss_bufsize
= 0; /* Size of Kerberos auth data buffer */
2501 #endif /* HAVE_GSSAPI */
2505 * Send the HTTP status header...
2508 if (code
== HTTP_CONTINUE
)
2511 * 100-continue doesn't send any headers...
2514 return (httpPrintf(HTTP(con
), "HTTP/%d.%d 100 Continue\r\n\r\n",
2515 con
->http
.version
/ 100, con
->http
.version
% 100) > 0);
2518 httpFlushWrite(HTTP(con
));
2520 con
->http
.data_encoding
= HTTP_ENCODE_FIELDS
;
2522 if (httpPrintf(HTTP(con
), "HTTP/%d.%d %d %s\r\n", con
->http
.version
/ 100,
2523 con
->http
.version
% 100, code
, httpStatus(code
)) < 0)
2525 if (httpPrintf(HTTP(con
), "Date: %s\r\n", httpGetDateString(time(NULL
))) < 0)
2528 if (httpPrintf(HTTP(con
), "Server: %s\r\n", ServerHeader
) < 0)
2530 if (con
->http
.keep_alive
&& con
->http
.version
>= HTTP_1_0
)
2532 if (httpPrintf(HTTP(con
), "Connection: Keep-Alive\r\n") < 0)
2534 if (httpPrintf(HTTP(con
), "Keep-Alive: timeout=%d\r\n",
2535 KeepAliveTimeout
) < 0)
2538 if (code
== HTTP_METHOD_NOT_ALLOWED
)
2539 if (httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n") < 0)
2542 if (code
== HTTP_UNAUTHORIZED
)
2544 if (auth_type
== CUPSD_AUTH_NONE
)
2546 if (!con
->best
|| con
->best
->type
<= CUPSD_AUTH_NONE
)
2547 auth_type
= DefaultAuthType
;
2549 auth_type
= con
->best
->type
;
2554 if (auth_type
== CUPSD_AUTH_BASIC
|| auth_type
== CUPSD_AUTH_BASICDIGEST
)
2555 strlcpy(auth_str
, "Basic realm=\"CUPS\"", sizeof(auth_str
));
2556 else if (auth_type
== CUPSD_AUTH_DIGEST
)
2557 snprintf(auth_str
, sizeof(auth_str
), "Digest realm=\"CUPS\", nonce=\"%s\"",
2558 con
->http
.hostname
);
2560 else if (auth_type
== CUPSD_AUTH_NEGOTIATE
&& con
->gss_output_token
.length
== 0)
2561 strlcpy(auth_str
, "Negotiate", sizeof(auth_str
));
2562 #endif /* HAVE_GSSAPI */
2564 #ifdef HAVE_AUTHORIZATION_H
2565 if (con
->best
&& auth_type
!= CUPSD_AUTH_NEGOTIATE
)
2567 int i
; /* Looping var */
2568 char *auth_key
; /* Auth key buffer */
2569 size_t auth_size
; /* Size of remaining buffer */
2572 auth_key
= auth_str
+ strlen(auth_str
);
2573 auth_size
= sizeof(auth_str
) - (auth_key
- auth_str
);
2575 for (i
= 0; i
< con
->best
->num_names
; i
++)
2577 if (!strncasecmp(con
->best
->names
[i
], "@AUTHKEY(", 9))
2579 snprintf(auth_key
, auth_size
, ", authkey=\"%s\"",
2580 con
->best
->names
[i
] + 9);
2581 /* end parenthesis is stripped in conf.c */
2584 else if (!strcasecmp(con
->best
->names
[i
], "@SYSTEM") &&
2587 snprintf(auth_key
, auth_size
, ", authkey=\"%s\"", SystemGroupAuthKey
);
2592 #endif /* HAVE_AUTHORIZATION_H */
2596 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendHeader: WWW-Authenticate: %s",
2599 if (httpPrintf(HTTP(con
), "WWW-Authenticate: %s\r\n", auth_str
) < 0)
2606 * WWW-Authenticate: Negotiate can be included even for
2607 * non-401 replies...
2610 if (con
->gss_output_token
.length
> 0 && con
->gss_output_token
.length
<= 65536)
2612 OM_uint32 minor_status
; /* Minor status code */
2613 int bufsize
; /* Size of output token buffer */
2616 bufsize
= con
->gss_output_token
.length
* 4 / 3 + 2;
2618 if (bufsize
> gss_bufsize
)
2620 char *buf
; /* New buffer */
2623 bufsize
= (bufsize
+ 1023) & 1023;/* Round up */
2626 buf
= realloc(gss_buf
, bufsize
);
2628 buf
= malloc(bufsize
);
2632 cupsdLogMessage(CUPSD_LOG_ERROR
,
2633 "Unable to allocate %d bytes for Kerberos credentials!",
2639 gss_bufsize
= bufsize
;
2642 httpEncode64_2(gss_buf
, gss_bufsize
,
2643 con
->gss_output_token
.value
,
2644 con
->gss_output_token
.length
);
2645 gss_release_buffer(&minor_status
, &con
->gss_output_token
);
2647 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2648 "cupsdSendHeader: WWW-Authenticate: Negotiate %s", gss_buf
);
2650 if (httpPrintf(HTTP(con
), "WWW-Authenticate: Negotiate %s\r\n",
2654 else if (con
->gss_output_token
.length
> 65536)
2656 cupsdLogMessage(CUPSD_LOG_ERROR
,
2657 "Kerberos credentials larger than 64k (%d)!",
2658 (int)con
->gss_output_token
.length
);
2661 #endif /* HAVE_GSSAPI */
2663 if (con
->language
&& strcmp(con
->language
->language
, "C"))
2665 if (httpPrintf(HTTP(con
), "Content-Language: %s\r\n",
2666 con
->language
->language
) < 0)
2672 if (!strcmp(type
, "text/html"))
2674 if (httpPrintf(HTTP(con
),
2675 "Content-Type: text/html; charset=utf-8\r\n") < 0)
2678 else if (httpPrintf(HTTP(con
), "Content-Type: %s\r\n", type
) < 0)
2687 * 'cupsdUpdateCGI()' - Read status messages from CGI scripts and programs.
2691 cupsdUpdateCGI(void)
2693 char *ptr
, /* Pointer to end of line in buffer */
2694 message
[1024]; /* Pointer to message text */
2695 int loglevel
; /* Log level for message */
2698 while ((ptr
= cupsdStatBufUpdate(CGIStatusBuffer
, &loglevel
,
2699 message
, sizeof(message
))) != NULL
)
2701 if (loglevel
== CUPSD_LOG_INFO
)
2702 cupsdLogMessage(CUPSD_LOG_INFO
, "%s", message
);
2704 if (!strchr(CGIStatusBuffer
->buffer
, '\n'))
2708 if (ptr
== NULL
&& !CGIStatusBuffer
->bufused
)
2711 * Fatal error on pipe - should never happen!
2714 cupsdLogMessage(CUPSD_LOG_CRIT
,
2715 "cupsdUpdateCGI: error reading from CGI error pipe - %s",
2722 * 'cupsdWriteClient()' - Write data to a client as needed.
2726 cupsdWriteClient(cupsd_client_t
*con
) /* I - Client connection */
2728 int bytes
; /* Number of bytes written */
2729 char buf
[16385]; /* Data buffer */
2730 char *bufptr
; /* Pointer into buffer */
2731 ipp_state_t ipp_state
; /* IPP state value */
2735 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2736 "cupsdWriteClient(con=%p) %d response=%p(%d), file=%d "
2737 "pipe_pid=%d state=%d",
2738 con
, con
->http
.fd
, con
->response
,
2739 con
->response
? con
->response
->state
: -1,
2740 con
->file
, con
->pipe_pid
, con
->http
.state
);
2743 if (con
->http
.state
!= HTTP_GET_SEND
&&
2744 con
->http
.state
!= HTTP_POST_SEND
)
2750 * Make sure we select on the CGI output...
2753 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2755 if (!con
->file_ready
)
2758 * Try again later when there is CGI output available...
2761 cupsdRemoveSelect(con
->http
.fd
);
2765 con
->file_ready
= 0;
2768 if (con
->response
&& con
->response
->state
!= IPP_DATA
)
2770 ipp_state
= ippWrite(HTTP(con
), con
->response
);
2771 bytes
= ipp_state
!= IPP_ERROR
&&
2772 (con
->file
>= 0 || ipp_state
!= IPP_DATA
);
2774 else if ((bytes
= read(con
->file
, buf
, sizeof(buf
) - 1)) > 0)
2776 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2777 "cupsdWriteClient: Read %d bytes from file %d...",
2780 if (con
->pipe_pid
&& !con
->got_fields
)
2783 * Inspect the data for Content-Type and other fields.
2788 for (bufptr
= buf
; !con
->got_fields
&& *bufptr
; bufptr
++)
2790 if (*bufptr
== '\n')
2793 * Send line to client...
2796 if (bufptr
> buf
&& bufptr
[-1] == '\r')
2800 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Script header: %s", buf
);
2802 if (!con
->sent_header
)
2805 * Handle redirection and CGI status codes...
2808 if (!strncasecmp(buf
, "Location:", 9))
2810 cupsdSendHeader(con
, HTTP_SEE_OTHER
, NULL
, CUPSD_AUTH_NONE
);
2811 con
->sent_header
= 2;
2813 if (httpPrintf(HTTP(con
), "Content-Length: 0\r\n") < 0)
2816 else if (!strncasecmp(buf
, "Status:", 7))
2818 cupsdSendError(con
, (http_status_t
)atoi(buf
+ 7), CUPSD_AUTH_NONE
);
2819 con
->sent_header
= 2;
2823 cupsdSendHeader(con
, HTTP_OK
, NULL
, CUPSD_AUTH_NONE
);
2824 con
->sent_header
= 1;
2826 if (con
->http
.version
== HTTP_1_1
)
2828 if (httpPrintf(HTTP(con
), "Transfer-Encoding: chunked\r\n") < 0)
2834 if (strncasecmp(buf
, "Status:", 7))
2835 httpPrintf(HTTP(con
), "%s\r\n", buf
);
2837 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdWriteClient: %d %s",
2844 bytes
-= (bufptr
- buf
);
2847 memmove(buf
, bufptr
, bytes
+ 1);
2854 * See if the line was empty...
2857 if (con
->field_col
== 0)
2859 con
->got_fields
= 1;
2861 if (cupsdFlushHeader(con
) < 0)
2863 cupsdCloseClient(con
);
2867 if (con
->http
.version
== HTTP_1_1
)
2868 con
->http
.data_encoding
= HTTP_ENCODE_CHUNKED
;
2873 else if (*bufptr
!= '\r')
2877 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2878 "cupsdWriteClient: %d bytes=%d, got_fields=%d",
2879 con
->http
.fd
, bytes
, con
->got_fields
);
2881 if (bytes
> 0 && !con
->got_fields
)
2884 * Remaining text needs to go out...
2887 httpPrintf(HTTP(con
), "%s", buf
);
2889 con
->http
.activity
= time(NULL
);
2892 else if (bytes
== 0)
2894 con
->http
.activity
= time(NULL
);
2901 if (httpWrite2(HTTP(con
), buf
, bytes
) < 0)
2903 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2904 "cupsdWriteClient: %d Write of %d bytes failed!",
2905 con
->http
.fd
, bytes
);
2907 cupsdCloseClient(con
);
2911 if (con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
)
2912 httpFlushWrite(HTTP(con
));
2914 con
->bytes
+= bytes
;
2916 if (con
->http
.state
== HTTP_WAITING
)
2923 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdWriteClient: %d bytes < 0",
2926 cupsdLogRequest(con
, HTTP_OK
);
2928 httpFlushWrite(HTTP(con
));
2930 if (con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
&& con
->sent_header
== 1)
2932 if (httpWrite2(HTTP(con
), "", 0) < 0)
2934 cupsdCloseClient(con
);
2939 con
->http
.state
= HTTP_WAITING
;
2941 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
2945 cupsdRemoveSelect(con
->file
);
2948 cupsdEndProcess(con
->pipe_pid
, 0);
2950 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2951 "cupsdWriteClient: %d Closing data file %d.",
2952 con
->http
.fd
, con
->file
);
2961 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2962 "cupsdWriteClient: %d Removing temp file %s",
2963 con
->http
.fd
, con
->filename
);
2964 unlink(con
->filename
);
2965 cupsdClearString(&con
->filename
);
2970 ippDelete(con
->request
);
2971 con
->request
= NULL
;
2976 ippDelete(con
->response
);
2977 con
->response
= NULL
;
2980 cupsdClearString(&con
->command
);
2981 cupsdClearString(&con
->options
);
2982 cupsdClearString(&con
->query_string
);
2984 if (!con
->http
.keep_alive
)
2986 cupsdCloseClient(con
);
2991 con
->http
.activity
= time(NULL
);
2996 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
2999 static int /* O - 1 if modified since */
3001 cupsd_client_t
*con
, /* I - Client connection */
3002 struct stat
*filestats
) /* I - File information */
3004 char *ptr
; /* Pointer into field */
3005 time_t date
; /* Time/date value */
3006 off_t size
; /* Size/length value */
3011 ptr
= con
->http
.fields
[HTTP_FIELD_IF_MODIFIED_SINCE
];
3016 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3017 "check_if_modified: %d If-Modified-Since=\"%s\"",
3020 while (*ptr
!= '\0')
3022 while (isspace(*ptr
) || *ptr
== ';')
3025 if (strncasecmp(ptr
, "length=", 7) == 0)
3028 size
= strtoll(ptr
, NULL
, 10);
3030 while (isdigit(*ptr
))
3033 else if (isalpha(*ptr
))
3035 date
= httpGetDateTime(ptr
);
3036 while (*ptr
!= '\0' && *ptr
!= ';')
3043 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3044 "check_if_modified: %d sizes=" CUPS_LLFMT
","
3045 CUPS_LLFMT
" dates=%d,%d",
3046 con
->http
.fd
, CUPS_LLCAST size
,
3047 CUPS_LLCAST filestats
->st_size
, (int)date
,
3048 (int)filestats
->st_mtime
);
3050 return ((size
!= filestats
->st_size
&& size
!= 0) ||
3051 (date
< filestats
->st_mtime
&& date
!= 0) ||
3052 (size
== 0 && date
== 0));
3057 * 'compare_clients()' - Compare two client connections.
3060 static int /* O - Result of comparison */
3061 compare_clients(cupsd_client_t
*a
, /* I - First client */
3062 cupsd_client_t
*b
, /* I - Second client */
3063 void *data
) /* I - User data (not used) */
3077 * 'data_ready()' - Check whether data is available from a client.
3080 static int /* O - 1 if data is ready, 0 otherwise */
3081 data_ready(cupsd_client_t
*con
) /* I - Client */
3083 if (con
->http
.used
> 0)
3086 else if (con
->http
.tls
)
3089 if (SSL_pending((SSL
*)(con
->http
.tls
)))
3091 # elif defined(HAVE_GNUTLS)
3092 if (gnutls_record_check_pending(((http_tls_t
*)(con
->http
.tls
))->session
))
3094 # elif defined(HAVE_CDSASSL)
3095 size_t bytes
; /* Bytes that are available */
3097 if (!SSLGetBufferedReadSize(((http_tls_t
*)(con
->http
.tls
))->session
,
3098 &bytes
) && bytes
> 0)
3100 # endif /* HAVE_LIBSSL */
3102 #endif /* HAVE_SSL */
3110 * 'encrypt_client()' - Enable encryption for the client...
3113 static int /* O - 1 on success, 0 on error */
3114 encrypt_client(cupsd_client_t
*con
) /* I - Client to encrypt */
3117 SSL_CTX
*context
; /* Context for encryption */
3118 SSL
*conn
; /* Connection for encryption */
3119 BIO
*bio
; /* BIO data */
3120 unsigned long error
; /* Error code */
3124 * Verify that we have a certificate...
3127 if (access(ServerKey
, 0) || access(ServerCertificate
, 0))
3130 * Nope, make a self-signed certificate...
3133 if (!make_certificate(con
))
3138 * Create the SSL context and accept the connection...
3141 context
= SSL_CTX_new(SSLv23_server_method());
3143 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
3144 if (SSLOptions
& CUPSD_SSL_NOEMPTY
)
3145 SSL_CTX_set_options(context
, SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
);
3146 SSL_CTX_use_PrivateKey_file(context
, ServerKey
, SSL_FILETYPE_PEM
);
3147 SSL_CTX_use_certificate_chain_file(context
, ServerCertificate
);
3149 bio
= BIO_new(_httpBIOMethods());
3150 BIO_ctrl(bio
, BIO_C_SET_FILE_PTR
, 0, (char *)HTTP(con
));
3152 conn
= SSL_new(context
);
3153 SSL_set_bio(conn
, bio
, bio
);
3155 if (SSL_accept(conn
) != 1)
3157 cupsdLogMessage(CUPSD_LOG_ERROR
,
3158 "encrypt_client: Unable to encrypt connection from %s!",
3159 con
->http
.hostname
);
3161 while ((error
= ERR_get_error()) != 0)
3162 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s",
3163 ERR_error_string(error
, NULL
));
3165 SSL_CTX_free(context
);
3170 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3171 "encrypt_client: %d Connection from %s now encrypted.",
3172 con
->http
.fd
, con
->http
.hostname
);
3174 con
->http
.tls
= conn
;
3177 # elif defined(HAVE_GNUTLS)
3178 http_tls_t
*conn
; /* TLS session object */
3179 int error
; /* Error code */
3180 gnutls_certificate_server_credentials
*credentials
;
3181 /* TLS credentials */
3185 * Verify that we have a certificate...
3188 if (access(ServerKey
, 0) || access(ServerCertificate
, 0))
3191 * Nope, make a self-signed certificate...
3194 if (!make_certificate(con
))
3199 * Create the SSL object and perform the SSL handshake...
3202 conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
));
3207 credentials
= (gnutls_certificate_server_credentials
*)
3208 malloc(sizeof(gnutls_certificate_server_credentials
));
3209 if (credentials
== NULL
)
3211 cupsdLogMessage(CUPSD_LOG_ERROR
,
3212 "encrypt_client: Unable to encrypt connection from %s!",
3213 con
->http
.hostname
);
3214 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s", strerror(errno
));
3220 gnutls_certificate_allocate_credentials(credentials
);
3221 gnutls_certificate_set_x509_key_file(*credentials
, ServerCertificate
,
3222 ServerKey
, GNUTLS_X509_FMT_PEM
);
3224 gnutls_init(&(conn
->session
), GNUTLS_SERVER
);
3225 gnutls_set_default_priority(conn
->session
);
3226 gnutls_credentials_set(conn
->session
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
3227 gnutls_transport_set_ptr(conn
->session
, (gnutls_transport_ptr
)HTTP(con
));
3228 gnutls_transport_set_pull_function(conn
->session
, _httpReadGNUTLS
);
3229 gnutls_transport_set_push_function(conn
->session
, _httpWriteGNUTLS
);
3231 error
= gnutls_handshake(conn
->session
);
3233 if (error
!= GNUTLS_E_SUCCESS
)
3235 cupsdLogMessage(CUPSD_LOG_ERROR
,
3236 "encrypt_client: Unable to encrypt connection from %s!",
3237 con
->http
.hostname
);
3238 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s",
3239 gnutls_strerror(error
));
3241 gnutls_deinit(conn
->session
);
3242 gnutls_certificate_free_credentials(*credentials
);
3248 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3249 "encrypt_client: %d Connection from %s now encrypted.",
3250 con
->http
.fd
, con
->http
.hostname
);
3252 conn
->credentials
= credentials
;
3253 con
->http
.tls
= conn
;
3256 # elif defined(HAVE_CDSASSL)
3257 OSStatus error
; /* Error code */
3258 http_tls_t
*conn
; /* CDSA connection information */
3261 if ((conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
))) == NULL
)
3265 conn
->session
= NULL
;
3266 conn
->certsArray
= get_cdsa_certificate(con
);
3268 if (!conn
->certsArray
)
3271 * No keychain (yet), make a self-signed certificate...
3274 if (make_certificate(con
))
3275 conn
->certsArray
= get_cdsa_certificate(con
);
3278 if (!conn
->certsArray
)
3280 cupsdLogMessage(CUPSD_LOG_ERROR
,
3281 "encrypt_client: Could not find signing key in keychain "
3282 "\"%s\"", ServerCertificate
);
3283 error
= errSSLBadCert
; /* errSSLBadConfiguration is a better choice, but not available on 10.2.x */
3287 error
= SSLNewContext(true, &conn
->session
);
3290 error
= SSLSetIOFuncs(conn
->session
, _httpReadCDSA
, _httpWriteCDSA
);
3293 error
= SSLSetProtocolVersionEnabled(conn
->session
, kSSLProtocol2
, false);
3296 error
= SSLSetConnection(conn
->session
, HTTP(con
));
3299 error
= SSLSetAllowsExpiredCerts(conn
->session
, true);
3302 error
= SSLSetAllowsAnyRoot(conn
->session
, true);
3305 error
= SSLSetCertificate(conn
->session
, conn
->certsArray
);
3310 * Perform SSL/TLS handshake
3313 while ((error
= SSLHandshake(conn
->session
)) == errSSLWouldBlock
)
3319 cupsdLogMessage(CUPSD_LOG_ERROR
,
3320 "encrypt_client: Unable to encrypt connection from %s!",
3321 con
->http
.hostname
);
3323 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s (%d)",
3324 cssmErrorString(error
), (int)error
);
3326 con
->http
.error
= error
;
3327 con
->http
.status
= HTTP_ERROR
;
3330 SSLDisposeContext(conn
->session
);
3332 if (conn
->certsArray
)
3333 CFRelease(conn
->certsArray
);
3340 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3341 "encrypt_client: %d Connection from %s now encrypted.",
3342 con
->http
.fd
, con
->http
.hostname
);
3344 con
->http
.tls
= conn
;
3347 # endif /* HAVE_LIBSSL */
3349 #endif /* HAVE_SSL */
3354 * 'get_cdsa_certificate()' - Get a SSL/TLS certificate from the System keychain.
3357 static CFArrayRef
/* O - Array of certificates */
3358 get_cdsa_certificate(cupsd_client_t
*con
) /* I - Client connection */
3360 OSStatus err
; /* Error info */
3361 SecKeychainRef keychain
; /* Keychain reference */
3362 SecIdentitySearchRef search
; /* Search reference */
3363 SecIdentityRef identity
; /* Identity */
3364 CFArrayRef certificates
= NULL
;
3365 /* Certificate array */
3368 if ((err
= SecKeychainOpen(ServerCertificate
, &keychain
)))
3370 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot open keychain \"%s\", %s",
3371 ServerCertificate
, cssmErrorString(err
));
3375 # if HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY
3377 * Use a policy to search for valid certificates who's common name matches the
3381 SecPolicySearchRef policy_search
; /* Policy search ref */
3382 SecPolicyRef policy
; /* Policy ref */
3383 CSSM_DATA options
; /* Policy options */
3384 CSSM_APPLE_TP_SSL_OPTIONS
3385 ssl_options
; /* SSL Option for hostname */
3388 if (SecPolicySearchCreate(CSSM_CERT_X_509v3
, &CSSMOID_APPLE_TP_SSL
,
3389 NULL
, &policy_search
))
3391 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot create a policy search reference");
3392 CFRelease(keychain
);
3396 if (SecPolicySearchCopyNext(policy_search
, &policy
))
3398 cupsdLogMessage(CUPSD_LOG_ERROR
,
3399 "Cannot find a policy to use for searching");
3400 CFRelease(keychain
);
3401 CFRelease(policy_search
);
3405 memset(&ssl_options
, 0, sizeof(ssl_options
));
3406 ssl_options
.Version
= CSSM_APPLE_TP_SSL_OPTS_VERSION
;
3407 ssl_options
.ServerName
= con
->servername
;
3408 ssl_options
.ServerNameLen
= strlen(con
->servername
);
3410 options
.Data
= (uint8
*)&ssl_options
;
3411 options
.Length
= sizeof(ssl_options
);
3413 if (SecPolicySetValue(policy
, &options
))
3415 cupsdLogMessage(CUPSD_LOG_ERROR
,
3416 "Cannot set policy value to use for searching");
3417 CFRelease(keychain
);
3418 CFRelease(policy_search
);
3422 err
= SecIdentitySearchCreateWithPolicy(policy
, NULL
, CSSM_KEYUSE_SIGN
,
3423 keychain
, FALSE
, &search
);
3426 * Assume there is exactly one SecIdentity in the keychain...
3429 err
= SecIdentitySearchCreate(keychain
, CSSM_KEYUSE_SIGN
, &search
);
3430 # endif /* HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY */
3433 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3434 "Cannot create keychain search reference: %s",
3435 cssmErrorString(err
));
3438 if ((err
= SecIdentitySearchCopyNext(search
, &identity
)))
3440 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3441 "Cannot find signing key in keychain \"%s\", error %d",
3442 ServerCertificate
, (int)err
);
3446 if (CFGetTypeID(identity
) != SecIdentityGetTypeID())
3447 cupsdLogMessage(CUPSD_LOG_ERROR
,
3448 "SecIdentitySearchCopyNext CFTypeID failure!");
3451 if ((certificates
= CFArrayCreate(NULL
, (const void **)&identity
,
3452 1, &kCFTypeArrayCallBacks
)) == NULL
)
3453 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot create certificate array");
3456 CFRelease(identity
);
3462 # if HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY
3464 CFRelease(policy_search
);
3465 # endif /* HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY */
3467 return (certificates
);
3469 #endif /* HAVE_CDSASSL */
3473 * 'get_file()' - Get a filename and state info.
3476 static char * /* O - Real filename */
3477 get_file(cupsd_client_t
*con
, /* I - Client connection */
3478 struct stat
*filestats
, /* O - File information */
3479 char *filename
, /* IO - Filename buffer */
3480 int len
) /* I - Buffer length */
3482 int status
; /* Status of filesystem calls */
3483 char *ptr
; /* Pointer info filename */
3484 int plen
; /* Remaining length after pointer */
3485 char language
[7]; /* Language subdirectory, if any */
3489 * Figure out the real filename...
3494 if (!strncmp(con
->uri
, "/ppd/", 5))
3495 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
);
3496 else if (!strncmp(con
->uri
, "/rss/", 5) && !strchr(con
->uri
+ 5, '/'))
3497 snprintf(filename
, len
, "%s/rss/%s", CacheDir
, con
->uri
+ 5);
3498 else if (!strncmp(con
->uri
, "/admin/conf/", 12))
3499 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
+ 11);
3500 else if (!strncmp(con
->uri
, "/admin/log/", 11))
3502 if (!strncmp(con
->uri
+ 11, "access_log", 10) && AccessLog
[0] == '/')
3503 strlcpy(filename
, AccessLog
, len
);
3504 else if (!strncmp(con
->uri
+ 11, "error_log", 9) && ErrorLog
[0] == '/')
3505 strlcpy(filename
, ErrorLog
, len
);
3506 else if (!strncmp(con
->uri
+ 11, "page_log", 8) && PageLog
[0] == '/')
3507 strlcpy(filename
, PageLog
, len
);
3511 else if (con
->language
)
3513 snprintf(language
, sizeof(language
), "/%s", con
->language
->language
);
3514 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3517 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3519 if ((ptr
= strchr(filename
, '?')) != NULL
)
3523 * Grab the status for this language; if there isn't a language-specific file
3524 * then fallback to the default one...
3527 if ((status
= stat(filename
, filestats
)) != 0 && language
[0] &&
3528 strncmp(con
->uri
, "/ppd/", 5) &&
3529 strncmp(con
->uri
, "/admin/conf/", 12) &&
3530 strncmp(con
->uri
, "/admin/log/", 11))
3533 * Drop the country code...
3537 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3539 if ((ptr
= strchr(filename
, '?')) != NULL
)
3542 if ((status
= stat(filename
, filestats
)) != 0)
3545 * Drop the language prefix and try the root directory...
3549 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3551 if ((ptr
= strchr(filename
, '?')) != NULL
)
3554 status
= stat(filename
, filestats
);
3559 * If we're found a directory, get the index.html file instead...
3562 if (!status
&& S_ISDIR(filestats
->st_mode
))
3565 * Make sure the URI ends with a slash...
3568 if (con
->uri
[strlen(con
->uri
) - 1] != '/')
3569 strlcat(con
->uri
, "/", sizeof(con
->uri
));
3572 * Find the directory index file, trying every language...
3577 if (status
&& language
[0])
3580 * Try a different language subset...
3584 language
[0] = '\0'; /* Strip country code */
3586 language
[0] = '\0'; /* Strip language */
3590 * Look for the index file...
3593 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3595 if ((ptr
= strchr(filename
, '?')) != NULL
)
3598 ptr
= filename
+ strlen(filename
);
3599 plen
= len
- (ptr
- filename
);
3601 strlcpy(ptr
, "index.html", plen
);
3602 status
= stat(filename
, filestats
);
3607 strlcpy(ptr
, "index.class", plen
);
3608 status
= stat(filename
, filestats
);
3610 #endif /* HAVE_JAVA */
3615 strlcpy(ptr
, "index.pl", plen
);
3616 status
= stat(filename
, filestats
);
3618 #endif /* HAVE_PERL */
3623 strlcpy(ptr
, "index.php", plen
);
3624 status
= stat(filename
, filestats
);
3626 #endif /* HAVE_PHP */
3631 strlcpy(ptr
, "index.pyc", plen
);
3632 status
= stat(filename
, filestats
);
3637 strlcpy(ptr
, "index.py", plen
);
3638 status
= stat(filename
, filestats
);
3640 #endif /* HAVE_PYTHON */
3643 while (status
&& language
[0]);
3646 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "get_file: %d filename=%s size=%d",
3647 con
->http
.fd
, filename
,
3648 status
? -1 : (int)filestats
->st_size
);
3651 con
->http
.data_remaining
= (int)filestats
->st_size
;
3661 * 'install_conf_file()' - Install a configuration file.
3664 static http_status_t
/* O - Status */
3665 install_conf_file(cupsd_client_t
*con
) /* I - Connection */
3667 cups_file_t
*in
, /* Input file */
3668 *out
; /* Output file */
3669 char buffer
[1024]; /* Copy buffer */
3670 int bytes
; /* Number of bytes */
3671 char conffile
[1024], /* Configuration filename */
3672 newfile
[1024], /* New config filename */
3673 oldfile
[1024]; /* Old config filename */
3674 struct stat confinfo
; /* Config file info */
3678 * First construct the filenames...
3681 snprintf(conffile
, sizeof(conffile
), "%s%s", ServerRoot
, con
->uri
+ 11);
3682 snprintf(newfile
, sizeof(newfile
), "%s%s.N", ServerRoot
, con
->uri
+ 11);
3683 snprintf(oldfile
, sizeof(oldfile
), "%s%s.O", ServerRoot
, con
->uri
+ 11);
3685 cupsdLogMessage(CUPSD_LOG_INFO
, "Installing config file \"%s\"...", conffile
);
3688 * Get the owner, group, and permissions of the configuration file.
3689 * If it doesn't exist, assign it to the User and Group in the
3690 * cupsd.conf file with mode 0640 permissions.
3693 if (stat(conffile
, &confinfo
))
3695 confinfo
.st_uid
= User
;
3696 confinfo
.st_gid
= Group
;
3697 confinfo
.st_mode
= ConfigFilePerm
;
3701 * Open the request file and new config file...
3704 if ((in
= cupsFileOpen(con
->filename
, "rb")) == NULL
)
3706 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open request file \"%s\" - %s",
3707 con
->filename
, strerror(errno
));
3708 return (HTTP_SERVER_ERROR
);
3711 if ((out
= cupsFileOpen(newfile
, "wb")) == NULL
)
3714 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open config file \"%s\" - %s",
3715 newfile
, strerror(errno
));
3716 return (HTTP_SERVER_ERROR
);
3719 fchmod(cupsFileNumber(out
), confinfo
.st_mode
);
3720 fchown(cupsFileNumber(out
), confinfo
.st_uid
, confinfo
.st_gid
);
3723 * Copy from the request to the new config file...
3726 while ((bytes
= cupsFileRead(in
, buffer
, sizeof(buffer
))) > 0)
3727 if (cupsFileWrite(out
, buffer
, bytes
) < bytes
)
3729 cupsdLogMessage(CUPSD_LOG_ERROR
,
3730 "Unable to copy to config file \"%s\" - %s",
3731 newfile
, strerror(errno
));
3737 return (HTTP_SERVER_ERROR
);
3741 * Close the files...
3745 if (cupsFileClose(out
))
3747 cupsdLogMessage(CUPSD_LOG_ERROR
,
3748 "Error file closing config file \"%s\" - %s",
3749 newfile
, strerror(errno
));
3753 return (HTTP_SERVER_ERROR
);
3757 * Remove the request file...
3760 unlink(con
->filename
);
3761 cupsdClearString(&con
->filename
);
3764 * Unlink the old backup, rename the current config file to the backup
3765 * filename, and rename the new config file to the config file name...
3768 if (unlink(oldfile
))
3769 if (errno
!= ENOENT
)
3771 cupsdLogMessage(CUPSD_LOG_ERROR
,
3772 "Unable to remove backup config file \"%s\" - %s",
3773 oldfile
, strerror(errno
));
3777 return (HTTP_SERVER_ERROR
);
3780 if (rename(conffile
, oldfile
))
3781 if (errno
!= ENOENT
)
3783 cupsdLogMessage(CUPSD_LOG_ERROR
,
3784 "Unable to rename old config file \"%s\" - %s",
3785 conffile
, strerror(errno
));
3789 return (HTTP_SERVER_ERROR
);
3792 if (rename(newfile
, conffile
))
3794 cupsdLogMessage(CUPSD_LOG_ERROR
,
3795 "Unable to rename new config file \"%s\" - %s",
3796 newfile
, strerror(errno
));
3798 rename(oldfile
, conffile
);
3801 return (HTTP_SERVER_ERROR
);
3805 * If the cupsd.conf file was updated, set the NeedReload flag...
3808 if (!strcmp(con
->uri
, "/admin/conf/cupsd.conf"))
3809 NeedReload
= RELOAD_CUPSD
;
3811 NeedReload
= RELOAD_ALL
;
3813 ReloadTime
= time(NULL
);
3816 * Return that the file was created successfully...
3819 return (HTTP_CREATED
);
3824 * 'is_cgi()' - Is the resource a CGI script/program?
3827 static int /* O - 1 = CGI, 0 = file */
3828 is_cgi(cupsd_client_t
*con
, /* I - Client connection */
3829 const char *filename
, /* I - Real filename */
3830 struct stat
*filestats
, /* I - File information */
3831 mime_type_t
*type
) /* I - MIME type */
3833 const char *options
; /* Options on URL */
3836 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3837 "is_cgi(con=%p, filename=\"%s\", filestats=%p, type=%s/%s)",
3838 con
, filename
, filestats
, type
? type
->super
: "unknown",
3839 type
? type
->type
: "unknown");
3842 * Get the options, if any...
3845 if ((options
= strchr(con
->uri
, '?')) != NULL
)
3848 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", options
);
3852 * Check for known types...
3855 if (!type
|| strcasecmp(type
->super
, "application"))
3857 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "is_cgi: Returning 0...");
3861 if (!strcasecmp(type
->type
, "x-httpd-cgi") &&
3862 (filestats
->st_mode
& 0111))
3865 * "application/x-httpd-cgi" is a CGI script.
3868 cupsdSetString(&con
->command
, filename
);
3871 cupsdSetStringf(&con
->options
, " %s", options
);
3873 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3874 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3875 con
->command
, con
->options
);
3880 else if (!strcasecmp(type
->type
, "x-httpd-java"))
3883 * "application/x-httpd-java" is a Java servlet.
3886 cupsdSetString(&con
->command
, CUPS_JAVA
);
3889 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3891 cupsdSetStringf(&con
->options
, " %s", filename
);
3893 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3894 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3895 con
->command
, con
->options
);
3899 #endif /* HAVE_JAVA */
3901 else if (!strcasecmp(type
->type
, "x-httpd-perl"))
3904 * "application/x-httpd-perl" is a Perl page.
3907 cupsdSetString(&con
->command
, CUPS_PERL
);
3910 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3912 cupsdSetStringf(&con
->options
, " %s", filename
);
3914 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3915 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3916 con
->command
, con
->options
);
3920 #endif /* HAVE_PERL */
3922 else if (!strcasecmp(type
->type
, "x-httpd-php"))
3925 * "application/x-httpd-php" is a PHP page.
3928 cupsdSetString(&con
->command
, CUPS_PHP
);
3931 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3933 cupsdSetStringf(&con
->options
, " %s", filename
);
3935 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3936 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3937 con
->command
, con
->options
);
3941 #endif /* HAVE_PHP */
3943 else if (!strcasecmp(type
->type
, "x-httpd-python"))
3946 * "application/x-httpd-python" is a Python page.
3949 cupsdSetString(&con
->command
, CUPS_PYTHON
);
3952 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3954 cupsdSetStringf(&con
->options
, " %s", filename
);
3956 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3957 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3958 con
->command
, con
->options
);
3962 #endif /* HAVE_PYTHON */
3964 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "is_cgi: Returning 0...");
3971 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
3974 static int /* O - 0 if relative, 1 if absolute */
3975 is_path_absolute(const char *path
) /* I - Input path */
3978 * Check for a leading slash...
3985 * Check for "/.." in the path...
3988 while ((path
= strstr(path
, "/..")) != NULL
)
3990 if (!path
[3] || path
[3] == '/')
3997 * If we haven't found any relative paths, return 1 indicating an
4007 * 'make_certificate()' - Make a self-signed SSL/TLS certificate.
4010 static int /* O - 1 on success, 0 on failure */
4011 make_certificate(cupsd_client_t
*con
) /* I - Client connection */
4013 #if defined(HAVE_LIBSSL) && defined(HAVE_WAITPID)
4014 int pid
, /* Process ID of command */
4015 status
; /* Status of command */
4016 char command
[1024], /* Command */
4017 *argv
[12], /* Command-line arguments */
4018 *envp
[MAX_ENV
+ 1], /* Environment variables */
4019 home
[1024], /* HOME environment variable */
4020 infofile
[1024], /* Type-in information for cert */
4021 seedfile
[1024]; /* Random number seed file */
4022 int envc
, /* Number of environment variables */
4023 bytes
; /* Bytes written */
4024 cups_file_t
*fp
; /* Seed/info file */
4025 int infofd
; /* Info file descriptor */
4029 * Run the "openssl" command to seed the random number generator and
4030 * generate a self-signed certificate that is good for 10 years:
4032 * openssl rand -rand seedfile 1
4034 * openssl req -new -x509 -keyout ServerKey \
4035 * -out ServerCertificate -days 3650 -nodes
4037 * The seeding step is crucial in ensuring that the openssl command
4038 * does not block on systems without sufficient entropy...
4041 if (!cupsFileFind("openssl", getenv("PATH"), 1, command
, sizeof(command
)))
4043 cupsdLogMessage(CUPSD_LOG_ERROR
,
4044 "No SSL certificate and openssl command not found!");
4048 if (access("/dev/urandom", 0))
4051 * If the system doesn't provide /dev/urandom, then any random source
4052 * will probably be blocking-style, so generate some random data to
4053 * use as a seed for the certificate. Note that we have already
4054 * seeded the random number generator in cupsdInitCerts()...
4057 cupsdLogMessage(CUPSD_LOG_INFO
,
4058 "Seeding the random number generator...");
4060 snprintf(home
, sizeof(home
), "HOME=%s", TempDir
);
4063 * Write the seed file...
4066 if ((fp
= cupsTempFile2(seedfile
, sizeof(seedfile
))) == NULL
)
4068 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to create seed file %s - %s",
4069 seedfile
, strerror(errno
));
4073 for (bytes
= 0; bytes
< 262144; bytes
++)
4074 cupsFilePutChar(fp
, random());
4079 * Run the openssl command to seed its random number generator...
4082 argv
[0] = "openssl";
4089 envc
= cupsdLoadEnv(envp
, MAX_ENV
);
4090 envp
[envc
++] = home
;
4093 if (!cupsdStartProcess(command
, argv
, envp
, -1, -1, -1, -1, -1, 1, NULL
,
4100 while (waitpid(pid
, &status
, 0) < 0)
4107 cupsdFinishProcess(pid
, command
, sizeof(command
));
4110 * Remove the seed file, as it is no longer needed...
4117 if (WIFEXITED(status
))
4118 cupsdLogMessage(CUPSD_LOG_ERROR
,
4119 "Unable to seed random number generator - "
4120 "the openssl command stopped with status %d!",
4121 WEXITSTATUS(status
));
4123 cupsdLogMessage(CUPSD_LOG_ERROR
,
4124 "Unable to seed random number generator - "
4125 "the openssl command crashed on signal %d!",
4133 * Create a file with the certificate information fields...
4135 * Note: This assumes that the default questions are asked by the openssl
4139 if ((fp
= cupsTempFile2(infofile
, sizeof(infofile
))) == NULL
)
4141 cupsdLogMessage(CUPSD_LOG_ERROR
,
4142 "Unable to create certificate information file %s - %s",
4143 infofile
, strerror(errno
));
4147 cupsFilePrintf(fp
, ".\n.\n.\n%s\n.\n%s\n%s\n",
4148 ServerName
, ServerName
, ServerAdmin
);
4151 cupsdLogMessage(CUPSD_LOG_INFO
,
4152 "Generating SSL server key and certificate...");
4154 argv
[0] = "openssl";
4158 argv
[4] = "-keyout";
4159 argv
[5] = ServerKey
;
4161 argv
[7] = ServerCertificate
;
4164 argv
[10] = "-nodes";
4167 cupsdLoadEnv(envp
, MAX_ENV
);
4169 infofd
= open(infofile
, O_RDONLY
);
4171 if (!cupsdStartProcess(command
, argv
, envp
, infofd
, -1, -1, -1, -1, 1, NULL
,
4182 while (waitpid(pid
, &status
, 0) < 0)
4189 cupsdFinishProcess(pid
, command
, sizeof(command
));
4193 if (WIFEXITED(status
))
4194 cupsdLogMessage(CUPSD_LOG_ERROR
,
4195 "Unable to create SSL server key and certificate - "
4196 "the openssl command stopped with status %d!",
4197 WEXITSTATUS(status
));
4199 cupsdLogMessage(CUPSD_LOG_ERROR
,
4200 "Unable to create SSL server key and certificate - "
4201 "the openssl command crashed on signal %d!",
4206 cupsdLogMessage(CUPSD_LOG_INFO
, "Created SSL server key file \"%s\"...",
4208 cupsdLogMessage(CUPSD_LOG_INFO
,
4209 "Created SSL server certificate file \"%s\"...",
4215 #elif defined(HAVE_GNUTLS)
4216 gnutls_x509_crt crt
; /* Self-signed certificate */
4217 gnutls_x509_privkey key
; /* Encryption key */
4218 cups_lang_t
*language
; /* Default language info */
4219 cups_file_t
*fp
; /* Key/cert file */
4220 unsigned char buffer
[8192]; /* Buffer for x509 data */
4221 size_t bytes
; /* Number of bytes of data */
4222 unsigned char serial
[4]; /* Serial number buffer */
4223 time_t curtime
; /* Current time */
4224 int result
; /* Result of GNU TLS calls */
4228 * Create the encryption key...
4231 cupsdLogMessage(CUPSD_LOG_INFO
, "Generating SSL server key...");
4233 gnutls_x509_privkey_init(&key
);
4234 gnutls_x509_privkey_generate(key
, GNUTLS_PK_RSA
, 2048, 0);
4240 bytes
= sizeof(buffer
);
4242 if ((result
= gnutls_x509_privkey_export(key
, GNUTLS_X509_FMT_PEM
,
4243 buffer
, &bytes
)) < 0)
4245 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to export SSL server key - %s",
4246 gnutls_strerror(result
));
4247 gnutls_x509_privkey_deinit(key
);
4250 else if ((fp
= cupsFileOpen(ServerKey
, "w")) != NULL
)
4252 cupsFileWrite(fp
, (char *)buffer
, bytes
);
4255 cupsdLogMessage(CUPSD_LOG_INFO
, "Created SSL server key file \"%s\"...",
4260 cupsdLogMessage(CUPSD_LOG_ERROR
,
4261 "Unable to create SSL server key file \"%s\" - %s",
4262 ServerKey
, strerror(errno
));
4263 gnutls_x509_privkey_deinit(key
);
4268 * Create the self-signed certificate...
4271 cupsdLogMessage(CUPSD_LOG_INFO
, "Generating self-signed SSL certificate...");
4273 language
= cupsLangDefault();
4274 curtime
= time(NULL
);
4275 serial
[0] = curtime
>> 24;
4276 serial
[1] = curtime
>> 16;
4277 serial
[2] = curtime
>> 8;
4278 serial
[3] = curtime
;
4280 gnutls_x509_crt_init(&crt
);
4281 if (strlen(language
->language
) == 5)
4282 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
4283 language
->language
+ 3, 2);
4285 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
4287 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COMMON_NAME
, 0,
4288 ServerName
, strlen(ServerName
));
4289 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATION_NAME
, 0,
4290 ServerName
, strlen(ServerName
));
4291 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATIONAL_UNIT_NAME
,
4293 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_STATE_OR_PROVINCE_NAME
, 0,
4295 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_LOCALITY_NAME
, 0,
4297 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_PKCS9_EMAIL
, 0,
4298 ServerAdmin
, strlen(ServerAdmin
));
4299 gnutls_x509_crt_set_key(crt
, key
);
4300 gnutls_x509_crt_set_serial(crt
, serial
, sizeof(serial
));
4301 gnutls_x509_crt_set_activation_time(crt
, curtime
);
4302 gnutls_x509_crt_set_expiration_time(crt
, curtime
+ 10 * 365 * 86400);
4303 gnutls_x509_crt_set_ca_status(crt
, 0);
4304 gnutls_x509_crt_set_subject_alternative_name(crt
, GNUTLS_SAN_DNSNAME
,
4306 gnutls_x509_crt_set_key_purpose_oid(crt
, GNUTLS_KP_TLS_WWW_SERVER
, 0);
4307 gnutls_x509_crt_set_key_usage(crt
, GNUTLS_KEY_KEY_ENCIPHERMENT
);
4308 gnutls_x509_crt_set_version(crt
, 3);
4310 bytes
= sizeof(buffer
);
4311 if (gnutls_x509_crt_get_key_id(crt
, 0, buffer
, &bytes
) >= 0)
4312 gnutls_x509_crt_set_subject_key_id(crt
, buffer
, bytes
);
4314 gnutls_x509_crt_sign(crt
, crt
, key
);
4320 bytes
= sizeof(buffer
);
4321 if ((result
= gnutls_x509_crt_export(crt
, GNUTLS_X509_FMT_PEM
,
4322 buffer
, &bytes
)) < 0)
4323 cupsdLogMessage(CUPSD_LOG_ERROR
,
4324 "Unable to export SSL server certificate - %s",
4325 gnutls_strerror(result
));
4326 else if ((fp
= cupsFileOpen(ServerCertificate
, "w")) != NULL
)
4328 cupsFileWrite(fp
, (char *)buffer
, bytes
);
4331 cupsdLogMessage(CUPSD_LOG_INFO
,
4332 "Created SSL server certificate file \"%s\"...",
4336 cupsdLogMessage(CUPSD_LOG_ERROR
,
4337 "Unable to create SSL server certificate file \"%s\" - %s",
4338 ServerCertificate
, strerror(errno
));
4344 gnutls_x509_crt_deinit(crt
);
4345 gnutls_x509_privkey_deinit(key
);
4349 #elif defined(HAVE_CDSASSL) && defined(HAVE_WAITPID)
4350 int pid
, /* Process ID of command */
4351 status
; /* Status of command */
4352 char command
[1024], /* Command */
4353 *argv
[4], /* Command-line arguments */
4354 *envp
[MAX_ENV
+ 1], /* Environment variables */
4355 keychain
[1024], /* Keychain argument */
4356 infofile
[1024]; /* Type-in information for cert */
4357 cups_file_t
*fp
; /* Seed/info file */
4358 int infofd
; /* Info file descriptor */
4362 * Run the "certtool" command to generate a self-signed certificate...
4365 if (!cupsFileFind("certtool", getenv("PATH"), 1, command
, sizeof(command
)))
4367 cupsdLogMessage(CUPSD_LOG_ERROR
,
4368 "No SSL certificate and certtool command not found!");
4373 * Create a file with the certificate information fields...
4375 * Note: This assumes that the default questions are asked by the certtool
4379 if ((fp
= cupsTempFile2(infofile
, sizeof(infofile
))) == NULL
)
4381 cupsdLogMessage(CUPSD_LOG_ERROR
,
4382 "Unable to create certificate information file %s - %s",
4383 infofile
, strerror(errno
));
4387 cupsFilePrintf(fp
, "%s\nr\n\ny\nb\ns\ny\n%s\n\n\n\n\n%s\ny\n",
4388 con
->servername
, con
->servername
, ServerAdmin
);
4391 cupsdLogMessage(CUPSD_LOG_INFO
,
4392 "Generating SSL server key and certificate...");
4394 snprintf(keychain
, sizeof(keychain
), "k=%s", ServerCertificate
);
4396 argv
[0] = "certtool";
4401 cupsdLoadEnv(envp
, MAX_ENV
);
4403 infofd
= open(infofile
, O_RDONLY
);
4405 if (!cupsdStartProcess(command
, argv
, envp
, infofd
, -1, -1, -1, -1, 1, NULL
,
4416 while (waitpid(pid
, &status
, 0) < 0)
4423 cupsdFinishProcess(pid
, command
, sizeof(command
));
4427 if (WIFEXITED(status
))
4428 cupsdLogMessage(CUPSD_LOG_ERROR
,
4429 "Unable to create SSL server key and certificate - "
4430 "the certtool command stopped with status %d!",
4431 WEXITSTATUS(status
));
4433 cupsdLogMessage(CUPSD_LOG_ERROR
,
4434 "Unable to create SSL server key and certificate - "
4435 "the certtool command crashed on signal %d!",
4440 cupsdLogMessage(CUPSD_LOG_INFO
,
4441 "Created SSL server certificate file \"%s\"...",
4449 #endif /* HAVE_LIBSSL && HAVE_WAITPID */
4451 #endif /* HAVE_SSL */
4455 * 'pipe_command()' - Pipe the output of a command to the remote client.
4458 static int /* O - Process ID */
4459 pipe_command(cupsd_client_t
*con
, /* I - Client connection */
4460 int infile
, /* I - Standard input for command */
4461 int *outfile
, /* O - Standard output for command */
4462 char *command
, /* I - Command to run */
4463 char *options
, /* I - Options for command */
4464 int root
) /* I - Run as root? */
4466 int i
; /* Looping var */
4467 int pid
; /* Process ID */
4468 char *commptr
, /* Command string pointer */
4469 commch
; /* Command string character */
4470 char *uriptr
; /* URI string pointer */
4471 int fds
[2]; /* Pipe FDs */
4472 int argc
; /* Number of arguments */
4473 int envc
; /* Number of environment variables */
4474 char argbuf
[10240], /* Argument buffer */
4475 *argv
[100], /* Argument strings */
4476 *envp
[MAX_ENV
+ 20]; /* Environment variables */
4477 char auth_type
[256], /* CUPSD_AUTH_TYPE environment variable */
4478 content_length
[1024], /* CONTENT_LENGTH environment variable */
4479 content_type
[1024], /* CONTENT_TYPE environment variable */
4480 http_cookie
[32768], /* HTTP_COOKIE environment variable */
4481 http_referer
[1024], /* HTTP_REFERER environment variable */
4482 http_user_agent
[1024], /* HTTP_USER_AGENT environment variable */
4483 lang
[1024], /* LANG environment variable */
4484 path_info
[1024], /* PATH_INFO environment variable */
4485 remote_addr
[1024], /* REMOTE_ADDR environment variable */
4486 remote_host
[1024], /* REMOTE_HOST environment variable */
4487 remote_user
[1024], /* REMOTE_USER environment variable */
4488 script_filename
[1024], /* SCRIPT_FILENAME environment variable */
4489 script_name
[1024], /* SCRIPT_NAME environment variable */
4490 server_name
[1024], /* SERVER_NAME environment variable */
4491 server_port
[1024]; /* SERVER_PORT environment variable */
4492 ipp_attribute_t
*attr
; /* attributes-natural-language attribute */
4494 krb5_ccache ccache
= NULL
; /* Kerberos credentials */
4495 # if defined(HAVE_KRB5_CC_NEW_UNIQUE) || defined(HAVE_HEIMDAL)
4496 char krb5ccname
[1024]; /* KRB5CCNAME environment variable */
4497 # endif /* HAVE_KRB5_CC_NEW_UNIQUE || HAVE_HEIMDAL */
4498 #endif /* HAVE_GSSAPI */
4502 * Parse a copy of the options string, which is of the form:
4504 * argument+argument+argument
4505 * ?argument+argument+argument
4506 * param=value¶m=value
4507 * ?param=value¶m=value
4508 * /name?argument+argument+argument
4509 * /name?param=value¶m=value
4511 * If the string contains an "=" character after the initial name,
4512 * then we treat it as a HTTP GET form request and make a copy of
4513 * the remaining string for the environment variable.
4515 * The string is always parsed out as command-line arguments, to
4516 * be consistent with Apache...
4519 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4520 "pipe_command: command=\"%s\", options=\"%s\"",
4521 command
, options
? options
: "(null)");
4526 strlcpy(argbuf
, options
, sizeof(argbuf
));
4530 if (argbuf
[0] == '/')
4533 * Found some trailing path information, set PATH_INFO...
4536 if ((commptr
= strchr(argbuf
, '?')) == NULL
)
4537 commptr
= argbuf
+ strlen(argbuf
);
4541 snprintf(path_info
, sizeof(path_info
), "PATH_INFO=%s", argbuf
);
4547 path_info
[0] = '\0';
4549 if (*commptr
== ' ')
4553 if (*commptr
== '?' && con
->operation
== HTTP_GET
&& !con
->query_string
)
4556 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", commptr
);
4563 argv
[argc
++] = commptr
;
4565 for (; *commptr
&& argc
< 99; commptr
++)
4568 * Break arguments whenever we see a + or space...
4571 if (*commptr
== ' ' || *commptr
== '+')
4573 while (*commptr
== ' ' || *commptr
== '+')
4577 * If we don't have a blank string, save it as another argument...
4582 argv
[argc
] = commptr
;
4588 else if (*commptr
== '%' && isxdigit(commptr
[1] & 255) &&
4589 isxdigit(commptr
[2] & 255))
4592 * Convert the %xx notation to the individual character.
4595 if (commptr
[1] >= '0' && commptr
[1] <= '9')
4596 *commptr
= (commptr
[1] - '0') << 4;
4598 *commptr
= (tolower(commptr
[1]) - 'a' + 10) << 4;
4600 if (commptr
[2] >= '0' && commptr
[2] <= '9')
4601 *commptr
|= commptr
[2] - '0';
4603 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
4605 _cups_strcpy(commptr
+ 1, commptr
+ 3);
4608 * Check for a %00 and break if that is the case...
4620 * Setup the environment variables as needed...
4623 if (con
->username
[0])
4625 snprintf(auth_type
, sizeof(auth_type
), "CUPSD_AUTH_TYPE=%s",
4626 httpGetField(HTTP(con
), HTTP_FIELD_AUTHORIZATION
));
4628 if ((uriptr
= strchr(auth_type
+ 10, ' ')) != NULL
)
4632 auth_type
[0] = '\0';
4635 (attr
= ippFindAttribute(con
->request
, "attributes-natural-language",
4636 IPP_TAG_LANGUAGE
)) != NULL
)
4638 switch (strlen(attr
->values
[0].string
.text
))
4642 * This is an unknown or badly formatted language code; use
4643 * the POSIX locale...
4646 strcpy(lang
, "LANG=C");
4651 * Just the language code (ll)...
4654 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8",
4655 attr
->values
[0].string
.text
);
4660 * Language and country code (ll-cc)...
4663 snprintf(lang
, sizeof(lang
), "LANG=%c%c_%c%c.UTF8",
4664 attr
->values
[0].string
.text
[0],
4665 attr
->values
[0].string
.text
[1],
4666 toupper(attr
->values
[0].string
.text
[3] & 255),
4667 toupper(attr
->values
[0].string
.text
[4] & 255));
4671 else if (con
->language
)
4672 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8", con
->language
->language
);
4674 strcpy(lang
, "LANG=C");
4676 strcpy(remote_addr
, "REMOTE_ADDR=");
4677 httpAddrString(con
->http
.hostaddr
, remote_addr
+ 12,
4678 sizeof(remote_addr
) - 12);
4680 snprintf(remote_host
, sizeof(remote_host
), "REMOTE_HOST=%s",
4681 con
->http
.hostname
);
4683 snprintf(script_name
, sizeof(script_name
), "SCRIPT_NAME=%s", con
->uri
);
4684 if ((uriptr
= strchr(script_name
, '?')) != NULL
)
4687 snprintf(script_filename
, sizeof(script_filename
), "SCRIPT_FILENAME=%s%s",
4688 DocumentRoot
, script_name
+ 12);
4690 sprintf(server_port
, "SERVER_PORT=%d", con
->serverport
);
4692 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
4695 envc
= cupsdLoadEnv(envp
, (int)(sizeof(envp
) / sizeof(envp
[0])));
4698 envp
[envc
++] = auth_type
;
4700 envp
[envc
++] = lang
;
4701 envp
[envc
++] = "REDIRECT_STATUS=1";
4702 envp
[envc
++] = "GATEWAY_INTERFACE=CGI/1.1";
4703 envp
[envc
++] = server_name
;
4704 envp
[envc
++] = server_port
;
4705 envp
[envc
++] = remote_addr
;
4706 envp
[envc
++] = remote_host
;
4707 envp
[envc
++] = script_name
;
4708 envp
[envc
++] = script_filename
;
4711 envp
[envc
++] = path_info
;
4713 if (con
->username
[0])
4715 snprintf(remote_user
, sizeof(remote_user
), "REMOTE_USER=%s", con
->username
);
4717 envp
[envc
++] = remote_user
;
4720 * Save Kerberos credentials, if any...
4724 if (con
->gss_have_creds
)
4726 # if !defined(HAVE_KRB5_CC_NEW_UNIQUE) && !defined(HAVE_HEIMDAL)
4727 cupsdLogMessage(CUPSD_LOG_INFO
,
4728 "Sorry, your version of Kerberos does not support "
4729 "delegated credentials!");
4732 krb5_error_code error
; /* Kerberos error code */
4733 OM_uint32 major_status
, /* Major status code */
4734 minor_status
; /* Minor status code */
4735 krb5_principal principal
; /* Kerberos principal */
4740 * If the weak-linked GSSAPI/Kerberos library is not present, don't try
4744 if (krb5_init_context
!= NULL
)
4746 # endif /* __APPLE__ */
4748 if (!KerberosInitialized
)
4751 * Setup a Kerberos context for the scheduler to use...
4754 KerberosInitialized
= 1;
4756 if (krb5_init_context(&KerberosContext
))
4758 KerberosContext
= NULL
;
4760 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to initialize Kerberos context");
4765 * We MUST create a file-based cache because memory-based caches are
4766 * only valid for the current process/address space.
4768 * Due to various bugs/features in different versions of Kerberos, we
4769 * need either the krb5_cc_new_unique() function or Heimdal's version
4770 * of krb5_cc_gen_new() to create a new FILE: credential cache that
4771 * can be passed to the backend. These functions create a temporary
4772 * file (typically in /tmp) containing the cached credentials, which
4773 * are removed when we have successfully printed a job.
4776 if (KerberosContext
)
4778 # ifdef HAVE_KRB5_CC_NEW_UNIQUE
4779 if ((error
= krb5_cc_new_unique(KerberosContext
, "FILE", NULL
,
4781 # else /* HAVE_HEIMDAL */
4782 if ((error
= krb5_cc_gen_new(KerberosContext
, &krb5_fcc_ops
,
4784 # endif /* HAVE_KRB5_CC_NEW_UNIQUE */
4786 cupsdLogMessage(CUPSD_LOG_ERROR
,
4787 "Unable to create new credentials cache (%d/%s)",
4788 error
, strerror(errno
));
4791 else if ((error
= krb5_parse_name(KerberosContext
, con
->username
,
4794 cupsdLogMessage(CUPSD_LOG_ERROR
,
4795 "Unable to parse kerberos username (%d/%s)", error
,
4797 krb5_cc_destroy(KerberosContext
, ccache
);
4800 else if ((error
= krb5_cc_initialize(KerberosContext
, ccache
,
4803 cupsdLogMessage(CUPSD_LOG_ERROR
,
4804 "Unable to initialize credentials cache (%d/%s)", error
,
4806 krb5_cc_destroy(KerberosContext
, ccache
);
4807 krb5_free_principal(KerberosContext
, principal
);
4812 krb5_free_principal(KerberosContext
, principal
);
4815 * Copy the user's credentials to the new cache file...
4818 major_status
= gss_krb5_copy_ccache(&minor_status
,
4819 con
->gss_delegated_cred
, ccache
);
4821 if (GSS_ERROR(major_status
))
4823 cupsdLogGSSMessage(CUPSD_LOG_ERROR
, major_status
, minor_status
,
4824 "Unable to import client credentials cache");
4825 krb5_cc_destroy(KerberosContext
, ccache
);
4831 * Add the KRB5CCNAME environment variable to the job so that the
4832 * backend can use the credentials when printing.
4835 snprintf(krb5ccname
, sizeof(krb5ccname
), "KRB5CCNAME=FILE:%s",
4836 krb5_cc_get_name(KerberosContext
, ccache
));
4837 envp
[envc
++] = krb5ccname
;
4840 chown(krb5_cc_get_name(KerberosContext
, ccache
), User
, Group
);
4846 # endif /* __APPLE__ */
4847 # endif /* HAVE_KRB5_CC_NEW_UNIQUE || HAVE_HEIMDAL */
4849 #endif /* HAVE_GSSAPI */
4852 if (con
->http
.version
== HTTP_1_1
)
4853 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.1";
4854 else if (con
->http
.version
== HTTP_1_0
)
4855 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.0";
4857 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/0.9";
4859 if (con
->http
.cookie
)
4861 snprintf(http_cookie
, sizeof(http_cookie
), "HTTP_COOKIE=%s",
4863 envp
[envc
++] = http_cookie
;
4866 if (con
->http
.fields
[HTTP_FIELD_USER_AGENT
][0])
4868 snprintf(http_user_agent
, sizeof(http_user_agent
), "HTTP_USER_AGENT=%s",
4869 con
->http
.fields
[HTTP_FIELD_USER_AGENT
]);
4870 envp
[envc
++] = http_user_agent
;
4873 if (con
->http
.fields
[HTTP_FIELD_REFERER
][0])
4875 snprintf(http_referer
, sizeof(http_referer
), "HTTP_REFERER=%s",
4876 con
->http
.fields
[HTTP_FIELD_REFERER
]);
4877 envp
[envc
++] = http_referer
;
4880 if (con
->operation
== HTTP_GET
)
4882 envp
[envc
++] = "REQUEST_METHOD=GET";
4884 if (con
->query_string
)
4887 * Add GET form variables after ?...
4890 envp
[envc
++] = con
->query_string
;
4893 envp
[envc
++] = "QUERY_STRING=";
4897 sprintf(content_length
, "CONTENT_LENGTH=" CUPS_LLFMT
,
4898 CUPS_LLCAST con
->bytes
);
4899 snprintf(content_type
, sizeof(content_type
), "CONTENT_TYPE=%s",
4900 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
4902 envp
[envc
++] = "REQUEST_METHOD=POST";
4903 envp
[envc
++] = content_length
;
4904 envp
[envc
++] = content_type
;
4908 * Tell the CGI if we are using encryption...
4912 envp
[envc
++] = "HTTPS=ON";
4915 * Terminate the environment array...
4920 if (LogLevel
== CUPSD_LOG_DEBUG2
)
4922 for (i
= 0; i
< argc
; i
++)
4923 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4924 "pipe_command: argv[%d] = \"%s\"", i
, argv
[i
]);
4925 for (i
= 0; i
< envc
; i
++)
4926 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4927 "pipe_command: envp[%d] = \"%s\"", i
, envp
[i
]);
4931 * Create a pipe for the output...
4934 if (cupsdOpenPipe(fds
))
4936 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to create pipes for CGI %s - %s",
4937 argv
[0], strerror(errno
));
4942 * Then execute the command...
4945 if (cupsdStartProcess(command
, argv
, envp
, infile
, fds
[1], CGIPipes
[1],
4946 -1, -1, root
, DefaultProfile
, &pid
) < 0)
4949 * Error - can't fork!
4952 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to fork for CGI %s - %s", argv
[0],
4955 cupsdClosePipe(fds
);
4961 * Fork successful - return the PID...
4964 if (con
->username
[0])
4966 cupsdAddCert(pid
, con
->username
, ccache
);
4968 cupsdAddCert(pid
, con
->username
, NULL
);
4969 #endif /* HAVE_GSSAPI */
4971 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[CGI] %s started - PID = %d",
4983 * 'write_file()' - Send a file via HTTP.
4986 static int /* O - 0 on failure, 1 on success */
4987 write_file(cupsd_client_t
*con
, /* I - Client connection */
4988 http_status_t code
, /* I - HTTP status */
4989 char *filename
, /* I - Filename */
4990 char *type
, /* I - File type */
4991 struct stat
*filestats
) /* O - File information */
4993 con
->file
= open(filename
, O_RDONLY
);
4995 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "write_file: %d file=%d", con
->http
.fd
,
5001 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
5005 if (!cupsdSendHeader(con
, code
, type
, CUPSD_AUTH_NONE
))
5008 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
5009 httpGetDateString(filestats
->st_mtime
)) < 0)
5011 if (httpPrintf(HTTP(con
), "Content-Length: " CUPS_LLFMT
"\r\n",
5012 CUPS_LLCAST filestats
->st_size
) < 0)
5014 if (httpPrintf(HTTP(con
), "\r\n") < 0)
5017 if (cupsdFlushHeader(con
) < 0)
5020 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
5021 con
->http
.data_remaining
= filestats
->st_size
;
5023 if (con
->http
.data_remaining
<= INT_MAX
)
5024 con
->http
._data_remaining
= con
->http
.data_remaining
;
5026 con
->http
._data_remaining
= INT_MAX
;
5028 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
,
5029 (cupsd_selfunc_t
)cupsdWriteClient
, con
);
5036 * 'write_pipe()' - Flag that data is available on the CGI pipe.
5040 write_pipe(cupsd_client_t
*con
) /* I - Client connection */
5042 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "write_pipe: CGI output on fd %d...",
5045 con
->file_ready
= 1;
5047 cupsdRemoveSelect(con
->file
);
5048 cupsdAddSelect(con
->http
.fd
, NULL
, (cupsd_selfunc_t
)cupsdWriteClient
, con
);
5053 * End of "$Id: client.c 7950 2008-09-17 00:21:59Z mike $".