2 * "$Id: client.c 7950 2008-09-17 00:21:59Z mike $"
4 * Client routines for the Common UNIX Printing System (CUPS) scheduler.
6 * Copyright 2007-2008 by Apple Inc.
7 * Copyright 1997-2007 by Easy Software Products, all rights reserved.
9 * This file contains Kerberos support code, copyright 2006 by
12 * These coded instructions, statements, and computer programs are the
13 * property of Apple Inc. and are protected by Federal copyright
14 * law. Distribution and use rights are outlined in the file "LICENSE.txt"
15 * which should have been included with this file. If this file is
16 * file is missing or damaged, see the license at "http://www.cups.org/".
20 * cupsdAcceptClient() - Accept a new client.
21 * cupsdCloseAllClients() - Close all remote clients immediately.
22 * cupsdCloseClient() - Close a remote client.
23 * cupsdFlushHeader() - Flush the header fields to the client.
24 * cupsdReadClient() - Read data from a client.
25 * cupsdSendCommand() - Send output from a command via HTTP.
26 * cupsdSendError() - Send an error message via HTTP.
27 * cupsdSendHeader() - Send an HTTP request.
28 * cupsdUpdateCGI() - Read status messages from CGI scripts and programs.
29 * cupsdWriteClient() - Write data to a client as needed.
30 * check_if_modified() - Decode an "If-Modified-Since" line.
31 * compare_clients() - Compare two client connections.
32 * data_ready() - Check whether data is available from a client.
33 * encrypt_client() - Enable encryption for the client...
34 * get_cdsa_certificate() - Convert a keychain name into the CFArrayRef
35 * required by SSLSetCertificate.
36 * get_file() - Get a filename and state info.
37 * install_conf_file() - Install a configuration file.
38 * is_cgi() - Is the resource a CGI script/program?
39 * is_path_absolute() - Is a path absolute and free of relative elements.
40 * make_certificate() - Make a self-signed SSL/TLS certificate.
41 * pipe_command() - Pipe the output of a command to the remote client.
42 * write_file() - Send a file via HTTP.
43 * write_pipe() - Flag that data is available on the CGI pipe.
47 * Include necessary headers...
53 # include <Security/Security.h>
54 # ifdef HAVE_SECIDENTITYSEARCHPRIV_H
55 # include <Security/SecIdentitySearchPriv.h>
56 # else /* Declare prototype for function in that header... */
57 extern OSStatus
SecIdentitySearchCreateWithPolicy(SecPolicyRef policy
,
58 CFStringRef idString
, CSSM_KEYUSE keyUsage
,
59 CFTypeRef keychainOrArray
,
60 Boolean returnOnlyValidIdentities
,
61 SecIdentitySearchRef
* searchRef
);
62 # endif /* HAVE_SECIDENTITYSEARCHPRIV_H */
63 # ifdef HAVE_SECPOLICYPRIV_H
64 # include <Security/SecPolicyPriv.h>
65 # else /* Declare prototype for function in that header... */
66 extern OSStatus
SecPolicySetValue(SecPolicyRef policyRef
,
67 const CSSM_DATA
*value
);
68 # endif /* HAVE_SECPOLICYPRIV_H */
69 # ifdef HAVE_SECBASEPRIV_H
70 # include <Security/SecBasePriv.h>
71 # else /* Declare prototype for function in that header... */
72 extern const char *cssmErrorString(int error
);
73 # endif /* HAVE_SECBASEPRIV_H */
74 #endif /* HAVE_CDSASSL */
77 # include <gnutls/x509.h>
78 #endif /* HAVE_GNUTLS */
82 #endif /* HAVE_TCPD_H */
89 static int check_if_modified(cupsd_client_t
*con
,
90 struct stat
*filestats
);
91 static int compare_clients(cupsd_client_t
*a
, cupsd_client_t
*b
,
93 static int data_ready(cupsd_client_t
*con
);
95 static int encrypt_client(cupsd_client_t
*con
);
98 static CFArrayRef
get_cdsa_certificate(cupsd_client_t
*con
);
99 #endif /* HAVE_CDSASSL */
100 static char *get_file(cupsd_client_t
*con
, struct stat
*filestats
,
101 char *filename
, int len
);
102 static http_status_t
install_conf_file(cupsd_client_t
*con
);
103 static int is_cgi(cupsd_client_t
*con
, const char *filename
,
104 struct stat
*filestats
, mime_type_t
*type
);
105 static int is_path_absolute(const char *path
);
107 static int make_certificate(cupsd_client_t
*con
);
108 #endif /* HAVE_SSL */
109 static int pipe_command(cupsd_client_t
*con
, int infile
, int *outfile
,
110 char *command
, char *options
, int root
);
111 static int write_file(cupsd_client_t
*con
, http_status_t code
,
112 char *filename
, char *type
,
113 struct stat
*filestats
);
114 static void write_pipe(cupsd_client_t
*con
);
118 * 'cupsdAcceptClient()' - Accept a new client.
122 cupsdAcceptClient(cupsd_listener_t
*lis
)/* I - Listener socket */
124 int count
; /* Count of connections on a host */
125 int val
; /* Parameter value */
126 cupsd_client_t
*con
, /* New client pointer */
127 *tempcon
; /* Temporary client pointer */
128 http_addrlist_t
*addrlist
, /* List of adddresses for host */
129 *addr
; /* Current address */
130 socklen_t addrlen
; /* Length of address */
131 char *hostname
; /* Hostname for address */
132 http_addr_t temp
; /* Temporary address variable */
133 static time_t last_dos
= 0; /* Time of last DoS attack */
135 struct request_info wrap_req
; /* TCP wrappers request information */
136 #endif /* HAVE_TCPD_H */
139 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
140 "cupsdAcceptClient(lis=%p) %d Clients = %d",
141 lis
, lis
->fd
, cupsArrayCount(Clients
));
144 * Make sure we don't have a full set of clients already...
147 if (cupsArrayCount(Clients
) == MaxClients
)
151 * Get a pointer to the next available client...
155 Clients
= cupsArrayNew(NULL
, NULL
);
159 cupsdLogMessage(CUPSD_LOG_ERROR
,
160 "Unable to allocate memory for clients array!");
161 cupsdPauseListening();
166 ActiveClients
= cupsArrayNew((cups_array_func_t
)compare_clients
, NULL
);
170 cupsdLogMessage(CUPSD_LOG_ERROR
,
171 "Unable to allocate memory for active clients array!");
172 cupsdPauseListening();
176 if ((con
= calloc(1, sizeof(cupsd_client_t
))) == NULL
)
178 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to allocate memory for client!");
179 cupsdPauseListening();
183 con
->http
.activity
= time(NULL
);
185 con
->http
.hostaddr
= &(con
->clientaddr
);
188 * Accept the client and get the remote address...
191 addrlen
= sizeof(http_addr_t
);
193 if ((con
->http
.fd
= accept(lis
->fd
, (struct sockaddr
*)con
->http
.hostaddr
,
196 if (errno
== ENFILE
|| errno
== EMFILE
)
197 cupsdPauseListening();
199 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to accept client connection - %s.",
207 if (lis
->address
.addr
.sa_family
== AF_INET6
)
210 * Save the connected port number...
213 con
->http
.hostaddr
->ipv6
.sin6_port
= lis
->address
.ipv6
.sin6_port
;
216 * Convert IPv4 over IPv6 addresses (::ffff:n.n.n.n) to IPv4 forms we
217 * can more easily use...
220 if (con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[0] == 0 &&
221 con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[1] == 0 &&
222 ntohl(con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[2]) == 0xffff)
223 con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[2] = 0;
226 #endif /* AF_INET6 */
227 if (lis
->address
.addr
.sa_family
== AF_INET
)
228 con
->http
.hostaddr
->ipv4
.sin_port
= lis
->address
.ipv4
.sin_port
;
231 * Check the number of clients on the same address...
234 for (count
= 0, tempcon
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
236 tempcon
= (cupsd_client_t
*)cupsArrayNext(Clients
))
237 if (httpAddrEqual(tempcon
->http
.hostaddr
, con
->http
.hostaddr
))
240 if (count
>= MaxClientsPerHost
)
244 if (count
>= MaxClientsPerHost
)
246 if ((time(NULL
) - last_dos
) >= 60)
248 last_dos
= time(NULL
);
249 cupsdLogMessage(CUPSD_LOG_WARN
,
250 "Possible DoS attack - more than %d clients connecting "
253 httpAddrString(con
->http
.hostaddr
, con
->http
.hostname
,
254 sizeof(con
->http
.hostname
)));
258 closesocket(con
->http
.fd
);
268 * Get the hostname or format the IP address as needed...
271 if (httpAddrLocalhost(con
->http
.hostaddr
))
274 * Map accesses from the loopback interface to "localhost"...
277 strlcpy(con
->http
.hostname
, "localhost", sizeof(con
->http
.hostname
));
278 hostname
= con
->http
.hostname
;
283 * Map accesses from the same host to the server name.
286 for (addr
= ServerAddrs
; addr
; addr
= addr
->next
)
287 if (httpAddrEqual(con
->http
.hostaddr
, &(addr
->addr
)))
292 strlcpy(con
->http
.hostname
, ServerName
, sizeof(con
->http
.hostname
));
293 hostname
= con
->http
.hostname
;
295 else if (HostNameLookups
)
296 hostname
= httpAddrLookup(con
->http
.hostaddr
, con
->http
.hostname
,
297 sizeof(con
->http
.hostname
));
301 httpAddrString(con
->http
.hostaddr
, con
->http
.hostname
,
302 sizeof(con
->http
.hostname
));
306 if (hostname
== NULL
&& HostNameLookups
== 2)
309 * Can't have an unresolved IP address with double-lookups enabled...
312 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
313 "cupsdAcceptClient: Closing connection %d...",
317 closesocket(con
->http
.fd
);
322 cupsdLogMessage(CUPSD_LOG_WARN
,
323 "Name lookup failed - connection from %s closed!",
330 if (HostNameLookups
== 2)
333 * Do double lookups as needed...
336 if ((addrlist
= httpAddrGetList(con
->http
.hostname
, AF_UNSPEC
, NULL
))
340 * See if the hostname maps to the same IP address...
343 for (addr
= addrlist
; addr
; addr
= addr
->next
)
344 if (httpAddrEqual(con
->http
.hostaddr
, &(addr
->addr
)))
350 httpAddrFreeList(addrlist
);
355 * Can't have a hostname that doesn't resolve to the same IP address
356 * with double-lookups enabled...
359 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
360 "cupsdAcceptClient: Closing connection %d...",
364 closesocket(con
->http
.fd
);
369 cupsdLogMessage(CUPSD_LOG_WARN
,
370 "IP lookup failed - connection from %s closed!",
379 * See if the connection is denied by TCP wrappers...
382 request_init(&wrap_req
, RQ_DAEMON
, "cupsd", RQ_FILE
, con
->http
.fd
, NULL
);
385 if (!hosts_access(&wrap_req
))
387 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
388 "cupsdAcceptClient: Closing connection %d...",
392 closesocket(con
->http
.fd
);
397 cupsdLogMessage(CUPSD_LOG_WARN
,
398 "Connection from %s refused by /etc/hosts.allow and "
399 "/etc/hosts.deny rules.", con
->http
.hostname
);
403 #endif /* HAVE_TCPD_H */
406 if (con
->http
.hostaddr
->addr
.sa_family
== AF_INET6
)
407 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdAcceptClient: %d from %s:%d (IPv6)",
408 con
->http
.fd
, con
->http
.hostname
,
409 ntohs(con
->http
.hostaddr
->ipv6
.sin6_port
));
411 #endif /* AF_INET6 */
413 if (con
->http
.hostaddr
->addr
.sa_family
== AF_LOCAL
)
414 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdAcceptClient: %d from %s (Domain)",
415 con
->http
.fd
, con
->http
.hostname
);
417 #endif /* AF_LOCAL */
418 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdAcceptClient: %d from %s:%d (IPv4)",
419 con
->http
.fd
, con
->http
.hostname
,
420 ntohs(con
->http
.hostaddr
->ipv4
.sin_port
));
423 * Get the local address the client connected to...
426 addrlen
= sizeof(temp
);
427 if (getsockname(con
->http
.fd
, (struct sockaddr
*)&temp
, &addrlen
))
429 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to get local address - %s",
432 strcpy(con
->servername
, "localhost");
433 con
->serverport
= LocalPort
;
438 if (temp
.addr
.sa_family
== AF_INET6
)
441 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
443 httpAddrString(&temp
, con
->servername
, sizeof(con
->servername
));
445 con
->serverport
= ntohs(lis
->address
.ipv6
.sin6_port
);
448 #endif /* AF_INET6 */
449 if (temp
.addr
.sa_family
== AF_INET
)
452 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
454 httpAddrString(&temp
, con
->servername
, sizeof(con
->servername
));
456 con
->serverport
= ntohs(lis
->address
.ipv4
.sin_port
);
460 strcpy(con
->servername
, "localhost");
461 con
->serverport
= LocalPort
;
465 cupsArrayAdd(Clients
, con
);
467 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
468 "cupsdAcceptClient: %d connected to server on %s:%d",
469 con
->http
.fd
, con
->servername
, con
->serverport
);
472 * Using TCP_NODELAY improves responsiveness, especially on systems
473 * with a slow loopback interface... Since we write large buffers
474 * when sending print files and requests, there shouldn't be any
475 * performance penalty for this...
479 setsockopt(con
->http
.fd
, IPPROTO_TCP
, TCP_NODELAY
, &val
, sizeof(val
));
482 * Close this file on all execs...
485 fcntl(con
->http
.fd
, F_SETFD
, fcntl(con
->http
.fd
, F_GETFD
) | FD_CLOEXEC
);
488 * Add the socket to the select() input mask.
491 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
494 * Temporarily suspend accept()'s until we lose a client...
497 if (cupsArrayCount(Clients
) == MaxClients
)
498 cupsdPauseListening();
502 * See if we are connecting on a secure port...
505 if (lis
->encryption
== HTTP_ENCRYPT_ALWAYS
)
508 * https connection; go secure...
511 con
->http
.encryption
= HTTP_ENCRYPT_ALWAYS
;
513 if (!encrypt_client(con
))
514 cupsdCloseClient(con
);
518 #endif /* HAVE_SSL */
523 * 'cupsdCloseAllClients()' - Close all remote clients immediately.
527 cupsdCloseAllClients(void)
529 cupsd_client_t
*con
; /* Current client */
532 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
534 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
535 if (cupsdCloseClient(con
))
536 cupsdCloseClient(con
);
541 * 'cupsdCloseClient()' - Close a remote client.
544 int /* O - 1 if partial close, 0 if fully closed */
545 cupsdCloseClient(cupsd_client_t
*con
) /* I - Client to close */
547 int partial
; /* Do partial close for SSL? */
549 SSL_CTX
*context
; /* Context for encryption */
550 SSL
*conn
; /* Connection for encryption */
551 unsigned long error
; /* Error code */
552 #elif defined(HAVE_GNUTLS)
553 http_tls_t
*conn
; /* TLS connection information */
554 int error
; /* Error code */
555 gnutls_certificate_server_credentials
*credentials
;
556 /* TLS credentials */
557 # elif defined(HAVE_CDSASSL)
558 http_tls_t
*conn
; /* CDSA connection information */
559 #endif /* HAVE_LIBSSL */
562 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdCloseClient: %d", con
->http
.fd
);
565 * Flush pending writes before closing...
568 httpFlushWrite(HTTP(con
));
574 * Shutdown encryption as needed...
582 conn
= (SSL
*)(con
->http
.tls
);
583 context
= SSL_get_SSL_CTX(conn
);
585 switch (SSL_shutdown(conn
))
588 cupsdLogMessage(CUPSD_LOG_DEBUG
,
589 "SSL shutdown successful!");
592 cupsdLogMessage(CUPSD_LOG_ERROR
,
593 "Fatal error during SSL shutdown!");
595 while ((error
= ERR_get_error()) != 0)
596 cupsdLogMessage(CUPSD_LOG_ERROR
, "SSL shutdown failed: %s",
597 ERR_error_string(error
, NULL
));
601 SSL_CTX_free(context
);
604 # elif defined(HAVE_GNUTLS)
605 conn
= (http_tls_t
*)(con
->http
.tls
);
606 credentials
= (gnutls_certificate_server_credentials
*)(conn
->credentials
);
608 error
= gnutls_bye(conn
->session
, GNUTLS_SHUT_WR
);
611 case GNUTLS_E_SUCCESS
:
612 cupsdLogMessage(CUPSD_LOG_DEBUG
,
613 "SSL shutdown successful!");
616 cupsdLogMessage(CUPSD_LOG_ERROR
,
617 "SSL shutdown failed: %s", gnutls_strerror(error
));
621 gnutls_deinit(conn
->session
);
622 gnutls_certificate_free_credentials(*credentials
);
626 # elif defined(HAVE_CDSASSL)
627 conn
= (http_tls_t
*)(con
->http
.tls
);
629 while (SSLClose(conn
->session
) == errSSLWouldBlock
)
632 SSLDisposeContext(conn
->session
);
634 if (conn
->certsArray
)
635 CFRelease(conn
->certsArray
);
638 # endif /* HAVE_LIBSSL */
640 con
->http
.tls
= NULL
;
642 #endif /* HAVE_SSL */
644 if (con
->pipe_pid
!= 0)
647 * Stop any CGI process...
650 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
651 "cupsdCloseClient: %d Killing process ID %d...",
652 con
->http
.fd
, con
->pipe_pid
);
653 cupsdEndProcess(con
->pipe_pid
, 1);
659 cupsdRemoveSelect(con
->file
);
661 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
662 "cupsdCloseClient: %d Closing data file %d.",
663 con
->http
.fd
, con
->file
);
670 * Close the socket and clear the file from the input set for select()...
673 if (con
->http
.fd
>= 0)
675 cupsArrayRemove(ActiveClients
, con
);
681 * Only do a partial close so that the encrypted client gets everything.
684 shutdown(con
->http
.fd
, 0);
685 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
690 * Shut the socket down fully...
693 cupsdRemoveSelect(con
->http
.fd
);
705 if (con
->http
.input_set
)
706 free(con
->http
.input_set
);
708 httpClearCookie(HTTP(con
));
709 httpClearFields(HTTP(con
));
711 cupsdClearString(&con
->filename
);
712 cupsdClearString(&con
->command
);
713 cupsdClearString(&con
->options
);
714 cupsdClearString(&con
->query_string
);
718 ippDelete(con
->request
);
724 ippDelete(con
->response
);
725 con
->response
= NULL
;
730 cupsLangFree(con
->language
);
731 con
->language
= NULL
;
734 #ifdef HAVE_AUTHORIZATION_H
737 AuthorizationFree(con
->authref
, kAuthorizationFlagDefaults
);
740 #endif /* HAVE_AUTHORIZATION_H */
743 * Re-enable new client connections if we are going back under the
747 if (cupsArrayCount(Clients
) == MaxClients
)
748 cupsdResumeListening();
751 * Compact the list of clients as necessary...
754 cupsArrayRemove(Clients
, con
);
764 * 'cupsdFlushHeader()' - Flush the header fields to the client.
767 int /* I - Bytes written or -1 on error */
768 cupsdFlushHeader(cupsd_client_t
*con
) /* I - Client to flush to */
770 int bytes
= httpFlushWrite(HTTP(con
));
772 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
779 * 'cupsdReadClient()' - Read data from a client.
783 cupsdReadClient(cupsd_client_t
*con
) /* I - Client to read from */
785 char line
[32768], /* Line from client... */
786 operation
[64], /* Operation code from socket */
787 version
[64], /* HTTP version number string */
788 locale
[64], /* Locale */
789 *ptr
; /* Pointer into strings */
790 int major
, minor
; /* HTTP version numbers */
791 http_status_t status
; /* Transfer status */
792 ipp_state_t ipp_state
; /* State of IPP transfer */
793 int bytes
; /* Number of bytes to POST */
794 char *filename
; /* Name of file for GET/HEAD */
795 char buf
[1024]; /* Buffer for real filename */
796 struct stat filestats
; /* File information */
797 mime_type_t
*type
; /* MIME type of file */
798 cupsd_printer_t
*p
; /* Printer */
799 static unsigned request_id
= 0; /* Request ID for temp files */
802 status
= HTTP_CONTINUE
;
804 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
805 "cupsdReadClient: %d, used=%d, file=%d state=%d",
806 con
->http
.fd
, con
->http
.used
, con
->file
, con
->http
.state
);
810 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdReadClient: http error seen...");
811 cupsdCloseClient(con
);
819 * Automatically check for a SSL/TLS handshake...
824 if (recv(con
->http
.fd
, buf
, 1, MSG_PEEK
) == 1 &&
825 (!buf
[0] || !strchr("DGHOPT", buf
[0])))
828 * Encrypt this connection...
831 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
832 "cupsdReadClient: Saw first byte %02X, auto-negotiating SSL/TLS session...",
835 if (!encrypt_client(con
))
836 cupsdCloseClient(con
);
841 #endif /* HAVE_SSL */
843 switch (con
->http
.state
)
847 * See if we've received a request line...
850 if (httpGets(line
, sizeof(line
) - 1, HTTP(con
)) == NULL
)
852 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
853 "cupsdReadClient: httpGets returned EOF...");
854 cupsdCloseClient(con
);
859 * Ignore blank request lines...
866 * Clear other state variables...
869 httpClearFields(HTTP(con
));
871 con
->http
.activity
= time(NULL
);
872 con
->http
.version
= HTTP_1_0
;
873 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
874 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
875 con
->http
.data_remaining
= 0;
876 con
->http
._data_remaining
= 0;
877 con
->operation
= HTTP_WAITING
;
882 con
->username
[0] = '\0';
883 con
->password
[0] = '\0';
886 cupsdClearString(&con
->command
);
887 cupsdClearString(&con
->options
);
888 cupsdClearString(&con
->query_string
);
892 ippDelete(con
->request
);
898 ippDelete(con
->response
);
899 con
->response
= NULL
;
904 cupsLangFree(con
->language
);
905 con
->language
= NULL
;
909 con
->gss_have_creds
= 0;
910 #endif /* HAVE_GSSAPI */
913 * Grab the request line...
916 switch (sscanf(line
, "%63s%1023s%63s", operation
, con
->uri
, version
))
921 cupsdLogMessage(CUPSD_LOG_ERROR
,
922 "Bad request line \"%s\" from %s!", line
,
924 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
925 cupsdCloseClient(con
);
929 con
->http
.version
= HTTP_0_9
;
932 if (sscanf(version
, "HTTP/%d.%d", &major
, &minor
) != 2)
934 cupsdLogMessage(CUPSD_LOG_ERROR
,
935 "Bad request line \"%s\" from %s!", line
,
937 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
938 cupsdCloseClient(con
);
944 con
->http
.version
= (http_version_t
)(major
* 100 + minor
);
945 if (con
->http
.version
== HTTP_1_1
&& KeepAlive
)
946 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
948 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
952 cupsdSendError(con
, HTTP_NOT_SUPPORTED
, CUPSD_AUTH_NONE
);
953 cupsdCloseClient(con
);
960 * Handle full URLs in the request line...
963 if (strcmp(con
->uri
, "*"))
965 char method
[HTTP_MAX_URI
], /* Method/scheme */
966 userpass
[HTTP_MAX_URI
], /* Username:password */
967 hostname
[HTTP_MAX_URI
], /* Hostname */
968 resource
[HTTP_MAX_URI
]; /* Resource path */
969 int port
; /* Port number */
973 * Separate the URI into its components...
976 httpSeparateURI(HTTP_URI_CODING_MOST
, con
->uri
,
977 method
, sizeof(method
),
978 userpass
, sizeof(userpass
),
979 hostname
, sizeof(hostname
), &port
,
980 resource
, sizeof(resource
));
983 * Only allow URIs with the servername, localhost, or an IP
987 if (strcmp(method
, "file") &&
988 strcasecmp(hostname
, ServerName
) &&
989 strcasecmp(hostname
, "localhost") &&
990 !isdigit(hostname
[0]))
993 * Nope, we don't do proxies...
996 cupsdLogMessage(CUPSD_LOG_ERROR
, "Bad URI \"%s\" in request!",
998 cupsdSendError(con
, HTTP_METHOD_NOT_ALLOWED
, CUPSD_AUTH_NONE
);
999 cupsdCloseClient(con
);
1004 * Copy the resource portion back into the URI; both resource and
1005 * con->uri are HTTP_MAX_URI bytes in size...
1008 strcpy(con
->uri
, resource
);
1012 * Process the request...
1015 if (!strcmp(operation
, "GET"))
1016 con
->http
.state
= HTTP_GET
;
1017 else if (!strcmp(operation
, "PUT"))
1018 con
->http
.state
= HTTP_PUT
;
1019 else if (!strcmp(operation
, "POST"))
1020 con
->http
.state
= HTTP_POST
;
1021 else if (!strcmp(operation
, "DELETE"))
1022 con
->http
.state
= HTTP_DELETE
;
1023 else if (!strcmp(operation
, "TRACE"))
1024 con
->http
.state
= HTTP_TRACE
;
1025 else if (!strcmp(operation
, "OPTIONS"))
1026 con
->http
.state
= HTTP_OPTIONS
;
1027 else if (!strcmp(operation
, "HEAD"))
1028 con
->http
.state
= HTTP_HEAD
;
1031 cupsdLogMessage(CUPSD_LOG_ERROR
, "Bad operation \"%s\"!", operation
);
1032 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
1033 cupsdCloseClient(con
);
1037 con
->start
= time(NULL
);
1038 con
->operation
= con
->http
.state
;
1040 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdReadClient: %d %s %s HTTP/%d.%d",
1041 con
->http
.fd
, operation
, con
->uri
,
1042 con
->http
.version
/ 100, con
->http
.version
% 100);
1044 con
->http
.status
= HTTP_OK
;
1046 if (!cupsArrayFind(ActiveClients
, con
))
1048 cupsArrayAdd(ActiveClients
, con
);
1049 cupsdSetBusyState();
1060 * Parse incoming parameters until the status changes...
1063 while ((status
= httpUpdate(HTTP(con
))) == HTTP_CONTINUE
)
1064 if (!data_ready(con
))
1067 if (status
!= HTTP_OK
&& status
!= HTTP_CONTINUE
)
1069 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
1070 cupsdCloseClient(con
);
1076 break; /* Anti-compiler-warning-code */
1080 * Handle new transfers...
1083 if (status
== HTTP_OK
)
1085 if (con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
][0])
1088 * Figure out the locale from the Accept-Language and Content-Type
1092 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ',')) != NULL
)
1095 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ';')) != NULL
)
1098 if ((ptr
= strstr(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
], "charset=")) != NULL
)
1101 * Combine language and charset, and trim any extra params in the
1105 snprintf(locale
, sizeof(locale
), "%s.%s",
1106 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ptr
+ 8);
1108 if ((ptr
= strchr(locale
, ',')) != NULL
)
1112 snprintf(locale
, sizeof(locale
), "%s.%s",
1113 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], DefaultCharset
);
1115 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1116 "cupsdReadClient: %d Browser asked for language \"%s\"...",
1117 con
->http
.fd
, locale
);
1119 con
->language
= cupsLangGet(locale
);
1122 con
->language
= cupsLangGet(DefaultLocale
);
1124 cupsdAuthorize(con
);
1126 if (!strncmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Keep-Alive", 10) &&
1128 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
1130 if (!con
->http
.fields
[HTTP_FIELD_HOST
][0] &&
1131 con
->http
.version
>= HTTP_1_1
)
1134 * HTTP/1.1 and higher require the "Host:" field...
1137 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1139 cupsdCloseClient(con
);
1143 else if (con
->operation
== HTTP_OPTIONS
)
1146 * Do OPTIONS command...
1149 if (con
->best
&& con
->best
->type
!= CUPSD_AUTH_NONE
)
1151 if (!cupsdSendHeader(con
, HTTP_UNAUTHORIZED
, NULL
, CUPSD_AUTH_NONE
))
1153 cupsdCloseClient(con
);
1158 if (!strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") &&
1159 con
->http
.tls
== NULL
)
1163 * Do encryption stuff...
1166 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
, CUPSD_AUTH_NONE
))
1168 cupsdCloseClient(con
);
1172 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1173 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1174 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1175 httpPrintf(HTTP(con
), "\r\n");
1177 if (cupsdFlushHeader(con
) < 0)
1179 cupsdCloseClient(con
);
1183 if (!encrypt_client(con
))
1185 cupsdCloseClient(con
);
1189 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
1191 cupsdCloseClient(con
);
1194 #endif /* HAVE_SSL */
1197 if (!cupsdSendHeader(con
, HTTP_OK
, NULL
, CUPSD_AUTH_NONE
))
1199 cupsdCloseClient(con
);
1203 httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n");
1204 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1205 httpPrintf(HTTP(con
), "\r\n");
1207 if (cupsdFlushHeader(con
) < 0)
1209 cupsdCloseClient(con
);
1213 else if (!is_path_absolute(con
->uri
))
1216 * Protect against malicious users!
1219 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1221 cupsdCloseClient(con
);
1227 if (!strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") &&
1228 con
->http
.tls
== NULL
)
1232 * Do encryption stuff...
1235 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
, CUPSD_AUTH_NONE
))
1237 cupsdCloseClient(con
);
1241 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1242 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1243 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1244 httpPrintf(HTTP(con
), "\r\n");
1246 if (cupsdFlushHeader(con
) < 0)
1248 cupsdCloseClient(con
);
1252 if (!encrypt_client(con
))
1254 cupsdCloseClient(con
);
1258 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
1260 cupsdCloseClient(con
);
1263 #endif /* HAVE_SSL */
1266 if ((status
= cupsdIsAuthorized(con
, NULL
)) != HTTP_OK
)
1268 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1269 "cupsdReadClient: Unauthorized request for %s...",
1271 cupsdSendError(con
, status
, CUPSD_AUTH_NONE
);
1272 cupsdCloseClient(con
);
1276 if (con
->http
.expect
&&
1277 (con
->operation
== HTTP_POST
|| con
->operation
== HTTP_PUT
))
1279 if (con
->http
.expect
== HTTP_CONTINUE
)
1282 * Send 100-continue header...
1285 if (!cupsdSendHeader(con
, HTTP_CONTINUE
, NULL
, CUPSD_AUTH_NONE
))
1287 cupsdCloseClient(con
);
1294 * Send 417-expectation-failed header...
1297 if (!cupsdSendHeader(con
, HTTP_EXPECTATION_FAILED
, NULL
, CUPSD_AUTH_NONE
))
1299 cupsdCloseClient(con
);
1303 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1304 httpPrintf(HTTP(con
), "\r\n");
1306 if (cupsdFlushHeader(con
) < 0)
1308 cupsdCloseClient(con
);
1314 switch (con
->http
.state
)
1316 case HTTP_GET_SEND
:
1317 if (!strncmp(con
->uri
, "/printers/", 10) &&
1318 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1321 * Send PPD file - get the real printer name since printer
1322 * names are not case sensitive but filenames can be...
1325 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1327 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1328 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1331 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1333 cupsdCloseClient(con
);
1341 if ((!strncmp(con
->uri
, "/admin", 6) &&
1342 strncmp(con
->uri
, "/admin/conf/", 12) &&
1343 strncmp(con
->uri
, "/admin/log/", 11)) ||
1344 !strncmp(con
->uri
, "/printers", 9) ||
1345 !strncmp(con
->uri
, "/classes", 8) ||
1346 !strncmp(con
->uri
, "/help", 5) ||
1347 !strncmp(con
->uri
, "/jobs", 5))
1350 * Send CGI output...
1353 if (!strncmp(con
->uri
, "/admin", 6))
1355 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1358 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1360 else if (!strncmp(con
->uri
, "/printers", 9))
1362 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1365 if (con
->uri
[9] && con
->uri
[10])
1366 cupsdSetString(&con
->options
, con
->uri
+ 9);
1368 cupsdSetString(&con
->options
, NULL
);
1370 else if (!strncmp(con
->uri
, "/classes", 8))
1372 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1375 if (con
->uri
[8] && con
->uri
[9])
1376 cupsdSetString(&con
->options
, con
->uri
+ 8);
1378 cupsdSetString(&con
->options
, NULL
);
1380 else if (!strncmp(con
->uri
, "/jobs", 5))
1382 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1385 if (con
->uri
[5] && con
->uri
[6])
1386 cupsdSetString(&con
->options
, con
->uri
+ 5);
1388 cupsdSetString(&con
->options
, NULL
);
1392 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1395 if (con
->uri
[5] && con
->uri
[6])
1396 cupsdSetString(&con
->options
, con
->uri
+ 5);
1398 cupsdSetString(&con
->options
, NULL
);
1401 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1403 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1405 cupsdCloseClient(con
);
1410 cupsdLogRequest(con
, HTTP_OK
);
1412 if (con
->http
.version
<= HTTP_1_0
)
1413 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1415 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1416 (strchr(con
->uri
+ 12, '/') ||
1417 strlen(con
->uri
) == 12)) ||
1418 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1419 (strchr(con
->uri
+ 11, '/') ||
1420 strlen(con
->uri
) == 11)))
1423 * GET can only be done to configuration files under
1427 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1429 cupsdCloseClient(con
);
1441 if ((filename
= get_file(con
, &filestats
, buf
,
1442 sizeof(buf
))) == NULL
)
1444 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1446 cupsdCloseClient(con
);
1453 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1455 if (is_cgi(con
, filename
, &filestats
, type
))
1458 * Note: con->command and con->options were set by
1462 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1464 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1466 cupsdCloseClient(con
);
1471 cupsdLogRequest(con
, HTTP_OK
);
1473 if (con
->http
.version
<= HTTP_1_0
)
1474 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1478 if (!check_if_modified(con
, &filestats
))
1480 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1482 cupsdCloseClient(con
);
1489 strcpy(line
, "text/plain");
1491 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1493 if (!write_file(con
, HTTP_OK
, filename
, line
, &filestats
))
1495 cupsdCloseClient(con
);
1502 case HTTP_POST_RECV
:
1504 * See if the POST request includes a Content-Length field, and if
1505 * so check the length against any limits that are set...
1508 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "POST %s", con
->uri
);
1509 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "CONTENT_TYPE = %s",
1510 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
1512 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1513 MaxRequestSize
> 0 &&
1514 con
->http
.data_remaining
> MaxRequestSize
)
1517 * Request too large...
1520 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1522 cupsdCloseClient(con
);
1528 else if (con
->http
.data_remaining
< 0 ||
1529 (!con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1530 con
->http
.data_encoding
== HTTP_ENCODE_LENGTH
))
1533 * Negative content lengths are invalid!
1536 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1538 cupsdCloseClient(con
);
1546 * See what kind of POST request this is; for IPP requests the
1547 * content-type field will be "application/ipp"...
1550 if (!strcmp(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
],
1552 con
->request
= ippNew();
1553 else if ((!strncmp(con
->uri
, "/admin", 6) &&
1554 strncmp(con
->uri
, "/admin/conf/", 12) &&
1555 strncmp(con
->uri
, "/admin/log/", 11)) ||
1556 !strncmp(con
->uri
, "/printers", 9) ||
1557 !strncmp(con
->uri
, "/classes", 8) ||
1558 !strncmp(con
->uri
, "/help", 5) ||
1559 !strncmp(con
->uri
, "/jobs", 5))
1565 if (!strncmp(con
->uri
, "/admin", 6))
1567 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1570 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1572 else if (!strncmp(con
->uri
, "/printers", 9))
1574 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1577 if (con
->uri
[9] && con
->uri
[10])
1578 cupsdSetString(&con
->options
, con
->uri
+ 9);
1580 cupsdSetString(&con
->options
, NULL
);
1582 else if (!strncmp(con
->uri
, "/classes", 8))
1584 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1587 if (con
->uri
[8] && con
->uri
[9])
1588 cupsdSetString(&con
->options
, con
->uri
+ 8);
1590 cupsdSetString(&con
->options
, NULL
);
1592 else if (!strncmp(con
->uri
, "/jobs", 5))
1594 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1597 if (con
->uri
[5] && con
->uri
[6])
1598 cupsdSetString(&con
->options
, con
->uri
+ 5);
1600 cupsdSetString(&con
->options
, NULL
);
1604 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1607 if (con
->uri
[5] && con
->uri
[6])
1608 cupsdSetString(&con
->options
, con
->uri
+ 5);
1610 cupsdSetString(&con
->options
, NULL
);
1613 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1614 "cupsdReadClient: %d command=\"%s\", "
1616 con
->http
.fd
, con
->command
,
1617 con
->options
? con
->options
: "(null)");
1619 if (con
->http
.version
<= HTTP_1_0
)
1620 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1628 if ((filename
= get_file(con
, &filestats
, buf
,
1629 sizeof(buf
))) == NULL
)
1631 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1633 cupsdCloseClient(con
);
1640 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1642 if (!is_cgi(con
, filename
, &filestats
, type
))
1645 * Only POST to CGI's...
1648 if (!cupsdSendError(con
, HTTP_UNAUTHORIZED
, CUPSD_AUTH_NONE
))
1650 cupsdCloseClient(con
);
1657 case HTTP_PUT_RECV
:
1659 * Validate the resource name...
1662 if (strncmp(con
->uri
, "/admin/conf/", 12) ||
1663 strchr(con
->uri
+ 12, '/') ||
1664 strlen(con
->uri
) == 12)
1667 * PUT can only be done to configuration files under
1671 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1673 cupsdCloseClient(con
);
1681 * See if the PUT request includes a Content-Length field, and if
1682 * so check the length against any limits that are set...
1685 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "PUT %s", con
->uri
);
1686 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "CONTENT_TYPE = %s",
1687 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
1689 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1690 MaxRequestSize
> 0 &&
1691 con
->http
.data_remaining
> MaxRequestSize
)
1694 * Request too large...
1697 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1699 cupsdCloseClient(con
);
1705 else if (con
->http
.data_remaining
< 0)
1708 * Negative content lengths are invalid!
1711 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1713 cupsdCloseClient(con
);
1721 * Open a temporary file to hold the request...
1724 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
1726 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1730 cupsdLogMessage(CUPSD_LOG_ERROR
,
1731 "Unable to create request file %s: %s",
1732 con
->filename
, strerror(errno
));
1734 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1736 cupsdCloseClient(con
);
1741 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1742 "cupsdReadClient: %d REQUEST %s=%d", con
->http
.fd
,
1743 con
->filename
, con
->file
);
1745 fchmod(con
->file
, 0640);
1746 fchown(con
->file
, RunUser
, Group
);
1747 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1752 cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
);
1753 cupsdCloseClient(con
);
1757 if (!strncmp(con
->uri
, "/printers/", 10) &&
1758 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1761 * Send PPD file - get the real printer name since printer
1762 * names are not case sensitive but filenames can be...
1765 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1767 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1768 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1771 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1773 cupsdCloseClient(con
);
1781 if ((!strncmp(con
->uri
, "/admin", 6) &&
1782 strncmp(con
->uri
, "/admin/conf/", 12) &&
1783 strncmp(con
->uri
, "/admin/log/", 11)) ||
1784 !strncmp(con
->uri
, "/printers", 9) ||
1785 !strncmp(con
->uri
, "/classes", 8) ||
1786 !strncmp(con
->uri
, "/help", 5) ||
1787 !strncmp(con
->uri
, "/jobs", 5))
1793 if (!cupsdSendHeader(con
, HTTP_OK
, "text/html", CUPSD_AUTH_NONE
))
1795 cupsdCloseClient(con
);
1799 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1801 cupsdCloseClient(con
);
1805 if (cupsdFlushHeader(con
) < 0)
1807 cupsdCloseClient(con
);
1811 cupsdLogRequest(con
, HTTP_OK
);
1813 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1814 (strchr(con
->uri
+ 12, '/') ||
1815 strlen(con
->uri
) == 12)) ||
1816 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1817 (strchr(con
->uri
+ 11, '/') ||
1818 strlen(con
->uri
) == 11)))
1821 * HEAD can only be done to configuration files under
1825 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1827 cupsdCloseClient(con
);
1833 else if ((filename
= get_file(con
, &filestats
, buf
,
1834 sizeof(buf
))) == NULL
)
1836 if (!cupsdSendHeader(con
, HTTP_NOT_FOUND
, "text/html", CUPSD_AUTH_NONE
))
1838 cupsdCloseClient(con
);
1842 cupsdLogRequest(con
, HTTP_NOT_FOUND
);
1844 else if (!check_if_modified(con
, &filestats
))
1846 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1848 cupsdCloseClient(con
);
1852 cupsdLogRequest(con
, HTTP_NOT_MODIFIED
);
1860 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1862 strcpy(line
, "text/plain");
1864 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1866 if (!cupsdSendHeader(con
, HTTP_OK
, line
, CUPSD_AUTH_NONE
))
1868 cupsdCloseClient(con
);
1872 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
1873 httpGetDateString(filestats
.st_mtime
)) < 0)
1875 cupsdCloseClient(con
);
1879 if (httpPrintf(HTTP(con
), "Content-Length: %lu\r\n",
1880 (unsigned long)filestats
.st_size
) < 0)
1882 cupsdCloseClient(con
);
1886 cupsdLogRequest(con
, HTTP_OK
);
1889 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1891 cupsdCloseClient(con
);
1895 if (cupsdFlushHeader(con
) < 0)
1897 cupsdCloseClient(con
);
1901 con
->http
.state
= HTTP_WAITING
;
1905 break; /* Anti-compiler-warning-code */
1911 * Handle any incoming data...
1914 switch (con
->http
.state
)
1916 case HTTP_PUT_RECV
:
1917 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1918 "cupsdReadClient: %d con->data_encoding=HTTP_ENCODE_%s, "
1919 "con->data_remaining=" CUPS_LLFMT
", con->file=%d",
1921 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
?
1922 "CHUNKED" : "LENGTH",
1923 CUPS_LLCAST con
->http
.data_remaining
, con
->file
);
1927 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
1929 cupsdCloseClient(con
);
1934 con
->bytes
+= bytes
;
1936 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1937 "cupsdReadClient: %d writing %d bytes to %d",
1938 con
->http
.fd
, bytes
, con
->file
);
1940 if (write(con
->file
, line
, bytes
) < bytes
)
1942 cupsdLogMessage(CUPSD_LOG_ERROR
,
1943 "cupsdReadClient: Unable to write %d bytes to %s: %s",
1944 bytes
, con
->filename
, strerror(errno
));
1946 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1947 "cupsdReadClient: Closing data file %d...",
1952 unlink(con
->filename
);
1953 cupsdClearString(&con
->filename
);
1955 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1957 cupsdCloseClient(con
);
1963 while (con
->http
.state
== HTTP_PUT_RECV
&& data_ready(con
));
1965 if (con
->http
.state
== HTTP_WAITING
)
1968 * End of file, see how big it is...
1971 fstat(con
->file
, &filestats
);
1973 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1974 "cupsdReadClient: %d Closing data file %d, size="
1976 con
->http
.fd
, con
->file
,
1977 CUPS_LLCAST filestats
.st_size
);
1982 if (filestats
.st_size
> MaxRequestSize
&&
1986 * Request is too big; remove it and send an error...
1989 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1990 "cupsdReadClient: %d Removing temp file %s",
1991 con
->http
.fd
, con
->filename
);
1992 unlink(con
->filename
);
1993 cupsdClearString(&con
->filename
);
1995 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1997 cupsdCloseClient(con
);
2003 * Install the configuration file...
2006 status
= install_conf_file(con
);
2009 * Return the status to the client...
2012 if (!cupsdSendError(con
, status
, CUPSD_AUTH_NONE
))
2014 cupsdCloseClient(con
);
2020 case HTTP_POST_RECV
:
2021 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2022 "cupsdReadClient: %d con->data_encoding=HTTP_ENCODE_"
2023 "%s, con->data_remaining=" CUPS_LLFMT
", con->file=%d",
2025 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
?
2026 "CHUNKED" : "LENGTH",
2027 CUPS_LLCAST con
->http
.data_remaining
, con
->file
);
2034 * Grab any request data from the connection...
2037 if ((ipp_state
= ippRead(&(con
->http
), con
->request
)) == IPP_ERROR
)
2039 cupsdLogMessage(CUPSD_LOG_ERROR
,
2040 "cupsdReadClient: %d IPP Read Error!",
2043 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
2044 cupsdCloseClient(con
);
2047 else if (ipp_state
!= IPP_DATA
)
2049 if (con
->http
.state
== HTTP_POST_SEND
)
2051 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
2052 cupsdCloseClient(con
);
2059 con
->bytes
+= ippLength(con
->request
);
2062 if (con
->file
< 0 && con
->http
.state
!= HTTP_POST_SEND
)
2065 * Create a file as needed for the request data...
2068 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
, request_id
++);
2069 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
2073 cupsdLogMessage(CUPSD_LOG_ERROR
,
2074 "Unable to create request file %s: %s",
2075 con
->filename
, strerror(errno
));
2077 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2079 cupsdCloseClient(con
);
2084 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdReadClient: %d REQUEST %s=%d", con
->http
.fd
,
2085 con
->filename
, con
->file
);
2087 fchmod(con
->file
, 0640);
2088 fchown(con
->file
, RunUser
, Group
);
2089 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2092 if (con
->http
.state
!= HTTP_POST_SEND
)
2094 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
2096 cupsdCloseClient(con
);
2101 con
->bytes
+= bytes
;
2103 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2104 "cupsdReadClient: %d writing %d bytes to %d",
2105 con
->http
.fd
, bytes
, con
->file
);
2107 if (write(con
->file
, line
, bytes
) < bytes
)
2109 cupsdLogMessage(CUPSD_LOG_ERROR
,
2110 "cupsdReadClient: Unable to write %d bytes to %s: %s",
2111 bytes
, con
->filename
, strerror(errno
));
2113 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2114 "cupsdReadClient: Closing file %d...",
2119 unlink(con
->filename
);
2120 cupsdClearString(&con
->filename
);
2122 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2124 cupsdCloseClient(con
);
2129 else if (con
->http
.state
== HTTP_POST_RECV
)
2131 else if (con
->http
.state
!= HTTP_POST_SEND
)
2133 cupsdCloseClient(con
);
2138 while (con
->http
.state
== HTTP_POST_RECV
&& data_ready(con
));
2140 if (con
->http
.state
== HTTP_POST_SEND
)
2144 fstat(con
->file
, &filestats
);
2146 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2147 "cupsdReadClient: %d Closing data file %d, "
2148 "size=" CUPS_LLFMT
".",
2149 con
->http
.fd
, con
->file
,
2150 CUPS_LLCAST filestats
.st_size
);
2155 if (filestats
.st_size
> MaxRequestSize
&&
2159 * Request is too big; remove it and send an error...
2162 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2163 "cupsdReadClient: %d Removing temp file %s",
2164 con
->http
.fd
, con
->filename
);
2165 unlink(con
->filename
);
2166 cupsdClearString(&con
->filename
);
2171 * Delete any IPP request data...
2174 ippDelete(con
->request
);
2175 con
->request
= NULL
;
2178 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2180 cupsdCloseClient(con
);
2187 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
2189 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
2191 cupsdCloseClient(con
);
2196 cupsdLogRequest(con
, HTTP_OK
);
2202 cupsdProcessIPPRequest(con
);
2206 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2207 "cupsdReadClient: %d Removing temp file %s",
2208 con
->http
.fd
, con
->filename
);
2209 unlink(con
->filename
);
2210 cupsdClearString(&con
->filename
);
2219 break; /* Anti-compiler-warning-code */
2222 if (con
->http
.state
== HTTP_WAITING
)
2224 if (!con
->http
.keep_alive
)
2225 cupsdCloseClient(con
);
2228 cupsArrayRemove(ActiveClients
, con
);
2229 cupsdSetBusyState();
2236 * 'cupsdSendCommand()' - Send output from a command via HTTP.
2239 int /* O - 1 on success, 0 on failure */
2241 cupsd_client_t
*con
, /* I - Client connection */
2242 char *command
, /* I - Command to run */
2243 char *options
, /* I - Command-line options */
2244 int root
) /* I - Run as root? */
2246 int fd
; /* Standard input file descriptor */
2251 fd
= open(con
->filename
, O_RDONLY
);
2255 cupsdLogMessage(CUPSD_LOG_ERROR
,
2256 "cupsdSendCommand: %d Unable to open \"%s\" for reading: %s",
2257 con
->http
.fd
, con
->filename
? con
->filename
: "/dev/null",
2262 fcntl(fd
, F_SETFD
, fcntl(fd
, F_GETFD
) | FD_CLOEXEC
);
2267 con
->pipe_pid
= pipe_command(con
, fd
, &(con
->file
), command
, options
, root
);
2272 cupsdLogMessage(CUPSD_LOG_INFO
, "Started \"%s\" (pid=%d)", command
,
2275 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendCommand: %d file=%d",
2276 con
->http
.fd
, con
->file
);
2278 if (con
->pipe_pid
== 0)
2281 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2283 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2285 con
->sent_header
= 0;
2286 con
->file_ready
= 0;
2287 con
->got_fields
= 0;
2295 * 'cupsdSendError()' - Send an error message via HTTP.
2298 int /* O - 1 if successful, 0 otherwise */
2299 cupsdSendError(cupsd_client_t
*con
, /* I - Connection */
2300 http_status_t code
, /* I - Error code */
2301 int auth_type
)/* I - Authentication type */
2305 * Force client to upgrade for authentication if that is how the
2306 * server is configured...
2309 if (code
== HTTP_UNAUTHORIZED
&&
2310 DefaultEncryption
== HTTP_ENCRYPT_REQUIRED
&&
2311 strcasecmp(con
->http
.hostname
, "localhost") &&
2314 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2315 "cupsdSendError: Encryption before authentication!");
2316 code
= HTTP_UPGRADE_REQUIRED
;
2318 #endif /* HAVE_SSL */
2321 * Put the request in the access_log file...
2324 cupsdLogRequest(con
, code
);
2326 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendError: %d code=%d (%s)",
2327 con
->http
.fd
, code
, httpStatus(code
));
2330 * To work around bugs in some proxies, don't use Keep-Alive for some
2333 * Kerberos authentication doesn't work without Keep-Alive, so
2334 * never disable it in that case.
2337 if (code
>= HTTP_BAD_REQUEST
&& con
->http
.auth_type
!= CUPSD_AUTH_NEGOTIATE
)
2338 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
2341 * Send an error message back to the client. If the error code is a
2342 * 400 or 500 series, make sure the message contains some text, too!
2345 if (!cupsdSendHeader(con
, code
, NULL
, auth_type
))
2349 if (code
== HTTP_UPGRADE_REQUIRED
)
2350 if (httpPrintf(HTTP(con
), "Connection: Upgrade\r\n") < 0)
2353 if (httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n") < 0)
2355 #endif /* HAVE_SSL */
2357 if (con
->http
.version
>= HTTP_1_1
&&
2358 con
->http
.keep_alive
== HTTP_KEEPALIVE_OFF
)
2360 if (httpPrintf(HTTP(con
), "Connection: close\r\n") < 0)
2364 if (code
>= HTTP_BAD_REQUEST
)
2367 * Send a human-readable error message.
2370 char message
[4096], /* Message for user */
2371 urltext
[1024], /* URL redirection text */
2372 redirect
[1024]; /* Redirection link */
2373 const char *text
; /* Status-specific text */
2378 if (code
== HTTP_UNAUTHORIZED
)
2379 text
= _cupsLangString(con
->language
,
2380 _("Enter your username and password or the "
2381 "root username and password to access this "
2382 "page. If you are using Kerberos authentication, "
2383 "make sure you have a valid Kerberos ticket."));
2384 else if (code
== HTTP_UPGRADE_REQUIRED
)
2388 snprintf(urltext
, sizeof(urltext
),
2389 _cupsLangString(con
->language
,
2390 _("You must access this page using the URL "
2391 "<A HREF=\"https://%s:%d%s\">"
2392 "https://%s:%d%s</A>.")),
2393 con
->servername
, con
->serverport
, con
->uri
,
2394 con
->servername
, con
->serverport
, con
->uri
);
2396 snprintf(redirect
, sizeof(redirect
),
2397 "<META HTTP-EQUIV=\"Refresh\" "
2398 "CONTENT=\"3;URL=https://%s:%d%s\">\n",
2399 con
->servername
, con
->serverport
, con
->uri
);
2404 snprintf(message
, sizeof(message
),
2405 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" "
2406 "\"http://www.w3.org/TR/REC-html40/loose.dtd\">\n"
2409 "\t<META HTTP-EQUIV=\"Content-Type\" "
2410 "CONTENT=\"text/html; charset=utf-8\">\n"
2411 "\t<TITLE>%d %s</TITLE>\n"
2412 "\t<LINK REL=\"STYLESHEET\" TYPE=\"text/css\" "
2413 "HREF=\"/cups.css\">\n"
2421 code
, httpStatus(code
), redirect
, code
, httpStatus(code
), text
);
2423 if (httpPrintf(HTTP(con
), "Content-Type: text/html; charset=utf-8\r\n") < 0)
2425 if (httpPrintf(HTTP(con
), "Content-Length: %d\r\n",
2426 (int)strlen(message
)) < 0)
2428 if (httpPrintf(HTTP(con
), "\r\n") < 0)
2430 if (httpPrintf(HTTP(con
), "%s", message
) < 0)
2433 else if (httpPrintf(HTTP(con
), "\r\n") < 0)
2436 if (cupsdFlushHeader(con
) < 0)
2439 con
->http
.state
= HTTP_WAITING
;
2446 * 'cupsdSendHeader()' - Send an HTTP request.
2449 int /* O - 1 on success, 0 on failure */
2451 cupsd_client_t
*con
, /* I - Client to send to */
2452 http_status_t code
, /* I - HTTP status code */
2453 char *type
, /* I - MIME type of document */
2454 int auth_type
) /* I - Type of authentication */
2456 char auth_str
[1024]; /* Authorization string */
2458 static char *gss_buf
= NULL
; /* Kerberos auth data buffer */
2459 static int gss_bufsize
= 0; /* Size of Kerberos auth data buffer */
2460 #endif /* HAVE_GSSAPI */
2464 * Send the HTTP status header...
2467 if (code
== HTTP_CONTINUE
)
2470 * 100-continue doesn't send any headers...
2473 return (httpPrintf(HTTP(con
), "HTTP/%d.%d 100 Continue\r\n\r\n",
2474 con
->http
.version
/ 100, con
->http
.version
% 100) > 0);
2477 httpFlushWrite(HTTP(con
));
2479 con
->http
.data_encoding
= HTTP_ENCODE_FIELDS
;
2481 if (httpPrintf(HTTP(con
), "HTTP/%d.%d %d %s\r\n", con
->http
.version
/ 100,
2482 con
->http
.version
% 100, code
, httpStatus(code
)) < 0)
2484 if (httpPrintf(HTTP(con
), "Date: %s\r\n", httpGetDateString(time(NULL
))) < 0)
2487 if (httpPrintf(HTTP(con
), "Server: %s\r\n", ServerHeader
) < 0)
2489 if (con
->http
.keep_alive
&& con
->http
.version
>= HTTP_1_0
)
2491 if (httpPrintf(HTTP(con
), "Connection: Keep-Alive\r\n") < 0)
2493 if (httpPrintf(HTTP(con
), "Keep-Alive: timeout=%d\r\n",
2494 KeepAliveTimeout
) < 0)
2497 if (code
== HTTP_METHOD_NOT_ALLOWED
)
2498 if (httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST\r\n") < 0)
2501 if (code
== HTTP_UNAUTHORIZED
)
2503 if (auth_type
== CUPSD_AUTH_NONE
)
2505 if (!con
->best
|| con
->best
->type
<= CUPSD_AUTH_NONE
)
2506 auth_type
= DefaultAuthType
;
2508 auth_type
= con
->best
->type
;
2513 if (auth_type
== CUPSD_AUTH_BASIC
|| auth_type
== CUPSD_AUTH_BASICDIGEST
)
2514 strlcpy(auth_str
, "Basic realm=\"CUPS\"", sizeof(auth_str
));
2515 else if (auth_type
== CUPSD_AUTH_DIGEST
)
2516 snprintf(auth_str
, sizeof(auth_str
), "Digest realm=\"CUPS\", nonce=\"%s\"",
2517 con
->http
.hostname
);
2519 else if (auth_type
== CUPSD_AUTH_NEGOTIATE
&& con
->gss_output_token
.length
== 0)
2520 strlcpy(auth_str
, "Negotiate", sizeof(auth_str
));
2521 #endif /* HAVE_GSSAPI */
2523 #ifdef HAVE_AUTHORIZATION_H
2524 if (con
->best
&& auth_type
!= CUPSD_AUTH_NEGOTIATE
)
2526 int i
; /* Looping var */
2527 char *auth_key
; /* Auth key buffer */
2528 size_t auth_size
; /* Size of remaining buffer */
2531 auth_key
= auth_str
+ strlen(auth_str
);
2532 auth_size
= sizeof(auth_str
) - (auth_key
- auth_str
);
2534 for (i
= 0; i
< con
->best
->num_names
; i
++)
2536 if (!strncasecmp(con
->best
->names
[i
], "@AUTHKEY(", 9))
2538 snprintf(auth_key
, auth_size
, ", authkey=\"%s\"",
2539 con
->best
->names
[i
] + 9);
2540 /* end parenthesis is stripped in conf.c */
2543 else if (!strcasecmp(con
->best
->names
[i
], "@SYSTEM") &&
2546 snprintf(auth_key
, auth_size
, ", authkey=\"%s\"", SystemGroupAuthKey
);
2551 #endif /* HAVE_AUTHORIZATION_H */
2555 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendHeader: WWW-Authenticate: %s",
2558 if (httpPrintf(HTTP(con
), "WWW-Authenticate: %s\r\n", auth_str
) < 0)
2565 * WWW-Authenticate: Negotiate can be included even for
2566 * non-401 replies...
2569 if (con
->gss_output_token
.length
> 0 && con
->gss_output_token
.length
<= 65536)
2571 OM_uint32 minor_status
; /* Minor status code */
2572 int bufsize
; /* Size of output token buffer */
2575 bufsize
= con
->gss_output_token
.length
* 4 / 3 + 2;
2577 if (bufsize
> gss_bufsize
)
2579 char *buf
; /* New buffer */
2582 bufsize
= (bufsize
+ 1023) & 1023;/* Round up */
2585 buf
= realloc(gss_buf
, bufsize
);
2587 buf
= malloc(bufsize
);
2591 cupsdLogMessage(CUPSD_LOG_ERROR
,
2592 "Unable to allocate %d bytes for Kerberos credentials!",
2598 gss_bufsize
= bufsize
;
2601 httpEncode64_2(gss_buf
, gss_bufsize
,
2602 con
->gss_output_token
.value
,
2603 con
->gss_output_token
.length
);
2604 gss_release_buffer(&minor_status
, &con
->gss_output_token
);
2606 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2607 "cupsdSendHeader: WWW-Authenticate: Negotiate %s", gss_buf
);
2609 if (httpPrintf(HTTP(con
), "WWW-Authenticate: Negotiate %s\r\n",
2613 else if (con
->gss_output_token
.length
> 65536)
2615 cupsdLogMessage(CUPSD_LOG_ERROR
,
2616 "Kerberos credentials larger than 64k (%d)!",
2617 (int)con
->gss_output_token
.length
);
2620 #endif /* HAVE_GSSAPI */
2622 if (con
->language
&& strcmp(con
->language
->language
, "C"))
2624 if (httpPrintf(HTTP(con
), "Content-Language: %s\r\n",
2625 con
->language
->language
) < 0)
2631 if (!strcmp(type
, "text/html"))
2633 if (httpPrintf(HTTP(con
),
2634 "Content-Type: text/html; charset=utf-8\r\n") < 0)
2637 else if (httpPrintf(HTTP(con
), "Content-Type: %s\r\n", type
) < 0)
2646 * 'cupsdUpdateCGI()' - Read status messages from CGI scripts and programs.
2650 cupsdUpdateCGI(void)
2652 char *ptr
, /* Pointer to end of line in buffer */
2653 message
[1024]; /* Pointer to message text */
2654 int loglevel
; /* Log level for message */
2657 while ((ptr
= cupsdStatBufUpdate(CGIStatusBuffer
, &loglevel
,
2658 message
, sizeof(message
))) != NULL
)
2659 if (!strchr(CGIStatusBuffer
->buffer
, '\n'))
2662 if (ptr
== NULL
&& !CGIStatusBuffer
->bufused
)
2665 * Fatal error on pipe - should never happen!
2668 cupsdLogMessage(CUPSD_LOG_CRIT
,
2669 "cupsdUpdateCGI: error reading from CGI error pipe - %s",
2676 * 'cupsdWriteClient()' - Write data to a client as needed.
2680 cupsdWriteClient(cupsd_client_t
*con
) /* I - Client connection */
2682 int bytes
; /* Number of bytes written */
2683 char buf
[16385]; /* Data buffer */
2684 char *bufptr
; /* Pointer into buffer */
2685 ipp_state_t ipp_state
; /* IPP state value */
2689 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2690 "cupsdWriteClient(con=%p) %d response=%p(%d), file=%d "
2691 "pipe_pid=%d state=%d",
2692 con
, con
->http
.fd
, con
->response
,
2693 con
->response
? con
->response
->state
: -1,
2694 con
->file
, con
->pipe_pid
, con
->http
.state
);
2697 if (con
->http
.state
!= HTTP_GET_SEND
&&
2698 con
->http
.state
!= HTTP_POST_SEND
)
2704 * Make sure we select on the CGI output...
2707 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2709 if (!con
->file_ready
)
2712 * Try again later when there is CGI output available...
2715 cupsdRemoveSelect(con
->http
.fd
);
2719 con
->file_ready
= 0;
2722 if (con
->response
&& con
->response
->state
!= IPP_DATA
)
2724 ipp_state
= ippWrite(HTTP(con
), con
->response
);
2725 bytes
= ipp_state
!= IPP_ERROR
&&
2726 (con
->file
>= 0 || ipp_state
!= IPP_DATA
);
2728 else if ((bytes
= read(con
->file
, buf
, sizeof(buf
) - 1)) > 0)
2730 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2731 "cupsdWriteClient: Read %d bytes from file %d...",
2734 if (con
->pipe_pid
&& !con
->got_fields
)
2737 * Inspect the data for Content-Type and other fields.
2742 for (bufptr
= buf
; !con
->got_fields
&& *bufptr
; bufptr
++)
2743 if (*bufptr
== '\n')
2746 * Send line to client...
2749 if (bufptr
> buf
&& bufptr
[-1] == '\r')
2753 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "Script header: %s", buf
);
2755 if (!con
->sent_header
)
2758 * Handle redirection and CGI status codes...
2761 if (!strncasecmp(buf
, "Location:", 9))
2763 cupsdSendHeader(con
, HTTP_SEE_OTHER
, NULL
, CUPSD_AUTH_NONE
);
2764 con
->sent_header
= 2;
2766 if (httpPrintf(HTTP(con
), "Content-Length: 0\r\n") < 0)
2769 else if (!strncasecmp(buf
, "Status:", 7))
2771 cupsdSendError(con
, (http_status_t
)atoi(buf
+ 7), CUPSD_AUTH_NONE
);
2772 con
->sent_header
= 2;
2776 cupsdSendHeader(con
, HTTP_OK
, NULL
, CUPSD_AUTH_NONE
);
2777 con
->sent_header
= 1;
2779 if (con
->http
.version
== HTTP_1_1
)
2781 if (httpPrintf(HTTP(con
), "Transfer-Encoding: chunked\r\n") < 0)
2787 if (strncasecmp(buf
, "Status:", 7))
2788 httpPrintf(HTTP(con
), "%s\r\n", buf
);
2790 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdWriteClient: %d %s",
2797 bytes
-= (bufptr
- buf
);
2798 memmove(buf
, bufptr
, bytes
+ 1);
2802 * See if the line was empty...
2805 if (con
->field_col
== 0)
2807 con
->got_fields
= 1;
2809 if (cupsdFlushHeader(con
) < 0)
2811 cupsdCloseClient(con
);
2815 if (con
->http
.version
== HTTP_1_1
)
2816 con
->http
.data_encoding
= HTTP_ENCODE_CHUNKED
;
2821 else if (*bufptr
!= '\r')
2824 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2825 "cupsdWriteClient: %d bytes=%d, got_fields=%d",
2826 con
->http
.fd
, bytes
, con
->got_fields
);
2828 if (bytes
> 0 && !con
->got_fields
)
2831 * Remaining text needs to go out...
2834 httpPrintf(HTTP(con
), "%s", buf
);
2836 con
->http
.activity
= time(NULL
);
2839 else if (bytes
== 0)
2841 con
->http
.activity
= time(NULL
);
2848 if (httpWrite2(HTTP(con
), buf
, bytes
) < 0)
2850 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2851 "cupsdWriteClient: %d Write of %d bytes failed!",
2852 con
->http
.fd
, bytes
);
2854 cupsdCloseClient(con
);
2858 if (con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
)
2859 httpFlushWrite(HTTP(con
));
2861 con
->bytes
+= bytes
;
2863 if (con
->http
.state
== HTTP_WAITING
)
2870 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdWriteClient: %d bytes < 0",
2873 cupsdLogRequest(con
, HTTP_OK
);
2875 httpFlushWrite(HTTP(con
));
2877 if (con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
&& con
->sent_header
== 1)
2879 if (httpWrite2(HTTP(con
), "", 0) < 0)
2881 cupsdCloseClient(con
);
2886 con
->http
.state
= HTTP_WAITING
;
2888 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
2892 cupsdRemoveSelect(con
->file
);
2895 cupsdEndProcess(con
->pipe_pid
, 0);
2897 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2898 "cupsdWriteClient: %d Closing data file %d.",
2899 con
->http
.fd
, con
->file
);
2908 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2909 "cupsdWriteClient: %d Removing temp file %s",
2910 con
->http
.fd
, con
->filename
);
2911 unlink(con
->filename
);
2912 cupsdClearString(&con
->filename
);
2917 ippDelete(con
->request
);
2918 con
->request
= NULL
;
2923 ippDelete(con
->response
);
2924 con
->response
= NULL
;
2927 cupsdClearString(&con
->command
);
2928 cupsdClearString(&con
->options
);
2929 cupsdClearString(&con
->query_string
);
2931 if (!con
->http
.keep_alive
)
2933 cupsdCloseClient(con
);
2938 con
->http
.activity
= time(NULL
);
2943 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
2946 static int /* O - 1 if modified since */
2948 cupsd_client_t
*con
, /* I - Client connection */
2949 struct stat
*filestats
) /* I - File information */
2951 char *ptr
; /* Pointer into field */
2952 time_t date
; /* Time/date value */
2953 off_t size
; /* Size/length value */
2958 ptr
= con
->http
.fields
[HTTP_FIELD_IF_MODIFIED_SINCE
];
2963 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2964 "check_if_modified: %d If-Modified-Since=\"%s\"",
2967 while (*ptr
!= '\0')
2969 while (isspace(*ptr
) || *ptr
== ';')
2972 if (strncasecmp(ptr
, "length=", 7) == 0)
2975 size
= strtoll(ptr
, NULL
, 10);
2977 while (isdigit(*ptr
))
2980 else if (isalpha(*ptr
))
2982 date
= httpGetDateTime(ptr
);
2983 while (*ptr
!= '\0' && *ptr
!= ';')
2990 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2991 "check_if_modified: %d sizes=" CUPS_LLFMT
","
2992 CUPS_LLFMT
" dates=%d,%d",
2993 con
->http
.fd
, CUPS_LLCAST size
,
2994 CUPS_LLCAST filestats
->st_size
, (int)date
,
2995 (int)filestats
->st_mtime
);
2997 return ((size
!= filestats
->st_size
&& size
!= 0) ||
2998 (date
< filestats
->st_mtime
&& date
!= 0) ||
2999 (size
== 0 && date
== 0));
3004 * 'compare_clients()' - Compare two client connections.
3007 static int /* O - Result of comparison */
3008 compare_clients(cupsd_client_t
*a
, /* I - First client */
3009 cupsd_client_t
*b
, /* I - Second client */
3010 void *data
) /* I - User data (not used) */
3024 * 'data_ready()' - Check whether data is available from a client.
3027 static int /* O - 1 if data is ready, 0 otherwise */
3028 data_ready(cupsd_client_t
*con
) /* I - Client */
3030 if (con
->http
.used
> 0)
3033 else if (con
->http
.tls
)
3036 if (SSL_pending((SSL
*)(con
->http
.tls
)))
3038 # elif defined(HAVE_GNUTLS)
3039 if (gnutls_record_check_pending(((http_tls_t
*)(con
->http
.tls
))->session
))
3041 # elif defined(HAVE_CDSASSL)
3042 size_t bytes
; /* Bytes that are available */
3044 if (!SSLGetBufferedReadSize(((http_tls_t
*)(con
->http
.tls
))->session
,
3045 &bytes
) && bytes
> 0)
3047 # endif /* HAVE_LIBSSL */
3049 #endif /* HAVE_SSL */
3057 * 'encrypt_client()' - Enable encryption for the client...
3060 static int /* O - 1 on success, 0 on error */
3061 encrypt_client(cupsd_client_t
*con
) /* I - Client to encrypt */
3064 SSL_CTX
*context
; /* Context for encryption */
3065 SSL
*conn
; /* Connection for encryption */
3066 BIO
*bio
; /* BIO data */
3067 unsigned long error
; /* Error code */
3071 * Verify that we have a certificate...
3074 if (access(ServerKey
, 0) || access(ServerCertificate
, 0))
3077 * Nope, make a self-signed certificate...
3080 if (!make_certificate(con
))
3085 * Create the SSL context and accept the connection...
3088 context
= SSL_CTX_new(SSLv23_server_method());
3090 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
3091 if (SSLOptions
& CUPSD_SSL_NOEMPTY
)
3092 SSL_CTX_set_options(context
, SSL_OP_DONTS_INSERT_EMPTY_FRAGMENTS
);
3093 SSL_CTX_use_PrivateKey_file(context
, ServerKey
, SSL_FILETYPE_PEM
);
3094 SSL_CTX_use_certificate_chain_file(context
, ServerCertificate
,
3097 bio
= BIO_new(_httpBIOMethods());
3098 BIO_ctrl(bio
, BIO_C_SET_FILE_PTR
, 0, (char *)HTTP(con
));
3100 conn
= SSL_new(context
);
3101 SSL_set_bio(conn
, bio
, bio
);
3103 if (SSL_accept(conn
) != 1)
3105 cupsdLogMessage(CUPSD_LOG_ERROR
,
3106 "encrypt_client: Unable to encrypt connection from %s!",
3107 con
->http
.hostname
);
3109 while ((error
= ERR_get_error()) != 0)
3110 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s",
3111 ERR_error_string(error
, NULL
));
3113 SSL_CTX_free(context
);
3118 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3119 "encrypt_client: %d Connection from %s now encrypted.",
3120 con
->http
.fd
, con
->http
.hostname
);
3122 con
->http
.tls
= conn
;
3125 # elif defined(HAVE_GNUTLS)
3126 http_tls_t
*conn
; /* TLS session object */
3127 int error
; /* Error code */
3128 gnutls_certificate_server_credentials
*credentials
;
3129 /* TLS credentials */
3133 * Verify that we have a certificate...
3136 if (access(ServerKey
, 0) || access(ServerCertificate
, 0))
3139 * Nope, make a self-signed certificate...
3142 if (!make_certificate(con
))
3147 * Create the SSL object and perform the SSL handshake...
3150 conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
));
3155 credentials
= (gnutls_certificate_server_credentials
*)
3156 malloc(sizeof(gnutls_certificate_server_credentials
));
3157 if (credentials
== NULL
)
3159 cupsdLogMessage(CUPSD_LOG_ERROR
,
3160 "encrypt_client: Unable to encrypt connection from %s!",
3161 con
->http
.hostname
);
3162 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s", strerror(errno
));
3168 gnutls_certificate_allocate_credentials(credentials
);
3169 gnutls_certificate_set_x509_key_file(*credentials
, ServerCertificate
,
3170 ServerKey
, GNUTLS_X509_FMT_PEM
);
3172 gnutls_init(&(conn
->session
), GNUTLS_SERVER
);
3173 gnutls_set_default_priority(conn
->session
);
3174 gnutls_credentials_set(conn
->session
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
3175 gnutls_transport_set_ptr(conn
->session
, (gnutls_transport_ptr
)HTTP(con
));
3176 gnutls_transport_set_pull_function(conn
->session
, _httpReadGNUTLS
);
3177 gnutls_transport_set_push_function(conn
->session
, _httpWriteGNUTLS
);
3179 error
= gnutls_handshake(conn
->session
);
3181 if (error
!= GNUTLS_E_SUCCESS
)
3183 cupsdLogMessage(CUPSD_LOG_ERROR
,
3184 "encrypt_client: Unable to encrypt connection from %s!",
3185 con
->http
.hostname
);
3186 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s",
3187 gnutls_strerror(error
));
3189 gnutls_deinit(conn
->session
);
3190 gnutls_certificate_free_credentials(*credentials
);
3196 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3197 "encrypt_client: %d Connection from %s now encrypted.",
3198 con
->http
.fd
, con
->http
.hostname
);
3200 conn
->credentials
= credentials
;
3201 con
->http
.tls
= conn
;
3204 # elif defined(HAVE_CDSASSL)
3205 OSStatus error
; /* Error code */
3206 http_tls_t
*conn
; /* CDSA connection information */
3209 if ((conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
))) == NULL
)
3213 conn
->session
= NULL
;
3214 conn
->certsArray
= get_cdsa_certificate(con
);
3216 if (!conn
->certsArray
)
3219 * No keychain (yet), make a self-signed certificate...
3222 if (make_certificate(con
))
3223 conn
->certsArray
= get_cdsa_certificate(con
);
3226 if (!conn
->certsArray
)
3228 cupsdLogMessage(CUPSD_LOG_ERROR
,
3229 "encrypt_client: Could not find signing key in keychain "
3230 "\"%s\"", ServerCertificate
);
3231 error
= errSSLBadCert
; /* errSSLBadConfiguration is a better choice, but not available on 10.2.x */
3235 error
= SSLNewContext(true, &conn
->session
);
3238 error
= SSLSetIOFuncs(conn
->session
, _httpReadCDSA
, _httpWriteCDSA
);
3241 error
= SSLSetProtocolVersionEnabled(conn
->session
, kSSLProtocol2
, false);
3244 error
= SSLSetConnection(conn
->session
, HTTP(con
));
3247 error
= SSLSetAllowsExpiredCerts(conn
->session
, true);
3250 error
= SSLSetAllowsAnyRoot(conn
->session
, true);
3253 error
= SSLSetCertificate(conn
->session
, conn
->certsArray
);
3258 * Perform SSL/TLS handshake
3261 while ((error
= SSLHandshake(conn
->session
)) == errSSLWouldBlock
)
3267 cupsdLogMessage(CUPSD_LOG_ERROR
,
3268 "encrypt_client: Unable to encrypt connection from %s!",
3269 con
->http
.hostname
);
3271 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s (%d)",
3272 cssmErrorString(error
), (int)error
);
3274 con
->http
.error
= error
;
3275 con
->http
.status
= HTTP_ERROR
;
3278 SSLDisposeContext(conn
->session
);
3280 if (conn
->certsArray
)
3281 CFRelease(conn
->certsArray
);
3288 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3289 "encrypt_client: %d Connection from %s now encrypted.",
3290 con
->http
.fd
, con
->http
.hostname
);
3292 con
->http
.tls
= conn
;
3295 # endif /* HAVE_LIBSSL */
3297 #endif /* HAVE_SSL */
3302 * 'get_cdsa_certificate()' - Get a SSL/TLS certificate from the System keychain.
3305 static CFArrayRef
/* O - Array of certificates */
3306 get_cdsa_certificate(cupsd_client_t
*con
) /* I - Client connection */
3308 OSStatus err
; /* Error info */
3309 SecKeychainRef keychain
; /* Keychain reference */
3310 SecIdentitySearchRef search
; /* Search reference */
3311 SecIdentityRef identity
; /* Identity */
3312 CFArrayRef certificates
= NULL
;
3313 /* Certificate array */
3316 if ((err
= SecKeychainOpen(ServerCertificate
, &keychain
)))
3318 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot open keychain \"%s\", %s",
3319 ServerCertificate
, cssmErrorString(err
));
3323 # if HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY
3325 * Use a policy to search for valid certificates who's common name matches the
3329 SecPolicySearchRef policy_search
; /* Policy search ref */
3330 SecPolicyRef policy
; /* Policy ref */
3331 CSSM_DATA options
; /* Policy options */
3332 CSSM_APPLE_TP_SSL_OPTIONS
3333 ssl_options
; /* SSL Option for hostname */
3336 if (SecPolicySearchCreate(CSSM_CERT_X_509v3
, &CSSMOID_APPLE_TP_SSL
,
3337 NULL
, &policy_search
))
3339 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot create a policy search reference");
3340 CFRelease(keychain
);
3344 if (SecPolicySearchCopyNext(policy_search
, &policy
))
3346 cupsdLogMessage(CUPSD_LOG_ERROR
,
3347 "Cannot find a policy to use for searching");
3348 CFRelease(keychain
);
3349 CFRelease(policy_search
);
3353 memset(&ssl_options
, 0, sizeof(ssl_options
));
3354 ssl_options
.Version
= CSSM_APPLE_TP_SSL_OPTS_VERSION
;
3355 ssl_options
.ServerName
= con
->servername
;
3356 ssl_options
.ServerNameLen
= strlen(con
->servername
);
3358 options
.Data
= (uint8
*)&ssl_options
;
3359 options
.Length
= sizeof(ssl_options
);
3361 if (SecPolicySetValue(policy
, &options
))
3363 cupsdLogMessage(CUPSD_LOG_ERROR
,
3364 "Cannot set policy value to use for searching");
3365 CFRelease(keychain
);
3366 CFRelease(policy_search
);
3370 err
= SecIdentitySearchCreateWithPolicy(policy
, NULL
, CSSM_KEYUSE_SIGN
,
3371 keychain
, FALSE
, &search
);
3374 * Assume there is exactly one SecIdentity in the keychain...
3377 err
= SecIdentitySearchCreate(keychain
, CSSM_KEYUSE_SIGN
, &search
);
3378 # endif /* HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY */
3381 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3382 "Cannot create keychain search reference: %s",
3383 cssmErrorString(err
));
3386 if ((err
= SecIdentitySearchCopyNext(search
, &identity
)))
3388 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3389 "Cannot find signing key in keychain \"%s\", error %d",
3390 ServerCertificate
, (int)err
);
3394 if (CFGetTypeID(identity
) != SecIdentityGetTypeID())
3395 cupsdLogMessage(CUPSD_LOG_ERROR
,
3396 "SecIdentitySearchCopyNext CFTypeID failure!");
3399 if ((certificates
= CFArrayCreate(NULL
, (const void **)&identity
,
3400 1, &kCFTypeArrayCallBacks
)) == NULL
)
3401 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot create certificate array");
3404 CFRelease(identity
);
3410 # if HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY
3412 CFRelease(policy_search
);
3413 # endif /* HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY */
3415 return (certificates
);
3417 #endif /* HAVE_CDSASSL */
3421 * 'get_file()' - Get a filename and state info.
3424 static char * /* O - Real filename */
3425 get_file(cupsd_client_t
*con
, /* I - Client connection */
3426 struct stat
*filestats
, /* O - File information */
3427 char *filename
, /* IO - Filename buffer */
3428 int len
) /* I - Buffer length */
3430 int status
; /* Status of filesystem calls */
3431 char *ptr
; /* Pointer info filename */
3432 int plen
; /* Remaining length after pointer */
3433 char language
[7]; /* Language subdirectory, if any */
3437 * Figure out the real filename...
3442 if (!strncmp(con
->uri
, "/ppd/", 5))
3443 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
);
3444 else if (!strncmp(con
->uri
, "/rss/", 5) && !strchr(con
->uri
+ 5, '/'))
3445 snprintf(filename
, len
, "%s/rss/%s", CacheDir
, con
->uri
+ 5);
3446 else if (!strncmp(con
->uri
, "/admin/conf/", 12))
3447 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
+ 11);
3448 else if (!strncmp(con
->uri
, "/admin/log/", 11))
3450 if (!strncmp(con
->uri
+ 11, "access_log", 10) && AccessLog
[0] == '/')
3451 strlcpy(filename
, AccessLog
, len
);
3452 else if (!strncmp(con
->uri
+ 11, "error_log", 9) && ErrorLog
[0] == '/')
3453 strlcpy(filename
, ErrorLog
, len
);
3454 else if (!strncmp(con
->uri
+ 11, "page_log", 8) && PageLog
[0] == '/')
3455 strlcpy(filename
, PageLog
, len
);
3459 else if (con
->language
)
3461 snprintf(language
, sizeof(language
), "/%s", con
->language
->language
);
3462 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3465 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3467 if ((ptr
= strchr(filename
, '?')) != NULL
)
3471 * Grab the status for this language; if there isn't a language-specific file
3472 * then fallback to the default one...
3475 if ((status
= stat(filename
, filestats
)) != 0 && language
[0] &&
3476 strncmp(con
->uri
, "/ppd/", 5) &&
3477 strncmp(con
->uri
, "/admin/conf/", 12) &&
3478 strncmp(con
->uri
, "/admin/log/", 11))
3481 * Drop the country code...
3485 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3487 if ((ptr
= strchr(filename
, '?')) != NULL
)
3490 if ((status
= stat(filename
, filestats
)) != 0)
3493 * Drop the language prefix and try the root directory...
3497 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3499 if ((ptr
= strchr(filename
, '?')) != NULL
)
3502 status
= stat(filename
, filestats
);
3507 * If we're found a directory, get the index.html file instead...
3510 if (!status
&& S_ISDIR(filestats
->st_mode
))
3513 * Make sure the URI ends with a slash...
3516 if (con
->uri
[strlen(con
->uri
) - 1] != '/')
3517 strlcat(con
->uri
, "/", sizeof(con
->uri
));
3520 * Find the directory index file, trying every language...
3525 if (status
&& language
[0])
3528 * Try a different language subset...
3532 language
[0] = '\0'; /* Strip country code */
3534 language
[0] = '\0'; /* Strip language */
3538 * Look for the index file...
3541 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3543 if ((ptr
= strchr(filename
, '?')) != NULL
)
3546 ptr
= filename
+ strlen(filename
);
3547 plen
= len
- (ptr
- filename
);
3549 strlcpy(ptr
, "index.html", plen
);
3550 status
= stat(filename
, filestats
);
3555 strlcpy(ptr
, "index.class", plen
);
3556 status
= stat(filename
, filestats
);
3558 #endif /* HAVE_JAVA */
3563 strlcpy(ptr
, "index.pl", plen
);
3564 status
= stat(filename
, filestats
);
3566 #endif /* HAVE_PERL */
3571 strlcpy(ptr
, "index.php", plen
);
3572 status
= stat(filename
, filestats
);
3574 #endif /* HAVE_PHP */
3579 strlcpy(ptr
, "index.pyc", plen
);
3580 status
= stat(filename
, filestats
);
3585 strlcpy(ptr
, "index.py", plen
);
3586 status
= stat(filename
, filestats
);
3588 #endif /* HAVE_PYTHON */
3591 while (status
&& language
[0]);
3594 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "get_file: %d filename=%s size=%d",
3595 con
->http
.fd
, filename
,
3596 status
? -1 : (int)filestats
->st_size
);
3599 con
->http
.data_remaining
= (int)filestats
->st_size
;
3609 * 'install_conf_file()' - Install a configuration file.
3612 static http_status_t
/* O - Status */
3613 install_conf_file(cupsd_client_t
*con
) /* I - Connection */
3615 cups_file_t
*in
, /* Input file */
3616 *out
; /* Output file */
3617 char buffer
[1024]; /* Copy buffer */
3618 int bytes
; /* Number of bytes */
3619 char conffile
[1024], /* Configuration filename */
3620 newfile
[1024], /* New config filename */
3621 oldfile
[1024]; /* Old config filename */
3622 struct stat confinfo
; /* Config file info */
3626 * First construct the filenames...
3629 snprintf(conffile
, sizeof(conffile
), "%s%s", ServerRoot
, con
->uri
+ 11);
3630 snprintf(newfile
, sizeof(newfile
), "%s%s.N", ServerRoot
, con
->uri
+ 11);
3631 snprintf(oldfile
, sizeof(oldfile
), "%s%s.O", ServerRoot
, con
->uri
+ 11);
3633 cupsdLogMessage(CUPSD_LOG_INFO
, "Installing config file \"%s\"...", conffile
);
3636 * Get the owner, group, and permissions of the configuration file.
3637 * If it doesn't exist, assign it to the User and Group in the
3638 * cupsd.conf file with mode 0640 permissions.
3641 if (stat(conffile
, &confinfo
))
3643 confinfo
.st_uid
= User
;
3644 confinfo
.st_gid
= Group
;
3645 confinfo
.st_mode
= ConfigFilePerm
;
3649 * Open the request file and new config file...
3652 if ((in
= cupsFileOpen(con
->filename
, "rb")) == NULL
)
3654 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open request file \"%s\" - %s",
3655 con
->filename
, strerror(errno
));
3656 return (HTTP_SERVER_ERROR
);
3659 if ((out
= cupsFileOpen(newfile
, "wb")) == NULL
)
3662 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open config file \"%s\" - %s",
3663 newfile
, strerror(errno
));
3664 return (HTTP_SERVER_ERROR
);
3667 fchmod(cupsFileNumber(out
), confinfo
.st_mode
);
3668 fchown(cupsFileNumber(out
), confinfo
.st_uid
, confinfo
.st_gid
);
3671 * Copy from the request to the new config file...
3674 while ((bytes
= cupsFileRead(in
, buffer
, sizeof(buffer
))) > 0)
3675 if (cupsFileWrite(out
, buffer
, bytes
) < bytes
)
3677 cupsdLogMessage(CUPSD_LOG_ERROR
,
3678 "Unable to copy to config file \"%s\" - %s",
3679 newfile
, strerror(errno
));
3685 return (HTTP_SERVER_ERROR
);
3689 * Close the files...
3693 if (cupsFileClose(out
))
3695 cupsdLogMessage(CUPSD_LOG_ERROR
,
3696 "Error file closing config file \"%s\" - %s",
3697 newfile
, strerror(errno
));
3701 return (HTTP_SERVER_ERROR
);
3705 * Remove the request file...
3708 unlink(con
->filename
);
3709 cupsdClearString(&con
->filename
);
3712 * Unlink the old backup, rename the current config file to the backup
3713 * filename, and rename the new config file to the config file name...
3716 if (unlink(oldfile
))
3717 if (errno
!= ENOENT
)
3719 cupsdLogMessage(CUPSD_LOG_ERROR
,
3720 "Unable to remove backup config file \"%s\" - %s",
3721 oldfile
, strerror(errno
));
3725 return (HTTP_SERVER_ERROR
);
3728 if (rename(conffile
, oldfile
))
3729 if (errno
!= ENOENT
)
3731 cupsdLogMessage(CUPSD_LOG_ERROR
,
3732 "Unable to rename old config file \"%s\" - %s",
3733 conffile
, strerror(errno
));
3737 return (HTTP_SERVER_ERROR
);
3740 if (rename(newfile
, conffile
))
3742 cupsdLogMessage(CUPSD_LOG_ERROR
,
3743 "Unable to rename new config file \"%s\" - %s",
3744 newfile
, strerror(errno
));
3746 rename(oldfile
, conffile
);
3749 return (HTTP_SERVER_ERROR
);
3753 * If the cupsd.conf file was updated, set the NeedReload flag...
3756 if (!strcmp(con
->uri
, "/admin/conf/cupsd.conf"))
3757 NeedReload
= RELOAD_CUPSD
;
3759 NeedReload
= RELOAD_ALL
;
3761 ReloadTime
= time(NULL
);
3764 * Return that the file was created successfully...
3767 return (HTTP_CREATED
);
3772 * 'is_cgi()' - Is the resource a CGI script/program?
3775 static int /* O - 1 = CGI, 0 = file */
3776 is_cgi(cupsd_client_t
*con
, /* I - Client connection */
3777 const char *filename
, /* I - Real filename */
3778 struct stat
*filestats
, /* I - File information */
3779 mime_type_t
*type
) /* I - MIME type */
3781 const char *options
; /* Options on URL */
3784 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3785 "is_cgi(con=%p, filename=\"%s\", filestats=%p, type=%s/%s)",
3786 con
, filename
, filestats
, type
? type
->super
: "unknown",
3787 type
? type
->type
: "unknown");
3790 * Get the options, if any...
3793 if ((options
= strchr(con
->uri
, '?')) != NULL
)
3796 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", options
);
3800 * Check for known types...
3803 if (!type
|| strcasecmp(type
->super
, "application"))
3805 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "is_cgi: Returning 0...");
3809 if (!strcasecmp(type
->type
, "x-httpd-cgi") &&
3810 (filestats
->st_mode
& 0111))
3813 * "application/x-httpd-cgi" is a CGI script.
3816 cupsdSetString(&con
->command
, filename
);
3819 cupsdSetStringf(&con
->options
, " %s", options
);
3821 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3822 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3823 con
->command
, con
->options
);
3828 else if (!strcasecmp(type
->type
, "x-httpd-java"))
3831 * "application/x-httpd-java" is a Java servlet.
3834 cupsdSetString(&con
->command
, CUPS_JAVA
);
3837 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3839 cupsdSetStringf(&con
->options
, " %s", filename
);
3841 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3842 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3843 con
->command
, con
->options
);
3847 #endif /* HAVE_JAVA */
3849 else if (!strcasecmp(type
->type
, "x-httpd-perl"))
3852 * "application/x-httpd-perl" is a Perl page.
3855 cupsdSetString(&con
->command
, CUPS_PERL
);
3858 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3860 cupsdSetStringf(&con
->options
, " %s", filename
);
3862 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3863 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3864 con
->command
, con
->options
);
3868 #endif /* HAVE_PERL */
3870 else if (!strcasecmp(type
->type
, "x-httpd-php"))
3873 * "application/x-httpd-php" is a PHP page.
3876 cupsdSetString(&con
->command
, CUPS_PHP
);
3879 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3881 cupsdSetStringf(&con
->options
, " %s", filename
);
3883 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3884 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3885 con
->command
, con
->options
);
3889 #endif /* HAVE_PHP */
3891 else if (!strcasecmp(type
->type
, "x-httpd-python"))
3894 * "application/x-httpd-python" is a Python page.
3897 cupsdSetString(&con
->command
, CUPS_PYTHON
);
3900 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3902 cupsdSetStringf(&con
->options
, " %s", filename
);
3904 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3905 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3906 con
->command
, con
->options
);
3910 #endif /* HAVE_PYTHON */
3912 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "is_cgi: Returning 0...");
3919 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
3922 static int /* O - 0 if relative, 1 if absolute */
3923 is_path_absolute(const char *path
) /* I - Input path */
3926 * Check for a leading slash...
3933 * Check for "/.." in the path...
3936 while ((path
= strstr(path
, "/..")) != NULL
)
3938 if (!path
[3] || path
[3] == '/')
3945 * If we haven't found any relative paths, return 1 indicating an
3955 * 'make_certificate()' - Make a self-signed SSL/TLS certificate.
3958 static int /* O - 1 on success, 0 on failure */
3959 make_certificate(cupsd_client_t
*con
) /* I - Client connection */
3961 #if defined(HAVE_LIBSSL) && defined(HAVE_WAITPID)
3962 int pid
, /* Process ID of command */
3963 status
; /* Status of command */
3964 char command
[1024], /* Command */
3965 *argv
[12], /* Command-line arguments */
3966 *envp
[MAX_ENV
+ 1], /* Environment variables */
3967 home
[1024], /* HOME environment variable */
3968 infofile
[1024], /* Type-in information for cert */
3969 seedfile
[1024]; /* Random number seed file */
3970 int envc
, /* Number of environment variables */
3971 bytes
; /* Bytes written */
3972 cups_file_t
*fp
; /* Seed/info file */
3973 int infofd
; /* Info file descriptor */
3977 * Run the "openssl" command to seed the random number generator and
3978 * generate a self-signed certificate that is good for 10 years:
3980 * openssl rand -rand seedfile 1
3982 * openssl req -new -x509 -keyout ServerKey \
3983 * -out ServerCertificate -days 3650 -nodes
3985 * The seeding step is crucial in ensuring that the openssl command
3986 * does not block on systems without sufficient entropy...
3989 if (!cupsFileFind("openssl", getenv("PATH"), 1, command
, sizeof(command
)))
3991 cupsdLogMessage(CUPSD_LOG_ERROR
,
3992 "No SSL certificate and openssl command not found!");
3996 if (access("/dev/urandom", 0))
3999 * If the system doesn't provide /dev/urandom, then any random source
4000 * will probably be blocking-style, so generate some random data to
4001 * use as a seed for the certificate. Note that we have already
4002 * seeded the random number generator in cupsdInitCerts()...
4005 cupsdLogMessage(CUPSD_LOG_INFO
,
4006 "Seeding the random number generator...");
4008 snprintf(home
, sizeof(home
), "HOME=%s", TempDir
);
4011 * Write the seed file...
4014 if ((fp
= cupsTempFile2(seedfile
, sizeof(seedfile
))) == NULL
)
4016 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to create seed file %s - %s",
4017 seedfile
, strerror(errno
));
4021 for (bytes
= 0; bytes
< 262144; bytes
++)
4022 cupsFilePutChar(fp
, random());
4027 * Run the openssl command to seed its random number generator...
4030 argv
[0] = "openssl";
4037 envc
= cupsdLoadEnv(envp
, MAX_ENV
);
4038 envp
[envc
++] = home
;
4041 if (!cupsdStartProcess(command
, argv
, envp
, -1, -1, -1, -1, -1, 1, NULL
,
4048 while (waitpid(pid
, &status
, 0) < 0)
4055 cupsdFinishProcess(pid
, command
, sizeof(command
));
4058 * Remove the seed file, as it is no longer needed...
4065 if (WIFEXITED(status
))
4066 cupsdLogMessage(CUPSD_LOG_ERROR
,
4067 "Unable to seed random number generator - "
4068 "the openssl command stopped with status %d!",
4069 WEXITSTATUS(status
));
4071 cupsdLogMessage(CUPSD_LOG_ERROR
,
4072 "Unable to seed random number generator - "
4073 "the openssl command crashed on signal %d!",
4081 * Create a file with the certificate information fields...
4083 * Note: This assumes that the default questions are asked by the openssl
4087 if ((fp
= cupsTempFile2(infofile
, sizeof(infofile
))) == NULL
)
4089 cupsdLogMessage(CUPSD_LOG_ERROR
,
4090 "Unable to create certificate information file %s - %s",
4091 infofile
, strerror(errno
));
4095 cupsFilePrintf(fp
, ".\n.\n.\n%s\n.\n%s\n%s\n",
4096 ServerName
, ServerName
, ServerAdmin
);
4099 cupsdLogMessage(CUPSD_LOG_INFO
,
4100 "Generating SSL server key and certificate...");
4102 argv
[0] = "openssl";
4106 argv
[4] = "-keyout";
4107 argv
[5] = ServerKey
;
4109 argv
[7] = ServerCertificate
;
4112 argv
[10] = "-nodes";
4115 cupsdLoadEnv(envp
, MAX_ENV
);
4117 infofd
= open(infofile
, O_RDONLY
);
4119 if (!cupsdStartProcess(command
, argv
, envp
, infofd
, -1, -1, -1, -1, 1, NULL
,
4130 while (waitpid(pid
, &status
, 0) < 0)
4137 cupsdFinishProcess(pid
, command
, sizeof(command
));
4141 if (WIFEXITED(status
))
4142 cupsdLogMessage(CUPSD_LOG_ERROR
,
4143 "Unable to create SSL server key and certificate - "
4144 "the openssl command stopped with status %d!",
4145 WEXITSTATUS(status
));
4147 cupsdLogMessage(CUPSD_LOG_ERROR
,
4148 "Unable to create SSL server key and certificate - "
4149 "the openssl command crashed on signal %d!",
4154 cupsdLogMessage(CUPSD_LOG_INFO
, "Created SSL server key file \"%s\"...",
4156 cupsdLogMessage(CUPSD_LOG_INFO
,
4157 "Created SSL server certificate file \"%s\"...",
4163 #elif defined(HAVE_GNUTLS)
4164 gnutls_x509_crt crt
; /* Self-signed certificate */
4165 gnutls_x509_privkey key
; /* Encryption key */
4166 cups_lang_t
*language
; /* Default language info */
4167 cups_file_t
*fp
; /* Key/cert file */
4168 unsigned char buffer
[8192]; /* Buffer for x509 data */
4169 size_t bytes
; /* Number of bytes of data */
4170 unsigned char serial
[4]; /* Serial number buffer */
4171 time_t curtime
; /* Current time */
4172 int result
; /* Result of GNU TLS calls */
4176 * Create the encryption key...
4179 cupsdLogMessage(CUPSD_LOG_INFO
, "Generating SSL server key...");
4181 gnutls_x509_privkey_init(&key
);
4182 gnutls_x509_privkey_generate(key
, GNUTLS_PK_RSA
, 2048, 0);
4188 bytes
= sizeof(buffer
);
4190 if ((result
= gnutls_x509_privkey_export(key
, GNUTLS_X509_FMT_PEM
,
4191 buffer
, &bytes
)) < 0)
4193 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to export SSL server key - %s",
4194 gnutls_strerror(result
));
4195 gnutls_x509_privkey_deinit(key
);
4198 else if ((fp
= cupsFileOpen(ServerKey
, "w")) != NULL
)
4200 cupsFileWrite(fp
, (char *)buffer
, bytes
);
4203 cupsdLogMessage(CUPSD_LOG_INFO
, "Created SSL server key file \"%s\"...",
4208 cupsdLogMessage(CUPSD_LOG_ERROR
,
4209 "Unable to create SSL server key file \"%s\" - %s",
4210 ServerKey
, strerror(errno
));
4211 gnutls_x509_privkey_deinit(key
);
4216 * Create the self-signed certificate...
4219 cupsdLogMessage(CUPSD_LOG_INFO
, "Generating self-signed SSL certificate...");
4221 language
= cupsLangDefault();
4222 curtime
= time(NULL
);
4223 serial
[0] = curtime
>> 24;
4224 serial
[1] = curtime
>> 16;
4225 serial
[2] = curtime
>> 8;
4226 serial
[3] = curtime
;
4228 gnutls_x509_crt_init(&crt
);
4229 if (strlen(language
->language
) == 5)
4230 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
4231 language
->language
+ 3, 2);
4233 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
4235 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COMMON_NAME
, 0,
4236 ServerName
, strlen(ServerName
));
4237 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATION_NAME
, 0,
4238 ServerName
, strlen(ServerName
));
4239 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATIONAL_UNIT_NAME
,
4241 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_STATE_OR_PROVINCE_NAME
, 0,
4243 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_LOCALITY_NAME
, 0,
4245 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_PKCS9_EMAIL
, 0,
4246 ServerAdmin
, strlen(ServerAdmin
));
4247 gnutls_x509_crt_set_key(crt
, key
);
4248 gnutls_x509_crt_set_serial(crt
, serial
, sizeof(serial
));
4249 gnutls_x509_crt_set_activation_time(crt
, curtime
);
4250 gnutls_x509_crt_set_expiration_time(crt
, curtime
+ 10 * 365 * 86400);
4251 gnutls_x509_crt_set_ca_status(crt
, 0);
4252 gnutls_x509_crt_set_subject_alternative_name(crt
, GNUTLS_SAN_DNSNAME
,
4254 gnutls_x509_crt_set_key_purpose_oid(crt
, GNUTLS_KP_TLS_WWW_SERVER
, 0);
4255 gnutls_x509_crt_set_key_usage(crt
, GNUTLS_KEY_KEY_ENCIPHERMENT
);
4256 gnutls_x509_crt_set_version(crt
, 3);
4258 bytes
= sizeof(buffer
);
4259 if (gnutls_x509_crt_get_key_id(crt
, 0, buffer
, &bytes
) >= 0)
4260 gnutls_x509_crt_set_subject_key_id(crt
, buffer
, bytes
);
4262 gnutls_x509_crt_sign(crt
, crt
, key
);
4268 bytes
= sizeof(buffer
);
4269 if ((result
= gnutls_x509_crt_export(crt
, GNUTLS_X509_FMT_PEM
,
4270 buffer
, &bytes
)) < 0)
4271 cupsdLogMessage(CUPSD_LOG_ERROR
,
4272 "Unable to export SSL server certificate - %s",
4273 gnutls_strerror(result
));
4274 else if ((fp
= cupsFileOpen(ServerCertificate
, "w")) != NULL
)
4276 cupsFileWrite(fp
, (char *)buffer
, bytes
);
4279 cupsdLogMessage(CUPSD_LOG_INFO
,
4280 "Created SSL server certificate file \"%s\"...",
4284 cupsdLogMessage(CUPSD_LOG_ERROR
,
4285 "Unable to create SSL server certificate file \"%s\" - %s",
4286 ServerCertificate
, strerror(errno
));
4292 gnutls_x509_crt_deinit(crt
);
4293 gnutls_x509_privkey_deinit(key
);
4297 #elif defined(HAVE_CDSASSL) && defined(HAVE_WAITPID)
4298 int pid
, /* Process ID of command */
4299 status
; /* Status of command */
4300 char command
[1024], /* Command */
4301 *argv
[4], /* Command-line arguments */
4302 *envp
[MAX_ENV
+ 1], /* Environment variables */
4303 keychain
[1024], /* Keychain argument */
4304 infofile
[1024]; /* Type-in information for cert */
4305 cups_file_t
*fp
; /* Seed/info file */
4306 int infofd
; /* Info file descriptor */
4310 * Run the "certtool" command to generate a self-signed certificate...
4313 if (!cupsFileFind("certtool", getenv("PATH"), 1, command
, sizeof(command
)))
4315 cupsdLogMessage(CUPSD_LOG_ERROR
,
4316 "No SSL certificate and certtool command not found!");
4321 * Create a file with the certificate information fields...
4323 * Note: This assumes that the default questions are asked by the certtool
4327 if ((fp
= cupsTempFile2(infofile
, sizeof(infofile
))) == NULL
)
4329 cupsdLogMessage(CUPSD_LOG_ERROR
,
4330 "Unable to create certificate information file %s - %s",
4331 infofile
, strerror(errno
));
4335 cupsFilePrintf(fp
, "%s\nr\n\ny\nb\ns\ny\n%s\n\n\n\n\n%s\ny\n",
4336 con
->servername
, con
->servername
, ServerAdmin
);
4339 cupsdLogMessage(CUPSD_LOG_INFO
,
4340 "Generating SSL server key and certificate...");
4342 snprintf(keychain
, sizeof(keychain
), "k=%s", ServerCertificate
);
4344 argv
[0] = "certtool";
4349 cupsdLoadEnv(envp
, MAX_ENV
);
4351 infofd
= open(infofile
, O_RDONLY
);
4353 if (!cupsdStartProcess(command
, argv
, envp
, infofd
, -1, -1, -1, -1, 1, NULL
,
4364 while (waitpid(pid
, &status
, 0) < 0)
4371 cupsdFinishProcess(pid
, command
, sizeof(command
));
4375 if (WIFEXITED(status
))
4376 cupsdLogMessage(CUPSD_LOG_ERROR
,
4377 "Unable to create SSL server key and certificate - "
4378 "the certtool command stopped with status %d!",
4379 WEXITSTATUS(status
));
4381 cupsdLogMessage(CUPSD_LOG_ERROR
,
4382 "Unable to create SSL server key and certificate - "
4383 "the certtool command crashed on signal %d!",
4388 cupsdLogMessage(CUPSD_LOG_INFO
,
4389 "Created SSL server certificate file \"%s\"...",
4397 #endif /* HAVE_LIBSSL && HAVE_WAITPID */
4399 #endif /* HAVE_SSL */
4403 * 'pipe_command()' - Pipe the output of a command to the remote client.
4406 static int /* O - Process ID */
4407 pipe_command(cupsd_client_t
*con
, /* I - Client connection */
4408 int infile
, /* I - Standard input for command */
4409 int *outfile
, /* O - Standard output for command */
4410 char *command
, /* I - Command to run */
4411 char *options
, /* I - Options for command */
4412 int root
) /* I - Run as root? */
4414 int i
; /* Looping var */
4415 int pid
; /* Process ID */
4416 char *commptr
, /* Command string pointer */
4417 commch
; /* Command string character */
4418 char *uriptr
; /* URI string pointer */
4419 int fds
[2]; /* Pipe FDs */
4420 int argc
; /* Number of arguments */
4421 int envc
; /* Number of environment variables */
4422 char argbuf
[10240], /* Argument buffer */
4423 *argv
[100], /* Argument strings */
4424 *envp
[MAX_ENV
+ 20]; /* Environment variables */
4425 char auth_type
[256], /* CUPSD_AUTH_TYPE environment variable */
4426 content_length
[1024], /* CONTENT_LENGTH environment variable */
4427 content_type
[1024], /* CONTENT_TYPE environment variable */
4428 http_cookie
[32768], /* HTTP_COOKIE environment variable */
4429 http_referer
[1024], /* HTTP_REFERER environment variable */
4430 http_user_agent
[1024], /* HTTP_USER_AGENT environment variable */
4431 lang
[1024], /* LANG environment variable */
4432 path_info
[1024], /* PATH_INFO environment variable */
4433 remote_addr
[1024], /* REMOTE_ADDR environment variable */
4434 remote_host
[1024], /* REMOTE_HOST environment variable */
4435 remote_user
[1024], /* REMOTE_USER environment variable */
4436 script_filename
[1024], /* SCRIPT_FILENAME environment variable */
4437 script_name
[1024], /* SCRIPT_NAME environment variable */
4438 server_name
[1024], /* SERVER_NAME environment variable */
4439 server_port
[1024]; /* SERVER_PORT environment variable */
4440 ipp_attribute_t
*attr
; /* attributes-natural-language attribute */
4442 krb5_ccache ccache
= NULL
; /* Kerberos credentials */
4443 char krb5ccname
[1024]; /* KRB5CCNAME environment variable */
4444 #endif /* HAVE_GSSAPI */
4448 * Parse a copy of the options string, which is of the form:
4450 * argument+argument+argument
4451 * ?argument+argument+argument
4452 * param=value¶m=value
4453 * ?param=value¶m=value
4454 * /name?argument+argument+argument
4455 * /name?param=value¶m=value
4457 * If the string contains an "=" character after the initial name,
4458 * then we treat it as a HTTP GET form request and make a copy of
4459 * the remaining string for the environment variable.
4461 * The string is always parsed out as command-line arguments, to
4462 * be consistent with Apache...
4465 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4466 "pipe_command: command=\"%s\", options=\"%s\"",
4467 command
, options
? options
: "(null)");
4472 strlcpy(argbuf
, options
, sizeof(argbuf
));
4476 if (argbuf
[0] == '/')
4479 * Found some trailing path information, set PATH_INFO...
4482 if ((commptr
= strchr(argbuf
, '?')) == NULL
)
4483 commptr
= argbuf
+ strlen(argbuf
);
4487 snprintf(path_info
, sizeof(path_info
), "PATH_INFO=%s", argbuf
);
4493 path_info
[0] = '\0';
4495 if (*commptr
== ' ')
4499 if (*commptr
== '?' && con
->operation
== HTTP_GET
&& !con
->query_string
)
4502 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", commptr
);
4509 argv
[argc
++] = commptr
;
4511 for (; *commptr
&& argc
< 99; commptr
++)
4514 * Break arguments whenever we see a + or space...
4517 if (*commptr
== ' ' || *commptr
== '+')
4519 while (*commptr
== ' ' || *commptr
== '+')
4523 * If we don't have a blank string, save it as another argument...
4528 argv
[argc
] = commptr
;
4534 else if (*commptr
== '%' && isxdigit(commptr
[1] & 255) &&
4535 isxdigit(commptr
[2] & 255))
4538 * Convert the %xx notation to the individual character.
4541 if (commptr
[1] >= '0' && commptr
[1] <= '9')
4542 *commptr
= (commptr
[1] - '0') << 4;
4544 *commptr
= (tolower(commptr
[1]) - 'a' + 10) << 4;
4546 if (commptr
[2] >= '0' && commptr
[2] <= '9')
4547 *commptr
|= commptr
[2] - '0';
4549 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
4551 _cups_strcpy(commptr
+ 1, commptr
+ 3);
4554 * Check for a %00 and break if that is the case...
4566 * Setup the environment variables as needed...
4569 if (con
->username
[0])
4571 snprintf(auth_type
, sizeof(auth_type
), "CUPSD_AUTH_TYPE=%s",
4572 httpGetField(HTTP(con
), HTTP_FIELD_AUTHORIZATION
));
4574 if ((uriptr
= strchr(auth_type
+ 10, ' ')) != NULL
)
4578 auth_type
[0] = '\0';
4581 (attr
= ippFindAttribute(con
->request
, "attributes-natural-language",
4582 IPP_TAG_LANGUAGE
)) != NULL
)
4584 switch (strlen(attr
->values
[0].string
.text
))
4588 * This is an unknown or badly formatted language code; use
4589 * the POSIX locale...
4592 strcpy(lang
, "LANG=C");
4597 * Just the language code (ll)...
4600 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8",
4601 attr
->values
[0].string
.text
);
4606 * Language and country code (ll-cc)...
4609 snprintf(lang
, sizeof(lang
), "LANG=%c%c_%c%c.UTF8",
4610 attr
->values
[0].string
.text
[0],
4611 attr
->values
[0].string
.text
[1],
4612 toupper(attr
->values
[0].string
.text
[3] & 255),
4613 toupper(attr
->values
[0].string
.text
[4] & 255));
4617 else if (con
->language
)
4618 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8", con
->language
->language
);
4620 strcpy(lang
, "LANG=C");
4622 strcpy(remote_addr
, "REMOTE_ADDR=");
4623 httpAddrString(con
->http
.hostaddr
, remote_addr
+ 12,
4624 sizeof(remote_addr
) - 12);
4626 snprintf(remote_host
, sizeof(remote_host
), "REMOTE_HOST=%s",
4627 con
->http
.hostname
);
4629 snprintf(script_name
, sizeof(script_name
), "SCRIPT_NAME=%s", con
->uri
);
4630 if ((uriptr
= strchr(script_name
, '?')) != NULL
)
4633 snprintf(script_filename
, sizeof(script_filename
), "SCRIPT_FILENAME=%s%s",
4634 DocumentRoot
, script_name
+ 12);
4636 sprintf(server_port
, "SERVER_PORT=%d", con
->serverport
);
4638 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
4641 envc
= cupsdLoadEnv(envp
, (int)(sizeof(envp
) / sizeof(envp
[0])));
4644 envp
[envc
++] = auth_type
;
4646 envp
[envc
++] = lang
;
4647 envp
[envc
++] = "REDIRECT_STATUS=1";
4648 envp
[envc
++] = "GATEWAY_INTERFACE=CGI/1.1";
4649 envp
[envc
++] = server_name
;
4650 envp
[envc
++] = server_port
;
4651 envp
[envc
++] = remote_addr
;
4652 envp
[envc
++] = remote_host
;
4653 envp
[envc
++] = script_name
;
4654 envp
[envc
++] = script_filename
;
4657 envp
[envc
++] = path_info
;
4659 if (con
->username
[0])
4661 snprintf(remote_user
, sizeof(remote_user
), "REMOTE_USER=%s", con
->username
);
4663 envp
[envc
++] = remote_user
;
4666 * Save Kerberos credentials, if any...
4670 if (con
->gss_have_creds
)
4672 # if !defined(HAVE_KRB5_CC_NEW_UNIQUE) && !defined(HAVE_HEIMDAL)
4673 cupsdLogMessage(CUPSD_LOG_INFO
,
4674 "Sorry, your version of Kerberos does not support "
4675 "delegated credentials!");
4678 krb5_error_code error
; /* Kerberos error code */
4679 OM_uint32 major_status
, /* Major status code */
4680 minor_status
; /* Minor status code */
4681 krb5_principal principal
; /* Kerberos principal */
4686 * If the weak-linked GSSAPI/Kerberos library is not present, don't try
4690 if (krb5_init_context
!= NULL
)
4692 # endif /* __APPLE__ */
4695 * We MUST create a file-based cache because memory-based caches are
4696 * only valid for the current process/address space.
4698 * Due to various bugs/features in different versions of Kerberos, we
4699 * need either the krb5_cc_new_unique() function or Heimdal's version
4700 * of krb5_cc_gen_new() to create a new FILE: credential cache that
4701 * can be passed to the backend. These functions create a temporary
4702 * file (typically in /tmp) containing the cached credentials, which
4703 * are removed when we have successfully printed a job.
4706 # ifdef HAVE_KRB5_CC_NEW_UNIQUE
4707 if ((error
= krb5_cc_new_unique(KerberosContext
, "FILE", NULL
,
4709 # else /* HAVE_HEIMDAL */
4710 if ((error
= krb5_cc_gen_new(KerberosContext
, &krb5_fcc_ops
,
4712 # endif /* HAVE_KRB5_CC_NEW_UNIQUE */
4714 cupsdLogMessage(CUPSD_LOG_ERROR
,
4715 "Unable to create new credentials cache (%d/%s)",
4716 error
, strerror(errno
));
4719 else if ((error
= krb5_parse_name(KerberosContext
, con
->username
,
4722 cupsdLogMessage(CUPSD_LOG_ERROR
,
4723 "Unable to parse kerberos username (%d/%s)", error
,
4725 krb5_cc_destroy(KerberosContext
, ccache
);
4728 else if ((error
= krb5_cc_initialize(KerberosContext
, ccache
,
4731 cupsdLogMessage(CUPSD_LOG_ERROR
,
4732 "Unable to initialize credentials cache (%d/%s)", error
,
4734 krb5_cc_destroy(KerberosContext
, ccache
);
4735 krb5_free_principal(KerberosContext
, principal
);
4740 krb5_free_principal(KerberosContext
, principal
);
4743 * Copy the user's credentials to the new cache file...
4746 major_status
= gss_krb5_copy_ccache(&minor_status
,
4747 con
->gss_delegated_cred
, ccache
);
4749 if (GSS_ERROR(major_status
))
4751 cupsdLogGSSMessage(CUPSD_LOG_ERROR
, major_status
, minor_status
,
4752 "Unable to import client credentials cache");
4753 krb5_cc_destroy(KerberosContext
, ccache
);
4759 * Add the KRB5CCNAME environment variable to the job so that the
4760 * backend can use the credentials when printing.
4763 snprintf(krb5ccname
, sizeof(krb5ccname
), "KRB5CCNAME=FILE:%s",
4764 krb5_cc_get_name(KerberosContext
, ccache
));
4765 envp
[envc
++] = krb5ccname
;
4768 chown(krb5_cc_get_name(KerberosContext
, ccache
), User
, Group
);
4773 # endif /* __APPLE__ */
4774 # endif /* HAVE_KRB5_CC_NEW_UNIQUE || HAVE_HEIMDAL */
4776 #endif /* HAVE_GSSAPI */
4780 if (con
->http
.version
== HTTP_1_1
)
4781 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.1";
4782 else if (con
->http
.version
== HTTP_1_0
)
4783 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.0";
4785 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/0.9";
4787 if (con
->http
.cookie
)
4789 snprintf(http_cookie
, sizeof(http_cookie
), "HTTP_COOKIE=%s",
4791 envp
[envc
++] = http_cookie
;
4794 if (con
->http
.fields
[HTTP_FIELD_USER_AGENT
][0])
4796 snprintf(http_user_agent
, sizeof(http_user_agent
), "HTTP_USER_AGENT=%s",
4797 con
->http
.fields
[HTTP_FIELD_USER_AGENT
]);
4798 envp
[envc
++] = http_user_agent
;
4801 if (con
->http
.fields
[HTTP_FIELD_REFERER
][0])
4803 snprintf(http_referer
, sizeof(http_referer
), "HTTP_REFERER=%s",
4804 con
->http
.fields
[HTTP_FIELD_REFERER
]);
4805 envp
[envc
++] = http_referer
;
4808 if (con
->operation
== HTTP_GET
)
4810 envp
[envc
++] = "REQUEST_METHOD=GET";
4812 if (con
->query_string
)
4815 * Add GET form variables after ?...
4818 envp
[envc
++] = con
->query_string
;
4821 envp
[envc
++] = "QUERY_STRING=";
4825 sprintf(content_length
, "CONTENT_LENGTH=" CUPS_LLFMT
,
4826 CUPS_LLCAST con
->bytes
);
4827 snprintf(content_type
, sizeof(content_type
), "CONTENT_TYPE=%s",
4828 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
4830 envp
[envc
++] = "REQUEST_METHOD=POST";
4831 envp
[envc
++] = content_length
;
4832 envp
[envc
++] = content_type
;
4836 * Tell the CGI if we are using encryption...
4840 envp
[envc
++] = "HTTPS=ON";
4843 * Terminate the environment array...
4848 if (LogLevel
== CUPSD_LOG_DEBUG2
)
4850 for (i
= 0; i
< argc
; i
++)
4851 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4852 "pipe_command: argv[%d] = \"%s\"", i
, argv
[i
]);
4853 for (i
= 0; i
< envc
; i
++)
4854 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4855 "pipe_command: envp[%d] = \"%s\"", i
, envp
[i
]);
4859 * Create a pipe for the output...
4862 if (cupsdOpenPipe(fds
))
4864 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to create pipes for CGI %s - %s",
4865 argv
[0], strerror(errno
));
4870 * Then execute the command...
4873 if (cupsdStartProcess(command
, argv
, envp
, infile
, fds
[1], CGIPipes
[1],
4874 -1, -1, root
, DefaultProfile
, &pid
) < 0)
4877 * Error - can't fork!
4880 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to fork for CGI %s - %s", argv
[0],
4883 cupsdClosePipe(fds
);
4889 * Fork successful - return the PID...
4892 if (con
->username
[0])
4894 cupsdAddCert(pid
, con
->username
, ccache
);
4896 cupsdAddCert(pid
, con
->username
, NULL
);
4897 #endif /* HAVE_GSSAPI */
4899 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[CGI] %s started - PID = %d",
4911 * 'write_file()' - Send a file via HTTP.
4914 static int /* O - 0 on failure, 1 on success */
4915 write_file(cupsd_client_t
*con
, /* I - Client connection */
4916 http_status_t code
, /* I - HTTP status */
4917 char *filename
, /* I - Filename */
4918 char *type
, /* I - File type */
4919 struct stat
*filestats
) /* O - File information */
4921 con
->file
= open(filename
, O_RDONLY
);
4923 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "write_file: %d file=%d", con
->http
.fd
,
4929 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
4933 if (!cupsdSendHeader(con
, code
, type
, CUPSD_AUTH_NONE
))
4936 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
4937 httpGetDateString(filestats
->st_mtime
)) < 0)
4939 if (httpPrintf(HTTP(con
), "Content-Length: " CUPS_LLFMT
"\r\n",
4940 CUPS_LLCAST filestats
->st_size
) < 0)
4942 if (httpPrintf(HTTP(con
), "\r\n") < 0)
4945 if (cupsdFlushHeader(con
) < 0)
4948 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
4949 con
->http
.data_remaining
= filestats
->st_size
;
4951 if (con
->http
.data_remaining
<= INT_MAX
)
4952 con
->http
._data_remaining
= con
->http
.data_remaining
;
4954 con
->http
._data_remaining
= INT_MAX
;
4956 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
,
4957 (cupsd_selfunc_t
)cupsdWriteClient
, con
);
4964 * 'write_pipe()' - Flag that data is available on the CGI pipe.
4968 write_pipe(cupsd_client_t
*con
) /* I - Client connection */
4970 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "write_pipe: CGI output on fd %d...",
4973 con
->file_ready
= 1;
4975 cupsdRemoveSelect(con
->file
);
4976 cupsdAddSelect(con
->http
.fd
, NULL
, (cupsd_selfunc_t
)cupsdWriteClient
, con
);
4981 * End of "$Id: client.c 7950 2008-09-17 00:21:59Z mike $".