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
)
2700 if (!strchr(CGIStatusBuffer
->buffer
, '\n'))
2703 if (ptr
== NULL
&& !CGIStatusBuffer
->bufused
)
2706 * Fatal error on pipe - should never happen!
2709 cupsdLogMessage(CUPSD_LOG_CRIT
,
2710 "cupsdUpdateCGI: error reading from CGI error pipe - %s",
2717 * 'cupsdWriteClient()' - Write data to a client as needed.
2721 cupsdWriteClient(cupsd_client_t
*con
) /* I - Client connection */
2723 int bytes
; /* Number of bytes written */
2724 char buf
[16385]; /* Data buffer */
2725 char *bufptr
; /* Pointer into buffer */
2726 ipp_state_t ipp_state
; /* IPP state value */
2730 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2731 "cupsdWriteClient(con=%p) %d response=%p(%d), file=%d "
2732 "pipe_pid=%d state=%d",
2733 con
, con
->http
.fd
, con
->response
,
2734 con
->response
? con
->response
->state
: -1,
2735 con
->file
, con
->pipe_pid
, con
->http
.state
);
2738 if (con
->http
.state
!= HTTP_GET_SEND
&&
2739 con
->http
.state
!= HTTP_POST_SEND
)
2745 * Make sure we select on the CGI output...
2748 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2750 if (!con
->file_ready
)
2753 * Try again later when there is CGI output available...
2756 cupsdRemoveSelect(con
->http
.fd
);
2760 con
->file_ready
= 0;
2763 if (con
->response
&& con
->response
->state
!= IPP_DATA
)
2765 ipp_state
= ippWrite(HTTP(con
), con
->response
);
2766 bytes
= ipp_state
!= IPP_ERROR
&&
2767 (con
->file
>= 0 || ipp_state
!= IPP_DATA
);
2769 else if ((bytes
= read(con
->file
, buf
, sizeof(buf
) - 1)) > 0)
2771 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2772 "cupsdWriteClient: Read %d bytes from file %d...",
2775 if (con
->pipe_pid
&& !con
->got_fields
)
2778 * Inspect the data for Content-Type and other fields.
2783 for (bufptr
= buf
; !con
->got_fields
&& *bufptr
; bufptr
++)
2785 if (*bufptr
== '\n')
2788 * Send line to client...
2791 if (bufptr
> buf
&& bufptr
[-1] == '\r')
2795 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Script header: %s", buf
);
2797 if (!con
->sent_header
)
2800 * Handle redirection and CGI status codes...
2803 if (!strncasecmp(buf
, "Location:", 9))
2805 cupsdSendHeader(con
, HTTP_SEE_OTHER
, NULL
, CUPSD_AUTH_NONE
);
2806 con
->sent_header
= 2;
2808 if (httpPrintf(HTTP(con
), "Content-Length: 0\r\n") < 0)
2811 else if (!strncasecmp(buf
, "Status:", 7))
2813 cupsdSendError(con
, (http_status_t
)atoi(buf
+ 7), CUPSD_AUTH_NONE
);
2814 con
->sent_header
= 2;
2818 cupsdSendHeader(con
, HTTP_OK
, NULL
, CUPSD_AUTH_NONE
);
2819 con
->sent_header
= 1;
2821 if (con
->http
.version
== HTTP_1_1
)
2823 if (httpPrintf(HTTP(con
), "Transfer-Encoding: chunked\r\n") < 0)
2829 if (strncasecmp(buf
, "Status:", 7))
2830 httpPrintf(HTTP(con
), "%s\r\n", buf
);
2832 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdWriteClient: %d %s",
2839 bytes
-= (bufptr
- buf
);
2842 memmove(buf
, bufptr
, bytes
+ 1);
2849 * See if the line was empty...
2852 if (con
->field_col
== 0)
2854 con
->got_fields
= 1;
2856 if (cupsdFlushHeader(con
) < 0)
2858 cupsdCloseClient(con
);
2862 if (con
->http
.version
== HTTP_1_1
)
2863 con
->http
.data_encoding
= HTTP_ENCODE_CHUNKED
;
2868 else if (*bufptr
!= '\r')
2872 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2873 "cupsdWriteClient: %d bytes=%d, got_fields=%d",
2874 con
->http
.fd
, bytes
, con
->got_fields
);
2876 if (bytes
> 0 && !con
->got_fields
)
2879 * Remaining text needs to go out...
2882 httpPrintf(HTTP(con
), "%s", buf
);
2884 con
->http
.activity
= time(NULL
);
2887 else if (bytes
== 0)
2889 con
->http
.activity
= time(NULL
);
2896 if (httpWrite2(HTTP(con
), buf
, bytes
) < 0)
2898 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2899 "cupsdWriteClient: %d Write of %d bytes failed!",
2900 con
->http
.fd
, bytes
);
2902 cupsdCloseClient(con
);
2906 if (con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
)
2907 httpFlushWrite(HTTP(con
));
2909 con
->bytes
+= bytes
;
2911 if (con
->http
.state
== HTTP_WAITING
)
2918 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdWriteClient: %d bytes < 0",
2921 cupsdLogRequest(con
, HTTP_OK
);
2923 httpFlushWrite(HTTP(con
));
2925 if (con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
&& con
->sent_header
== 1)
2927 if (httpWrite2(HTTP(con
), "", 0) < 0)
2929 cupsdCloseClient(con
);
2934 con
->http
.state
= HTTP_WAITING
;
2936 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
2940 cupsdRemoveSelect(con
->file
);
2943 cupsdEndProcess(con
->pipe_pid
, 0);
2945 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2946 "cupsdWriteClient: %d Closing data file %d.",
2947 con
->http
.fd
, con
->file
);
2956 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2957 "cupsdWriteClient: %d Removing temp file %s",
2958 con
->http
.fd
, con
->filename
);
2959 unlink(con
->filename
);
2960 cupsdClearString(&con
->filename
);
2965 ippDelete(con
->request
);
2966 con
->request
= NULL
;
2971 ippDelete(con
->response
);
2972 con
->response
= NULL
;
2975 cupsdClearString(&con
->command
);
2976 cupsdClearString(&con
->options
);
2977 cupsdClearString(&con
->query_string
);
2979 if (!con
->http
.keep_alive
)
2981 cupsdCloseClient(con
);
2986 con
->http
.activity
= time(NULL
);
2991 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
2994 static int /* O - 1 if modified since */
2996 cupsd_client_t
*con
, /* I - Client connection */
2997 struct stat
*filestats
) /* I - File information */
2999 char *ptr
; /* Pointer into field */
3000 time_t date
; /* Time/date value */
3001 off_t size
; /* Size/length value */
3006 ptr
= con
->http
.fields
[HTTP_FIELD_IF_MODIFIED_SINCE
];
3011 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3012 "check_if_modified: %d If-Modified-Since=\"%s\"",
3015 while (*ptr
!= '\0')
3017 while (isspace(*ptr
) || *ptr
== ';')
3020 if (strncasecmp(ptr
, "length=", 7) == 0)
3023 size
= strtoll(ptr
, NULL
, 10);
3025 while (isdigit(*ptr
))
3028 else if (isalpha(*ptr
))
3030 date
= httpGetDateTime(ptr
);
3031 while (*ptr
!= '\0' && *ptr
!= ';')
3038 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3039 "check_if_modified: %d sizes=" CUPS_LLFMT
","
3040 CUPS_LLFMT
" dates=%d,%d",
3041 con
->http
.fd
, CUPS_LLCAST size
,
3042 CUPS_LLCAST filestats
->st_size
, (int)date
,
3043 (int)filestats
->st_mtime
);
3045 return ((size
!= filestats
->st_size
&& size
!= 0) ||
3046 (date
< filestats
->st_mtime
&& date
!= 0) ||
3047 (size
== 0 && date
== 0));
3052 * 'compare_clients()' - Compare two client connections.
3055 static int /* O - Result of comparison */
3056 compare_clients(cupsd_client_t
*a
, /* I - First client */
3057 cupsd_client_t
*b
, /* I - Second client */
3058 void *data
) /* I - User data (not used) */
3072 * 'data_ready()' - Check whether data is available from a client.
3075 static int /* O - 1 if data is ready, 0 otherwise */
3076 data_ready(cupsd_client_t
*con
) /* I - Client */
3078 if (con
->http
.used
> 0)
3081 else if (con
->http
.tls
)
3084 if (SSL_pending((SSL
*)(con
->http
.tls
)))
3086 # elif defined(HAVE_GNUTLS)
3087 if (gnutls_record_check_pending(((http_tls_t
*)(con
->http
.tls
))->session
))
3089 # elif defined(HAVE_CDSASSL)
3090 size_t bytes
; /* Bytes that are available */
3092 if (!SSLGetBufferedReadSize(((http_tls_t
*)(con
->http
.tls
))->session
,
3093 &bytes
) && bytes
> 0)
3095 # endif /* HAVE_LIBSSL */
3097 #endif /* HAVE_SSL */
3105 * 'encrypt_client()' - Enable encryption for the client...
3108 static int /* O - 1 on success, 0 on error */
3109 encrypt_client(cupsd_client_t
*con
) /* I - Client to encrypt */
3112 SSL_CTX
*context
; /* Context for encryption */
3113 SSL
*conn
; /* Connection for encryption */
3114 BIO
*bio
; /* BIO data */
3115 unsigned long error
; /* Error code */
3119 * Verify that we have a certificate...
3122 if (access(ServerKey
, 0) || access(ServerCertificate
, 0))
3125 * Nope, make a self-signed certificate...
3128 if (!make_certificate(con
))
3133 * Create the SSL context and accept the connection...
3136 context
= SSL_CTX_new(SSLv23_server_method());
3138 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
3139 if (SSLOptions
& CUPSD_SSL_NOEMPTY
)
3140 SSL_CTX_set_options(context
, SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
);
3141 SSL_CTX_use_PrivateKey_file(context
, ServerKey
, SSL_FILETYPE_PEM
);
3142 SSL_CTX_use_certificate_chain_file(context
, ServerCertificate
);
3144 bio
= BIO_new(_httpBIOMethods());
3145 BIO_ctrl(bio
, BIO_C_SET_FILE_PTR
, 0, (char *)HTTP(con
));
3147 conn
= SSL_new(context
);
3148 SSL_set_bio(conn
, bio
, bio
);
3150 if (SSL_accept(conn
) != 1)
3152 cupsdLogMessage(CUPSD_LOG_ERROR
,
3153 "encrypt_client: Unable to encrypt connection from %s!",
3154 con
->http
.hostname
);
3156 while ((error
= ERR_get_error()) != 0)
3157 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s",
3158 ERR_error_string(error
, NULL
));
3160 SSL_CTX_free(context
);
3165 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3166 "encrypt_client: %d Connection from %s now encrypted.",
3167 con
->http
.fd
, con
->http
.hostname
);
3169 con
->http
.tls
= conn
;
3172 # elif defined(HAVE_GNUTLS)
3173 http_tls_t
*conn
; /* TLS session object */
3174 int error
; /* Error code */
3175 gnutls_certificate_server_credentials
*credentials
;
3176 /* TLS credentials */
3180 * Verify that we have a certificate...
3183 if (access(ServerKey
, 0) || access(ServerCertificate
, 0))
3186 * Nope, make a self-signed certificate...
3189 if (!make_certificate(con
))
3194 * Create the SSL object and perform the SSL handshake...
3197 conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
));
3202 credentials
= (gnutls_certificate_server_credentials
*)
3203 malloc(sizeof(gnutls_certificate_server_credentials
));
3204 if (credentials
== NULL
)
3206 cupsdLogMessage(CUPSD_LOG_ERROR
,
3207 "encrypt_client: Unable to encrypt connection from %s!",
3208 con
->http
.hostname
);
3209 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s", strerror(errno
));
3215 gnutls_certificate_allocate_credentials(credentials
);
3216 gnutls_certificate_set_x509_key_file(*credentials
, ServerCertificate
,
3217 ServerKey
, GNUTLS_X509_FMT_PEM
);
3219 gnutls_init(&(conn
->session
), GNUTLS_SERVER
);
3220 gnutls_set_default_priority(conn
->session
);
3221 gnutls_credentials_set(conn
->session
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
3222 gnutls_transport_set_ptr(conn
->session
, (gnutls_transport_ptr
)HTTP(con
));
3223 gnutls_transport_set_pull_function(conn
->session
, _httpReadGNUTLS
);
3224 gnutls_transport_set_push_function(conn
->session
, _httpWriteGNUTLS
);
3226 error
= gnutls_handshake(conn
->session
);
3228 if (error
!= GNUTLS_E_SUCCESS
)
3230 cupsdLogMessage(CUPSD_LOG_ERROR
,
3231 "encrypt_client: Unable to encrypt connection from %s!",
3232 con
->http
.hostname
);
3233 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s",
3234 gnutls_strerror(error
));
3236 gnutls_deinit(conn
->session
);
3237 gnutls_certificate_free_credentials(*credentials
);
3243 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3244 "encrypt_client: %d Connection from %s now encrypted.",
3245 con
->http
.fd
, con
->http
.hostname
);
3247 conn
->credentials
= credentials
;
3248 con
->http
.tls
= conn
;
3251 # elif defined(HAVE_CDSASSL)
3252 OSStatus error
; /* Error code */
3253 http_tls_t
*conn
; /* CDSA connection information */
3256 if ((conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
))) == NULL
)
3260 conn
->session
= NULL
;
3261 conn
->certsArray
= get_cdsa_certificate(con
);
3263 if (!conn
->certsArray
)
3266 * No keychain (yet), make a self-signed certificate...
3269 if (make_certificate(con
))
3270 conn
->certsArray
= get_cdsa_certificate(con
);
3273 if (!conn
->certsArray
)
3275 cupsdLogMessage(CUPSD_LOG_ERROR
,
3276 "encrypt_client: Could not find signing key in keychain "
3277 "\"%s\"", ServerCertificate
);
3278 error
= errSSLBadCert
; /* errSSLBadConfiguration is a better choice, but not available on 10.2.x */
3282 error
= SSLNewContext(true, &conn
->session
);
3285 error
= SSLSetIOFuncs(conn
->session
, _httpReadCDSA
, _httpWriteCDSA
);
3288 error
= SSLSetProtocolVersionEnabled(conn
->session
, kSSLProtocol2
, false);
3291 error
= SSLSetConnection(conn
->session
, HTTP(con
));
3294 error
= SSLSetAllowsExpiredCerts(conn
->session
, true);
3297 error
= SSLSetAllowsAnyRoot(conn
->session
, true);
3300 error
= SSLSetCertificate(conn
->session
, conn
->certsArray
);
3305 * Perform SSL/TLS handshake
3308 while ((error
= SSLHandshake(conn
->session
)) == errSSLWouldBlock
)
3314 cupsdLogMessage(CUPSD_LOG_ERROR
,
3315 "encrypt_client: Unable to encrypt connection from %s!",
3316 con
->http
.hostname
);
3318 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s (%d)",
3319 cssmErrorString(error
), (int)error
);
3321 con
->http
.error
= error
;
3322 con
->http
.status
= HTTP_ERROR
;
3325 SSLDisposeContext(conn
->session
);
3327 if (conn
->certsArray
)
3328 CFRelease(conn
->certsArray
);
3335 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3336 "encrypt_client: %d Connection from %s now encrypted.",
3337 con
->http
.fd
, con
->http
.hostname
);
3339 con
->http
.tls
= conn
;
3342 # endif /* HAVE_LIBSSL */
3344 #endif /* HAVE_SSL */
3349 * 'get_cdsa_certificate()' - Get a SSL/TLS certificate from the System keychain.
3352 static CFArrayRef
/* O - Array of certificates */
3353 get_cdsa_certificate(cupsd_client_t
*con
) /* I - Client connection */
3355 OSStatus err
; /* Error info */
3356 SecKeychainRef keychain
; /* Keychain reference */
3357 SecIdentitySearchRef search
; /* Search reference */
3358 SecIdentityRef identity
; /* Identity */
3359 CFArrayRef certificates
= NULL
;
3360 /* Certificate array */
3363 if ((err
= SecKeychainOpen(ServerCertificate
, &keychain
)))
3365 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot open keychain \"%s\", %s",
3366 ServerCertificate
, cssmErrorString(err
));
3370 # if HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY
3372 * Use a policy to search for valid certificates who's common name matches the
3376 SecPolicySearchRef policy_search
; /* Policy search ref */
3377 SecPolicyRef policy
; /* Policy ref */
3378 CSSM_DATA options
; /* Policy options */
3379 CSSM_APPLE_TP_SSL_OPTIONS
3380 ssl_options
; /* SSL Option for hostname */
3383 if (SecPolicySearchCreate(CSSM_CERT_X_509v3
, &CSSMOID_APPLE_TP_SSL
,
3384 NULL
, &policy_search
))
3386 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot create a policy search reference");
3387 CFRelease(keychain
);
3391 if (SecPolicySearchCopyNext(policy_search
, &policy
))
3393 cupsdLogMessage(CUPSD_LOG_ERROR
,
3394 "Cannot find a policy to use for searching");
3395 CFRelease(keychain
);
3396 CFRelease(policy_search
);
3400 memset(&ssl_options
, 0, sizeof(ssl_options
));
3401 ssl_options
.Version
= CSSM_APPLE_TP_SSL_OPTS_VERSION
;
3402 ssl_options
.ServerName
= con
->servername
;
3403 ssl_options
.ServerNameLen
= strlen(con
->servername
);
3405 options
.Data
= (uint8
*)&ssl_options
;
3406 options
.Length
= sizeof(ssl_options
);
3408 if (SecPolicySetValue(policy
, &options
))
3410 cupsdLogMessage(CUPSD_LOG_ERROR
,
3411 "Cannot set policy value to use for searching");
3412 CFRelease(keychain
);
3413 CFRelease(policy_search
);
3417 err
= SecIdentitySearchCreateWithPolicy(policy
, NULL
, CSSM_KEYUSE_SIGN
,
3418 keychain
, FALSE
, &search
);
3421 * Assume there is exactly one SecIdentity in the keychain...
3424 err
= SecIdentitySearchCreate(keychain
, CSSM_KEYUSE_SIGN
, &search
);
3425 # endif /* HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY */
3428 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3429 "Cannot create keychain search reference: %s",
3430 cssmErrorString(err
));
3433 if ((err
= SecIdentitySearchCopyNext(search
, &identity
)))
3435 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3436 "Cannot find signing key in keychain \"%s\", error %d",
3437 ServerCertificate
, (int)err
);
3441 if (CFGetTypeID(identity
) != SecIdentityGetTypeID())
3442 cupsdLogMessage(CUPSD_LOG_ERROR
,
3443 "SecIdentitySearchCopyNext CFTypeID failure!");
3446 if ((certificates
= CFArrayCreate(NULL
, (const void **)&identity
,
3447 1, &kCFTypeArrayCallBacks
)) == NULL
)
3448 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot create certificate array");
3451 CFRelease(identity
);
3457 # if HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY
3459 CFRelease(policy_search
);
3460 # endif /* HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY */
3462 return (certificates
);
3464 #endif /* HAVE_CDSASSL */
3468 * 'get_file()' - Get a filename and state info.
3471 static char * /* O - Real filename */
3472 get_file(cupsd_client_t
*con
, /* I - Client connection */
3473 struct stat
*filestats
, /* O - File information */
3474 char *filename
, /* IO - Filename buffer */
3475 int len
) /* I - Buffer length */
3477 int status
; /* Status of filesystem calls */
3478 char *ptr
; /* Pointer info filename */
3479 int plen
; /* Remaining length after pointer */
3480 char language
[7]; /* Language subdirectory, if any */
3484 * Figure out the real filename...
3489 if (!strncmp(con
->uri
, "/ppd/", 5))
3490 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
);
3491 else if (!strncmp(con
->uri
, "/rss/", 5) && !strchr(con
->uri
+ 5, '/'))
3492 snprintf(filename
, len
, "%s/rss/%s", CacheDir
, con
->uri
+ 5);
3493 else if (!strncmp(con
->uri
, "/admin/conf/", 12))
3494 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
+ 11);
3495 else if (!strncmp(con
->uri
, "/admin/log/", 11))
3497 if (!strncmp(con
->uri
+ 11, "access_log", 10) && AccessLog
[0] == '/')
3498 strlcpy(filename
, AccessLog
, len
);
3499 else if (!strncmp(con
->uri
+ 11, "error_log", 9) && ErrorLog
[0] == '/')
3500 strlcpy(filename
, ErrorLog
, len
);
3501 else if (!strncmp(con
->uri
+ 11, "page_log", 8) && PageLog
[0] == '/')
3502 strlcpy(filename
, PageLog
, len
);
3506 else if (con
->language
)
3508 snprintf(language
, sizeof(language
), "/%s", con
->language
->language
);
3509 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3512 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3514 if ((ptr
= strchr(filename
, '?')) != NULL
)
3518 * Grab the status for this language; if there isn't a language-specific file
3519 * then fallback to the default one...
3522 if ((status
= stat(filename
, filestats
)) != 0 && language
[0] &&
3523 strncmp(con
->uri
, "/ppd/", 5) &&
3524 strncmp(con
->uri
, "/admin/conf/", 12) &&
3525 strncmp(con
->uri
, "/admin/log/", 11))
3528 * Drop the country code...
3532 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3534 if ((ptr
= strchr(filename
, '?')) != NULL
)
3537 if ((status
= stat(filename
, filestats
)) != 0)
3540 * Drop the language prefix and try the root directory...
3544 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3546 if ((ptr
= strchr(filename
, '?')) != NULL
)
3549 status
= stat(filename
, filestats
);
3554 * If we're found a directory, get the index.html file instead...
3557 if (!status
&& S_ISDIR(filestats
->st_mode
))
3560 * Make sure the URI ends with a slash...
3563 if (con
->uri
[strlen(con
->uri
) - 1] != '/')
3564 strlcat(con
->uri
, "/", sizeof(con
->uri
));
3567 * Find the directory index file, trying every language...
3572 if (status
&& language
[0])
3575 * Try a different language subset...
3579 language
[0] = '\0'; /* Strip country code */
3581 language
[0] = '\0'; /* Strip language */
3585 * Look for the index file...
3588 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3590 if ((ptr
= strchr(filename
, '?')) != NULL
)
3593 ptr
= filename
+ strlen(filename
);
3594 plen
= len
- (ptr
- filename
);
3596 strlcpy(ptr
, "index.html", plen
);
3597 status
= stat(filename
, filestats
);
3602 strlcpy(ptr
, "index.class", plen
);
3603 status
= stat(filename
, filestats
);
3605 #endif /* HAVE_JAVA */
3610 strlcpy(ptr
, "index.pl", plen
);
3611 status
= stat(filename
, filestats
);
3613 #endif /* HAVE_PERL */
3618 strlcpy(ptr
, "index.php", plen
);
3619 status
= stat(filename
, filestats
);
3621 #endif /* HAVE_PHP */
3626 strlcpy(ptr
, "index.pyc", plen
);
3627 status
= stat(filename
, filestats
);
3632 strlcpy(ptr
, "index.py", plen
);
3633 status
= stat(filename
, filestats
);
3635 #endif /* HAVE_PYTHON */
3638 while (status
&& language
[0]);
3641 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "get_file: %d filename=%s size=%d",
3642 con
->http
.fd
, filename
,
3643 status
? -1 : (int)filestats
->st_size
);
3646 con
->http
.data_remaining
= (int)filestats
->st_size
;
3656 * 'install_conf_file()' - Install a configuration file.
3659 static http_status_t
/* O - Status */
3660 install_conf_file(cupsd_client_t
*con
) /* I - Connection */
3662 cups_file_t
*in
, /* Input file */
3663 *out
; /* Output file */
3664 char buffer
[1024]; /* Copy buffer */
3665 int bytes
; /* Number of bytes */
3666 char conffile
[1024], /* Configuration filename */
3667 newfile
[1024], /* New config filename */
3668 oldfile
[1024]; /* Old config filename */
3669 struct stat confinfo
; /* Config file info */
3673 * First construct the filenames...
3676 snprintf(conffile
, sizeof(conffile
), "%s%s", ServerRoot
, con
->uri
+ 11);
3677 snprintf(newfile
, sizeof(newfile
), "%s%s.N", ServerRoot
, con
->uri
+ 11);
3678 snprintf(oldfile
, sizeof(oldfile
), "%s%s.O", ServerRoot
, con
->uri
+ 11);
3680 cupsdLogMessage(CUPSD_LOG_INFO
, "Installing config file \"%s\"...", conffile
);
3683 * Get the owner, group, and permissions of the configuration file.
3684 * If it doesn't exist, assign it to the User and Group in the
3685 * cupsd.conf file with mode 0640 permissions.
3688 if (stat(conffile
, &confinfo
))
3690 confinfo
.st_uid
= User
;
3691 confinfo
.st_gid
= Group
;
3692 confinfo
.st_mode
= ConfigFilePerm
;
3696 * Open the request file and new config file...
3699 if ((in
= cupsFileOpen(con
->filename
, "rb")) == NULL
)
3701 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open request file \"%s\" - %s",
3702 con
->filename
, strerror(errno
));
3703 return (HTTP_SERVER_ERROR
);
3706 if ((out
= cupsFileOpen(newfile
, "wb")) == NULL
)
3709 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open config file \"%s\" - %s",
3710 newfile
, strerror(errno
));
3711 return (HTTP_SERVER_ERROR
);
3714 fchmod(cupsFileNumber(out
), confinfo
.st_mode
);
3715 fchown(cupsFileNumber(out
), confinfo
.st_uid
, confinfo
.st_gid
);
3718 * Copy from the request to the new config file...
3721 while ((bytes
= cupsFileRead(in
, buffer
, sizeof(buffer
))) > 0)
3722 if (cupsFileWrite(out
, buffer
, bytes
) < bytes
)
3724 cupsdLogMessage(CUPSD_LOG_ERROR
,
3725 "Unable to copy to config file \"%s\" - %s",
3726 newfile
, strerror(errno
));
3732 return (HTTP_SERVER_ERROR
);
3736 * Close the files...
3740 if (cupsFileClose(out
))
3742 cupsdLogMessage(CUPSD_LOG_ERROR
,
3743 "Error file closing config file \"%s\" - %s",
3744 newfile
, strerror(errno
));
3748 return (HTTP_SERVER_ERROR
);
3752 * Remove the request file...
3755 unlink(con
->filename
);
3756 cupsdClearString(&con
->filename
);
3759 * Unlink the old backup, rename the current config file to the backup
3760 * filename, and rename the new config file to the config file name...
3763 if (unlink(oldfile
))
3764 if (errno
!= ENOENT
)
3766 cupsdLogMessage(CUPSD_LOG_ERROR
,
3767 "Unable to remove backup config file \"%s\" - %s",
3768 oldfile
, strerror(errno
));
3772 return (HTTP_SERVER_ERROR
);
3775 if (rename(conffile
, oldfile
))
3776 if (errno
!= ENOENT
)
3778 cupsdLogMessage(CUPSD_LOG_ERROR
,
3779 "Unable to rename old config file \"%s\" - %s",
3780 conffile
, strerror(errno
));
3784 return (HTTP_SERVER_ERROR
);
3787 if (rename(newfile
, conffile
))
3789 cupsdLogMessage(CUPSD_LOG_ERROR
,
3790 "Unable to rename new config file \"%s\" - %s",
3791 newfile
, strerror(errno
));
3793 rename(oldfile
, conffile
);
3796 return (HTTP_SERVER_ERROR
);
3800 * If the cupsd.conf file was updated, set the NeedReload flag...
3803 if (!strcmp(con
->uri
, "/admin/conf/cupsd.conf"))
3804 NeedReload
= RELOAD_CUPSD
;
3806 NeedReload
= RELOAD_ALL
;
3808 ReloadTime
= time(NULL
);
3811 * Return that the file was created successfully...
3814 return (HTTP_CREATED
);
3819 * 'is_cgi()' - Is the resource a CGI script/program?
3822 static int /* O - 1 = CGI, 0 = file */
3823 is_cgi(cupsd_client_t
*con
, /* I - Client connection */
3824 const char *filename
, /* I - Real filename */
3825 struct stat
*filestats
, /* I - File information */
3826 mime_type_t
*type
) /* I - MIME type */
3828 const char *options
; /* Options on URL */
3831 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3832 "is_cgi(con=%p, filename=\"%s\", filestats=%p, type=%s/%s)",
3833 con
, filename
, filestats
, type
? type
->super
: "unknown",
3834 type
? type
->type
: "unknown");
3837 * Get the options, if any...
3840 if ((options
= strchr(con
->uri
, '?')) != NULL
)
3843 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", options
);
3847 * Check for known types...
3850 if (!type
|| strcasecmp(type
->super
, "application"))
3852 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "is_cgi: Returning 0...");
3856 if (!strcasecmp(type
->type
, "x-httpd-cgi") &&
3857 (filestats
->st_mode
& 0111))
3860 * "application/x-httpd-cgi" is a CGI script.
3863 cupsdSetString(&con
->command
, filename
);
3866 cupsdSetStringf(&con
->options
, " %s", options
);
3868 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3869 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3870 con
->command
, con
->options
);
3875 else if (!strcasecmp(type
->type
, "x-httpd-java"))
3878 * "application/x-httpd-java" is a Java servlet.
3881 cupsdSetString(&con
->command
, CUPS_JAVA
);
3884 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3886 cupsdSetStringf(&con
->options
, " %s", filename
);
3888 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3889 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3890 con
->command
, con
->options
);
3894 #endif /* HAVE_JAVA */
3896 else if (!strcasecmp(type
->type
, "x-httpd-perl"))
3899 * "application/x-httpd-perl" is a Perl page.
3902 cupsdSetString(&con
->command
, CUPS_PERL
);
3905 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3907 cupsdSetStringf(&con
->options
, " %s", filename
);
3909 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3910 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3911 con
->command
, con
->options
);
3915 #endif /* HAVE_PERL */
3917 else if (!strcasecmp(type
->type
, "x-httpd-php"))
3920 * "application/x-httpd-php" is a PHP page.
3923 cupsdSetString(&con
->command
, CUPS_PHP
);
3926 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3928 cupsdSetStringf(&con
->options
, " %s", filename
);
3930 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3931 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3932 con
->command
, con
->options
);
3936 #endif /* HAVE_PHP */
3938 else if (!strcasecmp(type
->type
, "x-httpd-python"))
3941 * "application/x-httpd-python" is a Python page.
3944 cupsdSetString(&con
->command
, CUPS_PYTHON
);
3947 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3949 cupsdSetStringf(&con
->options
, " %s", filename
);
3951 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3952 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3953 con
->command
, con
->options
);
3957 #endif /* HAVE_PYTHON */
3959 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "is_cgi: Returning 0...");
3966 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
3969 static int /* O - 0 if relative, 1 if absolute */
3970 is_path_absolute(const char *path
) /* I - Input path */
3973 * Check for a leading slash...
3980 * Check for "/.." in the path...
3983 while ((path
= strstr(path
, "/..")) != NULL
)
3985 if (!path
[3] || path
[3] == '/')
3992 * If we haven't found any relative paths, return 1 indicating an
4002 * 'make_certificate()' - Make a self-signed SSL/TLS certificate.
4005 static int /* O - 1 on success, 0 on failure */
4006 make_certificate(cupsd_client_t
*con
) /* I - Client connection */
4008 #if defined(HAVE_LIBSSL) && defined(HAVE_WAITPID)
4009 int pid
, /* Process ID of command */
4010 status
; /* Status of command */
4011 char command
[1024], /* Command */
4012 *argv
[12], /* Command-line arguments */
4013 *envp
[MAX_ENV
+ 1], /* Environment variables */
4014 home
[1024], /* HOME environment variable */
4015 infofile
[1024], /* Type-in information for cert */
4016 seedfile
[1024]; /* Random number seed file */
4017 int envc
, /* Number of environment variables */
4018 bytes
; /* Bytes written */
4019 cups_file_t
*fp
; /* Seed/info file */
4020 int infofd
; /* Info file descriptor */
4024 * Run the "openssl" command to seed the random number generator and
4025 * generate a self-signed certificate that is good for 10 years:
4027 * openssl rand -rand seedfile 1
4029 * openssl req -new -x509 -keyout ServerKey \
4030 * -out ServerCertificate -days 3650 -nodes
4032 * The seeding step is crucial in ensuring that the openssl command
4033 * does not block on systems without sufficient entropy...
4036 if (!cupsFileFind("openssl", getenv("PATH"), 1, command
, sizeof(command
)))
4038 cupsdLogMessage(CUPSD_LOG_ERROR
,
4039 "No SSL certificate and openssl command not found!");
4043 if (access("/dev/urandom", 0))
4046 * If the system doesn't provide /dev/urandom, then any random source
4047 * will probably be blocking-style, so generate some random data to
4048 * use as a seed for the certificate. Note that we have already
4049 * seeded the random number generator in cupsdInitCerts()...
4052 cupsdLogMessage(CUPSD_LOG_INFO
,
4053 "Seeding the random number generator...");
4055 snprintf(home
, sizeof(home
), "HOME=%s", TempDir
);
4058 * Write the seed file...
4061 if ((fp
= cupsTempFile2(seedfile
, sizeof(seedfile
))) == NULL
)
4063 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to create seed file %s - %s",
4064 seedfile
, strerror(errno
));
4068 for (bytes
= 0; bytes
< 262144; bytes
++)
4069 cupsFilePutChar(fp
, random());
4074 * Run the openssl command to seed its random number generator...
4077 argv
[0] = "openssl";
4084 envc
= cupsdLoadEnv(envp
, MAX_ENV
);
4085 envp
[envc
++] = home
;
4088 if (!cupsdStartProcess(command
, argv
, envp
, -1, -1, -1, -1, -1, 1, NULL
,
4095 while (waitpid(pid
, &status
, 0) < 0)
4102 cupsdFinishProcess(pid
, command
, sizeof(command
));
4105 * Remove the seed file, as it is no longer needed...
4112 if (WIFEXITED(status
))
4113 cupsdLogMessage(CUPSD_LOG_ERROR
,
4114 "Unable to seed random number generator - "
4115 "the openssl command stopped with status %d!",
4116 WEXITSTATUS(status
));
4118 cupsdLogMessage(CUPSD_LOG_ERROR
,
4119 "Unable to seed random number generator - "
4120 "the openssl command crashed on signal %d!",
4128 * Create a file with the certificate information fields...
4130 * Note: This assumes that the default questions are asked by the openssl
4134 if ((fp
= cupsTempFile2(infofile
, sizeof(infofile
))) == NULL
)
4136 cupsdLogMessage(CUPSD_LOG_ERROR
,
4137 "Unable to create certificate information file %s - %s",
4138 infofile
, strerror(errno
));
4142 cupsFilePrintf(fp
, ".\n.\n.\n%s\n.\n%s\n%s\n",
4143 ServerName
, ServerName
, ServerAdmin
);
4146 cupsdLogMessage(CUPSD_LOG_INFO
,
4147 "Generating SSL server key and certificate...");
4149 argv
[0] = "openssl";
4153 argv
[4] = "-keyout";
4154 argv
[5] = ServerKey
;
4156 argv
[7] = ServerCertificate
;
4159 argv
[10] = "-nodes";
4162 cupsdLoadEnv(envp
, MAX_ENV
);
4164 infofd
= open(infofile
, O_RDONLY
);
4166 if (!cupsdStartProcess(command
, argv
, envp
, infofd
, -1, -1, -1, -1, 1, NULL
,
4177 while (waitpid(pid
, &status
, 0) < 0)
4184 cupsdFinishProcess(pid
, command
, sizeof(command
));
4188 if (WIFEXITED(status
))
4189 cupsdLogMessage(CUPSD_LOG_ERROR
,
4190 "Unable to create SSL server key and certificate - "
4191 "the openssl command stopped with status %d!",
4192 WEXITSTATUS(status
));
4194 cupsdLogMessage(CUPSD_LOG_ERROR
,
4195 "Unable to create SSL server key and certificate - "
4196 "the openssl command crashed on signal %d!",
4201 cupsdLogMessage(CUPSD_LOG_INFO
, "Created SSL server key file \"%s\"...",
4203 cupsdLogMessage(CUPSD_LOG_INFO
,
4204 "Created SSL server certificate file \"%s\"...",
4210 #elif defined(HAVE_GNUTLS)
4211 gnutls_x509_crt crt
; /* Self-signed certificate */
4212 gnutls_x509_privkey key
; /* Encryption key */
4213 cups_lang_t
*language
; /* Default language info */
4214 cups_file_t
*fp
; /* Key/cert file */
4215 unsigned char buffer
[8192]; /* Buffer for x509 data */
4216 size_t bytes
; /* Number of bytes of data */
4217 unsigned char serial
[4]; /* Serial number buffer */
4218 time_t curtime
; /* Current time */
4219 int result
; /* Result of GNU TLS calls */
4223 * Create the encryption key...
4226 cupsdLogMessage(CUPSD_LOG_INFO
, "Generating SSL server key...");
4228 gnutls_x509_privkey_init(&key
);
4229 gnutls_x509_privkey_generate(key
, GNUTLS_PK_RSA
, 2048, 0);
4235 bytes
= sizeof(buffer
);
4237 if ((result
= gnutls_x509_privkey_export(key
, GNUTLS_X509_FMT_PEM
,
4238 buffer
, &bytes
)) < 0)
4240 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to export SSL server key - %s",
4241 gnutls_strerror(result
));
4242 gnutls_x509_privkey_deinit(key
);
4245 else if ((fp
= cupsFileOpen(ServerKey
, "w")) != NULL
)
4247 cupsFileWrite(fp
, (char *)buffer
, bytes
);
4250 cupsdLogMessage(CUPSD_LOG_INFO
, "Created SSL server key file \"%s\"...",
4255 cupsdLogMessage(CUPSD_LOG_ERROR
,
4256 "Unable to create SSL server key file \"%s\" - %s",
4257 ServerKey
, strerror(errno
));
4258 gnutls_x509_privkey_deinit(key
);
4263 * Create the self-signed certificate...
4266 cupsdLogMessage(CUPSD_LOG_INFO
, "Generating self-signed SSL certificate...");
4268 language
= cupsLangDefault();
4269 curtime
= time(NULL
);
4270 serial
[0] = curtime
>> 24;
4271 serial
[1] = curtime
>> 16;
4272 serial
[2] = curtime
>> 8;
4273 serial
[3] = curtime
;
4275 gnutls_x509_crt_init(&crt
);
4276 if (strlen(language
->language
) == 5)
4277 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
4278 language
->language
+ 3, 2);
4280 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
4282 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COMMON_NAME
, 0,
4283 ServerName
, strlen(ServerName
));
4284 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATION_NAME
, 0,
4285 ServerName
, strlen(ServerName
));
4286 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATIONAL_UNIT_NAME
,
4288 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_STATE_OR_PROVINCE_NAME
, 0,
4290 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_LOCALITY_NAME
, 0,
4292 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_PKCS9_EMAIL
, 0,
4293 ServerAdmin
, strlen(ServerAdmin
));
4294 gnutls_x509_crt_set_key(crt
, key
);
4295 gnutls_x509_crt_set_serial(crt
, serial
, sizeof(serial
));
4296 gnutls_x509_crt_set_activation_time(crt
, curtime
);
4297 gnutls_x509_crt_set_expiration_time(crt
, curtime
+ 10 * 365 * 86400);
4298 gnutls_x509_crt_set_ca_status(crt
, 0);
4299 gnutls_x509_crt_set_subject_alternative_name(crt
, GNUTLS_SAN_DNSNAME
,
4301 gnutls_x509_crt_set_key_purpose_oid(crt
, GNUTLS_KP_TLS_WWW_SERVER
, 0);
4302 gnutls_x509_crt_set_key_usage(crt
, GNUTLS_KEY_KEY_ENCIPHERMENT
);
4303 gnutls_x509_crt_set_version(crt
, 3);
4305 bytes
= sizeof(buffer
);
4306 if (gnutls_x509_crt_get_key_id(crt
, 0, buffer
, &bytes
) >= 0)
4307 gnutls_x509_crt_set_subject_key_id(crt
, buffer
, bytes
);
4309 gnutls_x509_crt_sign(crt
, crt
, key
);
4315 bytes
= sizeof(buffer
);
4316 if ((result
= gnutls_x509_crt_export(crt
, GNUTLS_X509_FMT_PEM
,
4317 buffer
, &bytes
)) < 0)
4318 cupsdLogMessage(CUPSD_LOG_ERROR
,
4319 "Unable to export SSL server certificate - %s",
4320 gnutls_strerror(result
));
4321 else if ((fp
= cupsFileOpen(ServerCertificate
, "w")) != NULL
)
4323 cupsFileWrite(fp
, (char *)buffer
, bytes
);
4326 cupsdLogMessage(CUPSD_LOG_INFO
,
4327 "Created SSL server certificate file \"%s\"...",
4331 cupsdLogMessage(CUPSD_LOG_ERROR
,
4332 "Unable to create SSL server certificate file \"%s\" - %s",
4333 ServerCertificate
, strerror(errno
));
4339 gnutls_x509_crt_deinit(crt
);
4340 gnutls_x509_privkey_deinit(key
);
4344 #elif defined(HAVE_CDSASSL) && defined(HAVE_WAITPID)
4345 int pid
, /* Process ID of command */
4346 status
; /* Status of command */
4347 char command
[1024], /* Command */
4348 *argv
[4], /* Command-line arguments */
4349 *envp
[MAX_ENV
+ 1], /* Environment variables */
4350 keychain
[1024], /* Keychain argument */
4351 infofile
[1024]; /* Type-in information for cert */
4352 cups_file_t
*fp
; /* Seed/info file */
4353 int infofd
; /* Info file descriptor */
4357 * Run the "certtool" command to generate a self-signed certificate...
4360 if (!cupsFileFind("certtool", getenv("PATH"), 1, command
, sizeof(command
)))
4362 cupsdLogMessage(CUPSD_LOG_ERROR
,
4363 "No SSL certificate and certtool command not found!");
4368 * Create a file with the certificate information fields...
4370 * Note: This assumes that the default questions are asked by the certtool
4374 if ((fp
= cupsTempFile2(infofile
, sizeof(infofile
))) == NULL
)
4376 cupsdLogMessage(CUPSD_LOG_ERROR
,
4377 "Unable to create certificate information file %s - %s",
4378 infofile
, strerror(errno
));
4382 cupsFilePrintf(fp
, "%s\nr\n\ny\nb\ns\ny\n%s\n\n\n\n\n%s\ny\n",
4383 con
->servername
, con
->servername
, ServerAdmin
);
4386 cupsdLogMessage(CUPSD_LOG_INFO
,
4387 "Generating SSL server key and certificate...");
4389 snprintf(keychain
, sizeof(keychain
), "k=%s", ServerCertificate
);
4391 argv
[0] = "certtool";
4396 cupsdLoadEnv(envp
, MAX_ENV
);
4398 infofd
= open(infofile
, O_RDONLY
);
4400 if (!cupsdStartProcess(command
, argv
, envp
, infofd
, -1, -1, -1, -1, 1, NULL
,
4411 while (waitpid(pid
, &status
, 0) < 0)
4418 cupsdFinishProcess(pid
, command
, sizeof(command
));
4422 if (WIFEXITED(status
))
4423 cupsdLogMessage(CUPSD_LOG_ERROR
,
4424 "Unable to create SSL server key and certificate - "
4425 "the certtool command stopped with status %d!",
4426 WEXITSTATUS(status
));
4428 cupsdLogMessage(CUPSD_LOG_ERROR
,
4429 "Unable to create SSL server key and certificate - "
4430 "the certtool command crashed on signal %d!",
4435 cupsdLogMessage(CUPSD_LOG_INFO
,
4436 "Created SSL server certificate file \"%s\"...",
4444 #endif /* HAVE_LIBSSL && HAVE_WAITPID */
4446 #endif /* HAVE_SSL */
4450 * 'pipe_command()' - Pipe the output of a command to the remote client.
4453 static int /* O - Process ID */
4454 pipe_command(cupsd_client_t
*con
, /* I - Client connection */
4455 int infile
, /* I - Standard input for command */
4456 int *outfile
, /* O - Standard output for command */
4457 char *command
, /* I - Command to run */
4458 char *options
, /* I - Options for command */
4459 int root
) /* I - Run as root? */
4461 int i
; /* Looping var */
4462 int pid
; /* Process ID */
4463 char *commptr
, /* Command string pointer */
4464 commch
; /* Command string character */
4465 char *uriptr
; /* URI string pointer */
4466 int fds
[2]; /* Pipe FDs */
4467 int argc
; /* Number of arguments */
4468 int envc
; /* Number of environment variables */
4469 char argbuf
[10240], /* Argument buffer */
4470 *argv
[100], /* Argument strings */
4471 *envp
[MAX_ENV
+ 20]; /* Environment variables */
4472 char auth_type
[256], /* CUPSD_AUTH_TYPE environment variable */
4473 content_length
[1024], /* CONTENT_LENGTH environment variable */
4474 content_type
[1024], /* CONTENT_TYPE environment variable */
4475 http_cookie
[32768], /* HTTP_COOKIE environment variable */
4476 http_referer
[1024], /* HTTP_REFERER environment variable */
4477 http_user_agent
[1024], /* HTTP_USER_AGENT environment variable */
4478 lang
[1024], /* LANG environment variable */
4479 path_info
[1024], /* PATH_INFO environment variable */
4480 remote_addr
[1024], /* REMOTE_ADDR environment variable */
4481 remote_host
[1024], /* REMOTE_HOST environment variable */
4482 remote_user
[1024], /* REMOTE_USER environment variable */
4483 script_filename
[1024], /* SCRIPT_FILENAME environment variable */
4484 script_name
[1024], /* SCRIPT_NAME environment variable */
4485 server_name
[1024], /* SERVER_NAME environment variable */
4486 server_port
[1024]; /* SERVER_PORT environment variable */
4487 ipp_attribute_t
*attr
; /* attributes-natural-language attribute */
4489 krb5_ccache ccache
= NULL
; /* Kerberos credentials */
4490 # if defined(HAVE_KRB5_CC_NEW_UNIQUE) || defined(HAVE_HEIMDAL)
4491 char krb5ccname
[1024]; /* KRB5CCNAME environment variable */
4492 # endif /* HAVE_KRB5_CC_NEW_UNIQUE || HAVE_HEIMDAL */
4493 #endif /* HAVE_GSSAPI */
4497 * Parse a copy of the options string, which is of the form:
4499 * argument+argument+argument
4500 * ?argument+argument+argument
4501 * param=value¶m=value
4502 * ?param=value¶m=value
4503 * /name?argument+argument+argument
4504 * /name?param=value¶m=value
4506 * If the string contains an "=" character after the initial name,
4507 * then we treat it as a HTTP GET form request and make a copy of
4508 * the remaining string for the environment variable.
4510 * The string is always parsed out as command-line arguments, to
4511 * be consistent with Apache...
4514 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4515 "pipe_command: command=\"%s\", options=\"%s\"",
4516 command
, options
? options
: "(null)");
4521 strlcpy(argbuf
, options
, sizeof(argbuf
));
4525 if (argbuf
[0] == '/')
4528 * Found some trailing path information, set PATH_INFO...
4531 if ((commptr
= strchr(argbuf
, '?')) == NULL
)
4532 commptr
= argbuf
+ strlen(argbuf
);
4536 snprintf(path_info
, sizeof(path_info
), "PATH_INFO=%s", argbuf
);
4542 path_info
[0] = '\0';
4544 if (*commptr
== ' ')
4548 if (*commptr
== '?' && con
->operation
== HTTP_GET
&& !con
->query_string
)
4551 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", commptr
);
4558 argv
[argc
++] = commptr
;
4560 for (; *commptr
&& argc
< 99; commptr
++)
4563 * Break arguments whenever we see a + or space...
4566 if (*commptr
== ' ' || *commptr
== '+')
4568 while (*commptr
== ' ' || *commptr
== '+')
4572 * If we don't have a blank string, save it as another argument...
4577 argv
[argc
] = commptr
;
4583 else if (*commptr
== '%' && isxdigit(commptr
[1] & 255) &&
4584 isxdigit(commptr
[2] & 255))
4587 * Convert the %xx notation to the individual character.
4590 if (commptr
[1] >= '0' && commptr
[1] <= '9')
4591 *commptr
= (commptr
[1] - '0') << 4;
4593 *commptr
= (tolower(commptr
[1]) - 'a' + 10) << 4;
4595 if (commptr
[2] >= '0' && commptr
[2] <= '9')
4596 *commptr
|= commptr
[2] - '0';
4598 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
4600 _cups_strcpy(commptr
+ 1, commptr
+ 3);
4603 * Check for a %00 and break if that is the case...
4615 * Setup the environment variables as needed...
4618 if (con
->username
[0])
4620 snprintf(auth_type
, sizeof(auth_type
), "CUPSD_AUTH_TYPE=%s",
4621 httpGetField(HTTP(con
), HTTP_FIELD_AUTHORIZATION
));
4623 if ((uriptr
= strchr(auth_type
+ 10, ' ')) != NULL
)
4627 auth_type
[0] = '\0';
4630 (attr
= ippFindAttribute(con
->request
, "attributes-natural-language",
4631 IPP_TAG_LANGUAGE
)) != NULL
)
4633 switch (strlen(attr
->values
[0].string
.text
))
4637 * This is an unknown or badly formatted language code; use
4638 * the POSIX locale...
4641 strcpy(lang
, "LANG=C");
4646 * Just the language code (ll)...
4649 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8",
4650 attr
->values
[0].string
.text
);
4655 * Language and country code (ll-cc)...
4658 snprintf(lang
, sizeof(lang
), "LANG=%c%c_%c%c.UTF8",
4659 attr
->values
[0].string
.text
[0],
4660 attr
->values
[0].string
.text
[1],
4661 toupper(attr
->values
[0].string
.text
[3] & 255),
4662 toupper(attr
->values
[0].string
.text
[4] & 255));
4666 else if (con
->language
)
4667 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8", con
->language
->language
);
4669 strcpy(lang
, "LANG=C");
4671 strcpy(remote_addr
, "REMOTE_ADDR=");
4672 httpAddrString(con
->http
.hostaddr
, remote_addr
+ 12,
4673 sizeof(remote_addr
) - 12);
4675 snprintf(remote_host
, sizeof(remote_host
), "REMOTE_HOST=%s",
4676 con
->http
.hostname
);
4678 snprintf(script_name
, sizeof(script_name
), "SCRIPT_NAME=%s", con
->uri
);
4679 if ((uriptr
= strchr(script_name
, '?')) != NULL
)
4682 snprintf(script_filename
, sizeof(script_filename
), "SCRIPT_FILENAME=%s%s",
4683 DocumentRoot
, script_name
+ 12);
4685 sprintf(server_port
, "SERVER_PORT=%d", con
->serverport
);
4687 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
4690 envc
= cupsdLoadEnv(envp
, (int)(sizeof(envp
) / sizeof(envp
[0])));
4693 envp
[envc
++] = auth_type
;
4695 envp
[envc
++] = lang
;
4696 envp
[envc
++] = "REDIRECT_STATUS=1";
4697 envp
[envc
++] = "GATEWAY_INTERFACE=CGI/1.1";
4698 envp
[envc
++] = server_name
;
4699 envp
[envc
++] = server_port
;
4700 envp
[envc
++] = remote_addr
;
4701 envp
[envc
++] = remote_host
;
4702 envp
[envc
++] = script_name
;
4703 envp
[envc
++] = script_filename
;
4706 envp
[envc
++] = path_info
;
4708 if (con
->username
[0])
4710 snprintf(remote_user
, sizeof(remote_user
), "REMOTE_USER=%s", con
->username
);
4712 envp
[envc
++] = remote_user
;
4715 * Save Kerberos credentials, if any...
4719 if (con
->gss_have_creds
)
4721 # if !defined(HAVE_KRB5_CC_NEW_UNIQUE) && !defined(HAVE_HEIMDAL)
4722 cupsdLogMessage(CUPSD_LOG_INFO
,
4723 "Sorry, your version of Kerberos does not support "
4724 "delegated credentials!");
4727 krb5_error_code error
; /* Kerberos error code */
4728 OM_uint32 major_status
, /* Major status code */
4729 minor_status
; /* Minor status code */
4730 krb5_principal principal
; /* Kerberos principal */
4735 * If the weak-linked GSSAPI/Kerberos library is not present, don't try
4739 if (krb5_init_context
!= NULL
)
4741 # endif /* __APPLE__ */
4743 if (!KerberosInitialized
)
4746 * Setup a Kerberos context for the scheduler to use...
4749 KerberosInitialized
= 1;
4751 if (krb5_init_context(&KerberosContext
))
4753 KerberosContext
= NULL
;
4755 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to initialize Kerberos context");
4760 * We MUST create a file-based cache because memory-based caches are
4761 * only valid for the current process/address space.
4763 * Due to various bugs/features in different versions of Kerberos, we
4764 * need either the krb5_cc_new_unique() function or Heimdal's version
4765 * of krb5_cc_gen_new() to create a new FILE: credential cache that
4766 * can be passed to the backend. These functions create a temporary
4767 * file (typically in /tmp) containing the cached credentials, which
4768 * are removed when we have successfully printed a job.
4771 if (KerberosContext
)
4773 # ifdef HAVE_KRB5_CC_NEW_UNIQUE
4774 if ((error
= krb5_cc_new_unique(KerberosContext
, "FILE", NULL
,
4776 # else /* HAVE_HEIMDAL */
4777 if ((error
= krb5_cc_gen_new(KerberosContext
, &krb5_fcc_ops
,
4779 # endif /* HAVE_KRB5_CC_NEW_UNIQUE */
4781 cupsdLogMessage(CUPSD_LOG_ERROR
,
4782 "Unable to create new credentials cache (%d/%s)",
4783 error
, strerror(errno
));
4786 else if ((error
= krb5_parse_name(KerberosContext
, con
->username
,
4789 cupsdLogMessage(CUPSD_LOG_ERROR
,
4790 "Unable to parse kerberos username (%d/%s)", error
,
4792 krb5_cc_destroy(KerberosContext
, ccache
);
4795 else if ((error
= krb5_cc_initialize(KerberosContext
, ccache
,
4798 cupsdLogMessage(CUPSD_LOG_ERROR
,
4799 "Unable to initialize credentials cache (%d/%s)", error
,
4801 krb5_cc_destroy(KerberosContext
, ccache
);
4802 krb5_free_principal(KerberosContext
, principal
);
4807 krb5_free_principal(KerberosContext
, principal
);
4810 * Copy the user's credentials to the new cache file...
4813 major_status
= gss_krb5_copy_ccache(&minor_status
,
4814 con
->gss_delegated_cred
, ccache
);
4816 if (GSS_ERROR(major_status
))
4818 cupsdLogGSSMessage(CUPSD_LOG_ERROR
, major_status
, minor_status
,
4819 "Unable to import client credentials cache");
4820 krb5_cc_destroy(KerberosContext
, ccache
);
4826 * Add the KRB5CCNAME environment variable to the job so that the
4827 * backend can use the credentials when printing.
4830 snprintf(krb5ccname
, sizeof(krb5ccname
), "KRB5CCNAME=FILE:%s",
4831 krb5_cc_get_name(KerberosContext
, ccache
));
4832 envp
[envc
++] = krb5ccname
;
4835 chown(krb5_cc_get_name(KerberosContext
, ccache
), User
, Group
);
4841 # endif /* __APPLE__ */
4842 # endif /* HAVE_KRB5_CC_NEW_UNIQUE || HAVE_HEIMDAL */
4844 #endif /* HAVE_GSSAPI */
4847 if (con
->http
.version
== HTTP_1_1
)
4848 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.1";
4849 else if (con
->http
.version
== HTTP_1_0
)
4850 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.0";
4852 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/0.9";
4854 if (con
->http
.cookie
)
4856 snprintf(http_cookie
, sizeof(http_cookie
), "HTTP_COOKIE=%s",
4858 envp
[envc
++] = http_cookie
;
4861 if (con
->http
.fields
[HTTP_FIELD_USER_AGENT
][0])
4863 snprintf(http_user_agent
, sizeof(http_user_agent
), "HTTP_USER_AGENT=%s",
4864 con
->http
.fields
[HTTP_FIELD_USER_AGENT
]);
4865 envp
[envc
++] = http_user_agent
;
4868 if (con
->http
.fields
[HTTP_FIELD_REFERER
][0])
4870 snprintf(http_referer
, sizeof(http_referer
), "HTTP_REFERER=%s",
4871 con
->http
.fields
[HTTP_FIELD_REFERER
]);
4872 envp
[envc
++] = http_referer
;
4875 if (con
->operation
== HTTP_GET
)
4877 envp
[envc
++] = "REQUEST_METHOD=GET";
4879 if (con
->query_string
)
4882 * Add GET form variables after ?...
4885 envp
[envc
++] = con
->query_string
;
4888 envp
[envc
++] = "QUERY_STRING=";
4892 sprintf(content_length
, "CONTENT_LENGTH=" CUPS_LLFMT
,
4893 CUPS_LLCAST con
->bytes
);
4894 snprintf(content_type
, sizeof(content_type
), "CONTENT_TYPE=%s",
4895 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
4897 envp
[envc
++] = "REQUEST_METHOD=POST";
4898 envp
[envc
++] = content_length
;
4899 envp
[envc
++] = content_type
;
4903 * Tell the CGI if we are using encryption...
4907 envp
[envc
++] = "HTTPS=ON";
4910 * Terminate the environment array...
4915 if (LogLevel
== CUPSD_LOG_DEBUG2
)
4917 for (i
= 0; i
< argc
; i
++)
4918 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4919 "pipe_command: argv[%d] = \"%s\"", i
, argv
[i
]);
4920 for (i
= 0; i
< envc
; i
++)
4921 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4922 "pipe_command: envp[%d] = \"%s\"", i
, envp
[i
]);
4926 * Create a pipe for the output...
4929 if (cupsdOpenPipe(fds
))
4931 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to create pipes for CGI %s - %s",
4932 argv
[0], strerror(errno
));
4937 * Then execute the command...
4940 if (cupsdStartProcess(command
, argv
, envp
, infile
, fds
[1], CGIPipes
[1],
4941 -1, -1, root
, DefaultProfile
, &pid
) < 0)
4944 * Error - can't fork!
4947 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to fork for CGI %s - %s", argv
[0],
4950 cupsdClosePipe(fds
);
4956 * Fork successful - return the PID...
4959 if (con
->username
[0])
4961 cupsdAddCert(pid
, con
->username
, ccache
);
4963 cupsdAddCert(pid
, con
->username
, NULL
);
4964 #endif /* HAVE_GSSAPI */
4966 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[CGI] %s started - PID = %d",
4978 * 'write_file()' - Send a file via HTTP.
4981 static int /* O - 0 on failure, 1 on success */
4982 write_file(cupsd_client_t
*con
, /* I - Client connection */
4983 http_status_t code
, /* I - HTTP status */
4984 char *filename
, /* I - Filename */
4985 char *type
, /* I - File type */
4986 struct stat
*filestats
) /* O - File information */
4988 con
->file
= open(filename
, O_RDONLY
);
4990 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "write_file: %d file=%d", con
->http
.fd
,
4996 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
5000 if (!cupsdSendHeader(con
, code
, type
, CUPSD_AUTH_NONE
))
5003 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
5004 httpGetDateString(filestats
->st_mtime
)) < 0)
5006 if (httpPrintf(HTTP(con
), "Content-Length: " CUPS_LLFMT
"\r\n",
5007 CUPS_LLCAST filestats
->st_size
) < 0)
5009 if (httpPrintf(HTTP(con
), "\r\n") < 0)
5012 if (cupsdFlushHeader(con
) < 0)
5015 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
5016 con
->http
.data_remaining
= filestats
->st_size
;
5018 if (con
->http
.data_remaining
<= INT_MAX
)
5019 con
->http
._data_remaining
= con
->http
.data_remaining
;
5021 con
->http
._data_remaining
= INT_MAX
;
5023 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
,
5024 (cupsd_selfunc_t
)cupsdWriteClient
, con
);
5031 * 'write_pipe()' - Flag that data is available on the CGI pipe.
5035 write_pipe(cupsd_client_t
*con
) /* I - Client connection */
5037 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "write_pipe: CGI output on fd %d...",
5040 con
->file_ready
= 1;
5042 cupsdRemoveSelect(con
->file
);
5043 cupsdAddSelect(con
->http
.fd
, NULL
, (cupsd_selfunc_t
)cupsdWriteClient
, con
);
5048 * End of "$Id: client.c 7950 2008-09-17 00:21:59Z mike $".