2 * "$Id: client.c 7673 2008-06-18 22:31:26Z mike $"
4 * Client routines for the Common UNIX Printing System (CUPS) scheduler.
6 * Copyright 2007-2008 by Apple Inc.
7 * Copyright 1997-2007 by Easy Software Products, all rights reserved.
9 * This file contains Kerberos support code, copyright 2006 by
12 * These coded instructions, statements, and computer programs are the
13 * property of Apple Inc. and are protected by Federal copyright
14 * law. Distribution and use rights are outlined in the file "LICENSE.txt"
15 * which should have been included with this file. If this file is
16 * file is missing or damaged, see the license at "http://www.cups.org/".
20 * cupsdAcceptClient() - Accept a new client.
21 * cupsdCloseAllClients() - Close all remote clients immediately.
22 * cupsdCloseClient() - Close a remote client.
23 * cupsdFlushHeader() - Flush the header fields to the client.
24 * cupsdReadClient() - Read data from a client.
25 * cupsdSendCommand() - Send output from a command via HTTP.
26 * cupsdSendError() - Send an error message via HTTP.
27 * cupsdSendHeader() - Send an HTTP request.
28 * cupsdUpdateCGI() - Read status messages from CGI scripts and programs.
29 * cupsdWriteClient() - Write data to a client as needed.
30 * check_if_modified() - Decode an "If-Modified-Since" line.
31 * compare_clients() - Compare two client connections.
32 * data_ready() - Check whether data is available from a client.
33 * encrypt_client() - Enable encryption for the client...
34 * get_cdsa_certificate() - Convert a keychain name into the CFArrayRef
35 * required by SSLSetCertificate.
36 * get_file() - Get a filename and state info.
37 * install_conf_file() - Install a configuration file.
38 * is_cgi() - Is the resource a CGI script/program?
39 * is_path_absolute() - Is a path absolute and free of relative elements.
40 * make_certificate() - Make a self-signed SSL/TLS certificate.
41 * pipe_command() - Pipe the output of a command to the remote client.
42 * write_file() - Send a file via HTTP.
43 * write_pipe() - Flag that data is available on the CGI pipe.
47 * Include necessary headers...
53 # include <Security/Security.h>
54 # ifdef HAVE_SECIDENTITYSEARCHPRIV_H
55 # include <Security/SecIdentitySearchPriv.h>
56 # else /* Declare prototype for function in that header... */
57 extern OSStatus
SecIdentitySearchCreateWithPolicy(SecPolicyRef policy
,
58 CFStringRef idString
, CSSM_KEYUSE keyUsage
,
59 CFTypeRef keychainOrArray
,
60 Boolean returnOnlyValidIdentities
,
61 SecIdentitySearchRef
* searchRef
);
62 # endif /* HAVE_SECIDENTITYSEARCHPRIV_H */
63 # ifdef HAVE_SECPOLICYPRIV_H
64 # include <Security/SecPolicyPriv.h>
65 # else /* Declare prototype for function in that header... */
66 extern OSStatus
SecPolicySetValue(SecPolicyRef policyRef
,
67 const CSSM_DATA
*value
);
68 # endif /* HAVE_SECPOLICYPRIV_H */
69 # ifdef HAVE_SECBASEPRIV_H
70 # include <Security/SecBasePriv.h>
71 # else /* Declare prototype for function in that header... */
72 extern const char *cssmErrorString(int error
);
73 # endif /* HAVE_SECBASEPRIV_H */
74 #endif /* HAVE_CDSASSL */
77 # include <gnutls/x509.h>
78 #endif /* HAVE_GNUTLS */
82 #endif /* HAVE_TCPD_H */
89 static int check_if_modified(cupsd_client_t
*con
,
90 struct stat
*filestats
);
91 static int compare_clients(cupsd_client_t
*a
, cupsd_client_t
*b
,
93 static int data_ready(cupsd_client_t
*con
);
95 static int encrypt_client(cupsd_client_t
*con
);
98 static CFArrayRef
get_cdsa_certificate(cupsd_client_t
*con
);
99 #endif /* HAVE_CDSASSL */
100 static char *get_file(cupsd_client_t
*con
, struct stat
*filestats
,
101 char *filename
, int len
);
102 static http_status_t
install_conf_file(cupsd_client_t
*con
);
103 static int is_cgi(cupsd_client_t
*con
, const char *filename
,
104 struct stat
*filestats
, mime_type_t
*type
);
105 static int is_path_absolute(const char *path
);
107 static int make_certificate(cupsd_client_t
*con
);
108 #endif /* HAVE_SSL */
109 static int pipe_command(cupsd_client_t
*con
, int infile
, int *outfile
,
110 char *command
, char *options
, int root
);
111 static int write_file(cupsd_client_t
*con
, http_status_t code
,
112 char *filename
, char *type
,
113 struct stat
*filestats
);
114 static void write_pipe(cupsd_client_t
*con
);
118 * 'cupsdAcceptClient()' - Accept a new client.
122 cupsdAcceptClient(cupsd_listener_t
*lis
)/* I - Listener socket */
124 int count
; /* Count of connections on a host */
125 int val
; /* Parameter value */
126 cupsd_client_t
*con
, /* New client pointer */
127 *tempcon
; /* Temporary client pointer */
128 http_addrlist_t
*addrlist
, /* List of adddresses for host */
129 *addr
; /* Current address */
130 socklen_t addrlen
; /* Length of address */
131 char *hostname
; /* Hostname for address */
132 http_addr_t temp
; /* Temporary address variable */
133 static time_t last_dos
= 0; /* Time of last DoS attack */
135 struct request_info wrap_req
; /* TCP wrappers request information */
136 #endif /* HAVE_TCPD_H */
139 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
140 "cupsdAcceptClient(lis=%p) %d Clients = %d",
141 lis
, lis
->fd
, cupsArrayCount(Clients
));
144 * Make sure we don't have a full set of clients already...
147 if (cupsArrayCount(Clients
) == MaxClients
)
151 * Get a pointer to the next available client...
155 Clients
= cupsArrayNew(NULL
, NULL
);
159 cupsdLogMessage(CUPSD_LOG_ERROR
,
160 "Unable to allocate memory for clients array!");
161 cupsdPauseListening();
166 ActiveClients
= cupsArrayNew((cups_array_func_t
)compare_clients
, NULL
);
170 cupsdLogMessage(CUPSD_LOG_ERROR
,
171 "Unable to allocate memory for active clients array!");
172 cupsdPauseListening();
176 if ((con
= calloc(1, sizeof(cupsd_client_t
))) == NULL
)
178 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to allocate memory for client!");
179 cupsdPauseListening();
183 con
->http
.activity
= time(NULL
);
185 con
->http
.hostaddr
= &(con
->clientaddr
);
188 * Accept the client and get the remote address...
191 addrlen
= sizeof(http_addr_t
);
193 if ((con
->http
.fd
= accept(lis
->fd
, (struct sockaddr
*)con
->http
.hostaddr
,
196 if (errno
== ENFILE
|| errno
== EMFILE
)
197 cupsdPauseListening();
199 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to accept client connection - %s.",
207 if (lis
->address
.addr
.sa_family
== AF_INET6
)
210 * Save the connected port number...
213 con
->http
.hostaddr
->ipv6
.sin6_port
= lis
->address
.ipv6
.sin6_port
;
216 * Convert IPv4 over IPv6 addresses (::ffff:n.n.n.n) to IPv4 forms we
217 * can more easily use...
220 if (con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[0] == 0 &&
221 con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[1] == 0 &&
222 ntohl(con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[2]) == 0xffff)
223 con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[2] = 0;
226 #endif /* AF_INET6 */
227 if (lis
->address
.addr
.sa_family
== AF_INET
)
228 con
->http
.hostaddr
->ipv4
.sin_port
= lis
->address
.ipv4
.sin_port
;
231 * Check the number of clients on the same address...
234 for (count
= 0, tempcon
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
236 tempcon
= (cupsd_client_t
*)cupsArrayNext(Clients
))
237 if (httpAddrEqual(tempcon
->http
.hostaddr
, con
->http
.hostaddr
))
240 if (count
>= MaxClientsPerHost
)
244 if (count
>= MaxClientsPerHost
)
246 if ((time(NULL
) - last_dos
) >= 60)
248 last_dos
= time(NULL
);
249 cupsdLogMessage(CUPSD_LOG_WARN
,
250 "Possible DoS attack - more than %d clients connecting "
253 httpAddrString(con
->http
.hostaddr
, con
->http
.hostname
,
254 sizeof(con
->http
.hostname
)));
258 closesocket(con
->http
.fd
);
268 * Get the hostname or format the IP address as needed...
271 if (httpAddrLocalhost(con
->http
.hostaddr
))
274 * Map accesses from the loopback interface to "localhost"...
277 strlcpy(con
->http
.hostname
, "localhost", sizeof(con
->http
.hostname
));
278 hostname
= con
->http
.hostname
;
283 * Map accesses from the same host to the server name.
286 for (addr
= ServerAddrs
; addr
; addr
= addr
->next
)
287 if (httpAddrEqual(con
->http
.hostaddr
, &(addr
->addr
)))
292 strlcpy(con
->http
.hostname
, ServerName
, sizeof(con
->http
.hostname
));
293 hostname
= con
->http
.hostname
;
295 else if (HostNameLookups
)
296 hostname
= httpAddrLookup(con
->http
.hostaddr
, con
->http
.hostname
,
297 sizeof(con
->http
.hostname
));
301 httpAddrString(con
->http
.hostaddr
, con
->http
.hostname
,
302 sizeof(con
->http
.hostname
));
306 if (hostname
== NULL
&& HostNameLookups
== 2)
309 * Can't have an unresolved IP address with double-lookups enabled...
312 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
313 "cupsdAcceptClient: Closing connection %d...",
317 closesocket(con
->http
.fd
);
322 cupsdLogMessage(CUPSD_LOG_WARN
,
323 "Name lookup failed - connection from %s closed!",
330 if (HostNameLookups
== 2)
333 * Do double lookups as needed...
336 if ((addrlist
= httpAddrGetList(con
->http
.hostname
, AF_UNSPEC
, NULL
))
340 * See if the hostname maps to the same IP address...
343 for (addr
= addrlist
; addr
; addr
= addr
->next
)
344 if (httpAddrEqual(con
->http
.hostaddr
, &(addr
->addr
)))
350 httpAddrFreeList(addrlist
);
355 * Can't have a hostname that doesn't resolve to the same IP address
356 * with double-lookups enabled...
359 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
360 "cupsdAcceptClient: Closing connection %d...",
364 closesocket(con
->http
.fd
);
369 cupsdLogMessage(CUPSD_LOG_WARN
,
370 "IP lookup failed - connection from %s closed!",
379 * See if the connection is denied by TCP wrappers...
382 request_init(&wrap_req
, RQ_DAEMON
, "cupsd", RQ_FILE
, con
->http
.fd
, NULL
);
385 if (!hosts_access(&wrap_req
))
387 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
388 "cupsdAcceptClient: Closing connection %d...",
392 closesocket(con
->http
.fd
);
397 cupsdLogMessage(CUPSD_LOG_WARN
,
398 "Connection from %s refused by /etc/hosts.allow and "
399 "/etc/hosts.deny rules.", con
->http
.hostname
);
403 #endif /* HAVE_TCPD_H */
406 if (con
->http
.hostaddr
->addr
.sa_family
== AF_INET6
)
407 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdAcceptClient: %d from %s:%d (IPv6)",
408 con
->http
.fd
, con
->http
.hostname
,
409 ntohs(con
->http
.hostaddr
->ipv6
.sin6_port
));
411 #endif /* AF_INET6 */
413 if (con
->http
.hostaddr
->addr
.sa_family
== AF_LOCAL
)
414 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdAcceptClient: %d from %s (Domain)",
415 con
->http
.fd
, con
->http
.hostname
);
417 #endif /* AF_LOCAL */
418 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdAcceptClient: %d from %s:%d (IPv4)",
419 con
->http
.fd
, con
->http
.hostname
,
420 ntohs(con
->http
.hostaddr
->ipv4
.sin_port
));
423 * Get the local address the client connected to...
426 addrlen
= sizeof(temp
);
427 if (getsockname(con
->http
.fd
, (struct sockaddr
*)&temp
, &addrlen
))
429 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to get local address - %s",
432 strcpy(con
->servername
, "localhost");
433 con
->serverport
= LocalPort
;
438 if (temp
.addr
.sa_family
== AF_INET6
)
440 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
441 con
->serverport
= ntohs(lis
->address
.ipv6
.sin6_port
);
444 #endif /* AF_INET6 */
445 if (temp
.addr
.sa_family
== AF_INET
)
447 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
448 con
->serverport
= ntohs(lis
->address
.ipv4
.sin_port
);
452 strcpy(con
->servername
, "localhost");
453 con
->serverport
= LocalPort
;
457 cupsArrayAdd(Clients
, con
);
459 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
460 "cupsdAcceptClient: %d connected to server on %s:%d",
461 con
->http
.fd
, con
->servername
, con
->serverport
);
464 * Using TCP_NODELAY improves responsiveness, especially on systems
465 * with a slow loopback interface... Since we write large buffers
466 * when sending print files and requests, there shouldn't be any
467 * performance penalty for this...
471 setsockopt(con
->http
.fd
, IPPROTO_TCP
, TCP_NODELAY
, &val
, sizeof(val
));
474 * Close this file on all execs...
477 fcntl(con
->http
.fd
, F_SETFD
, fcntl(con
->http
.fd
, F_GETFD
) | FD_CLOEXEC
);
480 * Add the socket to the select() input mask.
483 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
486 * Temporarily suspend accept()'s until we lose a client...
489 if (cupsArrayCount(Clients
) == MaxClients
)
490 cupsdPauseListening();
494 * See if we are connecting on a secure port...
497 if (lis
->encryption
== HTTP_ENCRYPT_ALWAYS
)
500 * https connection; go secure...
503 con
->http
.encryption
= HTTP_ENCRYPT_ALWAYS
;
505 if (!encrypt_client(con
))
506 cupsdCloseClient(con
);
510 #endif /* HAVE_SSL */
515 * 'cupsdCloseAllClients()' - Close all remote clients immediately.
519 cupsdCloseAllClients(void)
521 cupsd_client_t
*con
; /* Current client */
524 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
526 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
527 cupsdCloseClient(con
);
532 * 'cupsdCloseClient()' - Close a remote client.
535 int /* O - 1 if partial close, 0 if fully closed */
536 cupsdCloseClient(cupsd_client_t
*con
) /* I - Client to close */
538 int partial
; /* Do partial close for SSL? */
540 SSL_CTX
*context
; /* Context for encryption */
541 SSL
*conn
; /* Connection for encryption */
542 unsigned long error
; /* Error code */
543 #elif defined(HAVE_GNUTLS)
544 http_tls_t
*conn
; /* TLS connection information */
545 int error
; /* Error code */
546 gnutls_certificate_server_credentials
*credentials
;
547 /* TLS credentials */
548 # elif defined(HAVE_CDSASSL)
549 http_tls_t
*conn
; /* CDSA connection information */
550 #endif /* HAVE_LIBSSL */
553 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdCloseClient: %d", con
->http
.fd
);
556 * Flush pending writes before closing...
559 httpFlushWrite(HTTP(con
));
565 * Shutdown encryption as needed...
573 conn
= (SSL
*)(con
->http
.tls
);
574 context
= SSL_get_SSL_CTX(conn
);
576 switch (SSL_shutdown(conn
))
579 cupsdLogMessage(CUPSD_LOG_DEBUG
,
580 "SSL shutdown successful!");
583 cupsdLogMessage(CUPSD_LOG_ERROR
,
584 "Fatal error during SSL shutdown!");
586 while ((error
= ERR_get_error()) != 0)
587 cupsdLogMessage(CUPSD_LOG_ERROR
, "SSL shutdown failed: %s",
588 ERR_error_string(error
, NULL
));
592 SSL_CTX_free(context
);
595 # elif defined(HAVE_GNUTLS)
596 conn
= (http_tls_t
*)(con
->http
.tls
);
597 credentials
= (gnutls_certificate_server_credentials
*)(conn
->credentials
);
599 error
= gnutls_bye(conn
->session
, GNUTLS_SHUT_WR
);
602 case GNUTLS_E_SUCCESS
:
603 cupsdLogMessage(CUPSD_LOG_DEBUG
,
604 "SSL shutdown successful!");
607 cupsdLogMessage(CUPSD_LOG_ERROR
,
608 "SSL shutdown failed: %s", gnutls_strerror(error
));
612 gnutls_deinit(conn
->session
);
613 gnutls_certificate_free_credentials(*credentials
);
617 # elif defined(HAVE_CDSASSL)
618 conn
= (http_tls_t
*)(con
->http
.tls
);
620 while (SSLClose(conn
->session
) == errSSLWouldBlock
)
623 SSLDisposeContext(conn
->session
);
625 if (conn
->certsArray
)
626 CFRelease(conn
->certsArray
);
629 # endif /* HAVE_LIBSSL */
631 con
->http
.tls
= NULL
;
633 #endif /* HAVE_SSL */
635 if (con
->pipe_pid
!= 0)
638 * Stop any CGI process...
641 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
642 "cupsdCloseClient: %d Killing process ID %d...",
643 con
->http
.fd
, con
->pipe_pid
);
644 cupsdEndProcess(con
->pipe_pid
, 1);
650 cupsdRemoveSelect(con
->file
);
652 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
653 "cupsdCloseClient: %d Closing data file %d.",
654 con
->http
.fd
, con
->file
);
661 * Close the socket and clear the file from the input set for select()...
664 if (con
->http
.fd
>= 0)
666 cupsArrayRemove(ActiveClients
, con
);
672 * Only do a partial close so that the encrypted client gets everything.
675 shutdown(con
->http
.fd
, 0);
676 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
681 * Shut the socket down fully...
684 cupsdRemoveSelect(con
->http
.fd
);
696 if (con
->http
.input_set
)
697 free(con
->http
.input_set
);
699 httpClearCookie(HTTP(con
));
700 httpClearFields(HTTP(con
));
702 cupsdClearString(&con
->filename
);
703 cupsdClearString(&con
->command
);
704 cupsdClearString(&con
->options
);
705 cupsdClearString(&con
->query_string
);
709 ippDelete(con
->request
);
715 ippDelete(con
->response
);
716 con
->response
= NULL
;
721 cupsLangFree(con
->language
);
722 con
->language
= NULL
;
725 #ifdef HAVE_AUTHORIZATION_H
728 AuthorizationFree(con
->authref
, kAuthorizationFlagDefaults
);
731 #endif /* HAVE_AUTHORIZATION_H */
734 * Re-enable new client connections if we are going back under the
738 if (cupsArrayCount(Clients
) == MaxClients
)
739 cupsdResumeListening();
742 * Compact the list of clients as necessary...
745 cupsArrayRemove(Clients
, con
);
755 * 'cupsdFlushHeader()' - Flush the header fields to the client.
758 int /* I - Bytes written or -1 on error */
759 cupsdFlushHeader(cupsd_client_t
*con
) /* I - Client to flush to */
761 int bytes
= httpFlushWrite(HTTP(con
));
763 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
770 * 'cupsdReadClient()' - Read data from a client.
774 cupsdReadClient(cupsd_client_t
*con
) /* I - Client to read from */
776 char line
[32768], /* Line from client... */
777 operation
[64], /* Operation code from socket */
778 version
[64], /* HTTP version number string */
779 locale
[64], /* Locale */
780 *ptr
; /* Pointer into strings */
781 int major
, minor
; /* HTTP version numbers */
782 http_status_t status
; /* Transfer status */
783 ipp_state_t ipp_state
; /* State of IPP transfer */
784 int bytes
; /* Number of bytes to POST */
785 char *filename
; /* Name of file for GET/HEAD */
786 char buf
[1024]; /* Buffer for real filename */
787 struct stat filestats
; /* File information */
788 mime_type_t
*type
; /* MIME type of file */
789 cupsd_printer_t
*p
; /* Printer */
790 static unsigned request_id
= 0; /* Request ID for temp files */
793 status
= HTTP_CONTINUE
;
795 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
796 "cupsdReadClient: %d, used=%d, file=%d state=%d",
797 con
->http
.fd
, con
->http
.used
, con
->file
, con
->http
.state
);
801 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdReadClient: http error seen...");
802 cupsdCloseClient(con
);
810 * Automatically check for a SSL/TLS handshake...
815 if (recv(con
->http
.fd
, buf
, 1, MSG_PEEK
) == 1 &&
816 (!buf
[0] || !strchr("DGHOPT", buf
[0])))
819 * Encrypt this connection...
822 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
823 "cupsdReadClient: Saw first byte %02X, auto-negotiating SSL/TLS session...",
826 if (!encrypt_client(con
))
827 cupsdCloseClient(con
);
832 #endif /* HAVE_SSL */
834 switch (con
->http
.state
)
838 * See if we've received a request line...
841 if (httpGets(line
, sizeof(line
) - 1, HTTP(con
)) == NULL
)
843 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
844 "cupsdReadClient: httpGets returned EOF...");
845 cupsdCloseClient(con
);
850 * Ignore blank request lines...
857 * Clear other state variables...
860 httpClearFields(HTTP(con
));
862 con
->http
.activity
= time(NULL
);
863 con
->http
.version
= HTTP_1_0
;
864 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
865 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
866 con
->http
.data_remaining
= 0;
867 con
->http
._data_remaining
= 0;
868 con
->operation
= HTTP_WAITING
;
873 con
->username
[0] = '\0';
874 con
->password
[0] = '\0';
877 cupsdClearString(&con
->command
);
878 cupsdClearString(&con
->options
);
879 cupsdClearString(&con
->query_string
);
883 ippDelete(con
->request
);
889 ippDelete(con
->response
);
890 con
->response
= NULL
;
895 cupsLangFree(con
->language
);
896 con
->language
= NULL
;
900 con
->gss_have_creds
= 0;
901 #endif /* HAVE_GSSAPI */
904 * Grab the request line...
907 switch (sscanf(line
, "%63s%1023s%63s", operation
, con
->uri
, version
))
912 cupsdLogMessage(CUPSD_LOG_ERROR
,
913 "Bad request line \"%s\" from %s!", line
,
915 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
916 cupsdCloseClient(con
);
920 con
->http
.version
= HTTP_0_9
;
923 if (sscanf(version
, "HTTP/%d.%d", &major
, &minor
) != 2)
925 cupsdLogMessage(CUPSD_LOG_ERROR
,
926 "Bad request line \"%s\" from %s!", line
,
928 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
929 cupsdCloseClient(con
);
935 con
->http
.version
= (http_version_t
)(major
* 100 + minor
);
936 if (con
->http
.version
== HTTP_1_1
&& KeepAlive
)
937 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
939 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
943 cupsdSendError(con
, HTTP_NOT_SUPPORTED
, CUPSD_AUTH_NONE
);
944 cupsdCloseClient(con
);
951 * Handle full URLs in the request line...
954 if (strcmp(con
->uri
, "*"))
956 char method
[HTTP_MAX_URI
], /* Method/scheme */
957 userpass
[HTTP_MAX_URI
], /* Username:password */
958 hostname
[HTTP_MAX_URI
], /* Hostname */
959 resource
[HTTP_MAX_URI
]; /* Resource path */
960 int port
; /* Port number */
964 * Separate the URI into its components...
967 httpSeparateURI(HTTP_URI_CODING_MOST
, con
->uri
,
968 method
, sizeof(method
),
969 userpass
, sizeof(userpass
),
970 hostname
, sizeof(hostname
), &port
,
971 resource
, sizeof(resource
));
974 * Only allow URIs with the servername, localhost, or an IP
978 if (strcmp(method
, "file") &&
979 strcasecmp(hostname
, ServerName
) &&
980 strcasecmp(hostname
, "localhost") &&
981 !isdigit(hostname
[0]))
984 * Nope, we don't do proxies...
987 cupsdLogMessage(CUPSD_LOG_ERROR
, "Bad URI \"%s\" in request!",
989 cupsdSendError(con
, HTTP_METHOD_NOT_ALLOWED
, CUPSD_AUTH_NONE
);
990 cupsdCloseClient(con
);
995 * Copy the resource portion back into the URI; both resource and
996 * con->uri are HTTP_MAX_URI bytes in size...
999 strcpy(con
->uri
, resource
);
1003 * Process the request...
1006 if (!strcmp(operation
, "GET"))
1007 con
->http
.state
= HTTP_GET
;
1008 else if (!strcmp(operation
, "PUT"))
1009 con
->http
.state
= HTTP_PUT
;
1010 else if (!strcmp(operation
, "POST"))
1011 con
->http
.state
= HTTP_POST
;
1012 else if (!strcmp(operation
, "DELETE"))
1013 con
->http
.state
= HTTP_DELETE
;
1014 else if (!strcmp(operation
, "TRACE"))
1015 con
->http
.state
= HTTP_TRACE
;
1016 else if (!strcmp(operation
, "OPTIONS"))
1017 con
->http
.state
= HTTP_OPTIONS
;
1018 else if (!strcmp(operation
, "HEAD"))
1019 con
->http
.state
= HTTP_HEAD
;
1022 cupsdLogMessage(CUPSD_LOG_ERROR
, "Bad operation \"%s\"!", operation
);
1023 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
1024 cupsdCloseClient(con
);
1028 con
->start
= time(NULL
);
1029 con
->operation
= con
->http
.state
;
1031 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdReadClient: %d %s %s HTTP/%d.%d",
1032 con
->http
.fd
, operation
, con
->uri
,
1033 con
->http
.version
/ 100, con
->http
.version
% 100);
1035 con
->http
.status
= HTTP_OK
;
1037 cupsArrayAdd(ActiveClients
, con
);
1038 cupsdSetBusyState();
1048 * Parse incoming parameters until the status changes...
1051 while ((status
= httpUpdate(HTTP(con
))) == HTTP_CONTINUE
)
1052 if (!data_ready(con
))
1055 if (status
!= HTTP_OK
&& status
!= HTTP_CONTINUE
)
1057 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
1058 cupsdCloseClient(con
);
1064 break; /* Anti-compiler-warning-code */
1068 * Handle new transfers...
1071 if (status
== HTTP_OK
)
1073 if (con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
][0])
1076 * Figure out the locale from the Accept-Language and Content-Type
1080 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ',')) != NULL
)
1083 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ';')) != NULL
)
1086 if ((ptr
= strstr(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
], "charset=")) != NULL
)
1089 * Combine language and charset, and trim any extra params in the
1093 snprintf(locale
, sizeof(locale
), "%s.%s",
1094 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ptr
+ 8);
1096 if ((ptr
= strchr(locale
, ',')) != NULL
)
1100 snprintf(locale
, sizeof(locale
), "%s.%s",
1101 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], DefaultCharset
);
1103 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1104 "cupsdReadClient: %d Browser asked for language \"%s\"...",
1105 con
->http
.fd
, locale
);
1107 con
->language
= cupsLangGet(locale
);
1110 con
->language
= cupsLangGet(DefaultLocale
);
1112 cupsdAuthorize(con
);
1114 if (!strncmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Keep-Alive", 10) &&
1116 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
1118 if (!con
->http
.fields
[HTTP_FIELD_HOST
][0] &&
1119 con
->http
.version
>= HTTP_1_1
)
1122 * HTTP/1.1 and higher require the "Host:" field...
1125 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1127 cupsdCloseClient(con
);
1131 else if (con
->operation
== HTTP_OPTIONS
)
1134 * Do OPTIONS command...
1137 if (con
->best
&& con
->best
->type
!= CUPSD_AUTH_NONE
)
1139 if (!cupsdSendHeader(con
, HTTP_UNAUTHORIZED
, NULL
, CUPSD_AUTH_NONE
))
1141 cupsdCloseClient(con
);
1146 if (!strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") &&
1147 con
->http
.tls
== NULL
)
1151 * Do encryption stuff...
1154 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
, CUPSD_AUTH_NONE
))
1156 cupsdCloseClient(con
);
1160 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1161 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1162 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1163 httpPrintf(HTTP(con
), "\r\n");
1165 if (cupsdFlushHeader(con
) < 0)
1167 cupsdCloseClient(con
);
1171 if (!encrypt_client(con
))
1173 cupsdCloseClient(con
);
1177 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
1179 cupsdCloseClient(con
);
1182 #endif /* HAVE_SSL */
1185 if (!cupsdSendHeader(con
, HTTP_OK
, NULL
, CUPSD_AUTH_NONE
))
1187 cupsdCloseClient(con
);
1191 httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n");
1192 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1193 httpPrintf(HTTP(con
), "\r\n");
1195 if (cupsdFlushHeader(con
) < 0)
1197 cupsdCloseClient(con
);
1201 else if (!is_path_absolute(con
->uri
))
1204 * Protect against malicious users!
1207 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1209 cupsdCloseClient(con
);
1215 if (!strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") &&
1216 con
->http
.tls
== NULL
)
1220 * Do encryption stuff...
1223 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
, CUPSD_AUTH_NONE
))
1225 cupsdCloseClient(con
);
1229 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1230 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1231 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1232 httpPrintf(HTTP(con
), "\r\n");
1234 if (cupsdFlushHeader(con
) < 0)
1236 cupsdCloseClient(con
);
1240 if (!encrypt_client(con
))
1242 cupsdCloseClient(con
);
1246 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
1248 cupsdCloseClient(con
);
1251 #endif /* HAVE_SSL */
1254 if ((status
= cupsdIsAuthorized(con
, NULL
)) != HTTP_OK
)
1256 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1257 "cupsdReadClient: Unauthorized request for %s...",
1259 cupsdSendError(con
, status
, CUPSD_AUTH_NONE
);
1260 cupsdCloseClient(con
);
1264 if (con
->http
.expect
&&
1265 (con
->operation
== HTTP_POST
|| con
->operation
== HTTP_PUT
))
1267 if (con
->http
.expect
== HTTP_CONTINUE
)
1270 * Send 100-continue header...
1273 if (!cupsdSendHeader(con
, HTTP_CONTINUE
, NULL
, CUPSD_AUTH_NONE
))
1275 cupsdCloseClient(con
);
1282 * Send 417-expectation-failed header...
1285 if (!cupsdSendHeader(con
, HTTP_EXPECTATION_FAILED
, NULL
, CUPSD_AUTH_NONE
))
1287 cupsdCloseClient(con
);
1291 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1292 httpPrintf(HTTP(con
), "\r\n");
1294 if (cupsdFlushHeader(con
) < 0)
1296 cupsdCloseClient(con
);
1302 switch (con
->http
.state
)
1304 case HTTP_GET_SEND
:
1305 if (!strncmp(con
->uri
, "/printers/", 10) &&
1306 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1309 * Send PPD file - get the real printer name since printer
1310 * names are not case sensitive but filenames can be...
1313 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1315 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1316 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1319 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1321 cupsdCloseClient(con
);
1329 if ((!strncmp(con
->uri
, "/admin", 6) &&
1330 strncmp(con
->uri
, "/admin/conf/", 12) &&
1331 strncmp(con
->uri
, "/admin/log/", 11)) ||
1332 !strncmp(con
->uri
, "/printers", 9) ||
1333 !strncmp(con
->uri
, "/classes", 8) ||
1334 !strncmp(con
->uri
, "/help", 5) ||
1335 !strncmp(con
->uri
, "/jobs", 5))
1338 * Send CGI output...
1341 if (!strncmp(con
->uri
, "/admin", 6))
1343 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1346 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1348 else if (!strncmp(con
->uri
, "/printers", 9))
1350 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1353 if (con
->uri
[9] && con
->uri
[10])
1354 cupsdSetString(&con
->options
, con
->uri
+ 9);
1356 cupsdSetString(&con
->options
, NULL
);
1358 else if (!strncmp(con
->uri
, "/classes", 8))
1360 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1363 if (con
->uri
[8] && con
->uri
[9])
1364 cupsdSetString(&con
->options
, con
->uri
+ 8);
1366 cupsdSetString(&con
->options
, NULL
);
1368 else if (!strncmp(con
->uri
, "/jobs", 5))
1370 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1373 if (con
->uri
[5] && con
->uri
[6])
1374 cupsdSetString(&con
->options
, con
->uri
+ 5);
1376 cupsdSetString(&con
->options
, NULL
);
1380 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1383 if (con
->uri
[5] && con
->uri
[6])
1384 cupsdSetString(&con
->options
, con
->uri
+ 5);
1386 cupsdSetString(&con
->options
, NULL
);
1389 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1391 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1393 cupsdCloseClient(con
);
1398 cupsdLogRequest(con
, HTTP_OK
);
1400 if (con
->http
.version
<= HTTP_1_0
)
1401 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1403 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1404 (strchr(con
->uri
+ 12, '/') ||
1405 strlen(con
->uri
) == 12)) ||
1406 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1407 (strchr(con
->uri
+ 11, '/') ||
1408 strlen(con
->uri
) == 11)))
1411 * GET can only be done to configuration files under
1415 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1417 cupsdCloseClient(con
);
1429 if ((filename
= get_file(con
, &filestats
, buf
,
1430 sizeof(buf
))) == NULL
)
1432 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1434 cupsdCloseClient(con
);
1441 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1443 if (is_cgi(con
, filename
, &filestats
, type
))
1446 * Note: con->command and con->options were set by
1450 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1452 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1454 cupsdCloseClient(con
);
1459 cupsdLogRequest(con
, HTTP_OK
);
1461 if (con
->http
.version
<= HTTP_1_0
)
1462 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1466 if (!check_if_modified(con
, &filestats
))
1468 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1470 cupsdCloseClient(con
);
1477 strcpy(line
, "text/plain");
1479 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1481 if (!write_file(con
, HTTP_OK
, filename
, line
, &filestats
))
1483 cupsdCloseClient(con
);
1490 case HTTP_POST_RECV
:
1492 * See if the POST request includes a Content-Length field, and if
1493 * so check the length against any limits that are set...
1496 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "POST %s", con
->uri
);
1497 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "CONTENT_TYPE = %s",
1498 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
1500 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1501 MaxRequestSize
> 0 &&
1502 con
->http
.data_remaining
> MaxRequestSize
)
1505 * Request too large...
1508 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1510 cupsdCloseClient(con
);
1516 else if (con
->http
.data_remaining
< 0 ||
1517 (!con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1518 con
->http
.data_encoding
== HTTP_ENCODE_LENGTH
))
1521 * Negative content lengths are invalid!
1524 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1526 cupsdCloseClient(con
);
1534 * See what kind of POST request this is; for IPP requests the
1535 * content-type field will be "application/ipp"...
1538 if (!strcmp(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
],
1540 con
->request
= ippNew();
1541 else if ((!strncmp(con
->uri
, "/admin", 6) &&
1542 strncmp(con
->uri
, "/admin/conf/", 12) &&
1543 strncmp(con
->uri
, "/admin/log/", 11)) ||
1544 !strncmp(con
->uri
, "/printers", 9) ||
1545 !strncmp(con
->uri
, "/classes", 8) ||
1546 !strncmp(con
->uri
, "/help", 5) ||
1547 !strncmp(con
->uri
, "/jobs", 5))
1553 if (!strncmp(con
->uri
, "/admin", 6))
1555 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1558 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1560 else if (!strncmp(con
->uri
, "/printers", 9))
1562 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1565 if (con
->uri
[9] && con
->uri
[10])
1566 cupsdSetString(&con
->options
, con
->uri
+ 9);
1568 cupsdSetString(&con
->options
, NULL
);
1570 else if (!strncmp(con
->uri
, "/classes", 8))
1572 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1575 if (con
->uri
[8] && con
->uri
[9])
1576 cupsdSetString(&con
->options
, con
->uri
+ 8);
1578 cupsdSetString(&con
->options
, NULL
);
1580 else if (!strncmp(con
->uri
, "/jobs", 5))
1582 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1585 if (con
->uri
[5] && con
->uri
[6])
1586 cupsdSetString(&con
->options
, con
->uri
+ 5);
1588 cupsdSetString(&con
->options
, NULL
);
1592 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1595 if (con
->uri
[5] && con
->uri
[6])
1596 cupsdSetString(&con
->options
, con
->uri
+ 5);
1598 cupsdSetString(&con
->options
, NULL
);
1601 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1602 "cupsdReadClient: %d command=\"%s\", "
1604 con
->http
.fd
, con
->command
,
1605 con
->options
? con
->options
: "(null)");
1607 if (con
->http
.version
<= HTTP_1_0
)
1608 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1616 if ((filename
= get_file(con
, &filestats
, buf
,
1617 sizeof(buf
))) == NULL
)
1619 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1621 cupsdCloseClient(con
);
1628 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1630 if (!is_cgi(con
, filename
, &filestats
, type
))
1633 * Only POST to CGI's...
1636 if (!cupsdSendError(con
, HTTP_UNAUTHORIZED
, CUPSD_AUTH_NONE
))
1638 cupsdCloseClient(con
);
1645 case HTTP_PUT_RECV
:
1647 * Validate the resource name...
1650 if (strncmp(con
->uri
, "/admin/conf/", 12) ||
1651 strchr(con
->uri
+ 12, '/') ||
1652 strlen(con
->uri
) == 12)
1655 * PUT can only be done to configuration files under
1659 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1661 cupsdCloseClient(con
);
1669 * See if the PUT request includes a Content-Length field, and if
1670 * so check the length against any limits that are set...
1673 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "PUT %s", con
->uri
);
1674 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "CONTENT_TYPE = %s",
1675 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
1677 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1678 MaxRequestSize
> 0 &&
1679 con
->http
.data_remaining
> MaxRequestSize
)
1682 * Request too large...
1685 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1687 cupsdCloseClient(con
);
1693 else if (con
->http
.data_remaining
< 0)
1696 * Negative content lengths are invalid!
1699 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1701 cupsdCloseClient(con
);
1709 * Open a temporary file to hold the request...
1712 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
1714 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1718 cupsdLogMessage(CUPSD_LOG_ERROR
,
1719 "Unable to create request file %s: %s",
1720 con
->filename
, strerror(errno
));
1722 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1724 cupsdCloseClient(con
);
1729 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1730 "cupsdReadClient: %d REQUEST %s=%d", con
->http
.fd
,
1731 con
->filename
, con
->file
);
1733 fchmod(con
->file
, 0640);
1734 fchown(con
->file
, RunUser
, Group
);
1735 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1740 cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
);
1741 cupsdCloseClient(con
);
1745 if (!strncmp(con
->uri
, "/printers/", 10) &&
1746 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1749 * Send PPD file - get the real printer name since printer
1750 * names are not case sensitive but filenames can be...
1753 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1755 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1756 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1759 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1761 cupsdCloseClient(con
);
1769 if ((!strncmp(con
->uri
, "/admin", 6) &&
1770 strncmp(con
->uri
, "/admin/conf/", 12) &&
1771 strncmp(con
->uri
, "/admin/log/", 11)) ||
1772 !strncmp(con
->uri
, "/printers", 9) ||
1773 !strncmp(con
->uri
, "/classes", 8) ||
1774 !strncmp(con
->uri
, "/help", 5) ||
1775 !strncmp(con
->uri
, "/jobs", 5))
1781 if (!cupsdSendHeader(con
, HTTP_OK
, "text/html", CUPSD_AUTH_NONE
))
1783 cupsdCloseClient(con
);
1787 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1789 cupsdCloseClient(con
);
1793 if (cupsdFlushHeader(con
) < 0)
1795 cupsdCloseClient(con
);
1799 cupsdLogRequest(con
, HTTP_OK
);
1801 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1802 (strchr(con
->uri
+ 12, '/') ||
1803 strlen(con
->uri
) == 12)) ||
1804 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1805 (strchr(con
->uri
+ 11, '/') ||
1806 strlen(con
->uri
) == 11)))
1809 * HEAD can only be done to configuration files under
1813 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1815 cupsdCloseClient(con
);
1821 else if ((filename
= get_file(con
, &filestats
, buf
,
1822 sizeof(buf
))) == NULL
)
1824 if (!cupsdSendHeader(con
, HTTP_NOT_FOUND
, "text/html", CUPSD_AUTH_NONE
))
1826 cupsdCloseClient(con
);
1830 cupsdLogRequest(con
, HTTP_NOT_FOUND
);
1832 else if (!check_if_modified(con
, &filestats
))
1834 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1836 cupsdCloseClient(con
);
1840 cupsdLogRequest(con
, HTTP_NOT_MODIFIED
);
1848 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1850 strcpy(line
, "text/plain");
1852 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1854 if (!cupsdSendHeader(con
, HTTP_OK
, line
, CUPSD_AUTH_NONE
))
1856 cupsdCloseClient(con
);
1860 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
1861 httpGetDateString(filestats
.st_mtime
)) < 0)
1863 cupsdCloseClient(con
);
1867 if (httpPrintf(HTTP(con
), "Content-Length: %lu\r\n",
1868 (unsigned long)filestats
.st_size
) < 0)
1870 cupsdCloseClient(con
);
1874 cupsdLogRequest(con
, HTTP_OK
);
1877 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1879 cupsdCloseClient(con
);
1883 if (cupsdFlushHeader(con
) < 0)
1885 cupsdCloseClient(con
);
1889 con
->http
.state
= HTTP_WAITING
;
1893 break; /* Anti-compiler-warning-code */
1899 * Handle any incoming data...
1902 switch (con
->http
.state
)
1904 case HTTP_PUT_RECV
:
1905 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1906 "cupsdReadClient: %d con->data_encoding=HTTP_ENCODE_%s, "
1907 "con->data_remaining=" CUPS_LLFMT
", con->file=%d",
1909 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
?
1910 "CHUNKED" : "LENGTH",
1911 CUPS_LLCAST con
->http
.data_remaining
, con
->file
);
1915 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
1917 cupsdCloseClient(con
);
1922 con
->bytes
+= bytes
;
1924 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1925 "cupsdReadClient: %d writing %d bytes to %d",
1926 con
->http
.fd
, bytes
, con
->file
);
1928 if (write(con
->file
, line
, bytes
) < bytes
)
1930 cupsdLogMessage(CUPSD_LOG_ERROR
,
1931 "cupsdReadClient: Unable to write %d bytes to %s: %s",
1932 bytes
, con
->filename
, strerror(errno
));
1934 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1935 "cupsdReadClient: Closing data file %d...",
1940 unlink(con
->filename
);
1941 cupsdClearString(&con
->filename
);
1943 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1945 cupsdCloseClient(con
);
1951 while (con
->http
.state
== HTTP_PUT_RECV
&& data_ready(con
));
1953 if (con
->http
.state
== HTTP_WAITING
)
1956 * End of file, see how big it is...
1959 fstat(con
->file
, &filestats
);
1961 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1962 "cupsdReadClient: %d Closing data file %d, size="
1964 con
->http
.fd
, con
->file
,
1965 CUPS_LLCAST filestats
.st_size
);
1970 if (filestats
.st_size
> MaxRequestSize
&&
1974 * Request is too big; remove it and send an error...
1977 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1978 "cupsdReadClient: %d Removing temp file %s",
1979 con
->http
.fd
, con
->filename
);
1980 unlink(con
->filename
);
1981 cupsdClearString(&con
->filename
);
1983 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1985 cupsdCloseClient(con
);
1991 * Install the configuration file...
1994 status
= install_conf_file(con
);
1997 * Return the status to the client...
2000 if (!cupsdSendError(con
, status
, CUPSD_AUTH_NONE
))
2002 cupsdCloseClient(con
);
2008 case HTTP_POST_RECV
:
2009 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2010 "cupsdReadClient: %d con->data_encoding=HTTP_ENCODE_"
2011 "%s, con->data_remaining=" CUPS_LLFMT
", con->file=%d",
2013 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
?
2014 "CHUNKED" : "LENGTH",
2015 CUPS_LLCAST con
->http
.data_remaining
, con
->file
);
2022 * Grab any request data from the connection...
2025 if ((ipp_state
= ippRead(&(con
->http
), con
->request
)) == IPP_ERROR
)
2027 cupsdLogMessage(CUPSD_LOG_ERROR
,
2028 "cupsdReadClient: %d IPP Read Error!",
2031 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
2032 cupsdCloseClient(con
);
2035 else if (ipp_state
!= IPP_DATA
)
2037 if (con
->http
.state
== HTTP_POST_SEND
)
2039 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
2040 cupsdCloseClient(con
);
2047 con
->bytes
+= ippLength(con
->request
);
2050 if (con
->file
< 0 && con
->http
.state
!= HTTP_POST_SEND
)
2053 * Create a file as needed for the request data...
2056 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
, request_id
++);
2057 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
2061 cupsdLogMessage(CUPSD_LOG_ERROR
,
2062 "Unable to create request file %s: %s",
2063 con
->filename
, strerror(errno
));
2065 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2067 cupsdCloseClient(con
);
2072 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdReadClient: %d REQUEST %s=%d", con
->http
.fd
,
2073 con
->filename
, con
->file
);
2075 fchmod(con
->file
, 0640);
2076 fchown(con
->file
, RunUser
, Group
);
2077 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2080 if (con
->http
.state
!= HTTP_POST_SEND
)
2082 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
2084 cupsdCloseClient(con
);
2089 con
->bytes
+= bytes
;
2091 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2092 "cupsdReadClient: %d writing %d bytes to %d",
2093 con
->http
.fd
, bytes
, con
->file
);
2095 if (write(con
->file
, line
, bytes
) < bytes
)
2097 cupsdLogMessage(CUPSD_LOG_ERROR
,
2098 "cupsdReadClient: Unable to write %d bytes to %s: %s",
2099 bytes
, con
->filename
, strerror(errno
));
2101 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2102 "cupsdReadClient: Closing file %d...",
2107 unlink(con
->filename
);
2108 cupsdClearString(&con
->filename
);
2110 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2112 cupsdCloseClient(con
);
2117 else if (con
->http
.state
== HTTP_POST_RECV
)
2119 else if (con
->http
.state
!= HTTP_POST_SEND
)
2121 cupsdCloseClient(con
);
2126 while (con
->http
.state
== HTTP_POST_RECV
&& data_ready(con
));
2128 if (con
->http
.state
== HTTP_POST_SEND
)
2132 fstat(con
->file
, &filestats
);
2134 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2135 "cupsdReadClient: %d Closing data file %d, "
2136 "size=" CUPS_LLFMT
".",
2137 con
->http
.fd
, con
->file
,
2138 CUPS_LLCAST filestats
.st_size
);
2143 if (filestats
.st_size
> MaxRequestSize
&&
2147 * Request is too big; remove it and send an error...
2150 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2151 "cupsdReadClient: %d Removing temp file %s",
2152 con
->http
.fd
, con
->filename
);
2153 unlink(con
->filename
);
2154 cupsdClearString(&con
->filename
);
2159 * Delete any IPP request data...
2162 ippDelete(con
->request
);
2163 con
->request
= NULL
;
2166 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2168 cupsdCloseClient(con
);
2175 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
2177 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
2179 cupsdCloseClient(con
);
2184 cupsdLogRequest(con
, HTTP_OK
);
2190 cupsdProcessIPPRequest(con
);
2194 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2195 "cupsdReadClient: %d Removing temp file %s",
2196 con
->http
.fd
, con
->filename
);
2197 unlink(con
->filename
);
2198 cupsdClearString(&con
->filename
);
2207 break; /* Anti-compiler-warning-code */
2210 if (con
->http
.state
== HTTP_WAITING
)
2212 if (!con
->http
.keep_alive
)
2213 cupsdCloseClient(con
);
2216 cupsArrayRemove(ActiveClients
, con
);
2217 cupsdSetBusyState();
2224 * 'cupsdSendCommand()' - Send output from a command via HTTP.
2227 int /* O - 1 on success, 0 on failure */
2229 cupsd_client_t
*con
, /* I - Client connection */
2230 char *command
, /* I - Command to run */
2231 char *options
, /* I - Command-line options */
2232 int root
) /* I - Run as root? */
2234 int fd
; /* Standard input file descriptor */
2239 fd
= open(con
->filename
, O_RDONLY
);
2243 cupsdLogMessage(CUPSD_LOG_ERROR
,
2244 "cupsdSendCommand: %d Unable to open \"%s\" for reading: %s",
2245 con
->http
.fd
, con
->filename
? con
->filename
: "/dev/null",
2250 fcntl(fd
, F_SETFD
, fcntl(fd
, F_GETFD
) | FD_CLOEXEC
);
2255 con
->pipe_pid
= pipe_command(con
, fd
, &(con
->file
), command
, options
, root
);
2260 cupsdLogMessage(CUPSD_LOG_INFO
, "Started \"%s\" (pid=%d)", command
,
2263 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendCommand: %d file=%d",
2264 con
->http
.fd
, con
->file
);
2266 if (con
->pipe_pid
== 0)
2269 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2271 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2273 con
->sent_header
= 0;
2274 con
->file_ready
= 0;
2275 con
->got_fields
= 0;
2283 * 'cupsdSendError()' - Send an error message via HTTP.
2286 int /* O - 1 if successful, 0 otherwise */
2287 cupsdSendError(cupsd_client_t
*con
, /* I - Connection */
2288 http_status_t code
, /* I - Error code */
2289 int auth_type
)/* I - Authentication type */
2293 * Force client to upgrade for authentication if that is how the
2294 * server is configured...
2297 if (code
== HTTP_UNAUTHORIZED
&&
2298 DefaultEncryption
== HTTP_ENCRYPT_REQUIRED
&&
2299 strcasecmp(con
->http
.hostname
, "localhost") &&
2302 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2303 "cupsdSendError: Encryption before authentication!");
2304 code
= HTTP_UPGRADE_REQUIRED
;
2306 #endif /* HAVE_SSL */
2309 * Put the request in the access_log file...
2312 cupsdLogRequest(con
, code
);
2314 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendError: %d code=%d (%s)",
2315 con
->http
.fd
, code
, httpStatus(code
));
2318 * To work around bugs in some proxies, don't use Keep-Alive for some
2321 * Kerberos authentication doesn't work without Keep-Alive, so
2322 * never disable it in that case.
2325 if (code
>= HTTP_BAD_REQUEST
&& con
->http
.auth_type
!= CUPSD_AUTH_NEGOTIATE
)
2326 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
2329 * Send an error message back to the client. If the error code is a
2330 * 400 or 500 series, make sure the message contains some text, too!
2333 if (!cupsdSendHeader(con
, code
, NULL
, auth_type
))
2337 if (code
== HTTP_UPGRADE_REQUIRED
)
2338 if (httpPrintf(HTTP(con
), "Connection: Upgrade\r\n") < 0)
2341 if (httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n") < 0)
2343 #endif /* HAVE_SSL */
2345 if (con
->http
.version
>= HTTP_1_1
&&
2346 con
->http
.keep_alive
== HTTP_KEEPALIVE_OFF
)
2348 if (httpPrintf(HTTP(con
), "Connection: close\r\n") < 0)
2352 if (code
>= HTTP_BAD_REQUEST
)
2355 * Send a human-readable error message.
2358 char message
[4096], /* Message for user */
2359 urltext
[1024], /* URL redirection text */
2360 redirect
[1024]; /* Redirection link */
2361 const char *text
; /* Status-specific text */
2366 if (code
== HTTP_UNAUTHORIZED
)
2367 text
= _cupsLangString(con
->language
,
2368 _("Enter your username and password or the "
2369 "root username and password to access this "
2370 "page. If you are using Kerberos authentication, "
2371 "make sure you have a valid Kerberos ticket."));
2372 else if (code
== HTTP_UPGRADE_REQUIRED
)
2376 snprintf(urltext
, sizeof(urltext
),
2377 _cupsLangString(con
->language
,
2378 _("You must access this page using the URL "
2379 "<A HREF=\"https://%s:%d%s\">"
2380 "https://%s:%d%s</A>.")),
2381 con
->servername
, con
->serverport
, con
->uri
,
2382 con
->servername
, con
->serverport
, con
->uri
);
2384 snprintf(redirect
, sizeof(redirect
),
2385 "<META HTTP-EQUIV=\"Refresh\" "
2386 "CONTENT=\"3;URL=https://%s:%d%s\">\n",
2387 con
->servername
, con
->serverport
, con
->uri
);
2392 snprintf(message
, sizeof(message
),
2393 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" "
2394 "\"http://www.w3.org/TR/REC-html40/loose.dtd\">\n"
2397 "\t<META HTTP-EQUIV=\"Content-Type\" "
2398 "CONTENT=\"text/html; charset=utf-8\">\n"
2399 "\t<TITLE>%d %s</TITLE>\n"
2400 "\t<LINK REL=\"STYLESHEET\" TYPE=\"text/css\" "
2401 "HREF=\"/cups.css\">\n"
2409 code
, httpStatus(code
), redirect
, code
, httpStatus(code
), text
);
2411 if (httpPrintf(HTTP(con
), "Content-Type: text/html; charset=utf-8\r\n") < 0)
2413 if (httpPrintf(HTTP(con
), "Content-Length: %d\r\n",
2414 (int)strlen(message
)) < 0)
2416 if (httpPrintf(HTTP(con
), "\r\n") < 0)
2418 if (httpPrintf(HTTP(con
), "%s", message
) < 0)
2421 else if (httpPrintf(HTTP(con
), "\r\n") < 0)
2424 if (cupsdFlushHeader(con
) < 0)
2427 con
->http
.state
= HTTP_WAITING
;
2434 * 'cupsdSendHeader()' - Send an HTTP request.
2437 int /* O - 1 on success, 0 on failure */
2439 cupsd_client_t
*con
, /* I - Client to send to */
2440 http_status_t code
, /* I - HTTP status code */
2441 char *type
, /* I - MIME type of document */
2442 int auth_type
) /* I - Type of authentication */
2444 char auth_str
[1024]; /* Authorization string */
2446 static char *gss_buf
= NULL
; /* Kerberos auth data buffer */
2447 static int gss_bufsize
= 0; /* Size of Kerberos auth data buffer */
2448 #endif /* HAVE_GSSAPI */
2452 * Send the HTTP status header...
2455 if (code
== HTTP_CONTINUE
)
2458 * 100-continue doesn't send any headers...
2461 return (httpPrintf(HTTP(con
), "HTTP/%d.%d 100 Continue\r\n\r\n",
2462 con
->http
.version
/ 100, con
->http
.version
% 100) > 0);
2465 httpFlushWrite(HTTP(con
));
2467 con
->http
.data_encoding
= HTTP_ENCODE_FIELDS
;
2469 if (httpPrintf(HTTP(con
), "HTTP/%d.%d %d %s\r\n", con
->http
.version
/ 100,
2470 con
->http
.version
% 100, code
, httpStatus(code
)) < 0)
2472 if (httpPrintf(HTTP(con
), "Date: %s\r\n", httpGetDateString(time(NULL
))) < 0)
2475 if (httpPrintf(HTTP(con
), "Server: %s\r\n", ServerHeader
) < 0)
2477 if (con
->http
.keep_alive
&& con
->http
.version
>= HTTP_1_0
)
2479 if (httpPrintf(HTTP(con
), "Connection: Keep-Alive\r\n") < 0)
2481 if (httpPrintf(HTTP(con
), "Keep-Alive: timeout=%d\r\n",
2482 KeepAliveTimeout
) < 0)
2485 if (code
== HTTP_METHOD_NOT_ALLOWED
)
2486 if (httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST\r\n") < 0)
2489 if (code
== HTTP_UNAUTHORIZED
)
2491 if (auth_type
== CUPSD_AUTH_NONE
)
2493 if (!con
->best
|| con
->best
->type
<= CUPSD_AUTH_NONE
)
2494 auth_type
= DefaultAuthType
;
2496 auth_type
= con
->best
->type
;
2501 if (auth_type
== CUPSD_AUTH_BASIC
|| auth_type
== CUPSD_AUTH_BASICDIGEST
)
2502 strlcpy(auth_str
, "Basic realm=\"CUPS\"", sizeof(auth_str
));
2503 else if (auth_type
== CUPSD_AUTH_DIGEST
)
2504 snprintf(auth_str
, sizeof(auth_str
), "Digest realm=\"CUPS\", nonce=\"%s\"",
2505 con
->http
.hostname
);
2507 else if (auth_type
== CUPSD_AUTH_NEGOTIATE
&& con
->gss_output_token
.length
== 0)
2508 strlcpy(auth_str
, "Negotiate", sizeof(auth_str
));
2509 #endif /* HAVE_GSSAPI */
2511 #ifdef HAVE_AUTHORIZATION_H
2512 if (con
->best
&& auth_type
!= CUPSD_AUTH_NEGOTIATE
)
2514 int i
; /* Looping var */
2515 char *auth_key
; /* Auth key buffer */
2516 size_t auth_size
; /* Size of remaining buffer */
2519 auth_key
= auth_str
+ strlen(auth_str
);
2520 auth_size
= sizeof(auth_str
) - (auth_key
- auth_str
);
2522 for (i
= 0; i
< con
->best
->num_names
; i
++)
2524 if (!strncasecmp(con
->best
->names
[i
], "@AUTHKEY(", 9))
2526 snprintf(auth_key
, auth_size
, ", authkey=\"%s\"",
2527 con
->best
->names
[i
] + 9);
2528 /* end parenthesis is stripped in conf.c */
2531 else if (!strcasecmp(con
->best
->names
[i
], "@SYSTEM") &&
2534 snprintf(auth_key
, auth_size
, ", authkey=\"%s\"", SystemGroupAuthKey
);
2539 #endif /* HAVE_AUTHORIZATION_H */
2543 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendHeader: WWW-Authenticate: %s",
2546 if (httpPrintf(HTTP(con
), "WWW-Authenticate: %s\r\n", auth_str
) < 0)
2553 * WWW-Authenticate: Negotiate can be included even for
2554 * non-401 replies...
2557 if (con
->gss_output_token
.length
> 0 && con
->gss_output_token
.length
<= 65536)
2559 OM_uint32 minor_status
; /* Minor status code */
2560 int bufsize
; /* Size of output token buffer */
2563 bufsize
= con
->gss_output_token
.length
* 4 / 3 + 2;
2565 if (bufsize
> gss_bufsize
)
2567 char *buf
; /* New buffer */
2570 bufsize
= (bufsize
+ 1023) & 1023;/* Round up */
2573 buf
= realloc(gss_buf
, bufsize
);
2575 buf
= malloc(bufsize
);
2579 cupsdLogMessage(CUPSD_LOG_ERROR
,
2580 "Unable to allocate %d bytes for Kerberos credentials!",
2586 gss_bufsize
= bufsize
;
2589 httpEncode64_2(gss_buf
, gss_bufsize
,
2590 con
->gss_output_token
.value
,
2591 con
->gss_output_token
.length
);
2592 gss_release_buffer(&minor_status
, &con
->gss_output_token
);
2594 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2595 "cupsdSendHeader: WWW-Authenticate: Negotiate %s", gss_buf
);
2597 if (httpPrintf(HTTP(con
), "WWW-Authenticate: Negotiate %s\r\n",
2601 else if (con
->gss_output_token
.length
> 65536)
2603 cupsdLogMessage(CUPSD_LOG_ERROR
,
2604 "Kerberos credentials larger than 64k (%d)!",
2605 (int)con
->gss_output_token
.length
);
2608 #endif /* HAVE_GSSAPI */
2610 if (con
->language
&& strcmp(con
->language
->language
, "C"))
2612 if (httpPrintf(HTTP(con
), "Content-Language: %s\r\n",
2613 con
->language
->language
) < 0)
2619 if (!strcmp(type
, "text/html"))
2621 if (httpPrintf(HTTP(con
),
2622 "Content-Type: text/html; charset=utf-8\r\n") < 0)
2625 else if (httpPrintf(HTTP(con
), "Content-Type: %s\r\n", type
) < 0)
2634 * 'cupsdUpdateCGI()' - Read status messages from CGI scripts and programs.
2638 cupsdUpdateCGI(void)
2640 char *ptr
, /* Pointer to end of line in buffer */
2641 message
[1024]; /* Pointer to message text */
2642 int loglevel
; /* Log level for message */
2645 while ((ptr
= cupsdStatBufUpdate(CGIStatusBuffer
, &loglevel
,
2646 message
, sizeof(message
))) != NULL
)
2647 if (!strchr(CGIStatusBuffer
->buffer
, '\n'))
2650 if (ptr
== NULL
&& !CGIStatusBuffer
->bufused
)
2653 * Fatal error on pipe - should never happen!
2656 cupsdLogMessage(CUPSD_LOG_CRIT
,
2657 "cupsdUpdateCGI: error reading from CGI error pipe - %s",
2664 * 'cupsdWriteClient()' - Write data to a client as needed.
2668 cupsdWriteClient(cupsd_client_t
*con
) /* I - Client connection */
2670 int bytes
; /* Number of bytes written */
2671 char buf
[16385]; /* Data buffer */
2672 char *bufptr
; /* Pointer into buffer */
2673 ipp_state_t ipp_state
; /* IPP state value */
2677 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2678 "cupsdWriteClient(con=%p) %d response=%p(%d), file=%d "
2679 "pipe_pid=%d state=%d",
2680 con
, con
->http
.fd
, con
->response
,
2681 con
->response
? con
->response
->state
: -1,
2682 con
->file
, con
->pipe_pid
, con
->http
.state
);
2685 if (con
->http
.state
!= HTTP_GET_SEND
&&
2686 con
->http
.state
!= HTTP_POST_SEND
)
2692 * Make sure we select on the CGI output...
2695 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2697 if (!con
->file_ready
)
2700 * Try again later when there is CGI output available...
2703 cupsdRemoveSelect(con
->http
.fd
);
2707 con
->file_ready
= 0;
2710 if (con
->response
&& con
->response
->state
!= IPP_DATA
)
2712 ipp_state
= ippWrite(HTTP(con
), con
->response
);
2713 bytes
= ipp_state
!= IPP_ERROR
&&
2714 (con
->file
>= 0 || ipp_state
!= IPP_DATA
);
2716 else if ((bytes
= read(con
->file
, buf
, sizeof(buf
) - 1)) > 0)
2718 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2719 "cupsdWriteClient: Read %d bytes from file %d...",
2722 if (con
->pipe_pid
&& !con
->got_fields
)
2725 * Inspect the data for Content-Type and other fields.
2730 for (bufptr
= buf
; !con
->got_fields
&& *bufptr
; bufptr
++)
2731 if (*bufptr
== '\n')
2734 * Send line to client...
2737 if (bufptr
> buf
&& bufptr
[-1] == '\r')
2741 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "Script header: %s", buf
);
2743 if (!con
->sent_header
)
2746 * Handle redirection and CGI status codes...
2749 if (!strncasecmp(buf
, "Location:", 9))
2751 cupsdSendHeader(con
, HTTP_SEE_OTHER
, NULL
, CUPSD_AUTH_NONE
);
2752 con
->sent_header
= 2;
2754 if (httpPrintf(HTTP(con
), "Content-Length: 0\r\n") < 0)
2757 else if (!strncasecmp(buf
, "Status:", 7))
2759 cupsdSendError(con
, (http_status_t
)atoi(buf
+ 7), CUPSD_AUTH_NONE
);
2760 con
->sent_header
= 2;
2764 cupsdSendHeader(con
, HTTP_OK
, NULL
, CUPSD_AUTH_NONE
);
2765 con
->sent_header
= 1;
2767 if (con
->http
.version
== HTTP_1_1
)
2769 if (httpPrintf(HTTP(con
), "Transfer-Encoding: chunked\r\n") < 0)
2775 if (strncasecmp(buf
, "Status:", 7))
2776 httpPrintf(HTTP(con
), "%s\r\n", buf
);
2778 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdWriteClient: %d %s",
2785 bytes
-= (bufptr
- buf
);
2786 memmove(buf
, bufptr
, bytes
+ 1);
2790 * See if the line was empty...
2793 if (con
->field_col
== 0)
2795 con
->got_fields
= 1;
2797 if (cupsdFlushHeader(con
) < 0)
2799 cupsdCloseClient(con
);
2803 if (con
->http
.version
== HTTP_1_1
)
2804 con
->http
.data_encoding
= HTTP_ENCODE_CHUNKED
;
2809 else if (*bufptr
!= '\r')
2812 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2813 "cupsdWriteClient: %d bytes=%d, got_fields=%d",
2814 con
->http
.fd
, bytes
, con
->got_fields
);
2816 if (bytes
> 0 && !con
->got_fields
)
2819 * Remaining text needs to go out...
2822 httpPrintf(HTTP(con
), "%s", buf
);
2824 con
->http
.activity
= time(NULL
);
2827 else if (bytes
== 0)
2829 con
->http
.activity
= time(NULL
);
2836 if (httpWrite2(HTTP(con
), buf
, bytes
) < 0)
2838 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2839 "cupsdWriteClient: %d Write of %d bytes failed!",
2840 con
->http
.fd
, bytes
);
2842 cupsdCloseClient(con
);
2846 if (con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
)
2847 httpFlushWrite(HTTP(con
));
2849 con
->bytes
+= bytes
;
2851 if (con
->http
.state
== HTTP_WAITING
)
2858 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdWriteClient: %d bytes < 0",
2861 cupsdLogRequest(con
, HTTP_OK
);
2863 httpFlushWrite(HTTP(con
));
2865 if (con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
&& con
->sent_header
== 1)
2867 if (httpWrite2(HTTP(con
), "", 0) < 0)
2869 cupsdCloseClient(con
);
2874 con
->http
.state
= HTTP_WAITING
;
2876 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
2880 cupsdRemoveSelect(con
->file
);
2883 cupsdEndProcess(con
->pipe_pid
, 0);
2885 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2886 "cupsdWriteClient: %d Closing data file %d.",
2887 con
->http
.fd
, con
->file
);
2896 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2897 "cupsdWriteClient: %d Removing temp file %s",
2898 con
->http
.fd
, con
->filename
);
2899 unlink(con
->filename
);
2900 cupsdClearString(&con
->filename
);
2905 ippDelete(con
->request
);
2906 con
->request
= NULL
;
2911 ippDelete(con
->response
);
2912 con
->response
= NULL
;
2915 cupsdClearString(&con
->command
);
2916 cupsdClearString(&con
->options
);
2917 cupsdClearString(&con
->query_string
);
2919 if (!con
->http
.keep_alive
)
2921 cupsdCloseClient(con
);
2926 con
->http
.activity
= time(NULL
);
2931 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
2934 static int /* O - 1 if modified since */
2936 cupsd_client_t
*con
, /* I - Client connection */
2937 struct stat
*filestats
) /* I - File information */
2939 char *ptr
; /* Pointer into field */
2940 time_t date
; /* Time/date value */
2941 off_t size
; /* Size/length value */
2946 ptr
= con
->http
.fields
[HTTP_FIELD_IF_MODIFIED_SINCE
];
2951 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2952 "check_if_modified: %d If-Modified-Since=\"%s\"",
2955 while (*ptr
!= '\0')
2957 while (isspace(*ptr
) || *ptr
== ';')
2960 if (strncasecmp(ptr
, "length=", 7) == 0)
2963 size
= strtoll(ptr
, NULL
, 10);
2965 while (isdigit(*ptr
))
2968 else if (isalpha(*ptr
))
2970 date
= httpGetDateTime(ptr
);
2971 while (*ptr
!= '\0' && *ptr
!= ';')
2978 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2979 "check_if_modified: %d sizes=" CUPS_LLFMT
","
2980 CUPS_LLFMT
" dates=%d,%d",
2981 con
->http
.fd
, CUPS_LLCAST size
,
2982 CUPS_LLCAST filestats
->st_size
, (int)date
,
2983 (int)filestats
->st_mtime
);
2985 return ((size
!= filestats
->st_size
&& size
!= 0) ||
2986 (date
< filestats
->st_mtime
&& date
!= 0) ||
2987 (size
== 0 && date
== 0));
2992 * 'compare_clients()' - Compare two client connections.
2995 static int /* O - Result of comparison */
2996 compare_clients(cupsd_client_t
*a
, /* I - First client */
2997 cupsd_client_t
*b
, /* I - Second client */
2998 void *data
) /* I - User data (not used) */
3012 * 'data_ready()' - Check whether data is available from a client.
3015 static int /* O - 1 if data is ready, 0 otherwise */
3016 data_ready(cupsd_client_t
*con
) /* I - Client */
3018 if (con
->http
.used
> 0)
3021 else if (con
->http
.tls
)
3024 if (SSL_pending((SSL
*)(con
->http
.tls
)))
3026 # elif defined(HAVE_GNUTLS)
3027 if (gnutls_record_check_pending(((http_tls_t
*)(con
->http
.tls
))->session
))
3029 # elif defined(HAVE_CDSASSL)
3030 size_t bytes
; /* Bytes that are available */
3032 if (!SSLGetBufferedReadSize(((http_tls_t
*)(con
->http
.tls
))->session
,
3033 &bytes
) && bytes
> 0)
3035 # endif /* HAVE_LIBSSL */
3037 #endif /* HAVE_SSL */
3045 * 'encrypt_client()' - Enable encryption for the client...
3048 static int /* O - 1 on success, 0 on error */
3049 encrypt_client(cupsd_client_t
*con
) /* I - Client to encrypt */
3052 SSL_CTX
*context
; /* Context for encryption */
3053 SSL
*conn
; /* Connection for encryption */
3054 BIO
*bio
; /* BIO data */
3055 unsigned long error
; /* Error code */
3059 * Verify that we have a certificate...
3062 if (access(ServerKey
, 0) || access(ServerCertificate
, 0))
3065 * Nope, make a self-signed certificate...
3068 if (!make_certificate(con
))
3073 * Create the SSL context and accept the connection...
3076 context
= SSL_CTX_new(SSLv23_server_method());
3078 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
3079 SSL_CTX_use_PrivateKey_file(context
, ServerKey
, SSL_FILETYPE_PEM
);
3080 SSL_CTX_use_certificate_chain_file(context
, ServerCertificate
,
3083 bio
= BIO_new(_httpBIOMethods());
3084 BIO_ctrl(bio
, BIO_C_SET_FILE_PTR
, 0, (char *)HTTP(con
));
3086 conn
= SSL_new(context
);
3087 SSL_set_bio(conn
, bio
, bio
);
3089 if (SSL_accept(conn
) != 1)
3091 cupsdLogMessage(CUPSD_LOG_ERROR
,
3092 "encrypt_client: Unable to encrypt connection from %s!",
3093 con
->http
.hostname
);
3095 while ((error
= ERR_get_error()) != 0)
3096 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s",
3097 ERR_error_string(error
, NULL
));
3099 SSL_CTX_free(context
);
3104 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3105 "encrypt_client: %d Connection from %s now encrypted.",
3106 con
->http
.fd
, con
->http
.hostname
);
3108 con
->http
.tls
= conn
;
3111 # elif defined(HAVE_GNUTLS)
3112 http_tls_t
*conn
; /* TLS session object */
3113 int error
; /* Error code */
3114 gnutls_certificate_server_credentials
*credentials
;
3115 /* TLS credentials */
3119 * Verify that we have a certificate...
3122 if (access(ServerKey
, 0) || access(ServerCertificate
, 0))
3125 * Nope, make a self-signed certificate...
3128 if (!make_certificate(con
))
3133 * Create the SSL object and perform the SSL handshake...
3136 conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
));
3141 credentials
= (gnutls_certificate_server_credentials
*)
3142 malloc(sizeof(gnutls_certificate_server_credentials
));
3143 if (credentials
== NULL
)
3145 cupsdLogMessage(CUPSD_LOG_ERROR
,
3146 "encrypt_client: Unable to encrypt connection from %s!",
3147 con
->http
.hostname
);
3148 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s", strerror(errno
));
3154 gnutls_certificate_allocate_credentials(credentials
);
3155 gnutls_certificate_set_x509_key_file(*credentials
, ServerCertificate
,
3156 ServerKey
, GNUTLS_X509_FMT_PEM
);
3158 gnutls_init(&(conn
->session
), GNUTLS_SERVER
);
3159 gnutls_set_default_priority(conn
->session
);
3160 gnutls_credentials_set(conn
->session
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
3161 gnutls_transport_set_ptr(conn
->session
, (gnutls_transport_ptr
)HTTP(con
));
3162 gnutls_transport_set_pull_function(conn
->session
, _httpReadGNUTLS
);
3163 gnutls_transport_set_push_function(conn
->session
, _httpWriteGNUTLS
);
3165 error
= gnutls_handshake(conn
->session
);
3167 if (error
!= GNUTLS_E_SUCCESS
)
3169 cupsdLogMessage(CUPSD_LOG_ERROR
,
3170 "encrypt_client: Unable to encrypt connection from %s!",
3171 con
->http
.hostname
);
3172 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s",
3173 gnutls_strerror(error
));
3175 gnutls_deinit(conn
->session
);
3176 gnutls_certificate_free_credentials(*credentials
);
3182 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3183 "encrypt_client: %d Connection from %s now encrypted.",
3184 con
->http
.fd
, con
->http
.hostname
);
3186 conn
->credentials
= credentials
;
3187 con
->http
.tls
= conn
;
3190 # elif defined(HAVE_CDSASSL)
3191 OSStatus error
; /* Error code */
3192 http_tls_t
*conn
; /* CDSA connection information */
3195 if ((conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
))) == NULL
)
3199 conn
->session
= NULL
;
3200 conn
->certsArray
= get_cdsa_certificate(con
);
3202 if (!conn
->certsArray
)
3205 * No keychain (yet), make a self-signed certificate...
3208 if (make_certificate(con
))
3209 conn
->certsArray
= get_cdsa_certificate(con
);
3212 if (!conn
->certsArray
)
3214 cupsdLogMessage(CUPSD_LOG_ERROR
,
3215 "encrypt_client: Could not find signing key in keychain "
3216 "\"%s\"", ServerCertificate
);
3217 error
= errSSLBadCert
; /* errSSLBadConfiguration is a better choice, but not available on 10.2.x */
3221 error
= SSLNewContext(true, &conn
->session
);
3224 error
= SSLSetIOFuncs(conn
->session
, _httpReadCDSA
, _httpWriteCDSA
);
3227 error
= SSLSetProtocolVersionEnabled(conn
->session
, kSSLProtocol2
, false);
3230 error
= SSLSetConnection(conn
->session
, HTTP(con
));
3233 error
= SSLSetAllowsExpiredCerts(conn
->session
, true);
3236 error
= SSLSetAllowsAnyRoot(conn
->session
, true);
3239 error
= SSLSetCertificate(conn
->session
, conn
->certsArray
);
3244 * Perform SSL/TLS handshake
3247 while ((error
= SSLHandshake(conn
->session
)) == errSSLWouldBlock
)
3253 cupsdLogMessage(CUPSD_LOG_ERROR
,
3254 "encrypt_client: Unable to encrypt connection from %s!",
3255 con
->http
.hostname
);
3257 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s (%d)",
3258 cssmErrorString(error
), (int)error
);
3260 con
->http
.error
= error
;
3261 con
->http
.status
= HTTP_ERROR
;
3264 SSLDisposeContext(conn
->session
);
3266 if (conn
->certsArray
)
3267 CFRelease(conn
->certsArray
);
3274 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3275 "encrypt_client: %d Connection from %s now encrypted.",
3276 con
->http
.fd
, con
->http
.hostname
);
3278 con
->http
.tls
= conn
;
3281 # endif /* HAVE_LIBSSL */
3283 #endif /* HAVE_SSL */
3288 * 'get_cdsa_certificate()' - Get a SSL/TLS certificate from the System keychain.
3291 static CFArrayRef
/* O - Array of certificates */
3292 get_cdsa_certificate(cupsd_client_t
*con
) /* I - Client connection */
3294 OSStatus err
; /* Error info */
3295 SecKeychainRef keychain
; /* Keychain reference */
3296 SecIdentitySearchRef search
; /* Search reference */
3297 SecIdentityRef identity
; /* Identity */
3298 CFArrayRef certificates
= NULL
;
3299 /* Certificate array */
3302 if ((err
= SecKeychainOpen(ServerCertificate
, &keychain
)))
3304 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot open keychain \"%s\", %s",
3305 ServerCertificate
, cssmErrorString(err
));
3309 # if HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY
3311 * Use a policy to search for valid certificates who's common name matches the
3315 SecPolicySearchRef policy_search
; /* Policy search ref */
3316 SecPolicyRef policy
; /* Policy ref */
3317 CSSM_DATA options
; /* Policy options */
3318 CSSM_APPLE_TP_SSL_OPTIONS
3319 ssl_options
; /* SSL Option for hostname */
3322 if (SecPolicySearchCreate(CSSM_CERT_X_509v3
, &CSSMOID_APPLE_TP_SSL
,
3323 NULL
, &policy_search
))
3325 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot create a policy search reference");
3326 CFRelease(keychain
);
3330 if (SecPolicySearchCopyNext(policy_search
, &policy
))
3332 cupsdLogMessage(CUPSD_LOG_ERROR
,
3333 "Cannot find a policy to use for searching");
3334 CFRelease(keychain
);
3335 CFRelease(policy_search
);
3339 memset(&ssl_options
, 0, sizeof(ssl_options
));
3340 ssl_options
.Version
= CSSM_APPLE_TP_SSL_OPTS_VERSION
;
3341 ssl_options
.ServerName
= con
->servername
;
3342 ssl_options
.ServerNameLen
= strlen(con
->servername
);
3344 options
.Data
= (uint8
*)&ssl_options
;
3345 options
.Length
= sizeof(ssl_options
);
3347 if (SecPolicySetValue(policy
, &options
))
3349 cupsdLogMessage(CUPSD_LOG_ERROR
,
3350 "Cannot set policy value to use for searching");
3351 CFRelease(keychain
);
3352 CFRelease(policy_search
);
3356 err
= SecIdentitySearchCreateWithPolicy(policy
, NULL
, CSSM_KEYUSE_SIGN
,
3357 keychain
, FALSE
, &search
);
3360 * Assume there is exactly one SecIdentity in the keychain...
3363 err
= SecIdentitySearchCreate(keychain
, CSSM_KEYUSE_SIGN
, &search
);
3364 # endif /* HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY */
3367 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3368 "Cannot create keychain search reference: %s",
3369 cssmErrorString(err
));
3372 if ((err
= SecIdentitySearchCopyNext(search
, &identity
)))
3374 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3375 "Cannot find signing key in keychain \"%s\", error %d",
3376 ServerCertificate
, (int)err
);
3380 if (CFGetTypeID(identity
) != SecIdentityGetTypeID())
3381 cupsdLogMessage(CUPSD_LOG_ERROR
,
3382 "SecIdentitySearchCopyNext CFTypeID failure!");
3385 if ((certificates
= CFArrayCreate(NULL
, (const void **)&identity
,
3386 1, &kCFTypeArrayCallBacks
)) == NULL
)
3387 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot create certificate array");
3390 CFRelease(identity
);
3396 # if HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY
3398 CFRelease(policy_search
);
3399 # endif /* HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY */
3401 return (certificates
);
3403 #endif /* HAVE_CDSASSL */
3407 * 'get_file()' - Get a filename and state info.
3410 static char * /* O - Real filename */
3411 get_file(cupsd_client_t
*con
, /* I - Client connection */
3412 struct stat
*filestats
, /* O - File information */
3413 char *filename
, /* IO - Filename buffer */
3414 int len
) /* I - Buffer length */
3416 int status
; /* Status of filesystem calls */
3417 char *ptr
; /* Pointer info filename */
3418 int plen
; /* Remaining length after pointer */
3419 char language
[7]; /* Language subdirectory, if any */
3423 * Figure out the real filename...
3428 if (!strncmp(con
->uri
, "/ppd/", 5))
3429 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
);
3430 else if (!strncmp(con
->uri
, "/rss/", 5) && !strchr(con
->uri
+ 5, '/'))
3431 snprintf(filename
, len
, "%s/rss/%s", CacheDir
, con
->uri
+ 5);
3432 else if (!strncmp(con
->uri
, "/admin/conf/", 12))
3433 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
+ 11);
3434 else if (!strncmp(con
->uri
, "/admin/log/", 11))
3436 if (!strncmp(con
->uri
+ 11, "access_log", 10) && AccessLog
[0] == '/')
3437 strlcpy(filename
, AccessLog
, len
);
3438 else if (!strncmp(con
->uri
+ 11, "error_log", 9) && ErrorLog
[0] == '/')
3439 strlcpy(filename
, ErrorLog
, len
);
3440 else if (!strncmp(con
->uri
+ 11, "page_log", 8) && PageLog
[0] == '/')
3441 strlcpy(filename
, PageLog
, len
);
3445 else if (con
->language
)
3447 snprintf(language
, sizeof(language
), "/%s", con
->language
->language
);
3448 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3451 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3453 if ((ptr
= strchr(filename
, '?')) != NULL
)
3457 * Grab the status for this language; if there isn't a language-specific file
3458 * then fallback to the default one...
3461 if ((status
= stat(filename
, filestats
)) != 0 && language
[0] &&
3462 strncmp(con
->uri
, "/ppd/", 5) &&
3463 strncmp(con
->uri
, "/admin/conf/", 12) &&
3464 strncmp(con
->uri
, "/admin/log/", 11))
3467 * Drop the country code...
3471 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3473 if ((ptr
= strchr(filename
, '?')) != NULL
)
3476 if ((status
= stat(filename
, filestats
)) != 0)
3479 * Drop the language prefix and try the root directory...
3483 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3485 if ((ptr
= strchr(filename
, '?')) != NULL
)
3488 status
= stat(filename
, filestats
);
3493 * If we're found a directory, get the index.html file instead...
3496 if (!status
&& S_ISDIR(filestats
->st_mode
))
3499 * Make sure the URI ends with a slash...
3502 if (con
->uri
[strlen(con
->uri
) - 1] != '/')
3503 strlcat(con
->uri
, "/", sizeof(con
->uri
));
3506 * Find the directory index file, trying every language...
3511 if (status
&& language
[0])
3514 * Try a different language subset...
3518 language
[0] = '\0'; /* Strip country code */
3520 language
[0] = '\0'; /* Strip language */
3524 * Look for the index file...
3527 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3529 if ((ptr
= strchr(filename
, '?')) != NULL
)
3532 ptr
= filename
+ strlen(filename
);
3533 plen
= len
- (ptr
- filename
);
3535 strlcpy(ptr
, "index.html", plen
);
3536 status
= stat(filename
, filestats
);
3541 strlcpy(ptr
, "index.class", plen
);
3542 status
= stat(filename
, filestats
);
3544 #endif /* HAVE_JAVA */
3549 strlcpy(ptr
, "index.pl", plen
);
3550 status
= stat(filename
, filestats
);
3552 #endif /* HAVE_PERL */
3557 strlcpy(ptr
, "index.php", plen
);
3558 status
= stat(filename
, filestats
);
3560 #endif /* HAVE_PHP */
3565 strlcpy(ptr
, "index.pyc", plen
);
3566 status
= stat(filename
, filestats
);
3571 strlcpy(ptr
, "index.py", plen
);
3572 status
= stat(filename
, filestats
);
3574 #endif /* HAVE_PYTHON */
3577 while (status
&& language
[0]);
3580 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "get_file: %d filename=%s size=%d",
3581 con
->http
.fd
, filename
,
3582 status
? -1 : (int)filestats
->st_size
);
3585 con
->http
.data_remaining
= (int)filestats
->st_size
;
3595 * 'install_conf_file()' - Install a configuration file.
3598 static http_status_t
/* O - Status */
3599 install_conf_file(cupsd_client_t
*con
) /* I - Connection */
3601 cups_file_t
*in
, /* Input file */
3602 *out
; /* Output file */
3603 char buffer
[1024]; /* Copy buffer */
3604 int bytes
; /* Number of bytes */
3605 char conffile
[1024], /* Configuration filename */
3606 newfile
[1024], /* New config filename */
3607 oldfile
[1024]; /* Old config filename */
3608 struct stat confinfo
; /* Config file info */
3612 * First construct the filenames...
3615 snprintf(conffile
, sizeof(conffile
), "%s%s", ServerRoot
, con
->uri
+ 11);
3616 snprintf(newfile
, sizeof(newfile
), "%s%s.N", ServerRoot
, con
->uri
+ 11);
3617 snprintf(oldfile
, sizeof(oldfile
), "%s%s.O", ServerRoot
, con
->uri
+ 11);
3619 cupsdLogMessage(CUPSD_LOG_INFO
, "Installing config file \"%s\"...", conffile
);
3622 * Get the owner, group, and permissions of the configuration file.
3623 * If it doesn't exist, assign it to the User and Group in the
3624 * cupsd.conf file with mode 0640 permissions.
3627 if (stat(conffile
, &confinfo
))
3629 confinfo
.st_uid
= User
;
3630 confinfo
.st_gid
= Group
;
3631 confinfo
.st_mode
= ConfigFilePerm
;
3635 * Open the request file and new config file...
3638 if ((in
= cupsFileOpen(con
->filename
, "rb")) == NULL
)
3640 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open request file \"%s\" - %s",
3641 con
->filename
, strerror(errno
));
3642 return (HTTP_SERVER_ERROR
);
3645 if ((out
= cupsFileOpen(newfile
, "wb")) == NULL
)
3648 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open config file \"%s\" - %s",
3649 newfile
, strerror(errno
));
3650 return (HTTP_SERVER_ERROR
);
3653 fchmod(cupsFileNumber(out
), confinfo
.st_mode
);
3654 fchown(cupsFileNumber(out
), confinfo
.st_uid
, confinfo
.st_gid
);
3657 * Copy from the request to the new config file...
3660 while ((bytes
= cupsFileRead(in
, buffer
, sizeof(buffer
))) > 0)
3661 if (cupsFileWrite(out
, buffer
, bytes
) < bytes
)
3663 cupsdLogMessage(CUPSD_LOG_ERROR
,
3664 "Unable to copy to config file \"%s\" - %s",
3665 newfile
, strerror(errno
));
3671 return (HTTP_SERVER_ERROR
);
3675 * Close the files...
3679 if (cupsFileClose(out
))
3681 cupsdLogMessage(CUPSD_LOG_ERROR
,
3682 "Error file closing config file \"%s\" - %s",
3683 newfile
, strerror(errno
));
3687 return (HTTP_SERVER_ERROR
);
3691 * Remove the request file...
3694 unlink(con
->filename
);
3695 cupsdClearString(&con
->filename
);
3698 * Unlink the old backup, rename the current config file to the backup
3699 * filename, and rename the new config file to the config file name...
3702 if (unlink(oldfile
))
3703 if (errno
!= ENOENT
)
3705 cupsdLogMessage(CUPSD_LOG_ERROR
,
3706 "Unable to remove backup config file \"%s\" - %s",
3707 oldfile
, strerror(errno
));
3711 return (HTTP_SERVER_ERROR
);
3714 if (rename(conffile
, oldfile
))
3715 if (errno
!= ENOENT
)
3717 cupsdLogMessage(CUPSD_LOG_ERROR
,
3718 "Unable to rename old config file \"%s\" - %s",
3719 conffile
, strerror(errno
));
3723 return (HTTP_SERVER_ERROR
);
3726 if (rename(newfile
, conffile
))
3728 cupsdLogMessage(CUPSD_LOG_ERROR
,
3729 "Unable to rename new config file \"%s\" - %s",
3730 newfile
, strerror(errno
));
3732 rename(oldfile
, conffile
);
3735 return (HTTP_SERVER_ERROR
);
3739 * If the cupsd.conf file was updated, set the NeedReload flag...
3742 if (!strcmp(con
->uri
, "/admin/conf/cupsd.conf"))
3743 NeedReload
= RELOAD_CUPSD
;
3745 NeedReload
= RELOAD_ALL
;
3747 ReloadTime
= time(NULL
);
3750 * Return that the file was created successfully...
3753 return (HTTP_CREATED
);
3758 * 'is_cgi()' - Is the resource a CGI script/program?
3761 static int /* O - 1 = CGI, 0 = file */
3762 is_cgi(cupsd_client_t
*con
, /* I - Client connection */
3763 const char *filename
, /* I - Real filename */
3764 struct stat
*filestats
, /* I - File information */
3765 mime_type_t
*type
) /* I - MIME type */
3767 const char *options
; /* Options on URL */
3770 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3771 "is_cgi(con=%p, filename=\"%s\", filestats=%p, type=%s/%s)",
3772 con
, filename
, filestats
, type
? type
->super
: "unknown",
3773 type
? type
->type
: "unknown");
3776 * Get the options, if any...
3779 if ((options
= strchr(con
->uri
, '?')) != NULL
)
3782 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", options
);
3786 * Check for known types...
3789 if (!type
|| strcasecmp(type
->super
, "application"))
3791 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "is_cgi: Returning 0...");
3795 if (!strcasecmp(type
->type
, "x-httpd-cgi") &&
3796 (filestats
->st_mode
& 0111))
3799 * "application/x-httpd-cgi" is a CGI script.
3802 cupsdSetString(&con
->command
, filename
);
3805 cupsdSetStringf(&con
->options
, " %s", options
);
3807 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3808 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3809 con
->command
, con
->options
);
3814 else if (!strcasecmp(type
->type
, "x-httpd-java"))
3817 * "application/x-httpd-java" is a Java servlet.
3820 cupsdSetString(&con
->command
, CUPS_JAVA
);
3823 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3825 cupsdSetStringf(&con
->options
, " %s", filename
);
3827 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3828 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3829 con
->command
, con
->options
);
3833 #endif /* HAVE_JAVA */
3835 else if (!strcasecmp(type
->type
, "x-httpd-perl"))
3838 * "application/x-httpd-perl" is a Perl page.
3841 cupsdSetString(&con
->command
, CUPS_PERL
);
3844 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3846 cupsdSetStringf(&con
->options
, " %s", filename
);
3848 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3849 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3850 con
->command
, con
->options
);
3854 #endif /* HAVE_PERL */
3856 else if (!strcasecmp(type
->type
, "x-httpd-php"))
3859 * "application/x-httpd-php" is a PHP page.
3862 cupsdSetString(&con
->command
, CUPS_PHP
);
3865 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3867 cupsdSetStringf(&con
->options
, " %s", filename
);
3869 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3870 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3871 con
->command
, con
->options
);
3875 #endif /* HAVE_PHP */
3877 else if (!strcasecmp(type
->type
, "x-httpd-python"))
3880 * "application/x-httpd-python" is a Python page.
3883 cupsdSetString(&con
->command
, CUPS_PYTHON
);
3886 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3888 cupsdSetStringf(&con
->options
, " %s", filename
);
3890 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3891 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3892 con
->command
, con
->options
);
3896 #endif /* HAVE_PYTHON */
3898 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "is_cgi: Returning 0...");
3905 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
3908 static int /* O - 0 if relative, 1 if absolute */
3909 is_path_absolute(const char *path
) /* I - Input path */
3912 * Check for a leading slash...
3919 * Check for "/.." in the path...
3922 while ((path
= strstr(path
, "/..")) != NULL
)
3924 if (!path
[3] || path
[3] == '/')
3931 * If we haven't found any relative paths, return 1 indicating an
3941 * 'make_certificate()' - Make a self-signed SSL/TLS certificate.
3944 static int /* O - 1 on success, 0 on failure */
3945 make_certificate(cupsd_client_t
*con
) /* I - Client connection */
3947 #if defined(HAVE_LIBSSL) && defined(HAVE_WAITPID)
3948 int pid
, /* Process ID of command */
3949 status
; /* Status of command */
3950 char command
[1024], /* Command */
3951 *argv
[12], /* Command-line arguments */
3952 *envp
[MAX_ENV
+ 1], /* Environment variables */
3953 home
[1024], /* HOME environment variable */
3954 infofile
[1024], /* Type-in information for cert */
3955 seedfile
[1024]; /* Random number seed file */
3956 int envc
, /* Number of environment variables */
3957 bytes
; /* Bytes written */
3958 cups_file_t
*fp
; /* Seed/info file */
3959 int infofd
; /* Info file descriptor */
3963 * Run the "openssl" command to seed the random number generator and
3964 * generate a self-signed certificate that is good for 10 years:
3966 * openssl rand -rand seedfile 1
3968 * openssl req -new -x509 -keyout ServerKey \
3969 * -out ServerCertificate -days 3650 -nodes
3971 * The seeding step is crucial in ensuring that the openssl command
3972 * does not block on systems without sufficient entropy...
3975 if (!cupsFileFind("openssl", getenv("PATH"), 1, command
, sizeof(command
)))
3977 cupsdLogMessage(CUPSD_LOG_ERROR
,
3978 "No SSL certificate and openssl command not found!");
3982 if (access("/dev/urandom", 0))
3985 * If the system doesn't provide /dev/urandom, then any random source
3986 * will probably be blocking-style, so generate some random data to
3987 * use as a seed for the certificate. Note that we have already
3988 * seeded the random number generator in cupsdInitCerts()...
3991 cupsdLogMessage(CUPSD_LOG_INFO
,
3992 "Seeding the random number generator...");
3994 snprintf(home
, sizeof(home
), "HOME=%s", TempDir
);
3997 * Write the seed file...
4000 if ((fp
= cupsTempFile2(seedfile
, sizeof(seedfile
))) == NULL
)
4002 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to create seed file %s - %s",
4003 seedfile
, strerror(errno
));
4007 for (bytes
= 0; bytes
< 262144; bytes
++)
4008 cupsFilePutChar(fp
, random());
4013 * Run the openssl command to seed its random number generator...
4016 argv
[0] = "openssl";
4023 envc
= cupsdLoadEnv(envp
, MAX_ENV
);
4024 envp
[envc
++] = home
;
4027 if (!cupsdStartProcess(command
, argv
, envp
, -1, -1, -1, -1, -1, 1, NULL
,
4034 while (waitpid(pid
, &status
, 0) < 0)
4041 cupsdFinishProcess(pid
, command
, sizeof(command
));
4044 * Remove the seed file, as it is no longer needed...
4051 if (WIFEXITED(status
))
4052 cupsdLogMessage(CUPSD_LOG_ERROR
,
4053 "Unable to seed random number generator - "
4054 "the openssl command stopped with status %d!",
4055 WEXITSTATUS(status
));
4057 cupsdLogMessage(CUPSD_LOG_ERROR
,
4058 "Unable to seed random number generator - "
4059 "the openssl command crashed on signal %d!",
4067 * Create a file with the certificate information fields...
4069 * Note: This assumes that the default questions are asked by the openssl
4073 if ((fp
= cupsTempFile2(infofile
, sizeof(infofile
))) == NULL
)
4075 cupsdLogMessage(CUPSD_LOG_ERROR
,
4076 "Unable to create certificate information file %s - %s",
4077 infofile
, strerror(errno
));
4081 cupsFilePrintf(fp
, ".\n.\n.\n%s\n.\n%s\n%s\n",
4082 ServerName
, ServerName
, ServerAdmin
);
4085 cupsdLogMessage(CUPSD_LOG_INFO
,
4086 "Generating SSL server key and certificate...");
4088 argv
[0] = "openssl";
4092 argv
[4] = "-keyout";
4093 argv
[5] = ServerKey
;
4095 argv
[7] = ServerCertificate
;
4098 argv
[10] = "-nodes";
4101 cupsdLoadEnv(envp
, MAX_ENV
);
4103 infofd
= open(infofile
, O_RDONLY
);
4105 if (!cupsdStartProcess(command
, argv
, envp
, infofd
, -1, -1, -1, -1, 1, NULL
,
4116 while (waitpid(pid
, &status
, 0) < 0)
4123 cupsdFinishProcess(pid
, command
, sizeof(command
));
4127 if (WIFEXITED(status
))
4128 cupsdLogMessage(CUPSD_LOG_ERROR
,
4129 "Unable to create SSL server key and certificate - "
4130 "the openssl command stopped with status %d!",
4131 WEXITSTATUS(status
));
4133 cupsdLogMessage(CUPSD_LOG_ERROR
,
4134 "Unable to create SSL server key and certificate - "
4135 "the openssl command crashed on signal %d!",
4140 cupsdLogMessage(CUPSD_LOG_INFO
, "Created SSL server key file \"%s\"...",
4142 cupsdLogMessage(CUPSD_LOG_INFO
,
4143 "Created SSL server certificate file \"%s\"...",
4149 #elif defined(HAVE_GNUTLS)
4150 gnutls_x509_crt crt
; /* Self-signed certificate */
4151 gnutls_x509_privkey key
; /* Encryption key */
4152 cups_lang_t
*language
; /* Default language info */
4153 cups_file_t
*fp
; /* Key/cert file */
4154 unsigned char buffer
[8192]; /* Buffer for x509 data */
4155 size_t bytes
; /* Number of bytes of data */
4156 unsigned char serial
[4]; /* Serial number buffer */
4157 time_t curtime
; /* Current time */
4158 int result
; /* Result of GNU TLS calls */
4162 * Create the encryption key...
4165 cupsdLogMessage(CUPSD_LOG_INFO
, "Generating SSL server key...");
4167 gnutls_x509_privkey_init(&key
);
4168 gnutls_x509_privkey_generate(key
, GNUTLS_PK_RSA
, 2048, 0);
4174 bytes
= sizeof(buffer
);
4176 if ((result
= gnutls_x509_privkey_export(key
, GNUTLS_X509_FMT_PEM
,
4177 buffer
, &bytes
)) < 0)
4179 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to export SSL server key - %s",
4180 gnutls_strerror(result
));
4181 gnutls_x509_privkey_deinit(key
);
4184 else if ((fp
= cupsFileOpen(ServerKey
, "w")) != NULL
)
4186 cupsFileWrite(fp
, (char *)buffer
, bytes
);
4189 cupsdLogMessage(CUPSD_LOG_INFO
, "Created SSL server key file \"%s\"...",
4194 cupsdLogMessage(CUPSD_LOG_ERROR
,
4195 "Unable to create SSL server key file \"%s\" - %s",
4196 ServerKey
, strerror(errno
));
4197 gnutls_x509_privkey_deinit(key
);
4202 * Create the self-signed certificate...
4205 cupsdLogMessage(CUPSD_LOG_INFO
, "Generating self-signed SSL certificate...");
4207 language
= cupsLangDefault();
4208 curtime
= time(NULL
);
4209 serial
[0] = curtime
>> 24;
4210 serial
[1] = curtime
>> 16;
4211 serial
[2] = curtime
>> 8;
4212 serial
[3] = curtime
;
4214 gnutls_x509_crt_init(&crt
);
4215 if (strlen(language
->language
) == 5)
4216 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
4217 language
->language
+ 3, 2);
4219 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
4221 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COMMON_NAME
, 0,
4222 ServerName
, strlen(ServerName
));
4223 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATION_NAME
, 0,
4224 ServerName
, strlen(ServerName
));
4225 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATIONAL_UNIT_NAME
,
4227 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_STATE_OR_PROVINCE_NAME
, 0,
4229 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_LOCALITY_NAME
, 0,
4231 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_PKCS9_EMAIL
, 0,
4232 ServerAdmin
, strlen(ServerAdmin
));
4233 gnutls_x509_crt_set_key(crt
, key
);
4234 gnutls_x509_crt_set_serial(crt
, serial
, sizeof(serial
));
4235 gnutls_x509_crt_set_activation_time(crt
, curtime
);
4236 gnutls_x509_crt_set_expiration_time(crt
, curtime
+ 10 * 365 * 86400);
4237 gnutls_x509_crt_set_ca_status(crt
, 0);
4238 gnutls_x509_crt_set_subject_alternative_name(crt
, GNUTLS_SAN_DNSNAME
,
4240 gnutls_x509_crt_set_key_purpose_oid(crt
, GNUTLS_KP_TLS_WWW_SERVER
, 0);
4241 gnutls_x509_crt_set_key_usage(crt
, GNUTLS_KEY_KEY_ENCIPHERMENT
);
4242 gnutls_x509_crt_set_version(crt
, 3);
4244 bytes
= sizeof(buffer
);
4245 if (gnutls_x509_crt_get_key_id(crt
, 0, buffer
, &bytes
) >= 0)
4246 gnutls_x509_crt_set_subject_key_id(crt
, buffer
, bytes
);
4248 gnutls_x509_crt_sign(crt
, crt
, key
);
4254 bytes
= sizeof(buffer
);
4255 if ((result
= gnutls_x509_crt_export(crt
, GNUTLS_X509_FMT_PEM
,
4256 buffer
, &bytes
)) < 0)
4257 cupsdLogMessage(CUPSD_LOG_ERROR
,
4258 "Unable to export SSL server certificate - %s",
4259 gnutls_strerror(result
));
4260 else if ((fp
= cupsFileOpen(ServerCertificate
, "w")) != NULL
)
4262 cupsFileWrite(fp
, (char *)buffer
, bytes
);
4265 cupsdLogMessage(CUPSD_LOG_INFO
,
4266 "Created SSL server certificate file \"%s\"...",
4270 cupsdLogMessage(CUPSD_LOG_ERROR
,
4271 "Unable to create SSL server certificate file \"%s\" - %s",
4272 ServerCertificate
, strerror(errno
));
4278 gnutls_x509_crt_deinit(crt
);
4279 gnutls_x509_privkey_deinit(key
);
4283 #elif defined(HAVE_CDSASSL) && defined(HAVE_WAITPID)
4284 int pid
, /* Process ID of command */
4285 status
; /* Status of command */
4286 char command
[1024], /* Command */
4287 *argv
[4], /* Command-line arguments */
4288 *envp
[MAX_ENV
+ 1], /* Environment variables */
4289 keychain
[1024], /* Keychain argument */
4290 infofile
[1024]; /* Type-in information for cert */
4291 cups_file_t
*fp
; /* Seed/info file */
4292 int infofd
; /* Info file descriptor */
4296 * Run the "certtool" command to generate a self-signed certificate...
4299 if (!cupsFileFind("certtool", getenv("PATH"), 1, command
, sizeof(command
)))
4301 cupsdLogMessage(CUPSD_LOG_ERROR
,
4302 "No SSL certificate and certtool command not found!");
4307 * Create a file with the certificate information fields...
4309 * Note: This assumes that the default questions are asked by the certtool
4313 if ((fp
= cupsTempFile2(infofile
, sizeof(infofile
))) == NULL
)
4315 cupsdLogMessage(CUPSD_LOG_ERROR
,
4316 "Unable to create certificate information file %s - %s",
4317 infofile
, strerror(errno
));
4321 cupsFilePrintf(fp
, "%s\nr\n\ny\nb\ns\ny\n%s\n\n\n\n\n%s\ny\n",
4322 con
->servername
, con
->servername
, ServerAdmin
);
4325 cupsdLogMessage(CUPSD_LOG_INFO
,
4326 "Generating SSL server key and certificate...");
4328 snprintf(keychain
, sizeof(keychain
), "k=%s", ServerCertificate
);
4330 argv
[0] = "certtool";
4335 cupsdLoadEnv(envp
, MAX_ENV
);
4337 infofd
= open(infofile
, O_RDONLY
);
4339 if (!cupsdStartProcess(command
, argv
, envp
, infofd
, -1, -1, -1, -1, 1, NULL
,
4350 while (waitpid(pid
, &status
, 0) < 0)
4357 cupsdFinishProcess(pid
, command
, sizeof(command
));
4361 if (WIFEXITED(status
))
4362 cupsdLogMessage(CUPSD_LOG_ERROR
,
4363 "Unable to create SSL server key and certificate - "
4364 "the certtool command stopped with status %d!",
4365 WEXITSTATUS(status
));
4367 cupsdLogMessage(CUPSD_LOG_ERROR
,
4368 "Unable to create SSL server key and certificate - "
4369 "the certtool command crashed on signal %d!",
4374 cupsdLogMessage(CUPSD_LOG_INFO
,
4375 "Created SSL server certificate file \"%s\"...",
4383 #endif /* HAVE_LIBSSL && HAVE_WAITPID */
4385 #endif /* HAVE_SSL */
4389 * 'pipe_command()' - Pipe the output of a command to the remote client.
4392 static int /* O - Process ID */
4393 pipe_command(cupsd_client_t
*con
, /* I - Client connection */
4394 int infile
, /* I - Standard input for command */
4395 int *outfile
, /* O - Standard output for command */
4396 char *command
, /* I - Command to run */
4397 char *options
, /* I - Options for command */
4398 int root
) /* I - Run as root? */
4400 int i
; /* Looping var */
4401 int pid
; /* Process ID */
4402 char *commptr
, /* Command string pointer */
4403 commch
; /* Command string character */
4404 char *uriptr
; /* URI string pointer */
4405 int fds
[2]; /* Pipe FDs */
4406 int argc
; /* Number of arguments */
4407 int envc
; /* Number of environment variables */
4408 char argbuf
[10240], /* Argument buffer */
4409 *argv
[100], /* Argument strings */
4410 *envp
[MAX_ENV
+ 20]; /* Environment variables */
4411 char auth_type
[256], /* CUPSD_AUTH_TYPE environment variable */
4412 content_length
[1024], /* CONTENT_LENGTH environment variable */
4413 content_type
[1024], /* CONTENT_TYPE environment variable */
4414 http_cookie
[32768], /* HTTP_COOKIE environment variable */
4415 http_referer
[1024], /* HTTP_REFERER environment variable */
4416 http_user_agent
[1024], /* HTTP_USER_AGENT environment variable */
4417 lang
[1024], /* LANG environment variable */
4418 path_info
[1024], /* PATH_INFO environment variable */
4419 remote_addr
[1024], /* REMOTE_ADDR environment variable */
4420 remote_host
[1024], /* REMOTE_HOST environment variable */
4421 remote_user
[1024], /* REMOTE_USER environment variable */
4422 script_filename
[1024], /* SCRIPT_FILENAME environment variable */
4423 script_name
[1024], /* SCRIPT_NAME environment variable */
4424 server_name
[1024], /* SERVER_NAME environment variable */
4425 server_port
[1024]; /* SERVER_PORT environment variable */
4426 ipp_attribute_t
*attr
; /* attributes-natural-language attribute */
4428 krb5_ccache ccache
= NULL
; /* Kerberos credentials */
4429 char krb5ccname
[1024]; /* KRB5CCNAME environment variable */
4430 #endif /* HAVE_GSSAPI */
4434 * Parse a copy of the options string, which is of the form:
4436 * argument+argument+argument
4437 * ?argument+argument+argument
4438 * param=value¶m=value
4439 * ?param=value¶m=value
4440 * /name?argument+argument+argument
4441 * /name?param=value¶m=value
4443 * If the string contains an "=" character after the initial name,
4444 * then we treat it as a HTTP GET form request and make a copy of
4445 * the remaining string for the environment variable.
4447 * The string is always parsed out as command-line arguments, to
4448 * be consistent with Apache...
4451 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4452 "pipe_command: command=\"%s\", options=\"%s\"",
4453 command
, options
? options
: "(null)");
4458 strlcpy(argbuf
, options
, sizeof(argbuf
));
4462 if (argbuf
[0] == '/')
4465 * Found some trailing path information, set PATH_INFO...
4468 if ((commptr
= strchr(argbuf
, '?')) == NULL
)
4469 commptr
= argbuf
+ strlen(argbuf
);
4473 snprintf(path_info
, sizeof(path_info
), "PATH_INFO=%s", argbuf
);
4479 path_info
[0] = '\0';
4481 if (*commptr
== ' ')
4485 if (*commptr
== '?' && con
->operation
== HTTP_GET
&& !con
->query_string
)
4488 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", commptr
);
4495 argv
[argc
++] = commptr
;
4497 for (; *commptr
&& argc
< 99; commptr
++)
4500 * Break arguments whenever we see a + or space...
4503 if (*commptr
== ' ' || *commptr
== '+')
4505 while (*commptr
== ' ' || *commptr
== '+')
4509 * If we don't have a blank string, save it as another argument...
4514 argv
[argc
] = commptr
;
4520 else if (*commptr
== '%' && isxdigit(commptr
[1] & 255) &&
4521 isxdigit(commptr
[2] & 255))
4524 * Convert the %xx notation to the individual character.
4527 if (commptr
[1] >= '0' && commptr
[1] <= '9')
4528 *commptr
= (commptr
[1] - '0') << 4;
4530 *commptr
= (tolower(commptr
[1]) - 'a' + 10) << 4;
4532 if (commptr
[2] >= '0' && commptr
[2] <= '9')
4533 *commptr
|= commptr
[2] - '0';
4535 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
4537 _cups_strcpy(commptr
+ 1, commptr
+ 3);
4540 * Check for a %00 and break if that is the case...
4552 * Setup the environment variables as needed...
4555 if (con
->username
[0])
4557 snprintf(auth_type
, sizeof(auth_type
), "CUPSD_AUTH_TYPE=%s",
4558 httpGetField(HTTP(con
), HTTP_FIELD_AUTHORIZATION
));
4560 if ((uriptr
= strchr(auth_type
+ 10, ' ')) != NULL
)
4564 auth_type
[0] = '\0';
4567 (attr
= ippFindAttribute(con
->request
, "attributes-natural-language",
4568 IPP_TAG_LANGUAGE
)) != NULL
)
4570 switch (strlen(attr
->values
[0].string
.text
))
4574 * This is an unknown or badly formatted language code; use
4575 * the POSIX locale...
4578 strcpy(lang
, "LANG=C");
4583 * Just the language code (ll)...
4586 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8",
4587 attr
->values
[0].string
.text
);
4592 * Language and country code (ll-cc)...
4595 snprintf(lang
, sizeof(lang
), "LANG=%c%c_%c%c.UTF8",
4596 attr
->values
[0].string
.text
[0],
4597 attr
->values
[0].string
.text
[1],
4598 toupper(attr
->values
[0].string
.text
[3] & 255),
4599 toupper(attr
->values
[0].string
.text
[4] & 255));
4603 else if (con
->language
)
4604 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8", con
->language
->language
);
4606 strcpy(lang
, "LANG=C");
4608 strcpy(remote_addr
, "REMOTE_ADDR=");
4609 httpAddrString(con
->http
.hostaddr
, remote_addr
+ 12,
4610 sizeof(remote_addr
) - 12);
4612 snprintf(remote_host
, sizeof(remote_host
), "REMOTE_HOST=%s",
4613 con
->http
.hostname
);
4615 snprintf(script_name
, sizeof(script_name
), "SCRIPT_NAME=%s", con
->uri
);
4616 if ((uriptr
= strchr(script_name
, '?')) != NULL
)
4619 snprintf(script_filename
, sizeof(script_filename
), "SCRIPT_FILENAME=%s%s",
4620 DocumentRoot
, script_name
+ 12);
4622 sprintf(server_port
, "SERVER_PORT=%d", con
->serverport
);
4624 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
4627 envc
= cupsdLoadEnv(envp
, (int)(sizeof(envp
) / sizeof(envp
[0])));
4630 envp
[envc
++] = auth_type
;
4632 envp
[envc
++] = lang
;
4633 envp
[envc
++] = "REDIRECT_STATUS=1";
4634 envp
[envc
++] = "GATEWAY_INTERFACE=CGI/1.1";
4635 envp
[envc
++] = server_name
;
4636 envp
[envc
++] = server_port
;
4637 envp
[envc
++] = remote_addr
;
4638 envp
[envc
++] = remote_host
;
4639 envp
[envc
++] = script_name
;
4640 envp
[envc
++] = script_filename
;
4643 envp
[envc
++] = path_info
;
4645 if (con
->username
[0])
4647 snprintf(remote_user
, sizeof(remote_user
), "REMOTE_USER=%s", con
->username
);
4649 envp
[envc
++] = remote_user
;
4652 * Save Kerberos credentials, if any...
4656 if (con
->gss_have_creds
)
4658 # if !defined(HAVE_KRB5_CC_NEW_UNIQUE) && !defined(HAVE_HEIMDAL)
4659 cupsdLogMessage(CUPSD_LOG_INFO
,
4660 "Sorry, your version of Kerberos does not support "
4661 "delegated credentials!");
4664 krb5_error_code error
; /* Kerberos error code */
4665 OM_uint32 major_status
, /* Major status code */
4666 minor_status
; /* Minor status code */
4667 krb5_principal principal
; /* Kerberos principal */
4672 * If the weak-linked GSSAPI/Kerberos library is not present, don't try
4676 if (krb5_init_context
!= NULL
)
4678 # endif /* __APPLE__ */
4681 * We MUST create a file-based cache because memory-based caches are
4682 * only valid for the current process/address space.
4684 * Due to various bugs/features in different versions of Kerberos, we
4685 * need either the krb5_cc_new_unique() function or Heimdal's version
4686 * of krb5_cc_gen_new() to create a new FILE: credential cache that
4687 * can be passed to the backend. These functions create a temporary
4688 * file (typically in /tmp) containing the cached credentials, which
4689 * are removed when we have successfully printed a job.
4692 # ifdef HAVE_KRB5_CC_NEW_UNIQUE
4693 if ((error
= krb5_cc_new_unique(KerberosContext
, "FILE", NULL
,
4695 # else /* HAVE_HEIMDAL */
4696 if ((error
= krb5_cc_gen_new(KerberosContext
, &krb5_fcc_ops
,
4698 # endif /* HAVE_KRB5_CC_NEW_UNIQUE */
4700 cupsdLogMessage(CUPSD_LOG_ERROR
,
4701 "Unable to create new credentials cache (%d/%s)",
4702 error
, strerror(errno
));
4705 else if ((error
= krb5_parse_name(KerberosContext
, con
->username
,
4708 cupsdLogMessage(CUPSD_LOG_ERROR
,
4709 "Unable to parse kerberos username (%d/%s)", error
,
4711 krb5_cc_destroy(KerberosContext
, ccache
);
4714 else if ((error
= krb5_cc_initialize(KerberosContext
, ccache
,
4717 cupsdLogMessage(CUPSD_LOG_ERROR
,
4718 "Unable to initialize credentials cache (%d/%s)", error
,
4720 krb5_cc_destroy(KerberosContext
, ccache
);
4721 krb5_free_principal(KerberosContext
, principal
);
4726 krb5_free_principal(KerberosContext
, principal
);
4729 * Copy the user's credentials to the new cache file...
4732 major_status
= gss_krb5_copy_ccache(&minor_status
,
4733 con
->gss_delegated_cred
, ccache
);
4735 if (GSS_ERROR(major_status
))
4737 cupsdLogGSSMessage(CUPSD_LOG_ERROR
, major_status
, minor_status
,
4738 "Unable to import client credentials cache");
4739 krb5_cc_destroy(KerberosContext
, ccache
);
4745 * Add the KRB5CCNAME environment variable to the job so that the
4746 * backend can use the credentials when printing.
4749 snprintf(krb5ccname
, sizeof(krb5ccname
), "KRB5CCNAME=FILE:%s",
4750 krb5_cc_get_name(KerberosContext
, ccache
));
4751 envp
[envc
++] = krb5ccname
;
4754 chown(krb5_cc_get_name(KerberosContext
, ccache
), User
, Group
);
4759 # endif /* __APPLE__ */
4760 # endif /* HAVE_KRB5_CC_NEW_UNIQUE || HAVE_HEIMDAL */
4762 #endif /* HAVE_GSSAPI */
4766 if (con
->http
.version
== HTTP_1_1
)
4767 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.1";
4768 else if (con
->http
.version
== HTTP_1_0
)
4769 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.0";
4771 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/0.9";
4773 if (con
->http
.cookie
)
4775 snprintf(http_cookie
, sizeof(http_cookie
), "HTTP_COOKIE=%s",
4777 envp
[envc
++] = http_cookie
;
4780 if (con
->http
.fields
[HTTP_FIELD_USER_AGENT
][0])
4782 snprintf(http_user_agent
, sizeof(http_user_agent
), "HTTP_USER_AGENT=%s",
4783 con
->http
.fields
[HTTP_FIELD_USER_AGENT
]);
4784 envp
[envc
++] = http_user_agent
;
4787 if (con
->http
.fields
[HTTP_FIELD_REFERER
][0])
4789 snprintf(http_referer
, sizeof(http_referer
), "HTTP_REFERER=%s",
4790 con
->http
.fields
[HTTP_FIELD_REFERER
]);
4791 envp
[envc
++] = http_referer
;
4794 if (con
->operation
== HTTP_GET
)
4796 envp
[envc
++] = "REQUEST_METHOD=GET";
4798 if (con
->query_string
)
4801 * Add GET form variables after ?...
4804 envp
[envc
++] = con
->query_string
;
4807 envp
[envc
++] = "QUERY_STRING=";
4811 sprintf(content_length
, "CONTENT_LENGTH=" CUPS_LLFMT
,
4812 CUPS_LLCAST con
->bytes
);
4813 snprintf(content_type
, sizeof(content_type
), "CONTENT_TYPE=%s",
4814 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
4816 envp
[envc
++] = "REQUEST_METHOD=POST";
4817 envp
[envc
++] = content_length
;
4818 envp
[envc
++] = content_type
;
4822 * Tell the CGI if we are using encryption...
4826 envp
[envc
++] = "HTTPS=ON";
4829 * Terminate the environment array...
4834 if (LogLevel
== CUPSD_LOG_DEBUG2
)
4836 for (i
= 0; i
< argc
; i
++)
4837 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4838 "pipe_command: argv[%d] = \"%s\"", i
, argv
[i
]);
4839 for (i
= 0; i
< envc
; i
++)
4840 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4841 "pipe_command: envp[%d] = \"%s\"", i
, envp
[i
]);
4845 * Create a pipe for the output...
4848 if (cupsdOpenPipe(fds
))
4850 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to create pipes for CGI %s - %s",
4851 argv
[0], strerror(errno
));
4856 * Then execute the command...
4859 if (cupsdStartProcess(command
, argv
, envp
, infile
, fds
[1], CGIPipes
[1],
4860 -1, -1, root
, DefaultProfile
, &pid
) < 0)
4863 * Error - can't fork!
4866 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to fork for CGI %s - %s", argv
[0],
4869 cupsdClosePipe(fds
);
4875 * Fork successful - return the PID...
4878 if (con
->username
[0])
4880 cupsdAddCert(pid
, con
->username
, ccache
);
4882 cupsdAddCert(pid
, con
->username
, NULL
);
4883 #endif /* HAVE_GSSAPI */
4885 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[CGI] %s started - PID = %d",
4897 * 'write_file()' - Send a file via HTTP.
4900 static int /* O - 0 on failure, 1 on success */
4901 write_file(cupsd_client_t
*con
, /* I - Client connection */
4902 http_status_t code
, /* I - HTTP status */
4903 char *filename
, /* I - Filename */
4904 char *type
, /* I - File type */
4905 struct stat
*filestats
) /* O - File information */
4907 con
->file
= open(filename
, O_RDONLY
);
4909 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "write_file: %d file=%d", con
->http
.fd
,
4915 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
4919 if (!cupsdSendHeader(con
, code
, type
, CUPSD_AUTH_NONE
))
4922 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
4923 httpGetDateString(filestats
->st_mtime
)) < 0)
4925 if (httpPrintf(HTTP(con
), "Content-Length: " CUPS_LLFMT
"\r\n",
4926 CUPS_LLCAST filestats
->st_size
) < 0)
4928 if (httpPrintf(HTTP(con
), "\r\n") < 0)
4931 if (cupsdFlushHeader(con
) < 0)
4934 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
4935 con
->http
.data_remaining
= filestats
->st_size
;
4937 if (con
->http
.data_remaining
<= INT_MAX
)
4938 con
->http
._data_remaining
= con
->http
.data_remaining
;
4940 con
->http
._data_remaining
= INT_MAX
;
4942 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
,
4943 (cupsd_selfunc_t
)cupsdWriteClient
, con
);
4950 * 'write_pipe()' - Flag that data is available on the CGI pipe.
4954 write_pipe(cupsd_client_t
*con
) /* I - Client connection */
4956 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "write_pipe: CGI output on fd %d...",
4959 con
->file_ready
= 1;
4961 cupsdRemoveSelect(con
->file
);
4962 cupsdAddSelect(con
->http
.fd
, NULL
, (cupsd_selfunc_t
)cupsdWriteClient
, con
);
4967 * End of "$Id: client.c 7673 2008-06-18 22:31:26Z mike $".