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 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1250 cupsdCloseClient(con
);
1256 if (!strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") &&
1257 con
->http
.tls
== NULL
)
1261 * Do encryption stuff...
1264 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
, CUPSD_AUTH_NONE
))
1266 cupsdCloseClient(con
);
1270 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1271 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1272 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1273 httpPrintf(HTTP(con
), "\r\n");
1275 if (cupsdFlushHeader(con
) < 0)
1277 cupsdCloseClient(con
);
1281 if (!encrypt_client(con
))
1283 cupsdCloseClient(con
);
1287 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
1289 cupsdCloseClient(con
);
1292 #endif /* HAVE_SSL */
1295 if ((status
= cupsdIsAuthorized(con
, NULL
)) != HTTP_OK
)
1297 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1298 "cupsdReadClient: Unauthorized request for %s...",
1300 cupsdSendError(con
, status
, CUPSD_AUTH_NONE
);
1301 cupsdCloseClient(con
);
1305 if (con
->http
.expect
&&
1306 (con
->operation
== HTTP_POST
|| con
->operation
== HTTP_PUT
))
1308 if (con
->http
.expect
== HTTP_CONTINUE
)
1311 * Send 100-continue header...
1314 if (!cupsdSendHeader(con
, HTTP_CONTINUE
, NULL
, CUPSD_AUTH_NONE
))
1316 cupsdCloseClient(con
);
1323 * Send 417-expectation-failed header...
1326 if (!cupsdSendHeader(con
, HTTP_EXPECTATION_FAILED
, NULL
, CUPSD_AUTH_NONE
))
1328 cupsdCloseClient(con
);
1332 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1333 httpPrintf(HTTP(con
), "\r\n");
1335 if (cupsdFlushHeader(con
) < 0)
1337 cupsdCloseClient(con
);
1343 switch (con
->http
.state
)
1345 case HTTP_GET_SEND
:
1346 if (!strncmp(con
->uri
, "/printers/", 10) &&
1347 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1350 * Send PPD file - get the real printer name since printer
1351 * names are not case sensitive but filenames can be...
1354 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1356 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1357 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1360 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1362 cupsdCloseClient(con
);
1370 if ((!strncmp(con
->uri
, "/admin", 6) &&
1371 strncmp(con
->uri
, "/admin/conf/", 12) &&
1372 strncmp(con
->uri
, "/admin/log/", 11)) ||
1373 !strncmp(con
->uri
, "/printers", 9) ||
1374 !strncmp(con
->uri
, "/classes", 8) ||
1375 !strncmp(con
->uri
, "/help", 5) ||
1376 !strncmp(con
->uri
, "/jobs", 5))
1379 * Send CGI output...
1382 if (!strncmp(con
->uri
, "/admin", 6))
1384 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1387 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1389 else if (!strncmp(con
->uri
, "/printers", 9))
1391 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1394 if (con
->uri
[9] && con
->uri
[10])
1395 cupsdSetString(&con
->options
, con
->uri
+ 9);
1397 cupsdSetString(&con
->options
, NULL
);
1399 else if (!strncmp(con
->uri
, "/classes", 8))
1401 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1404 if (con
->uri
[8] && con
->uri
[9])
1405 cupsdSetString(&con
->options
, con
->uri
+ 8);
1407 cupsdSetString(&con
->options
, NULL
);
1409 else if (!strncmp(con
->uri
, "/jobs", 5))
1411 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1414 if (con
->uri
[5] && con
->uri
[6])
1415 cupsdSetString(&con
->options
, con
->uri
+ 5);
1417 cupsdSetString(&con
->options
, NULL
);
1421 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1424 if (con
->uri
[5] && con
->uri
[6])
1425 cupsdSetString(&con
->options
, con
->uri
+ 5);
1427 cupsdSetString(&con
->options
, NULL
);
1430 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1432 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1434 cupsdCloseClient(con
);
1439 cupsdLogRequest(con
, HTTP_OK
);
1441 if (con
->http
.version
<= HTTP_1_0
)
1442 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1444 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1445 (strchr(con
->uri
+ 12, '/') ||
1446 strlen(con
->uri
) == 12)) ||
1447 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1448 (strchr(con
->uri
+ 11, '/') ||
1449 strlen(con
->uri
) == 11)))
1452 * GET can only be done to configuration files under
1456 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1458 cupsdCloseClient(con
);
1470 if ((filename
= get_file(con
, &filestats
, buf
,
1471 sizeof(buf
))) == NULL
)
1473 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1475 cupsdCloseClient(con
);
1482 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1484 if (is_cgi(con
, filename
, &filestats
, type
))
1487 * Note: con->command and con->options were set by
1491 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1493 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1495 cupsdCloseClient(con
);
1500 cupsdLogRequest(con
, HTTP_OK
);
1502 if (con
->http
.version
<= HTTP_1_0
)
1503 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1507 if (!check_if_modified(con
, &filestats
))
1509 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1511 cupsdCloseClient(con
);
1518 strcpy(line
, "text/plain");
1520 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1522 if (!write_file(con
, HTTP_OK
, filename
, line
, &filestats
))
1524 cupsdCloseClient(con
);
1531 case HTTP_POST_RECV
:
1533 * See if the POST request includes a Content-Length field, and if
1534 * so check the length against any limits that are set...
1537 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "POST %s", con
->uri
);
1538 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "CONTENT_TYPE = %s",
1539 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
1541 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1542 MaxRequestSize
> 0 &&
1543 con
->http
.data_remaining
> MaxRequestSize
)
1546 * Request too large...
1549 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1551 cupsdCloseClient(con
);
1557 else if (con
->http
.data_remaining
< 0 ||
1558 (!con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1559 con
->http
.data_encoding
== HTTP_ENCODE_LENGTH
))
1562 * Negative content lengths are invalid!
1565 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1567 cupsdCloseClient(con
);
1575 * See what kind of POST request this is; for IPP requests the
1576 * content-type field will be "application/ipp"...
1579 if (!strcmp(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
],
1581 con
->request
= ippNew();
1582 else if ((!strncmp(con
->uri
, "/admin", 6) &&
1583 strncmp(con
->uri
, "/admin/conf/", 12) &&
1584 strncmp(con
->uri
, "/admin/log/", 11)) ||
1585 !strncmp(con
->uri
, "/printers", 9) ||
1586 !strncmp(con
->uri
, "/classes", 8) ||
1587 !strncmp(con
->uri
, "/help", 5) ||
1588 !strncmp(con
->uri
, "/jobs", 5))
1594 if (!strncmp(con
->uri
, "/admin", 6))
1596 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1599 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1601 else if (!strncmp(con
->uri
, "/printers", 9))
1603 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1606 if (con
->uri
[9] && con
->uri
[10])
1607 cupsdSetString(&con
->options
, con
->uri
+ 9);
1609 cupsdSetString(&con
->options
, NULL
);
1611 else if (!strncmp(con
->uri
, "/classes", 8))
1613 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1616 if (con
->uri
[8] && con
->uri
[9])
1617 cupsdSetString(&con
->options
, con
->uri
+ 8);
1619 cupsdSetString(&con
->options
, NULL
);
1621 else if (!strncmp(con
->uri
, "/jobs", 5))
1623 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1626 if (con
->uri
[5] && con
->uri
[6])
1627 cupsdSetString(&con
->options
, con
->uri
+ 5);
1629 cupsdSetString(&con
->options
, NULL
);
1633 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1636 if (con
->uri
[5] && con
->uri
[6])
1637 cupsdSetString(&con
->options
, con
->uri
+ 5);
1639 cupsdSetString(&con
->options
, NULL
);
1642 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1643 "cupsdReadClient: %d command=\"%s\", "
1645 con
->http
.fd
, con
->command
,
1646 con
->options
? con
->options
: "(null)");
1648 if (con
->http
.version
<= HTTP_1_0
)
1649 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1657 if ((filename
= get_file(con
, &filestats
, buf
,
1658 sizeof(buf
))) == NULL
)
1660 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1662 cupsdCloseClient(con
);
1669 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1671 if (!is_cgi(con
, filename
, &filestats
, type
))
1674 * Only POST to CGI's...
1677 if (!cupsdSendError(con
, HTTP_UNAUTHORIZED
, CUPSD_AUTH_NONE
))
1679 cupsdCloseClient(con
);
1686 case HTTP_PUT_RECV
:
1688 * Validate the resource name...
1691 if (strncmp(con
->uri
, "/admin/conf/", 12) ||
1692 strchr(con
->uri
+ 12, '/') ||
1693 strlen(con
->uri
) == 12)
1696 * PUT can only be done to configuration files under
1700 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1702 cupsdCloseClient(con
);
1710 * See if the PUT request includes a Content-Length field, and if
1711 * so check the length against any limits that are set...
1714 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "PUT %s", con
->uri
);
1715 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "CONTENT_TYPE = %s",
1716 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
1718 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1719 MaxRequestSize
> 0 &&
1720 con
->http
.data_remaining
> MaxRequestSize
)
1723 * Request too large...
1726 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1728 cupsdCloseClient(con
);
1734 else if (con
->http
.data_remaining
< 0)
1737 * Negative content lengths are invalid!
1740 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1742 cupsdCloseClient(con
);
1750 * Open a temporary file to hold the request...
1753 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
1755 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1759 cupsdLogMessage(CUPSD_LOG_ERROR
,
1760 "Unable to create request file %s: %s",
1761 con
->filename
, strerror(errno
));
1763 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1765 cupsdCloseClient(con
);
1770 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1771 "cupsdReadClient: %d REQUEST %s=%d", con
->http
.fd
,
1772 con
->filename
, con
->file
);
1774 fchmod(con
->file
, 0640);
1775 fchown(con
->file
, RunUser
, Group
);
1776 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1781 cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
);
1782 cupsdCloseClient(con
);
1786 if (!strncmp(con
->uri
, "/printers/", 10) &&
1787 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1790 * Send PPD file - get the real printer name since printer
1791 * names are not case sensitive but filenames can be...
1794 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1796 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1797 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1800 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1802 cupsdCloseClient(con
);
1810 if ((!strncmp(con
->uri
, "/admin", 6) &&
1811 strncmp(con
->uri
, "/admin/conf/", 12) &&
1812 strncmp(con
->uri
, "/admin/log/", 11)) ||
1813 !strncmp(con
->uri
, "/printers", 9) ||
1814 !strncmp(con
->uri
, "/classes", 8) ||
1815 !strncmp(con
->uri
, "/help", 5) ||
1816 !strncmp(con
->uri
, "/jobs", 5))
1822 if (!cupsdSendHeader(con
, HTTP_OK
, "text/html", CUPSD_AUTH_NONE
))
1824 cupsdCloseClient(con
);
1828 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1830 cupsdCloseClient(con
);
1834 if (cupsdFlushHeader(con
) < 0)
1836 cupsdCloseClient(con
);
1840 cupsdLogRequest(con
, HTTP_OK
);
1842 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1843 (strchr(con
->uri
+ 12, '/') ||
1844 strlen(con
->uri
) == 12)) ||
1845 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1846 (strchr(con
->uri
+ 11, '/') ||
1847 strlen(con
->uri
) == 11)))
1850 * HEAD can only be done to configuration files under
1854 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1856 cupsdCloseClient(con
);
1862 else if ((filename
= get_file(con
, &filestats
, buf
,
1863 sizeof(buf
))) == NULL
)
1865 if (!cupsdSendHeader(con
, HTTP_NOT_FOUND
, "text/html", CUPSD_AUTH_NONE
))
1867 cupsdCloseClient(con
);
1871 cupsdLogRequest(con
, HTTP_NOT_FOUND
);
1873 else if (!check_if_modified(con
, &filestats
))
1875 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1877 cupsdCloseClient(con
);
1881 cupsdLogRequest(con
, HTTP_NOT_MODIFIED
);
1889 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1891 strcpy(line
, "text/plain");
1893 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1895 if (!cupsdSendHeader(con
, HTTP_OK
, line
, CUPSD_AUTH_NONE
))
1897 cupsdCloseClient(con
);
1901 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
1902 httpGetDateString(filestats
.st_mtime
)) < 0)
1904 cupsdCloseClient(con
);
1908 if (httpPrintf(HTTP(con
), "Content-Length: %lu\r\n",
1909 (unsigned long)filestats
.st_size
) < 0)
1911 cupsdCloseClient(con
);
1915 cupsdLogRequest(con
, HTTP_OK
);
1918 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1920 cupsdCloseClient(con
);
1924 if (cupsdFlushHeader(con
) < 0)
1926 cupsdCloseClient(con
);
1930 con
->http
.state
= HTTP_WAITING
;
1934 break; /* Anti-compiler-warning-code */
1940 * Handle any incoming data...
1943 switch (con
->http
.state
)
1945 case HTTP_PUT_RECV
:
1946 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1947 "cupsdReadClient: %d con->data_encoding=HTTP_ENCODE_%s, "
1948 "con->data_remaining=" CUPS_LLFMT
", con->file=%d",
1950 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
?
1951 "CHUNKED" : "LENGTH",
1952 CUPS_LLCAST con
->http
.data_remaining
, con
->file
);
1956 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
1958 cupsdCloseClient(con
);
1963 con
->bytes
+= bytes
;
1965 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1966 "cupsdReadClient: %d writing %d bytes to %d",
1967 con
->http
.fd
, bytes
, con
->file
);
1969 if (write(con
->file
, line
, bytes
) < bytes
)
1971 cupsdLogMessage(CUPSD_LOG_ERROR
,
1972 "cupsdReadClient: Unable to write %d bytes to %s: %s",
1973 bytes
, con
->filename
, strerror(errno
));
1975 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1976 "cupsdReadClient: Closing data file %d...",
1981 unlink(con
->filename
);
1982 cupsdClearString(&con
->filename
);
1984 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1986 cupsdCloseClient(con
);
1992 while (con
->http
.state
== HTTP_PUT_RECV
&& data_ready(con
));
1994 if (con
->http
.state
== HTTP_WAITING
)
1997 * End of file, see how big it is...
2000 fstat(con
->file
, &filestats
);
2002 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2003 "cupsdReadClient: %d Closing data file %d, size="
2005 con
->http
.fd
, con
->file
,
2006 CUPS_LLCAST filestats
.st_size
);
2011 if (filestats
.st_size
> MaxRequestSize
&&
2015 * Request is too big; remove it and send an error...
2018 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2019 "cupsdReadClient: %d Removing temp file %s",
2020 con
->http
.fd
, con
->filename
);
2021 unlink(con
->filename
);
2022 cupsdClearString(&con
->filename
);
2024 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2026 cupsdCloseClient(con
);
2032 * Install the configuration file...
2035 status
= install_conf_file(con
);
2038 * Return the status to the client...
2041 if (!cupsdSendError(con
, status
, CUPSD_AUTH_NONE
))
2043 cupsdCloseClient(con
);
2049 case HTTP_POST_RECV
:
2050 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2051 "cupsdReadClient: %d con->data_encoding=HTTP_ENCODE_"
2052 "%s, con->data_remaining=" CUPS_LLFMT
", con->file=%d",
2054 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
?
2055 "CHUNKED" : "LENGTH",
2056 CUPS_LLCAST con
->http
.data_remaining
, con
->file
);
2063 * Grab any request data from the connection...
2066 if ((ipp_state
= ippRead(&(con
->http
), con
->request
)) == IPP_ERROR
)
2068 cupsdLogMessage(CUPSD_LOG_ERROR
,
2069 "cupsdReadClient: %d IPP Read Error!",
2072 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
2073 cupsdCloseClient(con
);
2076 else if (ipp_state
!= IPP_DATA
)
2078 if (con
->http
.state
== HTTP_POST_SEND
)
2080 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
2081 cupsdCloseClient(con
);
2088 con
->bytes
+= ippLength(con
->request
);
2091 if (con
->file
< 0 && con
->http
.state
!= HTTP_POST_SEND
)
2094 * Create a file as needed for the request data...
2097 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
, request_id
++);
2098 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
2102 cupsdLogMessage(CUPSD_LOG_ERROR
,
2103 "Unable to create request file %s: %s",
2104 con
->filename
, strerror(errno
));
2106 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2108 cupsdCloseClient(con
);
2113 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdReadClient: %d REQUEST %s=%d", con
->http
.fd
,
2114 con
->filename
, con
->file
);
2116 fchmod(con
->file
, 0640);
2117 fchown(con
->file
, RunUser
, Group
);
2118 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2121 if (con
->http
.state
!= HTTP_POST_SEND
)
2123 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
2125 cupsdCloseClient(con
);
2130 con
->bytes
+= bytes
;
2132 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2133 "cupsdReadClient: %d writing %d bytes to %d",
2134 con
->http
.fd
, bytes
, con
->file
);
2136 if (write(con
->file
, line
, bytes
) < bytes
)
2138 cupsdLogMessage(CUPSD_LOG_ERROR
,
2139 "cupsdReadClient: Unable to write %d bytes to %s: %s",
2140 bytes
, con
->filename
, strerror(errno
));
2142 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2143 "cupsdReadClient: Closing file %d...",
2148 unlink(con
->filename
);
2149 cupsdClearString(&con
->filename
);
2151 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2153 cupsdCloseClient(con
);
2158 else if (con
->http
.state
== HTTP_POST_RECV
)
2160 else if (con
->http
.state
!= HTTP_POST_SEND
)
2162 cupsdCloseClient(con
);
2167 while (con
->http
.state
== HTTP_POST_RECV
&& data_ready(con
));
2169 if (con
->http
.state
== HTTP_POST_SEND
)
2173 fstat(con
->file
, &filestats
);
2175 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2176 "cupsdReadClient: %d Closing data file %d, "
2177 "size=" CUPS_LLFMT
".",
2178 con
->http
.fd
, con
->file
,
2179 CUPS_LLCAST filestats
.st_size
);
2184 if (filestats
.st_size
> MaxRequestSize
&&
2188 * Request is too big; remove it and send an error...
2191 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2192 "cupsdReadClient: %d Removing temp file %s",
2193 con
->http
.fd
, con
->filename
);
2194 unlink(con
->filename
);
2195 cupsdClearString(&con
->filename
);
2200 * Delete any IPP request data...
2203 ippDelete(con
->request
);
2204 con
->request
= NULL
;
2207 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2209 cupsdCloseClient(con
);
2216 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
2218 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
2220 cupsdCloseClient(con
);
2225 cupsdLogRequest(con
, HTTP_OK
);
2231 cupsdProcessIPPRequest(con
);
2235 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2236 "cupsdReadClient: %d Removing temp file %s",
2237 con
->http
.fd
, con
->filename
);
2238 unlink(con
->filename
);
2239 cupsdClearString(&con
->filename
);
2248 break; /* Anti-compiler-warning-code */
2251 if (con
->http
.state
== HTTP_WAITING
)
2253 if (!con
->http
.keep_alive
)
2254 cupsdCloseClient(con
);
2257 cupsArrayRemove(ActiveClients
, con
);
2258 cupsdSetBusyState();
2265 * 'cupsdSendCommand()' - Send output from a command via HTTP.
2268 int /* O - 1 on success, 0 on failure */
2270 cupsd_client_t
*con
, /* I - Client connection */
2271 char *command
, /* I - Command to run */
2272 char *options
, /* I - Command-line options */
2273 int root
) /* I - Run as root? */
2275 int fd
; /* Standard input file descriptor */
2280 fd
= open(con
->filename
, O_RDONLY
);
2284 cupsdLogMessage(CUPSD_LOG_ERROR
,
2285 "cupsdSendCommand: %d Unable to open \"%s\" for reading: %s",
2286 con
->http
.fd
, con
->filename
? con
->filename
: "/dev/null",
2291 fcntl(fd
, F_SETFD
, fcntl(fd
, F_GETFD
) | FD_CLOEXEC
);
2296 con
->pipe_pid
= pipe_command(con
, fd
, &(con
->file
), command
, options
, root
);
2301 cupsdLogMessage(CUPSD_LOG_INFO
, "Started \"%s\" (pid=%d)", command
,
2304 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendCommand: %d file=%d",
2305 con
->http
.fd
, con
->file
);
2307 if (con
->pipe_pid
== 0)
2310 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2312 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2314 con
->sent_header
= 0;
2315 con
->file_ready
= 0;
2316 con
->got_fields
= 0;
2324 * 'cupsdSendError()' - Send an error message via HTTP.
2327 int /* O - 1 if successful, 0 otherwise */
2328 cupsdSendError(cupsd_client_t
*con
, /* I - Connection */
2329 http_status_t code
, /* I - Error code */
2330 int auth_type
)/* I - Authentication type */
2334 * Force client to upgrade for authentication if that is how the
2335 * server is configured...
2338 if (code
== HTTP_UNAUTHORIZED
&&
2339 DefaultEncryption
== HTTP_ENCRYPT_REQUIRED
&&
2340 strcasecmp(con
->http
.hostname
, "localhost") &&
2343 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2344 "cupsdSendError: Encryption before authentication!");
2345 code
= HTTP_UPGRADE_REQUIRED
;
2347 #endif /* HAVE_SSL */
2350 * Put the request in the access_log file...
2353 cupsdLogRequest(con
, code
);
2355 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendError: %d code=%d (%s)",
2356 con
->http
.fd
, code
, httpStatus(code
));
2359 * To work around bugs in some proxies, don't use Keep-Alive for some
2362 * Kerberos authentication doesn't work without Keep-Alive, so
2363 * never disable it in that case.
2366 if (code
>= HTTP_BAD_REQUEST
&& con
->http
.auth_type
!= CUPSD_AUTH_NEGOTIATE
)
2367 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
2370 * Send an error message back to the client. If the error code is a
2371 * 400 or 500 series, make sure the message contains some text, too!
2374 if (!cupsdSendHeader(con
, code
, NULL
, auth_type
))
2378 if (code
== HTTP_UPGRADE_REQUIRED
)
2379 if (httpPrintf(HTTP(con
), "Connection: Upgrade\r\n") < 0)
2382 if (httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n") < 0)
2384 #endif /* HAVE_SSL */
2386 if (con
->http
.version
>= HTTP_1_1
&&
2387 con
->http
.keep_alive
== HTTP_KEEPALIVE_OFF
)
2389 if (httpPrintf(HTTP(con
), "Connection: close\r\n") < 0)
2393 if (code
>= HTTP_BAD_REQUEST
)
2396 * Send a human-readable error message.
2399 char message
[4096], /* Message for user */
2400 urltext
[1024], /* URL redirection text */
2401 redirect
[1024]; /* Redirection link */
2402 const char *text
; /* Status-specific text */
2407 if (code
== HTTP_UNAUTHORIZED
)
2408 text
= _cupsLangString(con
->language
,
2409 _("Enter your username and password or the "
2410 "root username and password to access this "
2411 "page. If you are using Kerberos authentication, "
2412 "make sure you have a valid Kerberos ticket."));
2413 else if (code
== HTTP_UPGRADE_REQUIRED
)
2417 snprintf(urltext
, sizeof(urltext
),
2418 _cupsLangString(con
->language
,
2419 _("You must access this page using the URL "
2420 "<A HREF=\"https://%s:%d%s\">"
2421 "https://%s:%d%s</A>.")),
2422 con
->servername
, con
->serverport
, con
->uri
,
2423 con
->servername
, con
->serverport
, con
->uri
);
2425 snprintf(redirect
, sizeof(redirect
),
2426 "<META HTTP-EQUIV=\"Refresh\" "
2427 "CONTENT=\"3;URL=https://%s:%d%s\">\n",
2428 con
->servername
, con
->serverport
, con
->uri
);
2433 snprintf(message
, sizeof(message
),
2434 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" "
2435 "\"http://www.w3.org/TR/REC-html40/loose.dtd\">\n"
2438 "\t<META HTTP-EQUIV=\"Content-Type\" "
2439 "CONTENT=\"text/html; charset=utf-8\">\n"
2440 "\t<TITLE>%d %s</TITLE>\n"
2441 "\t<LINK REL=\"STYLESHEET\" TYPE=\"text/css\" "
2442 "HREF=\"/cups.css\">\n"
2450 code
, httpStatus(code
), redirect
, code
, httpStatus(code
), text
);
2452 if (httpPrintf(HTTP(con
), "Content-Type: text/html; charset=utf-8\r\n") < 0)
2454 if (httpPrintf(HTTP(con
), "Content-Length: %d\r\n",
2455 (int)strlen(message
)) < 0)
2457 if (httpPrintf(HTTP(con
), "\r\n") < 0)
2459 if (httpPrintf(HTTP(con
), "%s", message
) < 0)
2462 else if (httpPrintf(HTTP(con
), "\r\n") < 0)
2465 if (cupsdFlushHeader(con
) < 0)
2468 con
->http
.state
= HTTP_WAITING
;
2475 * 'cupsdSendHeader()' - Send an HTTP request.
2478 int /* O - 1 on success, 0 on failure */
2480 cupsd_client_t
*con
, /* I - Client to send to */
2481 http_status_t code
, /* I - HTTP status code */
2482 char *type
, /* I - MIME type of document */
2483 int auth_type
) /* I - Type of authentication */
2485 char auth_str
[1024]; /* Authorization string */
2487 static char *gss_buf
= NULL
; /* Kerberos auth data buffer */
2488 static int gss_bufsize
= 0; /* Size of Kerberos auth data buffer */
2489 #endif /* HAVE_GSSAPI */
2493 * Send the HTTP status header...
2496 if (code
== HTTP_CONTINUE
)
2499 * 100-continue doesn't send any headers...
2502 return (httpPrintf(HTTP(con
), "HTTP/%d.%d 100 Continue\r\n\r\n",
2503 con
->http
.version
/ 100, con
->http
.version
% 100) > 0);
2506 httpFlushWrite(HTTP(con
));
2508 con
->http
.data_encoding
= HTTP_ENCODE_FIELDS
;
2510 if (httpPrintf(HTTP(con
), "HTTP/%d.%d %d %s\r\n", con
->http
.version
/ 100,
2511 con
->http
.version
% 100, code
, httpStatus(code
)) < 0)
2513 if (httpPrintf(HTTP(con
), "Date: %s\r\n", httpGetDateString(time(NULL
))) < 0)
2516 if (httpPrintf(HTTP(con
), "Server: %s\r\n", ServerHeader
) < 0)
2518 if (con
->http
.keep_alive
&& con
->http
.version
>= HTTP_1_0
)
2520 if (httpPrintf(HTTP(con
), "Connection: Keep-Alive\r\n") < 0)
2522 if (httpPrintf(HTTP(con
), "Keep-Alive: timeout=%d\r\n",
2523 KeepAliveTimeout
) < 0)
2526 if (code
== HTTP_METHOD_NOT_ALLOWED
)
2527 if (httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n") < 0)
2530 if (code
== HTTP_UNAUTHORIZED
)
2532 if (auth_type
== CUPSD_AUTH_NONE
)
2534 if (!con
->best
|| con
->best
->type
<= CUPSD_AUTH_NONE
)
2535 auth_type
= DefaultAuthType
;
2537 auth_type
= con
->best
->type
;
2542 if (auth_type
== CUPSD_AUTH_BASIC
|| auth_type
== CUPSD_AUTH_BASICDIGEST
)
2543 strlcpy(auth_str
, "Basic realm=\"CUPS\"", sizeof(auth_str
));
2544 else if (auth_type
== CUPSD_AUTH_DIGEST
)
2545 snprintf(auth_str
, sizeof(auth_str
), "Digest realm=\"CUPS\", nonce=\"%s\"",
2546 con
->http
.hostname
);
2548 else if (auth_type
== CUPSD_AUTH_NEGOTIATE
&& con
->gss_output_token
.length
== 0)
2549 strlcpy(auth_str
, "Negotiate", sizeof(auth_str
));
2550 #endif /* HAVE_GSSAPI */
2552 #ifdef HAVE_AUTHORIZATION_H
2553 if (con
->best
&& auth_type
!= CUPSD_AUTH_NEGOTIATE
)
2555 int i
; /* Looping var */
2556 char *auth_key
; /* Auth key buffer */
2557 size_t auth_size
; /* Size of remaining buffer */
2560 auth_key
= auth_str
+ strlen(auth_str
);
2561 auth_size
= sizeof(auth_str
) - (auth_key
- auth_str
);
2563 for (i
= 0; i
< con
->best
->num_names
; i
++)
2565 if (!strncasecmp(con
->best
->names
[i
], "@AUTHKEY(", 9))
2567 snprintf(auth_key
, auth_size
, ", authkey=\"%s\"",
2568 con
->best
->names
[i
] + 9);
2569 /* end parenthesis is stripped in conf.c */
2572 else if (!strcasecmp(con
->best
->names
[i
], "@SYSTEM") &&
2575 snprintf(auth_key
, auth_size
, ", authkey=\"%s\"", SystemGroupAuthKey
);
2580 #endif /* HAVE_AUTHORIZATION_H */
2584 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendHeader: WWW-Authenticate: %s",
2587 if (httpPrintf(HTTP(con
), "WWW-Authenticate: %s\r\n", auth_str
) < 0)
2594 * WWW-Authenticate: Negotiate can be included even for
2595 * non-401 replies...
2598 if (con
->gss_output_token
.length
> 0 && con
->gss_output_token
.length
<= 65536)
2600 OM_uint32 minor_status
; /* Minor status code */
2601 int bufsize
; /* Size of output token buffer */
2604 bufsize
= con
->gss_output_token
.length
* 4 / 3 + 2;
2606 if (bufsize
> gss_bufsize
)
2608 char *buf
; /* New buffer */
2611 bufsize
= (bufsize
+ 1023) & 1023;/* Round up */
2614 buf
= realloc(gss_buf
, bufsize
);
2616 buf
= malloc(bufsize
);
2620 cupsdLogMessage(CUPSD_LOG_ERROR
,
2621 "Unable to allocate %d bytes for Kerberos credentials!",
2627 gss_bufsize
= bufsize
;
2630 httpEncode64_2(gss_buf
, gss_bufsize
,
2631 con
->gss_output_token
.value
,
2632 con
->gss_output_token
.length
);
2633 gss_release_buffer(&minor_status
, &con
->gss_output_token
);
2635 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2636 "cupsdSendHeader: WWW-Authenticate: Negotiate %s", gss_buf
);
2638 if (httpPrintf(HTTP(con
), "WWW-Authenticate: Negotiate %s\r\n",
2642 else if (con
->gss_output_token
.length
> 65536)
2644 cupsdLogMessage(CUPSD_LOG_ERROR
,
2645 "Kerberos credentials larger than 64k (%d)!",
2646 (int)con
->gss_output_token
.length
);
2649 #endif /* HAVE_GSSAPI */
2651 if (con
->language
&& strcmp(con
->language
->language
, "C"))
2653 if (httpPrintf(HTTP(con
), "Content-Language: %s\r\n",
2654 con
->language
->language
) < 0)
2660 if (!strcmp(type
, "text/html"))
2662 if (httpPrintf(HTTP(con
),
2663 "Content-Type: text/html; charset=utf-8\r\n") < 0)
2666 else if (httpPrintf(HTTP(con
), "Content-Type: %s\r\n", type
) < 0)
2675 * 'cupsdUpdateCGI()' - Read status messages from CGI scripts and programs.
2679 cupsdUpdateCGI(void)
2681 char *ptr
, /* Pointer to end of line in buffer */
2682 message
[1024]; /* Pointer to message text */
2683 int loglevel
; /* Log level for message */
2686 while ((ptr
= cupsdStatBufUpdate(CGIStatusBuffer
, &loglevel
,
2687 message
, sizeof(message
))) != NULL
)
2688 if (!strchr(CGIStatusBuffer
->buffer
, '\n'))
2691 if (ptr
== NULL
&& !CGIStatusBuffer
->bufused
)
2694 * Fatal error on pipe - should never happen!
2697 cupsdLogMessage(CUPSD_LOG_CRIT
,
2698 "cupsdUpdateCGI: error reading from CGI error pipe - %s",
2705 * 'cupsdWriteClient()' - Write data to a client as needed.
2709 cupsdWriteClient(cupsd_client_t
*con
) /* I - Client connection */
2711 int bytes
; /* Number of bytes written */
2712 char buf
[16385]; /* Data buffer */
2713 char *bufptr
; /* Pointer into buffer */
2714 ipp_state_t ipp_state
; /* IPP state value */
2718 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2719 "cupsdWriteClient(con=%p) %d response=%p(%d), file=%d "
2720 "pipe_pid=%d state=%d",
2721 con
, con
->http
.fd
, con
->response
,
2722 con
->response
? con
->response
->state
: -1,
2723 con
->file
, con
->pipe_pid
, con
->http
.state
);
2726 if (con
->http
.state
!= HTTP_GET_SEND
&&
2727 con
->http
.state
!= HTTP_POST_SEND
)
2733 * Make sure we select on the CGI output...
2736 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2738 if (!con
->file_ready
)
2741 * Try again later when there is CGI output available...
2744 cupsdRemoveSelect(con
->http
.fd
);
2748 con
->file_ready
= 0;
2751 if (con
->response
&& con
->response
->state
!= IPP_DATA
)
2753 ipp_state
= ippWrite(HTTP(con
), con
->response
);
2754 bytes
= ipp_state
!= IPP_ERROR
&&
2755 (con
->file
>= 0 || ipp_state
!= IPP_DATA
);
2757 else if ((bytes
= read(con
->file
, buf
, sizeof(buf
) - 1)) > 0)
2759 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2760 "cupsdWriteClient: Read %d bytes from file %d...",
2763 if (con
->pipe_pid
&& !con
->got_fields
)
2766 * Inspect the data for Content-Type and other fields.
2771 for (bufptr
= buf
; !con
->got_fields
&& *bufptr
; bufptr
++)
2773 if (*bufptr
== '\n')
2776 * Send line to client...
2779 if (bufptr
> buf
&& bufptr
[-1] == '\r')
2783 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Script header: %s", buf
);
2785 if (!con
->sent_header
)
2788 * Handle redirection and CGI status codes...
2791 if (!strncasecmp(buf
, "Location:", 9))
2793 cupsdSendHeader(con
, HTTP_SEE_OTHER
, NULL
, CUPSD_AUTH_NONE
);
2794 con
->sent_header
= 2;
2796 if (httpPrintf(HTTP(con
), "Content-Length: 0\r\n") < 0)
2799 else if (!strncasecmp(buf
, "Status:", 7))
2801 cupsdSendError(con
, (http_status_t
)atoi(buf
+ 7), CUPSD_AUTH_NONE
);
2802 con
->sent_header
= 2;
2806 cupsdSendHeader(con
, HTTP_OK
, NULL
, CUPSD_AUTH_NONE
);
2807 con
->sent_header
= 1;
2809 if (con
->http
.version
== HTTP_1_1
)
2811 if (httpPrintf(HTTP(con
), "Transfer-Encoding: chunked\r\n") < 0)
2817 if (strncasecmp(buf
, "Status:", 7))
2818 httpPrintf(HTTP(con
), "%s\r\n", buf
);
2820 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdWriteClient: %d %s",
2827 bytes
-= (bufptr
- buf
);
2830 memmove(buf
, bufptr
, bytes
+ 1);
2837 * See if the line was empty...
2840 if (con
->field_col
== 0)
2842 con
->got_fields
= 1;
2844 if (cupsdFlushHeader(con
) < 0)
2846 cupsdCloseClient(con
);
2850 if (con
->http
.version
== HTTP_1_1
)
2851 con
->http
.data_encoding
= HTTP_ENCODE_CHUNKED
;
2856 else if (*bufptr
!= '\r')
2860 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2861 "cupsdWriteClient: %d bytes=%d, got_fields=%d",
2862 con
->http
.fd
, bytes
, con
->got_fields
);
2864 if (bytes
> 0 && !con
->got_fields
)
2867 * Remaining text needs to go out...
2870 httpPrintf(HTTP(con
), "%s", buf
);
2872 con
->http
.activity
= time(NULL
);
2875 else if (bytes
== 0)
2877 con
->http
.activity
= time(NULL
);
2884 if (httpWrite2(HTTP(con
), buf
, bytes
) < 0)
2886 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2887 "cupsdWriteClient: %d Write of %d bytes failed!",
2888 con
->http
.fd
, bytes
);
2890 cupsdCloseClient(con
);
2894 if (con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
)
2895 httpFlushWrite(HTTP(con
));
2897 con
->bytes
+= bytes
;
2899 if (con
->http
.state
== HTTP_WAITING
)
2906 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdWriteClient: %d bytes < 0",
2909 cupsdLogRequest(con
, HTTP_OK
);
2911 httpFlushWrite(HTTP(con
));
2913 if (con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
&& con
->sent_header
== 1)
2915 if (httpWrite2(HTTP(con
), "", 0) < 0)
2917 cupsdCloseClient(con
);
2922 con
->http
.state
= HTTP_WAITING
;
2924 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
2928 cupsdRemoveSelect(con
->file
);
2931 cupsdEndProcess(con
->pipe_pid
, 0);
2933 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2934 "cupsdWriteClient: %d Closing data file %d.",
2935 con
->http
.fd
, con
->file
);
2944 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2945 "cupsdWriteClient: %d Removing temp file %s",
2946 con
->http
.fd
, con
->filename
);
2947 unlink(con
->filename
);
2948 cupsdClearString(&con
->filename
);
2953 ippDelete(con
->request
);
2954 con
->request
= NULL
;
2959 ippDelete(con
->response
);
2960 con
->response
= NULL
;
2963 cupsdClearString(&con
->command
);
2964 cupsdClearString(&con
->options
);
2965 cupsdClearString(&con
->query_string
);
2967 if (!con
->http
.keep_alive
)
2969 cupsdCloseClient(con
);
2974 con
->http
.activity
= time(NULL
);
2979 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
2982 static int /* O - 1 if modified since */
2984 cupsd_client_t
*con
, /* I - Client connection */
2985 struct stat
*filestats
) /* I - File information */
2987 char *ptr
; /* Pointer into field */
2988 time_t date
; /* Time/date value */
2989 off_t size
; /* Size/length value */
2994 ptr
= con
->http
.fields
[HTTP_FIELD_IF_MODIFIED_SINCE
];
2999 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3000 "check_if_modified: %d If-Modified-Since=\"%s\"",
3003 while (*ptr
!= '\0')
3005 while (isspace(*ptr
) || *ptr
== ';')
3008 if (strncasecmp(ptr
, "length=", 7) == 0)
3011 size
= strtoll(ptr
, NULL
, 10);
3013 while (isdigit(*ptr
))
3016 else if (isalpha(*ptr
))
3018 date
= httpGetDateTime(ptr
);
3019 while (*ptr
!= '\0' && *ptr
!= ';')
3026 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3027 "check_if_modified: %d sizes=" CUPS_LLFMT
","
3028 CUPS_LLFMT
" dates=%d,%d",
3029 con
->http
.fd
, CUPS_LLCAST size
,
3030 CUPS_LLCAST filestats
->st_size
, (int)date
,
3031 (int)filestats
->st_mtime
);
3033 return ((size
!= filestats
->st_size
&& size
!= 0) ||
3034 (date
< filestats
->st_mtime
&& date
!= 0) ||
3035 (size
== 0 && date
== 0));
3040 * 'compare_clients()' - Compare two client connections.
3043 static int /* O - Result of comparison */
3044 compare_clients(cupsd_client_t
*a
, /* I - First client */
3045 cupsd_client_t
*b
, /* I - Second client */
3046 void *data
) /* I - User data (not used) */
3060 * 'data_ready()' - Check whether data is available from a client.
3063 static int /* O - 1 if data is ready, 0 otherwise */
3064 data_ready(cupsd_client_t
*con
) /* I - Client */
3066 if (con
->http
.used
> 0)
3069 else if (con
->http
.tls
)
3072 if (SSL_pending((SSL
*)(con
->http
.tls
)))
3074 # elif defined(HAVE_GNUTLS)
3075 if (gnutls_record_check_pending(((http_tls_t
*)(con
->http
.tls
))->session
))
3077 # elif defined(HAVE_CDSASSL)
3078 size_t bytes
; /* Bytes that are available */
3080 if (!SSLGetBufferedReadSize(((http_tls_t
*)(con
->http
.tls
))->session
,
3081 &bytes
) && bytes
> 0)
3083 # endif /* HAVE_LIBSSL */
3085 #endif /* HAVE_SSL */
3093 * 'encrypt_client()' - Enable encryption for the client...
3096 static int /* O - 1 on success, 0 on error */
3097 encrypt_client(cupsd_client_t
*con
) /* I - Client to encrypt */
3100 SSL_CTX
*context
; /* Context for encryption */
3101 SSL
*conn
; /* Connection for encryption */
3102 BIO
*bio
; /* BIO data */
3103 unsigned long error
; /* Error code */
3107 * Verify that we have a certificate...
3110 if (access(ServerKey
, 0) || access(ServerCertificate
, 0))
3113 * Nope, make a self-signed certificate...
3116 if (!make_certificate(con
))
3121 * Create the SSL context and accept the connection...
3124 context
= SSL_CTX_new(SSLv23_server_method());
3126 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
3127 if (SSLOptions
& CUPSD_SSL_NOEMPTY
)
3128 SSL_CTX_set_options(context
, SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
);
3129 SSL_CTX_use_PrivateKey_file(context
, ServerKey
, SSL_FILETYPE_PEM
);
3130 SSL_CTX_use_certificate_chain_file(context
, ServerCertificate
);
3132 bio
= BIO_new(_httpBIOMethods());
3133 BIO_ctrl(bio
, BIO_C_SET_FILE_PTR
, 0, (char *)HTTP(con
));
3135 conn
= SSL_new(context
);
3136 SSL_set_bio(conn
, bio
, bio
);
3138 if (SSL_accept(conn
) != 1)
3140 cupsdLogMessage(CUPSD_LOG_ERROR
,
3141 "encrypt_client: Unable to encrypt connection from %s!",
3142 con
->http
.hostname
);
3144 while ((error
= ERR_get_error()) != 0)
3145 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s",
3146 ERR_error_string(error
, NULL
));
3148 SSL_CTX_free(context
);
3153 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3154 "encrypt_client: %d Connection from %s now encrypted.",
3155 con
->http
.fd
, con
->http
.hostname
);
3157 con
->http
.tls
= conn
;
3160 # elif defined(HAVE_GNUTLS)
3161 http_tls_t
*conn
; /* TLS session object */
3162 int error
; /* Error code */
3163 gnutls_certificate_server_credentials
*credentials
;
3164 /* TLS credentials */
3168 * Verify that we have a certificate...
3171 if (access(ServerKey
, 0) || access(ServerCertificate
, 0))
3174 * Nope, make a self-signed certificate...
3177 if (!make_certificate(con
))
3182 * Create the SSL object and perform the SSL handshake...
3185 conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
));
3190 credentials
= (gnutls_certificate_server_credentials
*)
3191 malloc(sizeof(gnutls_certificate_server_credentials
));
3192 if (credentials
== NULL
)
3194 cupsdLogMessage(CUPSD_LOG_ERROR
,
3195 "encrypt_client: Unable to encrypt connection from %s!",
3196 con
->http
.hostname
);
3197 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s", strerror(errno
));
3203 gnutls_certificate_allocate_credentials(credentials
);
3204 gnutls_certificate_set_x509_key_file(*credentials
, ServerCertificate
,
3205 ServerKey
, GNUTLS_X509_FMT_PEM
);
3207 gnutls_init(&(conn
->session
), GNUTLS_SERVER
);
3208 gnutls_set_default_priority(conn
->session
);
3209 gnutls_credentials_set(conn
->session
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
3210 gnutls_transport_set_ptr(conn
->session
, (gnutls_transport_ptr
)HTTP(con
));
3211 gnutls_transport_set_pull_function(conn
->session
, _httpReadGNUTLS
);
3212 gnutls_transport_set_push_function(conn
->session
, _httpWriteGNUTLS
);
3214 error
= gnutls_handshake(conn
->session
);
3216 if (error
!= GNUTLS_E_SUCCESS
)
3218 cupsdLogMessage(CUPSD_LOG_ERROR
,
3219 "encrypt_client: Unable to encrypt connection from %s!",
3220 con
->http
.hostname
);
3221 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s",
3222 gnutls_strerror(error
));
3224 gnutls_deinit(conn
->session
);
3225 gnutls_certificate_free_credentials(*credentials
);
3231 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3232 "encrypt_client: %d Connection from %s now encrypted.",
3233 con
->http
.fd
, con
->http
.hostname
);
3235 conn
->credentials
= credentials
;
3236 con
->http
.tls
= conn
;
3239 # elif defined(HAVE_CDSASSL)
3240 OSStatus error
; /* Error code */
3241 http_tls_t
*conn
; /* CDSA connection information */
3244 if ((conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
))) == NULL
)
3248 conn
->session
= NULL
;
3249 conn
->certsArray
= get_cdsa_certificate(con
);
3251 if (!conn
->certsArray
)
3254 * No keychain (yet), make a self-signed certificate...
3257 if (make_certificate(con
))
3258 conn
->certsArray
= get_cdsa_certificate(con
);
3261 if (!conn
->certsArray
)
3263 cupsdLogMessage(CUPSD_LOG_ERROR
,
3264 "encrypt_client: Could not find signing key in keychain "
3265 "\"%s\"", ServerCertificate
);
3266 error
= errSSLBadCert
; /* errSSLBadConfiguration is a better choice, but not available on 10.2.x */
3270 error
= SSLNewContext(true, &conn
->session
);
3273 error
= SSLSetIOFuncs(conn
->session
, _httpReadCDSA
, _httpWriteCDSA
);
3276 error
= SSLSetProtocolVersionEnabled(conn
->session
, kSSLProtocol2
, false);
3279 error
= SSLSetConnection(conn
->session
, HTTP(con
));
3282 error
= SSLSetAllowsExpiredCerts(conn
->session
, true);
3285 error
= SSLSetAllowsAnyRoot(conn
->session
, true);
3288 error
= SSLSetCertificate(conn
->session
, conn
->certsArray
);
3293 * Perform SSL/TLS handshake
3296 while ((error
= SSLHandshake(conn
->session
)) == errSSLWouldBlock
)
3302 cupsdLogMessage(CUPSD_LOG_ERROR
,
3303 "encrypt_client: Unable to encrypt connection from %s!",
3304 con
->http
.hostname
);
3306 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s (%d)",
3307 cssmErrorString(error
), (int)error
);
3309 con
->http
.error
= error
;
3310 con
->http
.status
= HTTP_ERROR
;
3313 SSLDisposeContext(conn
->session
);
3315 if (conn
->certsArray
)
3316 CFRelease(conn
->certsArray
);
3323 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3324 "encrypt_client: %d Connection from %s now encrypted.",
3325 con
->http
.fd
, con
->http
.hostname
);
3327 con
->http
.tls
= conn
;
3330 # endif /* HAVE_LIBSSL */
3332 #endif /* HAVE_SSL */
3337 * 'get_cdsa_certificate()' - Get a SSL/TLS certificate from the System keychain.
3340 static CFArrayRef
/* O - Array of certificates */
3341 get_cdsa_certificate(cupsd_client_t
*con
) /* I - Client connection */
3343 OSStatus err
; /* Error info */
3344 SecKeychainRef keychain
; /* Keychain reference */
3345 SecIdentitySearchRef search
; /* Search reference */
3346 SecIdentityRef identity
; /* Identity */
3347 CFArrayRef certificates
= NULL
;
3348 /* Certificate array */
3351 if ((err
= SecKeychainOpen(ServerCertificate
, &keychain
)))
3353 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot open keychain \"%s\", %s",
3354 ServerCertificate
, cssmErrorString(err
));
3358 # if HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY
3360 * Use a policy to search for valid certificates who's common name matches the
3364 SecPolicySearchRef policy_search
; /* Policy search ref */
3365 SecPolicyRef policy
; /* Policy ref */
3366 CSSM_DATA options
; /* Policy options */
3367 CSSM_APPLE_TP_SSL_OPTIONS
3368 ssl_options
; /* SSL Option for hostname */
3371 if (SecPolicySearchCreate(CSSM_CERT_X_509v3
, &CSSMOID_APPLE_TP_SSL
,
3372 NULL
, &policy_search
))
3374 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot create a policy search reference");
3375 CFRelease(keychain
);
3379 if (SecPolicySearchCopyNext(policy_search
, &policy
))
3381 cupsdLogMessage(CUPSD_LOG_ERROR
,
3382 "Cannot find a policy to use for searching");
3383 CFRelease(keychain
);
3384 CFRelease(policy_search
);
3388 memset(&ssl_options
, 0, sizeof(ssl_options
));
3389 ssl_options
.Version
= CSSM_APPLE_TP_SSL_OPTS_VERSION
;
3390 ssl_options
.ServerName
= con
->servername
;
3391 ssl_options
.ServerNameLen
= strlen(con
->servername
);
3393 options
.Data
= (uint8
*)&ssl_options
;
3394 options
.Length
= sizeof(ssl_options
);
3396 if (SecPolicySetValue(policy
, &options
))
3398 cupsdLogMessage(CUPSD_LOG_ERROR
,
3399 "Cannot set policy value to use for searching");
3400 CFRelease(keychain
);
3401 CFRelease(policy_search
);
3405 err
= SecIdentitySearchCreateWithPolicy(policy
, NULL
, CSSM_KEYUSE_SIGN
,
3406 keychain
, FALSE
, &search
);
3409 * Assume there is exactly one SecIdentity in the keychain...
3412 err
= SecIdentitySearchCreate(keychain
, CSSM_KEYUSE_SIGN
, &search
);
3413 # endif /* HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY */
3416 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3417 "Cannot create keychain search reference: %s",
3418 cssmErrorString(err
));
3421 if ((err
= SecIdentitySearchCopyNext(search
, &identity
)))
3423 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3424 "Cannot find signing key in keychain \"%s\", error %d",
3425 ServerCertificate
, (int)err
);
3429 if (CFGetTypeID(identity
) != SecIdentityGetTypeID())
3430 cupsdLogMessage(CUPSD_LOG_ERROR
,
3431 "SecIdentitySearchCopyNext CFTypeID failure!");
3434 if ((certificates
= CFArrayCreate(NULL
, (const void **)&identity
,
3435 1, &kCFTypeArrayCallBacks
)) == NULL
)
3436 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot create certificate array");
3439 CFRelease(identity
);
3445 # if HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY
3447 CFRelease(policy_search
);
3448 # endif /* HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY */
3450 return (certificates
);
3452 #endif /* HAVE_CDSASSL */
3456 * 'get_file()' - Get a filename and state info.
3459 static char * /* O - Real filename */
3460 get_file(cupsd_client_t
*con
, /* I - Client connection */
3461 struct stat
*filestats
, /* O - File information */
3462 char *filename
, /* IO - Filename buffer */
3463 int len
) /* I - Buffer length */
3465 int status
; /* Status of filesystem calls */
3466 char *ptr
; /* Pointer info filename */
3467 int plen
; /* Remaining length after pointer */
3468 char language
[7]; /* Language subdirectory, if any */
3472 * Figure out the real filename...
3477 if (!strncmp(con
->uri
, "/ppd/", 5))
3478 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
);
3479 else if (!strncmp(con
->uri
, "/rss/", 5) && !strchr(con
->uri
+ 5, '/'))
3480 snprintf(filename
, len
, "%s/rss/%s", CacheDir
, con
->uri
+ 5);
3481 else if (!strncmp(con
->uri
, "/admin/conf/", 12))
3482 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
+ 11);
3483 else if (!strncmp(con
->uri
, "/admin/log/", 11))
3485 if (!strncmp(con
->uri
+ 11, "access_log", 10) && AccessLog
[0] == '/')
3486 strlcpy(filename
, AccessLog
, len
);
3487 else if (!strncmp(con
->uri
+ 11, "error_log", 9) && ErrorLog
[0] == '/')
3488 strlcpy(filename
, ErrorLog
, len
);
3489 else if (!strncmp(con
->uri
+ 11, "page_log", 8) && PageLog
[0] == '/')
3490 strlcpy(filename
, PageLog
, len
);
3494 else if (con
->language
)
3496 snprintf(language
, sizeof(language
), "/%s", con
->language
->language
);
3497 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3500 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3502 if ((ptr
= strchr(filename
, '?')) != NULL
)
3506 * Grab the status for this language; if there isn't a language-specific file
3507 * then fallback to the default one...
3510 if ((status
= stat(filename
, filestats
)) != 0 && language
[0] &&
3511 strncmp(con
->uri
, "/ppd/", 5) &&
3512 strncmp(con
->uri
, "/admin/conf/", 12) &&
3513 strncmp(con
->uri
, "/admin/log/", 11))
3516 * Drop the country code...
3520 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3522 if ((ptr
= strchr(filename
, '?')) != NULL
)
3525 if ((status
= stat(filename
, filestats
)) != 0)
3528 * Drop the language prefix and try the root directory...
3532 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3534 if ((ptr
= strchr(filename
, '?')) != NULL
)
3537 status
= stat(filename
, filestats
);
3542 * If we're found a directory, get the index.html file instead...
3545 if (!status
&& S_ISDIR(filestats
->st_mode
))
3548 * Make sure the URI ends with a slash...
3551 if (con
->uri
[strlen(con
->uri
) - 1] != '/')
3552 strlcat(con
->uri
, "/", sizeof(con
->uri
));
3555 * Find the directory index file, trying every language...
3560 if (status
&& language
[0])
3563 * Try a different language subset...
3567 language
[0] = '\0'; /* Strip country code */
3569 language
[0] = '\0'; /* Strip language */
3573 * Look for the index file...
3576 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3578 if ((ptr
= strchr(filename
, '?')) != NULL
)
3581 ptr
= filename
+ strlen(filename
);
3582 plen
= len
- (ptr
- filename
);
3584 strlcpy(ptr
, "index.html", plen
);
3585 status
= stat(filename
, filestats
);
3590 strlcpy(ptr
, "index.class", plen
);
3591 status
= stat(filename
, filestats
);
3593 #endif /* HAVE_JAVA */
3598 strlcpy(ptr
, "index.pl", plen
);
3599 status
= stat(filename
, filestats
);
3601 #endif /* HAVE_PERL */
3606 strlcpy(ptr
, "index.php", plen
);
3607 status
= stat(filename
, filestats
);
3609 #endif /* HAVE_PHP */
3614 strlcpy(ptr
, "index.pyc", plen
);
3615 status
= stat(filename
, filestats
);
3620 strlcpy(ptr
, "index.py", plen
);
3621 status
= stat(filename
, filestats
);
3623 #endif /* HAVE_PYTHON */
3626 while (status
&& language
[0]);
3629 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "get_file: %d filename=%s size=%d",
3630 con
->http
.fd
, filename
,
3631 status
? -1 : (int)filestats
->st_size
);
3634 con
->http
.data_remaining
= (int)filestats
->st_size
;
3644 * 'install_conf_file()' - Install a configuration file.
3647 static http_status_t
/* O - Status */
3648 install_conf_file(cupsd_client_t
*con
) /* I - Connection */
3650 cups_file_t
*in
, /* Input file */
3651 *out
; /* Output file */
3652 char buffer
[1024]; /* Copy buffer */
3653 int bytes
; /* Number of bytes */
3654 char conffile
[1024], /* Configuration filename */
3655 newfile
[1024], /* New config filename */
3656 oldfile
[1024]; /* Old config filename */
3657 struct stat confinfo
; /* Config file info */
3661 * First construct the filenames...
3664 snprintf(conffile
, sizeof(conffile
), "%s%s", ServerRoot
, con
->uri
+ 11);
3665 snprintf(newfile
, sizeof(newfile
), "%s%s.N", ServerRoot
, con
->uri
+ 11);
3666 snprintf(oldfile
, sizeof(oldfile
), "%s%s.O", ServerRoot
, con
->uri
+ 11);
3668 cupsdLogMessage(CUPSD_LOG_INFO
, "Installing config file \"%s\"...", conffile
);
3671 * Get the owner, group, and permissions of the configuration file.
3672 * If it doesn't exist, assign it to the User and Group in the
3673 * cupsd.conf file with mode 0640 permissions.
3676 if (stat(conffile
, &confinfo
))
3678 confinfo
.st_uid
= User
;
3679 confinfo
.st_gid
= Group
;
3680 confinfo
.st_mode
= ConfigFilePerm
;
3684 * Open the request file and new config file...
3687 if ((in
= cupsFileOpen(con
->filename
, "rb")) == NULL
)
3689 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open request file \"%s\" - %s",
3690 con
->filename
, strerror(errno
));
3691 return (HTTP_SERVER_ERROR
);
3694 if ((out
= cupsFileOpen(newfile
, "wb")) == NULL
)
3697 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open config file \"%s\" - %s",
3698 newfile
, strerror(errno
));
3699 return (HTTP_SERVER_ERROR
);
3702 fchmod(cupsFileNumber(out
), confinfo
.st_mode
);
3703 fchown(cupsFileNumber(out
), confinfo
.st_uid
, confinfo
.st_gid
);
3706 * Copy from the request to the new config file...
3709 while ((bytes
= cupsFileRead(in
, buffer
, sizeof(buffer
))) > 0)
3710 if (cupsFileWrite(out
, buffer
, bytes
) < bytes
)
3712 cupsdLogMessage(CUPSD_LOG_ERROR
,
3713 "Unable to copy to config file \"%s\" - %s",
3714 newfile
, strerror(errno
));
3720 return (HTTP_SERVER_ERROR
);
3724 * Close the files...
3728 if (cupsFileClose(out
))
3730 cupsdLogMessage(CUPSD_LOG_ERROR
,
3731 "Error file closing config file \"%s\" - %s",
3732 newfile
, strerror(errno
));
3736 return (HTTP_SERVER_ERROR
);
3740 * Remove the request file...
3743 unlink(con
->filename
);
3744 cupsdClearString(&con
->filename
);
3747 * Unlink the old backup, rename the current config file to the backup
3748 * filename, and rename the new config file to the config file name...
3751 if (unlink(oldfile
))
3752 if (errno
!= ENOENT
)
3754 cupsdLogMessage(CUPSD_LOG_ERROR
,
3755 "Unable to remove backup config file \"%s\" - %s",
3756 oldfile
, strerror(errno
));
3760 return (HTTP_SERVER_ERROR
);
3763 if (rename(conffile
, oldfile
))
3764 if (errno
!= ENOENT
)
3766 cupsdLogMessage(CUPSD_LOG_ERROR
,
3767 "Unable to rename old config file \"%s\" - %s",
3768 conffile
, strerror(errno
));
3772 return (HTTP_SERVER_ERROR
);
3775 if (rename(newfile
, conffile
))
3777 cupsdLogMessage(CUPSD_LOG_ERROR
,
3778 "Unable to rename new config file \"%s\" - %s",
3779 newfile
, strerror(errno
));
3781 rename(oldfile
, conffile
);
3784 return (HTTP_SERVER_ERROR
);
3788 * If the cupsd.conf file was updated, set the NeedReload flag...
3791 if (!strcmp(con
->uri
, "/admin/conf/cupsd.conf"))
3792 NeedReload
= RELOAD_CUPSD
;
3794 NeedReload
= RELOAD_ALL
;
3796 ReloadTime
= time(NULL
);
3799 * Return that the file was created successfully...
3802 return (HTTP_CREATED
);
3807 * 'is_cgi()' - Is the resource a CGI script/program?
3810 static int /* O - 1 = CGI, 0 = file */
3811 is_cgi(cupsd_client_t
*con
, /* I - Client connection */
3812 const char *filename
, /* I - Real filename */
3813 struct stat
*filestats
, /* I - File information */
3814 mime_type_t
*type
) /* I - MIME type */
3816 const char *options
; /* Options on URL */
3819 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3820 "is_cgi(con=%p, filename=\"%s\", filestats=%p, type=%s/%s)",
3821 con
, filename
, filestats
, type
? type
->super
: "unknown",
3822 type
? type
->type
: "unknown");
3825 * Get the options, if any...
3828 if ((options
= strchr(con
->uri
, '?')) != NULL
)
3831 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", options
);
3835 * Check for known types...
3838 if (!type
|| strcasecmp(type
->super
, "application"))
3840 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "is_cgi: Returning 0...");
3844 if (!strcasecmp(type
->type
, "x-httpd-cgi") &&
3845 (filestats
->st_mode
& 0111))
3848 * "application/x-httpd-cgi" is a CGI script.
3851 cupsdSetString(&con
->command
, filename
);
3854 cupsdSetStringf(&con
->options
, " %s", options
);
3856 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3857 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3858 con
->command
, con
->options
);
3863 else if (!strcasecmp(type
->type
, "x-httpd-java"))
3866 * "application/x-httpd-java" is a Java servlet.
3869 cupsdSetString(&con
->command
, CUPS_JAVA
);
3872 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3874 cupsdSetStringf(&con
->options
, " %s", filename
);
3876 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3877 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3878 con
->command
, con
->options
);
3882 #endif /* HAVE_JAVA */
3884 else if (!strcasecmp(type
->type
, "x-httpd-perl"))
3887 * "application/x-httpd-perl" is a Perl page.
3890 cupsdSetString(&con
->command
, CUPS_PERL
);
3893 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3895 cupsdSetStringf(&con
->options
, " %s", filename
);
3897 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3898 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3899 con
->command
, con
->options
);
3903 #endif /* HAVE_PERL */
3905 else if (!strcasecmp(type
->type
, "x-httpd-php"))
3908 * "application/x-httpd-php" is a PHP page.
3911 cupsdSetString(&con
->command
, CUPS_PHP
);
3914 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3916 cupsdSetStringf(&con
->options
, " %s", filename
);
3918 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3919 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3920 con
->command
, con
->options
);
3924 #endif /* HAVE_PHP */
3926 else if (!strcasecmp(type
->type
, "x-httpd-python"))
3929 * "application/x-httpd-python" is a Python page.
3932 cupsdSetString(&con
->command
, CUPS_PYTHON
);
3935 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3937 cupsdSetStringf(&con
->options
, " %s", filename
);
3939 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3940 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3941 con
->command
, con
->options
);
3945 #endif /* HAVE_PYTHON */
3947 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "is_cgi: Returning 0...");
3954 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
3957 static int /* O - 0 if relative, 1 if absolute */
3958 is_path_absolute(const char *path
) /* I - Input path */
3961 * Check for a leading slash...
3968 * Check for "/.." in the path...
3971 while ((path
= strstr(path
, "/..")) != NULL
)
3973 if (!path
[3] || path
[3] == '/')
3980 * If we haven't found any relative paths, return 1 indicating an
3990 * 'make_certificate()' - Make a self-signed SSL/TLS certificate.
3993 static int /* O - 1 on success, 0 on failure */
3994 make_certificate(cupsd_client_t
*con
) /* I - Client connection */
3996 #if defined(HAVE_LIBSSL) && defined(HAVE_WAITPID)
3997 int pid
, /* Process ID of command */
3998 status
; /* Status of command */
3999 char command
[1024], /* Command */
4000 *argv
[12], /* Command-line arguments */
4001 *envp
[MAX_ENV
+ 1], /* Environment variables */
4002 home
[1024], /* HOME environment variable */
4003 infofile
[1024], /* Type-in information for cert */
4004 seedfile
[1024]; /* Random number seed file */
4005 int envc
, /* Number of environment variables */
4006 bytes
; /* Bytes written */
4007 cups_file_t
*fp
; /* Seed/info file */
4008 int infofd
; /* Info file descriptor */
4012 * Run the "openssl" command to seed the random number generator and
4013 * generate a self-signed certificate that is good for 10 years:
4015 * openssl rand -rand seedfile 1
4017 * openssl req -new -x509 -keyout ServerKey \
4018 * -out ServerCertificate -days 3650 -nodes
4020 * The seeding step is crucial in ensuring that the openssl command
4021 * does not block on systems without sufficient entropy...
4024 if (!cupsFileFind("openssl", getenv("PATH"), 1, command
, sizeof(command
)))
4026 cupsdLogMessage(CUPSD_LOG_ERROR
,
4027 "No SSL certificate and openssl command not found!");
4031 if (access("/dev/urandom", 0))
4034 * If the system doesn't provide /dev/urandom, then any random source
4035 * will probably be blocking-style, so generate some random data to
4036 * use as a seed for the certificate. Note that we have already
4037 * seeded the random number generator in cupsdInitCerts()...
4040 cupsdLogMessage(CUPSD_LOG_INFO
,
4041 "Seeding the random number generator...");
4043 snprintf(home
, sizeof(home
), "HOME=%s", TempDir
);
4046 * Write the seed file...
4049 if ((fp
= cupsTempFile2(seedfile
, sizeof(seedfile
))) == NULL
)
4051 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to create seed file %s - %s",
4052 seedfile
, strerror(errno
));
4056 for (bytes
= 0; bytes
< 262144; bytes
++)
4057 cupsFilePutChar(fp
, random());
4062 * Run the openssl command to seed its random number generator...
4065 argv
[0] = "openssl";
4072 envc
= cupsdLoadEnv(envp
, MAX_ENV
);
4073 envp
[envc
++] = home
;
4076 if (!cupsdStartProcess(command
, argv
, envp
, -1, -1, -1, -1, -1, 1, NULL
,
4083 while (waitpid(pid
, &status
, 0) < 0)
4090 cupsdFinishProcess(pid
, command
, sizeof(command
));
4093 * Remove the seed file, as it is no longer needed...
4100 if (WIFEXITED(status
))
4101 cupsdLogMessage(CUPSD_LOG_ERROR
,
4102 "Unable to seed random number generator - "
4103 "the openssl command stopped with status %d!",
4104 WEXITSTATUS(status
));
4106 cupsdLogMessage(CUPSD_LOG_ERROR
,
4107 "Unable to seed random number generator - "
4108 "the openssl command crashed on signal %d!",
4116 * Create a file with the certificate information fields...
4118 * Note: This assumes that the default questions are asked by the openssl
4122 if ((fp
= cupsTempFile2(infofile
, sizeof(infofile
))) == NULL
)
4124 cupsdLogMessage(CUPSD_LOG_ERROR
,
4125 "Unable to create certificate information file %s - %s",
4126 infofile
, strerror(errno
));
4130 cupsFilePrintf(fp
, ".\n.\n.\n%s\n.\n%s\n%s\n",
4131 ServerName
, ServerName
, ServerAdmin
);
4134 cupsdLogMessage(CUPSD_LOG_INFO
,
4135 "Generating SSL server key and certificate...");
4137 argv
[0] = "openssl";
4141 argv
[4] = "-keyout";
4142 argv
[5] = ServerKey
;
4144 argv
[7] = ServerCertificate
;
4147 argv
[10] = "-nodes";
4150 cupsdLoadEnv(envp
, MAX_ENV
);
4152 infofd
= open(infofile
, O_RDONLY
);
4154 if (!cupsdStartProcess(command
, argv
, envp
, infofd
, -1, -1, -1, -1, 1, NULL
,
4165 while (waitpid(pid
, &status
, 0) < 0)
4172 cupsdFinishProcess(pid
, command
, sizeof(command
));
4176 if (WIFEXITED(status
))
4177 cupsdLogMessage(CUPSD_LOG_ERROR
,
4178 "Unable to create SSL server key and certificate - "
4179 "the openssl command stopped with status %d!",
4180 WEXITSTATUS(status
));
4182 cupsdLogMessage(CUPSD_LOG_ERROR
,
4183 "Unable to create SSL server key and certificate - "
4184 "the openssl command crashed on signal %d!",
4189 cupsdLogMessage(CUPSD_LOG_INFO
, "Created SSL server key file \"%s\"...",
4191 cupsdLogMessage(CUPSD_LOG_INFO
,
4192 "Created SSL server certificate file \"%s\"...",
4198 #elif defined(HAVE_GNUTLS)
4199 gnutls_x509_crt crt
; /* Self-signed certificate */
4200 gnutls_x509_privkey key
; /* Encryption key */
4201 cups_lang_t
*language
; /* Default language info */
4202 cups_file_t
*fp
; /* Key/cert file */
4203 unsigned char buffer
[8192]; /* Buffer for x509 data */
4204 size_t bytes
; /* Number of bytes of data */
4205 unsigned char serial
[4]; /* Serial number buffer */
4206 time_t curtime
; /* Current time */
4207 int result
; /* Result of GNU TLS calls */
4211 * Create the encryption key...
4214 cupsdLogMessage(CUPSD_LOG_INFO
, "Generating SSL server key...");
4216 gnutls_x509_privkey_init(&key
);
4217 gnutls_x509_privkey_generate(key
, GNUTLS_PK_RSA
, 2048, 0);
4223 bytes
= sizeof(buffer
);
4225 if ((result
= gnutls_x509_privkey_export(key
, GNUTLS_X509_FMT_PEM
,
4226 buffer
, &bytes
)) < 0)
4228 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to export SSL server key - %s",
4229 gnutls_strerror(result
));
4230 gnutls_x509_privkey_deinit(key
);
4233 else if ((fp
= cupsFileOpen(ServerKey
, "w")) != NULL
)
4235 cupsFileWrite(fp
, (char *)buffer
, bytes
);
4238 cupsdLogMessage(CUPSD_LOG_INFO
, "Created SSL server key file \"%s\"...",
4243 cupsdLogMessage(CUPSD_LOG_ERROR
,
4244 "Unable to create SSL server key file \"%s\" - %s",
4245 ServerKey
, strerror(errno
));
4246 gnutls_x509_privkey_deinit(key
);
4251 * Create the self-signed certificate...
4254 cupsdLogMessage(CUPSD_LOG_INFO
, "Generating self-signed SSL certificate...");
4256 language
= cupsLangDefault();
4257 curtime
= time(NULL
);
4258 serial
[0] = curtime
>> 24;
4259 serial
[1] = curtime
>> 16;
4260 serial
[2] = curtime
>> 8;
4261 serial
[3] = curtime
;
4263 gnutls_x509_crt_init(&crt
);
4264 if (strlen(language
->language
) == 5)
4265 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
4266 language
->language
+ 3, 2);
4268 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
4270 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COMMON_NAME
, 0,
4271 ServerName
, strlen(ServerName
));
4272 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATION_NAME
, 0,
4273 ServerName
, strlen(ServerName
));
4274 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATIONAL_UNIT_NAME
,
4276 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_STATE_OR_PROVINCE_NAME
, 0,
4278 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_LOCALITY_NAME
, 0,
4280 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_PKCS9_EMAIL
, 0,
4281 ServerAdmin
, strlen(ServerAdmin
));
4282 gnutls_x509_crt_set_key(crt
, key
);
4283 gnutls_x509_crt_set_serial(crt
, serial
, sizeof(serial
));
4284 gnutls_x509_crt_set_activation_time(crt
, curtime
);
4285 gnutls_x509_crt_set_expiration_time(crt
, curtime
+ 10 * 365 * 86400);
4286 gnutls_x509_crt_set_ca_status(crt
, 0);
4287 gnutls_x509_crt_set_subject_alternative_name(crt
, GNUTLS_SAN_DNSNAME
,
4289 gnutls_x509_crt_set_key_purpose_oid(crt
, GNUTLS_KP_TLS_WWW_SERVER
, 0);
4290 gnutls_x509_crt_set_key_usage(crt
, GNUTLS_KEY_KEY_ENCIPHERMENT
);
4291 gnutls_x509_crt_set_version(crt
, 3);
4293 bytes
= sizeof(buffer
);
4294 if (gnutls_x509_crt_get_key_id(crt
, 0, buffer
, &bytes
) >= 0)
4295 gnutls_x509_crt_set_subject_key_id(crt
, buffer
, bytes
);
4297 gnutls_x509_crt_sign(crt
, crt
, key
);
4303 bytes
= sizeof(buffer
);
4304 if ((result
= gnutls_x509_crt_export(crt
, GNUTLS_X509_FMT_PEM
,
4305 buffer
, &bytes
)) < 0)
4306 cupsdLogMessage(CUPSD_LOG_ERROR
,
4307 "Unable to export SSL server certificate - %s",
4308 gnutls_strerror(result
));
4309 else if ((fp
= cupsFileOpen(ServerCertificate
, "w")) != NULL
)
4311 cupsFileWrite(fp
, (char *)buffer
, bytes
);
4314 cupsdLogMessage(CUPSD_LOG_INFO
,
4315 "Created SSL server certificate file \"%s\"...",
4319 cupsdLogMessage(CUPSD_LOG_ERROR
,
4320 "Unable to create SSL server certificate file \"%s\" - %s",
4321 ServerCertificate
, strerror(errno
));
4327 gnutls_x509_crt_deinit(crt
);
4328 gnutls_x509_privkey_deinit(key
);
4332 #elif defined(HAVE_CDSASSL) && defined(HAVE_WAITPID)
4333 int pid
, /* Process ID of command */
4334 status
; /* Status of command */
4335 char command
[1024], /* Command */
4336 *argv
[4], /* Command-line arguments */
4337 *envp
[MAX_ENV
+ 1], /* Environment variables */
4338 keychain
[1024], /* Keychain argument */
4339 infofile
[1024]; /* Type-in information for cert */
4340 cups_file_t
*fp
; /* Seed/info file */
4341 int infofd
; /* Info file descriptor */
4345 * Run the "certtool" command to generate a self-signed certificate...
4348 if (!cupsFileFind("certtool", getenv("PATH"), 1, command
, sizeof(command
)))
4350 cupsdLogMessage(CUPSD_LOG_ERROR
,
4351 "No SSL certificate and certtool command not found!");
4356 * Create a file with the certificate information fields...
4358 * Note: This assumes that the default questions are asked by the certtool
4362 if ((fp
= cupsTempFile2(infofile
, sizeof(infofile
))) == NULL
)
4364 cupsdLogMessage(CUPSD_LOG_ERROR
,
4365 "Unable to create certificate information file %s - %s",
4366 infofile
, strerror(errno
));
4370 cupsFilePrintf(fp
, "%s\nr\n\ny\nb\ns\ny\n%s\n\n\n\n\n%s\ny\n",
4371 con
->servername
, con
->servername
, ServerAdmin
);
4374 cupsdLogMessage(CUPSD_LOG_INFO
,
4375 "Generating SSL server key and certificate...");
4377 snprintf(keychain
, sizeof(keychain
), "k=%s", ServerCertificate
);
4379 argv
[0] = "certtool";
4384 cupsdLoadEnv(envp
, MAX_ENV
);
4386 infofd
= open(infofile
, O_RDONLY
);
4388 if (!cupsdStartProcess(command
, argv
, envp
, infofd
, -1, -1, -1, -1, 1, NULL
,
4399 while (waitpid(pid
, &status
, 0) < 0)
4406 cupsdFinishProcess(pid
, command
, sizeof(command
));
4410 if (WIFEXITED(status
))
4411 cupsdLogMessage(CUPSD_LOG_ERROR
,
4412 "Unable to create SSL server key and certificate - "
4413 "the certtool command stopped with status %d!",
4414 WEXITSTATUS(status
));
4416 cupsdLogMessage(CUPSD_LOG_ERROR
,
4417 "Unable to create SSL server key and certificate - "
4418 "the certtool command crashed on signal %d!",
4423 cupsdLogMessage(CUPSD_LOG_INFO
,
4424 "Created SSL server certificate file \"%s\"...",
4432 #endif /* HAVE_LIBSSL && HAVE_WAITPID */
4434 #endif /* HAVE_SSL */
4438 * 'pipe_command()' - Pipe the output of a command to the remote client.
4441 static int /* O - Process ID */
4442 pipe_command(cupsd_client_t
*con
, /* I - Client connection */
4443 int infile
, /* I - Standard input for command */
4444 int *outfile
, /* O - Standard output for command */
4445 char *command
, /* I - Command to run */
4446 char *options
, /* I - Options for command */
4447 int root
) /* I - Run as root? */
4449 int i
; /* Looping var */
4450 int pid
; /* Process ID */
4451 char *commptr
, /* Command string pointer */
4452 commch
; /* Command string character */
4453 char *uriptr
; /* URI string pointer */
4454 int fds
[2]; /* Pipe FDs */
4455 int argc
; /* Number of arguments */
4456 int envc
; /* Number of environment variables */
4457 char argbuf
[10240], /* Argument buffer */
4458 *argv
[100], /* Argument strings */
4459 *envp
[MAX_ENV
+ 20]; /* Environment variables */
4460 char auth_type
[256], /* CUPSD_AUTH_TYPE environment variable */
4461 content_length
[1024], /* CONTENT_LENGTH environment variable */
4462 content_type
[1024], /* CONTENT_TYPE environment variable */
4463 http_cookie
[32768], /* HTTP_COOKIE environment variable */
4464 http_referer
[1024], /* HTTP_REFERER environment variable */
4465 http_user_agent
[1024], /* HTTP_USER_AGENT environment variable */
4466 lang
[1024], /* LANG environment variable */
4467 path_info
[1024], /* PATH_INFO environment variable */
4468 remote_addr
[1024], /* REMOTE_ADDR environment variable */
4469 remote_host
[1024], /* REMOTE_HOST environment variable */
4470 remote_user
[1024], /* REMOTE_USER environment variable */
4471 script_filename
[1024], /* SCRIPT_FILENAME environment variable */
4472 script_name
[1024], /* SCRIPT_NAME environment variable */
4473 server_name
[1024], /* SERVER_NAME environment variable */
4474 server_port
[1024]; /* SERVER_PORT environment variable */
4475 ipp_attribute_t
*attr
; /* attributes-natural-language attribute */
4477 krb5_ccache ccache
= NULL
; /* Kerberos credentials */
4478 # if defined(HAVE_KRB5_CC_NEW_UNIQUE) || defined(HAVE_HEIMDAL)
4479 char krb5ccname
[1024]; /* KRB5CCNAME environment variable */
4480 # endif /* HAVE_KRB5_CC_NEW_UNIQUE || HAVE_HEIMDAL */
4481 #endif /* HAVE_GSSAPI */
4485 * Parse a copy of the options string, which is of the form:
4487 * argument+argument+argument
4488 * ?argument+argument+argument
4489 * param=value¶m=value
4490 * ?param=value¶m=value
4491 * /name?argument+argument+argument
4492 * /name?param=value¶m=value
4494 * If the string contains an "=" character after the initial name,
4495 * then we treat it as a HTTP GET form request and make a copy of
4496 * the remaining string for the environment variable.
4498 * The string is always parsed out as command-line arguments, to
4499 * be consistent with Apache...
4502 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4503 "pipe_command: command=\"%s\", options=\"%s\"",
4504 command
, options
? options
: "(null)");
4509 strlcpy(argbuf
, options
, sizeof(argbuf
));
4513 if (argbuf
[0] == '/')
4516 * Found some trailing path information, set PATH_INFO...
4519 if ((commptr
= strchr(argbuf
, '?')) == NULL
)
4520 commptr
= argbuf
+ strlen(argbuf
);
4524 snprintf(path_info
, sizeof(path_info
), "PATH_INFO=%s", argbuf
);
4530 path_info
[0] = '\0';
4532 if (*commptr
== ' ')
4536 if (*commptr
== '?' && con
->operation
== HTTP_GET
&& !con
->query_string
)
4539 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", commptr
);
4546 argv
[argc
++] = commptr
;
4548 for (; *commptr
&& argc
< 99; commptr
++)
4551 * Break arguments whenever we see a + or space...
4554 if (*commptr
== ' ' || *commptr
== '+')
4556 while (*commptr
== ' ' || *commptr
== '+')
4560 * If we don't have a blank string, save it as another argument...
4565 argv
[argc
] = commptr
;
4571 else if (*commptr
== '%' && isxdigit(commptr
[1] & 255) &&
4572 isxdigit(commptr
[2] & 255))
4575 * Convert the %xx notation to the individual character.
4578 if (commptr
[1] >= '0' && commptr
[1] <= '9')
4579 *commptr
= (commptr
[1] - '0') << 4;
4581 *commptr
= (tolower(commptr
[1]) - 'a' + 10) << 4;
4583 if (commptr
[2] >= '0' && commptr
[2] <= '9')
4584 *commptr
|= commptr
[2] - '0';
4586 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
4588 _cups_strcpy(commptr
+ 1, commptr
+ 3);
4591 * Check for a %00 and break if that is the case...
4603 * Setup the environment variables as needed...
4606 if (con
->username
[0])
4608 snprintf(auth_type
, sizeof(auth_type
), "CUPSD_AUTH_TYPE=%s",
4609 httpGetField(HTTP(con
), HTTP_FIELD_AUTHORIZATION
));
4611 if ((uriptr
= strchr(auth_type
+ 10, ' ')) != NULL
)
4615 auth_type
[0] = '\0';
4618 (attr
= ippFindAttribute(con
->request
, "attributes-natural-language",
4619 IPP_TAG_LANGUAGE
)) != NULL
)
4621 switch (strlen(attr
->values
[0].string
.text
))
4625 * This is an unknown or badly formatted language code; use
4626 * the POSIX locale...
4629 strcpy(lang
, "LANG=C");
4634 * Just the language code (ll)...
4637 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8",
4638 attr
->values
[0].string
.text
);
4643 * Language and country code (ll-cc)...
4646 snprintf(lang
, sizeof(lang
), "LANG=%c%c_%c%c.UTF8",
4647 attr
->values
[0].string
.text
[0],
4648 attr
->values
[0].string
.text
[1],
4649 toupper(attr
->values
[0].string
.text
[3] & 255),
4650 toupper(attr
->values
[0].string
.text
[4] & 255));
4654 else if (con
->language
)
4655 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8", con
->language
->language
);
4657 strcpy(lang
, "LANG=C");
4659 strcpy(remote_addr
, "REMOTE_ADDR=");
4660 httpAddrString(con
->http
.hostaddr
, remote_addr
+ 12,
4661 sizeof(remote_addr
) - 12);
4663 snprintf(remote_host
, sizeof(remote_host
), "REMOTE_HOST=%s",
4664 con
->http
.hostname
);
4666 snprintf(script_name
, sizeof(script_name
), "SCRIPT_NAME=%s", con
->uri
);
4667 if ((uriptr
= strchr(script_name
, '?')) != NULL
)
4670 snprintf(script_filename
, sizeof(script_filename
), "SCRIPT_FILENAME=%s%s",
4671 DocumentRoot
, script_name
+ 12);
4673 sprintf(server_port
, "SERVER_PORT=%d", con
->serverport
);
4675 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
4678 envc
= cupsdLoadEnv(envp
, (int)(sizeof(envp
) / sizeof(envp
[0])));
4681 envp
[envc
++] = auth_type
;
4683 envp
[envc
++] = lang
;
4684 envp
[envc
++] = "REDIRECT_STATUS=1";
4685 envp
[envc
++] = "GATEWAY_INTERFACE=CGI/1.1";
4686 envp
[envc
++] = server_name
;
4687 envp
[envc
++] = server_port
;
4688 envp
[envc
++] = remote_addr
;
4689 envp
[envc
++] = remote_host
;
4690 envp
[envc
++] = script_name
;
4691 envp
[envc
++] = script_filename
;
4694 envp
[envc
++] = path_info
;
4696 if (con
->username
[0])
4698 snprintf(remote_user
, sizeof(remote_user
), "REMOTE_USER=%s", con
->username
);
4700 envp
[envc
++] = remote_user
;
4703 * Save Kerberos credentials, if any...
4707 if (con
->gss_have_creds
)
4709 # if !defined(HAVE_KRB5_CC_NEW_UNIQUE) && !defined(HAVE_HEIMDAL)
4710 cupsdLogMessage(CUPSD_LOG_INFO
,
4711 "Sorry, your version of Kerberos does not support "
4712 "delegated credentials!");
4715 krb5_error_code error
; /* Kerberos error code */
4716 OM_uint32 major_status
, /* Major status code */
4717 minor_status
; /* Minor status code */
4718 krb5_principal principal
; /* Kerberos principal */
4723 * If the weak-linked GSSAPI/Kerberos library is not present, don't try
4727 if (krb5_init_context
!= NULL
)
4729 # endif /* __APPLE__ */
4731 if (!KerberosInitialized
)
4734 * Setup a Kerberos context for the scheduler to use...
4737 KerberosInitialized
= 1;
4739 if (krb5_init_context(&KerberosContext
))
4741 KerberosContext
= NULL
;
4743 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to initialize Kerberos context");
4748 * We MUST create a file-based cache because memory-based caches are
4749 * only valid for the current process/address space.
4751 * Due to various bugs/features in different versions of Kerberos, we
4752 * need either the krb5_cc_new_unique() function or Heimdal's version
4753 * of krb5_cc_gen_new() to create a new FILE: credential cache that
4754 * can be passed to the backend. These functions create a temporary
4755 * file (typically in /tmp) containing the cached credentials, which
4756 * are removed when we have successfully printed a job.
4759 if (KerberosContext
)
4761 # ifdef HAVE_KRB5_CC_NEW_UNIQUE
4762 if ((error
= krb5_cc_new_unique(KerberosContext
, "FILE", NULL
,
4764 # else /* HAVE_HEIMDAL */
4765 if ((error
= krb5_cc_gen_new(KerberosContext
, &krb5_fcc_ops
,
4767 # endif /* HAVE_KRB5_CC_NEW_UNIQUE */
4769 cupsdLogMessage(CUPSD_LOG_ERROR
,
4770 "Unable to create new credentials cache (%d/%s)",
4771 error
, strerror(errno
));
4774 else if ((error
= krb5_parse_name(KerberosContext
, con
->username
,
4777 cupsdLogMessage(CUPSD_LOG_ERROR
,
4778 "Unable to parse kerberos username (%d/%s)", error
,
4780 krb5_cc_destroy(KerberosContext
, ccache
);
4783 else if ((error
= krb5_cc_initialize(KerberosContext
, ccache
,
4786 cupsdLogMessage(CUPSD_LOG_ERROR
,
4787 "Unable to initialize credentials cache (%d/%s)", error
,
4789 krb5_cc_destroy(KerberosContext
, ccache
);
4790 krb5_free_principal(KerberosContext
, principal
);
4795 krb5_free_principal(KerberosContext
, principal
);
4798 * Copy the user's credentials to the new cache file...
4801 major_status
= gss_krb5_copy_ccache(&minor_status
,
4802 con
->gss_delegated_cred
, ccache
);
4804 if (GSS_ERROR(major_status
))
4806 cupsdLogGSSMessage(CUPSD_LOG_ERROR
, major_status
, minor_status
,
4807 "Unable to import client credentials cache");
4808 krb5_cc_destroy(KerberosContext
, ccache
);
4814 * Add the KRB5CCNAME environment variable to the job so that the
4815 * backend can use the credentials when printing.
4818 snprintf(krb5ccname
, sizeof(krb5ccname
), "KRB5CCNAME=FILE:%s",
4819 krb5_cc_get_name(KerberosContext
, ccache
));
4820 envp
[envc
++] = krb5ccname
;
4823 chown(krb5_cc_get_name(KerberosContext
, ccache
), User
, Group
);
4829 # endif /* __APPLE__ */
4830 # endif /* HAVE_KRB5_CC_NEW_UNIQUE || HAVE_HEIMDAL */
4832 #endif /* HAVE_GSSAPI */
4835 if (con
->http
.version
== HTTP_1_1
)
4836 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.1";
4837 else if (con
->http
.version
== HTTP_1_0
)
4838 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.0";
4840 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/0.9";
4842 if (con
->http
.cookie
)
4844 snprintf(http_cookie
, sizeof(http_cookie
), "HTTP_COOKIE=%s",
4846 envp
[envc
++] = http_cookie
;
4849 if (con
->http
.fields
[HTTP_FIELD_USER_AGENT
][0])
4851 snprintf(http_user_agent
, sizeof(http_user_agent
), "HTTP_USER_AGENT=%s",
4852 con
->http
.fields
[HTTP_FIELD_USER_AGENT
]);
4853 envp
[envc
++] = http_user_agent
;
4856 if (con
->http
.fields
[HTTP_FIELD_REFERER
][0])
4858 snprintf(http_referer
, sizeof(http_referer
), "HTTP_REFERER=%s",
4859 con
->http
.fields
[HTTP_FIELD_REFERER
]);
4860 envp
[envc
++] = http_referer
;
4863 if (con
->operation
== HTTP_GET
)
4865 envp
[envc
++] = "REQUEST_METHOD=GET";
4867 if (con
->query_string
)
4870 * Add GET form variables after ?...
4873 envp
[envc
++] = con
->query_string
;
4876 envp
[envc
++] = "QUERY_STRING=";
4880 sprintf(content_length
, "CONTENT_LENGTH=" CUPS_LLFMT
,
4881 CUPS_LLCAST con
->bytes
);
4882 snprintf(content_type
, sizeof(content_type
), "CONTENT_TYPE=%s",
4883 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
4885 envp
[envc
++] = "REQUEST_METHOD=POST";
4886 envp
[envc
++] = content_length
;
4887 envp
[envc
++] = content_type
;
4891 * Tell the CGI if we are using encryption...
4895 envp
[envc
++] = "HTTPS=ON";
4898 * Terminate the environment array...
4903 if (LogLevel
== CUPSD_LOG_DEBUG2
)
4905 for (i
= 0; i
< argc
; i
++)
4906 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4907 "pipe_command: argv[%d] = \"%s\"", i
, argv
[i
]);
4908 for (i
= 0; i
< envc
; i
++)
4909 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4910 "pipe_command: envp[%d] = \"%s\"", i
, envp
[i
]);
4914 * Create a pipe for the output...
4917 if (cupsdOpenPipe(fds
))
4919 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to create pipes for CGI %s - %s",
4920 argv
[0], strerror(errno
));
4925 * Then execute the command...
4928 if (cupsdStartProcess(command
, argv
, envp
, infile
, fds
[1], CGIPipes
[1],
4929 -1, -1, root
, DefaultProfile
, &pid
) < 0)
4932 * Error - can't fork!
4935 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to fork for CGI %s - %s", argv
[0],
4938 cupsdClosePipe(fds
);
4944 * Fork successful - return the PID...
4947 if (con
->username
[0])
4949 cupsdAddCert(pid
, con
->username
, ccache
);
4951 cupsdAddCert(pid
, con
->username
, NULL
);
4952 #endif /* HAVE_GSSAPI */
4954 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[CGI] %s started - PID = %d",
4966 * 'write_file()' - Send a file via HTTP.
4969 static int /* O - 0 on failure, 1 on success */
4970 write_file(cupsd_client_t
*con
, /* I - Client connection */
4971 http_status_t code
, /* I - HTTP status */
4972 char *filename
, /* I - Filename */
4973 char *type
, /* I - File type */
4974 struct stat
*filestats
) /* O - File information */
4976 con
->file
= open(filename
, O_RDONLY
);
4978 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "write_file: %d file=%d", con
->http
.fd
,
4984 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
4988 if (!cupsdSendHeader(con
, code
, type
, CUPSD_AUTH_NONE
))
4991 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
4992 httpGetDateString(filestats
->st_mtime
)) < 0)
4994 if (httpPrintf(HTTP(con
), "Content-Length: " CUPS_LLFMT
"\r\n",
4995 CUPS_LLCAST filestats
->st_size
) < 0)
4997 if (httpPrintf(HTTP(con
), "\r\n") < 0)
5000 if (cupsdFlushHeader(con
) < 0)
5003 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
5004 con
->http
.data_remaining
= filestats
->st_size
;
5006 if (con
->http
.data_remaining
<= INT_MAX
)
5007 con
->http
._data_remaining
= con
->http
.data_remaining
;
5009 con
->http
._data_remaining
= INT_MAX
;
5011 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
,
5012 (cupsd_selfunc_t
)cupsdWriteClient
, con
);
5019 * 'write_pipe()' - Flag that data is available on the CGI pipe.
5023 write_pipe(cupsd_client_t
*con
) /* I - Client connection */
5025 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "write_pipe: CGI output on fd %d...",
5028 con
->file_ready
= 1;
5030 cupsdRemoveSelect(con
->file
);
5031 cupsdAddSelect(con
->http
.fd
, NULL
, (cupsd_selfunc_t
)cupsdWriteClient
, con
);
5036 * End of "$Id: client.c 7950 2008-09-17 00:21:59Z mike $".