2 * "$Id: client.c 7950 2008-09-17 00:21:59Z mike $"
4 * Client routines for the Common UNIX Printing System (CUPS) scheduler.
6 * Copyright 2007-2009 by Apple Inc.
7 * Copyright 1997-2007 by Easy Software Products, all rights reserved.
9 * This file contains Kerberos support code, copyright 2006 by
12 * These coded instructions, statements, and computer programs are the
13 * property of Apple Inc. and are protected by Federal copyright
14 * law. Distribution and use rights are outlined in the file "LICENSE.txt"
15 * which should have been included with this file. If this file is
16 * file is missing or damaged, see the license at "http://www.cups.org/".
20 * cupsdAcceptClient() - Accept a new client.
21 * cupsdCloseAllClients() - Close all remote clients immediately.
22 * cupsdCloseClient() - Close a remote client.
23 * cupsdFlushHeader() - Flush the header fields to the client.
24 * cupsdReadClient() - Read data from a client.
25 * cupsdSendCommand() - Send output from a command via HTTP.
26 * cupsdSendError() - Send an error message via HTTP.
27 * cupsdSendHeader() - Send an HTTP request.
28 * cupsdUpdateCGI() - Read status messages from CGI scripts and programs.
29 * cupsdWriteClient() - Write data to a client as needed.
30 * check_if_modified() - Decode an "If-Modified-Since" line.
31 * compare_clients() - Compare two client connections.
32 * data_ready() - Check whether data is available from a client.
33 * encrypt_client() - Enable encryption for the client...
34 * get_cdsa_certificate() - Convert a keychain name into the CFArrayRef
35 * required by SSLSetCertificate.
36 * get_file() - Get a filename and state info.
37 * install_conf_file() - Install a configuration file.
38 * is_cgi() - Is the resource a CGI script/program?
39 * is_path_absolute() - Is a path absolute and free of relative elements.
40 * make_certificate() - Make a self-signed SSL/TLS certificate.
41 * pipe_command() - Pipe the output of a command to the remote client.
42 * write_file() - Send a file via HTTP.
43 * write_pipe() - Flag that data is available on the CGI pipe.
47 * Include necessary headers...
53 # include <Security/Security.h>
54 # ifdef HAVE_SECIDENTITYSEARCHPRIV_H
55 # include <Security/SecIdentitySearchPriv.h>
56 # else /* Declare prototype for function in that header... */
57 extern OSStatus
SecIdentitySearchCreateWithPolicy(SecPolicyRef policy
,
58 CFStringRef idString
, CSSM_KEYUSE keyUsage
,
59 CFTypeRef keychainOrArray
,
60 Boolean returnOnlyValidIdentities
,
61 SecIdentitySearchRef
* searchRef
);
62 # endif /* HAVE_SECIDENTITYSEARCHPRIV_H */
63 # ifdef HAVE_SECPOLICYPRIV_H
64 # include <Security/SecPolicyPriv.h>
65 # else /* Declare prototype for function in that header... */
66 extern OSStatus
SecPolicySetValue(SecPolicyRef policyRef
,
67 const CSSM_DATA
*value
);
68 # endif /* HAVE_SECPOLICYPRIV_H */
69 # ifdef HAVE_SECBASEPRIV_H
70 # include <Security/SecBasePriv.h>
71 # else /* Declare prototype for function in that header... */
72 extern const char *cssmErrorString(int error
);
73 # endif /* HAVE_SECBASEPRIV_H */
74 #endif /* HAVE_CDSASSL */
77 # include <gnutls/x509.h>
78 #endif /* HAVE_GNUTLS */
82 #endif /* HAVE_TCPD_H */
89 static int check_if_modified(cupsd_client_t
*con
,
90 struct stat
*filestats
);
91 static int compare_clients(cupsd_client_t
*a
, cupsd_client_t
*b
,
93 static int data_ready(cupsd_client_t
*con
);
95 static int encrypt_client(cupsd_client_t
*con
);
98 static CFArrayRef
get_cdsa_certificate(cupsd_client_t
*con
);
99 #endif /* HAVE_CDSASSL */
100 static char *get_file(cupsd_client_t
*con
, struct stat
*filestats
,
101 char *filename
, int len
);
102 static http_status_t
install_conf_file(cupsd_client_t
*con
);
103 static int is_cgi(cupsd_client_t
*con
, const char *filename
,
104 struct stat
*filestats
, mime_type_t
*type
);
105 static int is_path_absolute(const char *path
);
107 static int make_certificate(cupsd_client_t
*con
);
108 #endif /* HAVE_SSL */
109 static int pipe_command(cupsd_client_t
*con
, int infile
, int *outfile
,
110 char *command
, char *options
, int root
);
111 static int write_file(cupsd_client_t
*con
, http_status_t code
,
112 char *filename
, char *type
,
113 struct stat
*filestats
);
114 static void write_pipe(cupsd_client_t
*con
);
118 * 'cupsdAcceptClient()' - Accept a new client.
122 cupsdAcceptClient(cupsd_listener_t
*lis
)/* I - Listener socket */
124 int count
; /* Count of connections on a host */
125 int val
; /* Parameter value */
126 cupsd_client_t
*con
, /* New client pointer */
127 *tempcon
; /* Temporary client pointer */
128 http_addrlist_t
*addrlist
, /* List of adddresses for host */
129 *addr
; /* Current address */
130 socklen_t addrlen
; /* Length of address */
131 char *hostname
; /* Hostname for address */
132 http_addr_t temp
; /* Temporary address variable */
133 static time_t last_dos
= 0; /* Time of last DoS attack */
135 struct request_info wrap_req
; /* TCP wrappers request information */
136 #endif /* HAVE_TCPD_H */
139 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
140 "cupsdAcceptClient(lis=%p(%d)) Clients=%d",
141 lis
, lis
->fd
, cupsArrayCount(Clients
));
144 * Make sure we don't have a full set of clients already...
147 if (cupsArrayCount(Clients
) == MaxClients
)
151 * Get a pointer to the next available client...
155 Clients
= cupsArrayNew(NULL
, NULL
);
159 cupsdLogMessage(CUPSD_LOG_ERROR
,
160 "Unable to allocate memory for clients array!");
161 cupsdPauseListening();
166 ActiveClients
= cupsArrayNew((cups_array_func_t
)compare_clients
, NULL
);
170 cupsdLogMessage(CUPSD_LOG_ERROR
,
171 "Unable to allocate memory for active clients array!");
172 cupsdPauseListening();
176 if ((con
= calloc(1, sizeof(cupsd_client_t
))) == NULL
)
178 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to allocate memory for client!");
179 cupsdPauseListening();
183 con
->http
.activity
= time(NULL
);
185 con
->http
.hostaddr
= &(con
->clientaddr
);
188 * Accept the client and get the remote address...
191 addrlen
= sizeof(http_addr_t
);
193 if ((con
->http
.fd
= accept(lis
->fd
, (struct sockaddr
*)con
->http
.hostaddr
,
196 if (errno
== ENFILE
|| errno
== EMFILE
)
197 cupsdPauseListening();
199 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to accept client connection - %s.",
207 if (lis
->address
.addr
.sa_family
== AF_INET6
)
210 * Save the connected port number...
213 con
->http
.hostaddr
->ipv6
.sin6_port
= lis
->address
.ipv6
.sin6_port
;
216 * Convert IPv4 over IPv6 addresses (::ffff:n.n.n.n) to IPv4 forms we
217 * can more easily use...
220 if (con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[0] == 0 &&
221 con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[1] == 0 &&
222 ntohl(con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[2]) == 0xffff)
223 con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[2] = 0;
226 #endif /* AF_INET6 */
227 if (lis
->address
.addr
.sa_family
== AF_INET
)
228 con
->http
.hostaddr
->ipv4
.sin_port
= lis
->address
.ipv4
.sin_port
;
231 * Check the number of clients on the same address...
234 for (count
= 0, tempcon
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
236 tempcon
= (cupsd_client_t
*)cupsArrayNext(Clients
))
237 if (httpAddrEqual(tempcon
->http
.hostaddr
, con
->http
.hostaddr
))
240 if (count
>= MaxClientsPerHost
)
244 if (count
>= MaxClientsPerHost
)
246 if ((time(NULL
) - last_dos
) >= 60)
248 last_dos
= time(NULL
);
249 cupsdLogMessage(CUPSD_LOG_WARN
,
250 "Possible DoS attack - more than %d clients connecting "
253 httpAddrString(con
->http
.hostaddr
, con
->http
.hostname
,
254 sizeof(con
->http
.hostname
)));
258 closesocket(con
->http
.fd
);
268 * Get the hostname or format the IP address as needed...
271 if (httpAddrLocalhost(con
->http
.hostaddr
))
274 * Map accesses from the loopback interface to "localhost"...
277 strlcpy(con
->http
.hostname
, "localhost", sizeof(con
->http
.hostname
));
278 hostname
= con
->http
.hostname
;
283 * Map accesses from the same host to the server name.
287 hostname
= httpAddrLookup(con
->http
.hostaddr
, con
->http
.hostname
,
288 sizeof(con
->http
.hostname
));
292 httpAddrString(con
->http
.hostaddr
, con
->http
.hostname
,
293 sizeof(con
->http
.hostname
));
297 if (hostname
== NULL
&& HostNameLookups
== 2)
300 * Can't have an unresolved IP address with double-lookups enabled...
304 closesocket(con
->http
.fd
);
309 cupsdLogMessage(CUPSD_LOG_WARN
,
310 "Name lookup failed - connection from %s closed!",
317 if (HostNameLookups
== 2)
320 * Do double lookups as needed...
323 if ((addrlist
= httpAddrGetList(con
->http
.hostname
, AF_UNSPEC
, NULL
))
327 * See if the hostname maps to the same IP address...
330 for (addr
= addrlist
; addr
; addr
= addr
->next
)
331 if (httpAddrEqual(con
->http
.hostaddr
, &(addr
->addr
)))
337 httpAddrFreeList(addrlist
);
342 * Can't have a hostname that doesn't resolve to the same IP address
343 * with double-lookups enabled...
347 closesocket(con
->http
.fd
);
352 cupsdLogMessage(CUPSD_LOG_WARN
,
353 "IP lookup failed - connection from %s closed!",
362 * See if the connection is denied by TCP wrappers...
365 request_init(&wrap_req
, RQ_DAEMON
, "cupsd", RQ_FILE
, con
->http
.fd
, NULL
);
368 if (!hosts_access(&wrap_req
))
371 closesocket(con
->http
.fd
);
376 cupsdLogMessage(CUPSD_LOG_WARN
,
377 "Connection from %s refused by /etc/hosts.allow and "
378 "/etc/hosts.deny rules.", con
->http
.hostname
);
382 #endif /* HAVE_TCPD_H */
385 if (con
->http
.hostaddr
->addr
.sa_family
== AF_INET6
)
386 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdAcceptClient: %d from %s:%d (IPv6)",
387 con
->http
.fd
, con
->http
.hostname
,
388 ntohs(con
->http
.hostaddr
->ipv6
.sin6_port
));
390 #endif /* AF_INET6 */
392 if (con
->http
.hostaddr
->addr
.sa_family
== AF_LOCAL
)
393 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdAcceptClient: %d from %s (Domain)",
394 con
->http
.fd
, con
->http
.hostname
);
396 #endif /* AF_LOCAL */
397 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdAcceptClient: %d from %s:%d (IPv4)",
398 con
->http
.fd
, con
->http
.hostname
,
399 ntohs(con
->http
.hostaddr
->ipv4
.sin_port
));
402 * Get the local address the client connected to...
405 addrlen
= sizeof(temp
);
406 if (getsockname(con
->http
.fd
, (struct sockaddr
*)&temp
, &addrlen
))
408 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to get local address - %s",
411 strcpy(con
->servername
, "localhost");
412 con
->serverport
= LocalPort
;
417 if (temp
.addr
.sa_family
== AF_INET6
)
420 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
421 else if (httpAddrLocalhost(&temp
))
422 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
424 httpAddrString(&temp
, con
->servername
, sizeof(con
->servername
));
426 con
->serverport
= ntohs(lis
->address
.ipv6
.sin6_port
);
429 #endif /* AF_INET6 */
430 if (temp
.addr
.sa_family
== AF_INET
)
433 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
434 else if (httpAddrLocalhost(&temp
))
435 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
437 httpAddrString(&temp
, con
->servername
, sizeof(con
->servername
));
439 con
->serverport
= ntohs(lis
->address
.ipv4
.sin_port
);
443 strcpy(con
->servername
, "localhost");
444 con
->serverport
= LocalPort
;
448 cupsArrayAdd(Clients
, con
);
451 * Using TCP_NODELAY improves responsiveness, especially on systems with a slow
452 * loopback interface. Since we write large buffers when sending print files
453 * and requests there shouldn't be any performance penalty for this...
457 setsockopt(con
->http
.fd
, IPPROTO_TCP
, TCP_NODELAY
, &val
, sizeof(val
));
460 * Close this file on all execs...
463 fcntl(con
->http
.fd
, F_SETFD
, fcntl(con
->http
.fd
, F_GETFD
) | FD_CLOEXEC
);
466 * Add the socket to the server select.
469 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
472 * Temporarily suspend accept()'s until we lose a client...
475 if (cupsArrayCount(Clients
) == MaxClients
)
476 cupsdPauseListening();
480 * See if we are connecting on a secure port...
483 if (lis
->encryption
== HTTP_ENCRYPT_ALWAYS
)
486 * https connection; go secure...
489 con
->http
.encryption
= HTTP_ENCRYPT_ALWAYS
;
491 if (!encrypt_client(con
))
492 cupsdCloseClient(con
);
496 #endif /* HAVE_SSL */
501 * 'cupsdCloseAllClients()' - Close all remote clients immediately.
505 cupsdCloseAllClients(void)
507 cupsd_client_t
*con
; /* Current client */
510 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdCloseAllClients() Clients=%d",
511 cupsArrayCount(Clients
));
513 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
515 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
516 if (cupsdCloseClient(con
))
517 cupsdCloseClient(con
);
522 * 'cupsdCloseClient()' - Close a remote client.
525 int /* O - 1 if partial close, 0 if fully closed */
526 cupsdCloseClient(cupsd_client_t
*con
) /* I - Client to close */
528 int partial
; /* Do partial close for SSL? */
530 SSL_CTX
*context
; /* Context for encryption */
531 SSL
*conn
; /* Connection for encryption */
532 unsigned long error
; /* Error code */
533 #elif defined(HAVE_GNUTLS)
534 http_tls_t
*conn
; /* TLS connection information */
535 int error
; /* Error code */
536 gnutls_certificate_server_credentials
*credentials
;
537 /* TLS credentials */
538 # elif defined(HAVE_CDSASSL)
539 http_tls_t
*conn
; /* CDSA connection information */
540 #endif /* HAVE_LIBSSL */
543 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdCloseClient(con=%p(%d))", con
,
547 * Flush pending writes before closing...
550 httpFlushWrite(HTTP(con
));
556 * Shutdown encryption as needed...
564 conn
= (SSL
*)(con
->http
.tls
);
565 context
= SSL_get_SSL_CTX(conn
);
567 switch (SSL_shutdown(conn
))
570 cupsdLogMessage(CUPSD_LOG_DEBUG
,
571 "SSL shutdown successful!");
574 cupsdLogMessage(CUPSD_LOG_ERROR
,
575 "Fatal error during SSL shutdown!");
577 while ((error
= ERR_get_error()) != 0)
578 cupsdLogMessage(CUPSD_LOG_ERROR
, "SSL shutdown failed: %s",
579 ERR_error_string(error
, NULL
));
583 SSL_CTX_free(context
);
586 # elif defined(HAVE_GNUTLS)
587 conn
= (http_tls_t
*)(con
->http
.tls
);
588 credentials
= (gnutls_certificate_server_credentials
*)(conn
->credentials
);
590 error
= gnutls_bye(conn
->session
, GNUTLS_SHUT_WR
);
593 case GNUTLS_E_SUCCESS
:
594 cupsdLogMessage(CUPSD_LOG_DEBUG
,
595 "SSL shutdown successful!");
598 cupsdLogMessage(CUPSD_LOG_ERROR
,
599 "SSL shutdown failed: %s", gnutls_strerror(error
));
603 gnutls_deinit(conn
->session
);
604 gnutls_certificate_free_credentials(*credentials
);
608 # elif defined(HAVE_CDSASSL)
609 conn
= (http_tls_t
*)(con
->http
.tls
);
611 while (SSLClose(conn
->session
) == errSSLWouldBlock
)
614 SSLDisposeContext(conn
->session
);
616 if (conn
->certsArray
)
617 CFRelease(conn
->certsArray
);
620 # endif /* HAVE_LIBSSL */
622 con
->http
.tls
= NULL
;
624 #endif /* HAVE_SSL */
626 if (con
->pipe_pid
!= 0)
629 * Stop any CGI process...
632 cupsdEndProcess(con
->pipe_pid
, 1);
638 cupsdRemoveSelect(con
->file
);
645 * Close the socket and clear the file from the input set for select()...
648 if (con
->http
.fd
>= 0)
650 cupsArrayRemove(ActiveClients
, con
);
656 * Only do a partial close so that the encrypted client gets everything.
659 shutdown(con
->http
.fd
, 0);
660 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
665 * Shut the socket down fully...
668 cupsdRemoveSelect(con
->http
.fd
);
680 if (con
->http
.input_set
)
681 free(con
->http
.input_set
);
683 httpClearCookie(HTTP(con
));
684 httpClearFields(HTTP(con
));
686 cupsdClearString(&con
->filename
);
687 cupsdClearString(&con
->command
);
688 cupsdClearString(&con
->options
);
689 cupsdClearString(&con
->query_string
);
693 ippDelete(con
->request
);
699 ippDelete(con
->response
);
700 con
->response
= NULL
;
705 cupsLangFree(con
->language
);
706 con
->language
= NULL
;
709 #ifdef HAVE_AUTHORIZATION_H
712 AuthorizationFree(con
->authref
, kAuthorizationFlagDefaults
);
715 #endif /* HAVE_AUTHORIZATION_H */
718 * Re-enable new client connections if we are going back under the
722 if (cupsArrayCount(Clients
) == MaxClients
)
723 cupsdResumeListening();
726 * Compact the list of clients as necessary...
729 cupsArrayRemove(Clients
, con
);
739 * 'cupsdFlushHeader()' - Flush the header fields to the client.
742 int /* I - Bytes written or -1 on error */
743 cupsdFlushHeader(cupsd_client_t
*con
) /* I - Client to flush to */
745 int bytes
= httpFlushWrite(HTTP(con
));
747 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
754 * 'cupsdReadClient()' - Read data from a client.
758 cupsdReadClient(cupsd_client_t
*con
) /* I - Client to read from */
760 char line
[32768], /* Line from client... */
761 operation
[64], /* Operation code from socket */
762 version
[64], /* HTTP version number string */
763 locale
[64], /* Locale */
764 *ptr
; /* Pointer into strings */
765 int major
, minor
; /* HTTP version numbers */
766 http_status_t status
; /* Transfer status */
767 ipp_state_t ipp_state
; /* State of IPP transfer */
768 int bytes
; /* Number of bytes to POST */
769 char *filename
; /* Name of file for GET/HEAD */
770 char buf
[1024]; /* Buffer for real filename */
771 struct stat filestats
; /* File information */
772 mime_type_t
*type
; /* MIME type of file */
773 cupsd_printer_t
*p
; /* Printer */
774 static unsigned request_id
= 0; /* Request ID for temp files */
777 status
= HTTP_CONTINUE
;
779 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
780 "cupsdReadClient(con=%p(%d)) "
781 "con->http.error=%d "
782 "con->http.used=%d, "
783 "con->http.state=%d "
784 "con->data_encoding=HTTP_ENCODE_%s, "
785 "con->data_remaining=" CUPS_LLFMT
", "
787 con
, con
->http
.fd
, con
->http
.error
, con
->http
.used
,
789 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
?
790 "CHUNKED" : "LENGTH",
791 CUPS_LLCAST con
->http
.data_remaining
, con
->file
);
795 cupsdCloseClient(con
);
803 * Automatically check for a SSL/TLS handshake...
808 if (recv(con
->http
.fd
, buf
, 1, MSG_PEEK
) == 1 &&
809 (!buf
[0] || !strchr("DGHOPT", buf
[0])))
812 * Encrypt this connection...
815 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
816 "cupsdReadClient: Saw first byte %02X, auto-negotiating "
817 "SSL/TLS session...", buf
[0] & 255);
819 if (!encrypt_client(con
))
820 cupsdCloseClient(con
);
825 #endif /* HAVE_SSL */
827 switch (con
->http
.state
)
831 * See if we've received a request line...
834 if (httpGets(line
, sizeof(line
) - 1, HTTP(con
)) == NULL
)
836 cupsdCloseClient(con
);
841 * Ignore blank request lines...
848 * Clear other state variables...
851 httpClearFields(HTTP(con
));
853 con
->http
.activity
= time(NULL
);
854 con
->http
.version
= HTTP_1_0
;
855 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
856 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
857 con
->http
.data_remaining
= 0;
858 con
->http
._data_remaining
= 0;
859 con
->operation
= HTTP_WAITING
;
864 con
->username
[0] = '\0';
865 con
->password
[0] = '\0';
868 cupsdClearString(&con
->command
);
869 cupsdClearString(&con
->options
);
870 cupsdClearString(&con
->query_string
);
874 ippDelete(con
->request
);
880 ippDelete(con
->response
);
881 con
->response
= NULL
;
886 cupsLangFree(con
->language
);
887 con
->language
= NULL
;
891 con
->gss_have_creds
= 0;
892 #endif /* HAVE_GSSAPI */
895 * Grab the request line...
898 switch (sscanf(line
, "%63s%1023s%63s", operation
, con
->uri
, version
))
903 cupsdLogMessage(CUPSD_LOG_ERROR
,
904 "Bad request line \"%s\" from %s!", line
,
906 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
907 cupsdCloseClient(con
);
911 con
->http
.version
= HTTP_0_9
;
914 if (sscanf(version
, "HTTP/%d.%d", &major
, &minor
) != 2)
916 cupsdLogMessage(CUPSD_LOG_ERROR
,
917 "Bad request line \"%s\" from %s!", line
,
919 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
920 cupsdCloseClient(con
);
926 con
->http
.version
= (http_version_t
)(major
* 100 + minor
);
927 if (con
->http
.version
== HTTP_1_1
&& KeepAlive
)
928 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
930 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
934 cupsdSendError(con
, HTTP_NOT_SUPPORTED
, CUPSD_AUTH_NONE
);
935 cupsdCloseClient(con
);
942 * Handle full URLs in the request line...
945 if (strcmp(con
->uri
, "*"))
947 char scheme
[HTTP_MAX_URI
], /* Method/scheme */
948 userpass
[HTTP_MAX_URI
], /* Username:password */
949 hostname
[HTTP_MAX_URI
], /* Hostname */
950 resource
[HTTP_MAX_URI
]; /* Resource path */
951 int port
; /* Port number */
955 * Separate the URI into its components...
958 httpSeparateURI(HTTP_URI_CODING_MOST
, con
->uri
,
959 scheme
, sizeof(scheme
),
960 userpass
, sizeof(userpass
),
961 hostname
, sizeof(hostname
), &port
,
962 resource
, sizeof(resource
));
965 * Only allow URIs with the servername, localhost, or an IP
969 if (strcmp(scheme
, "file") &&
970 strcasecmp(hostname
, ServerName
) &&
971 strcasecmp(hostname
, "localhost") &&
972 !isdigit(hostname
[0]) && hostname
[0] != '[')
975 * Nope, we don't do proxies...
978 cupsdLogMessage(CUPSD_LOG_ERROR
, "Bad URI \"%s\" in request!",
980 cupsdSendError(con
, HTTP_METHOD_NOT_ALLOWED
, CUPSD_AUTH_NONE
);
981 cupsdCloseClient(con
);
986 * Copy the resource portion back into the URI; both resource and
987 * con->uri are HTTP_MAX_URI bytes in size...
990 strcpy(con
->uri
, resource
);
994 * Process the request...
997 if (!strcmp(operation
, "GET"))
998 con
->http
.state
= HTTP_GET
;
999 else if (!strcmp(operation
, "PUT"))
1000 con
->http
.state
= HTTP_PUT
;
1001 else if (!strcmp(operation
, "POST"))
1002 con
->http
.state
= HTTP_POST
;
1003 else if (!strcmp(operation
, "DELETE"))
1004 con
->http
.state
= HTTP_DELETE
;
1005 else if (!strcmp(operation
, "TRACE"))
1006 con
->http
.state
= HTTP_TRACE
;
1007 else if (!strcmp(operation
, "OPTIONS"))
1008 con
->http
.state
= HTTP_OPTIONS
;
1009 else if (!strcmp(operation
, "HEAD"))
1010 con
->http
.state
= HTTP_HEAD
;
1013 cupsdLogMessage(CUPSD_LOG_ERROR
, "Bad operation \"%s\"!", operation
);
1014 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
1015 cupsdCloseClient(con
);
1019 gettimeofday(&(con
->start
), NULL
);
1020 con
->operation
= con
->http
.state
;
1022 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdReadClient: %d %s %s HTTP/%d.%d",
1023 con
->http
.fd
, operation
, con
->uri
,
1024 con
->http
.version
/ 100, con
->http
.version
% 100);
1026 con
->http
.status
= HTTP_OK
;
1028 if (!cupsArrayFind(ActiveClients
, con
))
1030 cupsArrayAdd(ActiveClients
, con
);
1031 cupsdSetBusyState();
1042 * Parse incoming parameters until the status changes...
1045 while ((status
= httpUpdate(HTTP(con
))) == HTTP_CONTINUE
)
1046 if (!data_ready(con
))
1049 if (status
!= HTTP_OK
&& status
!= HTTP_CONTINUE
)
1051 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
1052 cupsdCloseClient(con
);
1058 if (!data_ready(con
) && recv(con
->http
.fd
, buf
, 1, MSG_PEEK
) < 1)
1061 * Connection closed...
1064 cupsdCloseClient(con
);
1067 break; /* Anti-compiler-warning-code */
1071 * Handle new transfers...
1074 if (status
== HTTP_OK
)
1076 if (con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
][0])
1079 * Figure out the locale from the Accept-Language and Content-Type
1083 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ',')) != NULL
)
1086 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ';')) != NULL
)
1089 if ((ptr
= strstr(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
], "charset=")) != NULL
)
1092 * Combine language and charset, and trim any extra params in the
1096 snprintf(locale
, sizeof(locale
), "%s.%s",
1097 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ptr
+ 8);
1099 if ((ptr
= strchr(locale
, ',')) != NULL
)
1103 snprintf(locale
, sizeof(locale
), "%s.%s",
1104 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], DefaultCharset
);
1106 con
->language
= cupsLangGet(locale
);
1109 con
->language
= cupsLangGet(DefaultLocale
);
1111 cupsdAuthorize(con
);
1113 if (!strncasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Keep-Alive", 10) &&
1115 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
1116 else if (!strncasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "close", 5))
1117 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1119 if (!con
->http
.fields
[HTTP_FIELD_HOST
][0] &&
1120 con
->http
.version
>= HTTP_1_1
)
1123 * HTTP/1.1 and higher require the "Host:" field...
1126 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1128 cupsdCloseClient(con
);
1132 else if (httpAddrLocalhost(con
->http
.hostaddr
) &&
1133 strcasecmp(con
->http
.fields
[HTTP_FIELD_HOST
], "localhost") &&
1134 strncasecmp(con
->http
.fields
[HTTP_FIELD_HOST
], "localhost:", 10) &&
1135 strcmp(con
->http
.fields
[HTTP_FIELD_HOST
], "127.0.0.1") &&
1136 strncmp(con
->http
.fields
[HTTP_FIELD_HOST
], "127.0.0.1:", 10) &&
1137 strcmp(con
->http
.fields
[HTTP_FIELD_HOST
], "[::1]") &&
1138 strncmp(con
->http
.fields
[HTTP_FIELD_HOST
], "[::1]:", 6))
1141 * Access to localhost must use "localhost" or the corresponding IPv4
1142 * or IPv6 values in the Host: field.
1145 cupsdLogMessage(CUPSD_LOG_WARN
,
1146 "Request from \"%s\" using invalid Host: field \"%s\"",
1147 con
->http
.hostname
, con
->http
.fields
[HTTP_FIELD_HOST
]);
1149 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1151 cupsdCloseClient(con
);
1155 else if (con
->operation
== HTTP_OPTIONS
)
1158 * Do OPTIONS command...
1161 if (con
->best
&& con
->best
->type
!= CUPSD_AUTH_NONE
)
1163 if (!cupsdSendHeader(con
, HTTP_UNAUTHORIZED
, NULL
, CUPSD_AUTH_NONE
))
1165 cupsdCloseClient(con
);
1170 if (!strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") &&
1171 con
->http
.tls
== NULL
)
1175 * Do encryption stuff...
1178 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
, CUPSD_AUTH_NONE
))
1180 cupsdCloseClient(con
);
1184 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1185 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1186 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1187 httpPrintf(HTTP(con
), "\r\n");
1189 if (cupsdFlushHeader(con
) < 0)
1191 cupsdCloseClient(con
);
1195 if (!encrypt_client(con
))
1197 cupsdCloseClient(con
);
1201 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
1203 cupsdCloseClient(con
);
1206 #endif /* HAVE_SSL */
1209 if (!cupsdSendHeader(con
, HTTP_OK
, NULL
, CUPSD_AUTH_NONE
))
1211 cupsdCloseClient(con
);
1215 httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n");
1216 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1217 httpPrintf(HTTP(con
), "\r\n");
1219 if (cupsdFlushHeader(con
) < 0)
1221 cupsdCloseClient(con
);
1225 else if (!is_path_absolute(con
->uri
))
1228 * Protect against malicious users!
1231 cupsdLogMessage(CUPSD_LOG_ERROR
,
1232 "Request for non-absolute resource \"%s\"!", con
->uri
);
1234 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1236 cupsdCloseClient(con
);
1242 if (!strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") &&
1243 con
->http
.tls
== NULL
)
1247 * Do encryption stuff...
1250 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
, CUPSD_AUTH_NONE
))
1252 cupsdCloseClient(con
);
1256 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1257 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1258 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1259 httpPrintf(HTTP(con
), "\r\n");
1261 if (cupsdFlushHeader(con
) < 0)
1263 cupsdCloseClient(con
);
1267 if (!encrypt_client(con
))
1269 cupsdCloseClient(con
);
1273 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
1275 cupsdCloseClient(con
);
1278 #endif /* HAVE_SSL */
1281 if ((status
= cupsdIsAuthorized(con
, NULL
)) != HTTP_OK
)
1283 cupsdSendError(con
, status
, CUPSD_AUTH_NONE
);
1284 cupsdCloseClient(con
);
1288 if (con
->http
.expect
&&
1289 (con
->operation
== HTTP_POST
|| con
->operation
== HTTP_PUT
))
1291 if (con
->http
.expect
== HTTP_CONTINUE
)
1294 * Send 100-continue header...
1297 if (!cupsdSendHeader(con
, HTTP_CONTINUE
, NULL
, CUPSD_AUTH_NONE
))
1299 cupsdCloseClient(con
);
1306 * Send 417-expectation-failed header...
1309 if (!cupsdSendHeader(con
, HTTP_EXPECTATION_FAILED
, NULL
, CUPSD_AUTH_NONE
))
1311 cupsdCloseClient(con
);
1315 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1316 httpPrintf(HTTP(con
), "\r\n");
1318 if (cupsdFlushHeader(con
) < 0)
1320 cupsdCloseClient(con
);
1326 switch (con
->http
.state
)
1328 case HTTP_GET_SEND
:
1329 if (!strncmp(con
->uri
, "/printers/", 10) &&
1330 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1333 * Send PPD file - get the real printer name since printer
1334 * names are not case sensitive but filenames can be...
1337 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1339 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1340 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1343 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1345 cupsdCloseClient(con
);
1353 if ((!strncmp(con
->uri
, "/admin", 6) &&
1354 strncmp(con
->uri
, "/admin/conf/", 12) &&
1355 strncmp(con
->uri
, "/admin/log/", 11)) ||
1356 !strncmp(con
->uri
, "/printers", 9) ||
1357 !strncmp(con
->uri
, "/classes", 8) ||
1358 !strncmp(con
->uri
, "/help", 5) ||
1359 !strncmp(con
->uri
, "/jobs", 5))
1362 * Send CGI output...
1365 if (!strncmp(con
->uri
, "/admin", 6))
1367 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1370 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1372 else if (!strncmp(con
->uri
, "/printers", 9))
1374 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1377 if (con
->uri
[9] && con
->uri
[10])
1378 cupsdSetString(&con
->options
, con
->uri
+ 9);
1380 cupsdSetString(&con
->options
, NULL
);
1382 else if (!strncmp(con
->uri
, "/classes", 8))
1384 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1387 if (con
->uri
[8] && con
->uri
[9])
1388 cupsdSetString(&con
->options
, con
->uri
+ 8);
1390 cupsdSetString(&con
->options
, NULL
);
1392 else if (!strncmp(con
->uri
, "/jobs", 5))
1394 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1397 if (con
->uri
[5] && con
->uri
[6])
1398 cupsdSetString(&con
->options
, con
->uri
+ 5);
1400 cupsdSetString(&con
->options
, NULL
);
1404 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1407 if (con
->uri
[5] && con
->uri
[6])
1408 cupsdSetString(&con
->options
, con
->uri
+ 5);
1410 cupsdSetString(&con
->options
, NULL
);
1413 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1415 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1417 cupsdCloseClient(con
);
1422 cupsdLogRequest(con
, HTTP_OK
);
1424 if (con
->http
.version
<= HTTP_1_0
)
1425 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1427 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1428 (strchr(con
->uri
+ 12, '/') ||
1429 strlen(con
->uri
) == 12)) ||
1430 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1431 (strchr(con
->uri
+ 11, '/') ||
1432 strlen(con
->uri
) == 11)))
1435 * GET can only be done to configuration files directly under
1439 cupsdLogMessage(CUPSD_LOG_ERROR
,
1440 "Request for subdirectory \"%s\"!", con
->uri
);
1442 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1444 cupsdCloseClient(con
);
1456 if ((filename
= get_file(con
, &filestats
, buf
,
1457 sizeof(buf
))) == NULL
)
1459 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1461 cupsdCloseClient(con
);
1468 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1470 if (is_cgi(con
, filename
, &filestats
, type
))
1473 * Note: con->command and con->options were set by
1477 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1479 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1481 cupsdCloseClient(con
);
1486 cupsdLogRequest(con
, HTTP_OK
);
1488 if (con
->http
.version
<= HTTP_1_0
)
1489 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1493 if (!check_if_modified(con
, &filestats
))
1495 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1497 cupsdCloseClient(con
);
1504 strcpy(line
, "text/plain");
1506 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1508 if (!write_file(con
, HTTP_OK
, filename
, line
, &filestats
))
1510 cupsdCloseClient(con
);
1517 case HTTP_POST_RECV
:
1519 * See if the POST request includes a Content-Length field, and if
1520 * so check the length against any limits that are set...
1523 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1524 MaxRequestSize
> 0 &&
1525 con
->http
.data_remaining
> MaxRequestSize
)
1528 * Request too large...
1531 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1533 cupsdCloseClient(con
);
1539 else if (con
->http
.data_remaining
< 0 ||
1540 (!con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1541 con
->http
.data_encoding
== HTTP_ENCODE_LENGTH
))
1544 * Negative content lengths are invalid!
1547 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1549 cupsdCloseClient(con
);
1557 * See what kind of POST request this is; for IPP requests the
1558 * content-type field will be "application/ipp"...
1561 if (!strcmp(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
],
1563 con
->request
= ippNew();
1564 else if ((!strncmp(con
->uri
, "/admin", 6) &&
1565 strncmp(con
->uri
, "/admin/conf/", 12) &&
1566 strncmp(con
->uri
, "/admin/log/", 11)) ||
1567 !strncmp(con
->uri
, "/printers", 9) ||
1568 !strncmp(con
->uri
, "/classes", 8) ||
1569 !strncmp(con
->uri
, "/help", 5) ||
1570 !strncmp(con
->uri
, "/jobs", 5))
1576 if (!strncmp(con
->uri
, "/admin", 6))
1578 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1581 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1583 else if (!strncmp(con
->uri
, "/printers", 9))
1585 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1588 if (con
->uri
[9] && con
->uri
[10])
1589 cupsdSetString(&con
->options
, con
->uri
+ 9);
1591 cupsdSetString(&con
->options
, NULL
);
1593 else if (!strncmp(con
->uri
, "/classes", 8))
1595 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1598 if (con
->uri
[8] && con
->uri
[9])
1599 cupsdSetString(&con
->options
, con
->uri
+ 8);
1601 cupsdSetString(&con
->options
, NULL
);
1603 else if (!strncmp(con
->uri
, "/jobs", 5))
1605 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1608 if (con
->uri
[5] && con
->uri
[6])
1609 cupsdSetString(&con
->options
, con
->uri
+ 5);
1611 cupsdSetString(&con
->options
, NULL
);
1615 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1618 if (con
->uri
[5] && con
->uri
[6])
1619 cupsdSetString(&con
->options
, con
->uri
+ 5);
1621 cupsdSetString(&con
->options
, NULL
);
1624 if (con
->http
.version
<= HTTP_1_0
)
1625 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1633 if ((filename
= get_file(con
, &filestats
, buf
,
1634 sizeof(buf
))) == NULL
)
1636 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1638 cupsdCloseClient(con
);
1645 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1647 if (!is_cgi(con
, filename
, &filestats
, type
))
1650 * Only POST to CGI's...
1653 if (!cupsdSendError(con
, HTTP_UNAUTHORIZED
, CUPSD_AUTH_NONE
))
1655 cupsdCloseClient(con
);
1662 case HTTP_PUT_RECV
:
1664 * Validate the resource name...
1667 if (strncmp(con
->uri
, "/admin/conf/", 12) ||
1668 strchr(con
->uri
+ 12, '/') ||
1669 strlen(con
->uri
) == 12)
1672 * PUT can only be done to configuration files under
1676 cupsdLogMessage(CUPSD_LOG_ERROR
,
1677 "Request for subdirectory \"%s\"!", con
->uri
);
1679 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1681 cupsdCloseClient(con
);
1689 * See if the PUT request includes a Content-Length field, and if
1690 * so check the length against any limits that are set...
1693 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1694 MaxRequestSize
> 0 &&
1695 con
->http
.data_remaining
> MaxRequestSize
)
1698 * Request too large...
1701 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1703 cupsdCloseClient(con
);
1709 else if (con
->http
.data_remaining
< 0)
1712 * Negative content lengths are invalid!
1715 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1717 cupsdCloseClient(con
);
1725 * Open a temporary file to hold the request...
1728 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
1730 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1734 cupsdLogMessage(CUPSD_LOG_ERROR
,
1735 "Unable to create request file %s: %s",
1736 con
->filename
, strerror(errno
));
1738 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1740 cupsdCloseClient(con
);
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 cupsdLogMessage(CUPSD_LOG_ERROR
,
1826 "Request for subdirectory \"%s\"!", con
->uri
);
1828 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1830 cupsdCloseClient(con
);
1836 else if ((filename
= get_file(con
, &filestats
, buf
,
1837 sizeof(buf
))) == NULL
)
1839 if (!cupsdSendHeader(con
, HTTP_NOT_FOUND
, "text/html", CUPSD_AUTH_NONE
))
1841 cupsdCloseClient(con
);
1845 cupsdLogRequest(con
, HTTP_NOT_FOUND
);
1847 else if (!check_if_modified(con
, &filestats
))
1849 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1851 cupsdCloseClient(con
);
1855 cupsdLogRequest(con
, HTTP_NOT_MODIFIED
);
1863 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1865 strcpy(line
, "text/plain");
1867 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1869 if (!cupsdSendHeader(con
, HTTP_OK
, line
, CUPSD_AUTH_NONE
))
1871 cupsdCloseClient(con
);
1875 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
1876 httpGetDateString(filestats
.st_mtime
)) < 0)
1878 cupsdCloseClient(con
);
1882 if (httpPrintf(HTTP(con
), "Content-Length: %lu\r\n",
1883 (unsigned long)filestats
.st_size
) < 0)
1885 cupsdCloseClient(con
);
1889 cupsdLogRequest(con
, HTTP_OK
);
1892 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1894 cupsdCloseClient(con
);
1898 if (cupsdFlushHeader(con
) < 0)
1900 cupsdCloseClient(con
);
1904 con
->http
.state
= HTTP_WAITING
;
1908 break; /* Anti-compiler-warning-code */
1914 * Handle any incoming data...
1917 switch (con
->http
.state
)
1919 case HTTP_PUT_RECV
:
1922 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
1924 cupsdCloseClient(con
);
1929 con
->bytes
+= bytes
;
1931 if (write(con
->file
, line
, bytes
) < bytes
)
1933 cupsdLogMessage(CUPSD_LOG_ERROR
,
1934 "cupsdReadClient: Unable to write %d bytes to %s: %s",
1935 bytes
, con
->filename
, strerror(errno
));
1939 unlink(con
->filename
);
1940 cupsdClearString(&con
->filename
);
1942 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1944 cupsdCloseClient(con
);
1950 while (con
->http
.state
== HTTP_PUT_RECV
&& data_ready(con
));
1952 if (con
->http
.state
== HTTP_WAITING
)
1955 * End of file, see how big it is...
1958 fstat(con
->file
, &filestats
);
1963 if (filestats
.st_size
> MaxRequestSize
&&
1967 * Request is too big; remove it and send an error...
1970 unlink(con
->filename
);
1971 cupsdClearString(&con
->filename
);
1973 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1975 cupsdCloseClient(con
);
1981 * Install the configuration file...
1984 status
= install_conf_file(con
);
1987 * Return the status to the client...
1990 if (!cupsdSendError(con
, status
, CUPSD_AUTH_NONE
))
1992 cupsdCloseClient(con
);
1998 case HTTP_POST_RECV
:
2004 * Grab any request data from the connection...
2007 if ((ipp_state
= ippRead(&(con
->http
), con
->request
)) == IPP_ERROR
)
2009 cupsdLogMessage(CUPSD_LOG_ERROR
,
2010 "cupsdReadClient: %d IPP Read Error!",
2013 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
2014 cupsdCloseClient(con
);
2017 else if (ipp_state
!= IPP_DATA
)
2019 if (con
->http
.state
== HTTP_POST_SEND
)
2021 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
2022 cupsdCloseClient(con
);
2029 con
->bytes
+= ippLength(con
->request
);
2032 if (con
->file
< 0 && con
->http
.state
!= HTTP_POST_SEND
)
2035 * Create a file as needed for the request data...
2038 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
, request_id
++);
2039 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
2043 cupsdLogMessage(CUPSD_LOG_ERROR
,
2044 "Unable to create request file %s: %s",
2045 con
->filename
, strerror(errno
));
2047 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2049 cupsdCloseClient(con
);
2054 fchmod(con
->file
, 0640);
2055 fchown(con
->file
, RunUser
, Group
);
2056 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2059 if (con
->http
.state
!= HTTP_POST_SEND
)
2061 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
2063 cupsdCloseClient(con
);
2068 con
->bytes
+= bytes
;
2070 if (write(con
->file
, line
, bytes
) < bytes
)
2072 cupsdLogMessage(CUPSD_LOG_ERROR
,
2073 "cupsdReadClient: Unable to write %d bytes to %s: %s",
2074 bytes
, con
->filename
, strerror(errno
));
2078 unlink(con
->filename
);
2079 cupsdClearString(&con
->filename
);
2081 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2083 cupsdCloseClient(con
);
2088 else if (con
->http
.state
== HTTP_POST_RECV
)
2090 else if (con
->http
.state
!= HTTP_POST_SEND
)
2092 cupsdCloseClient(con
);
2097 while (con
->http
.state
== HTTP_POST_RECV
&& data_ready(con
));
2099 if (con
->http
.state
== HTTP_POST_SEND
)
2103 fstat(con
->file
, &filestats
);
2108 if (filestats
.st_size
> MaxRequestSize
&&
2112 * Request is too big; remove it and send an error...
2115 unlink(con
->filename
);
2116 cupsdClearString(&con
->filename
);
2121 * Delete any IPP request data...
2124 ippDelete(con
->request
);
2125 con
->request
= NULL
;
2128 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2130 cupsdCloseClient(con
);
2137 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
2139 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
2141 cupsdCloseClient(con
);
2146 cupsdLogRequest(con
, HTTP_OK
);
2152 cupsdProcessIPPRequest(con
);
2156 unlink(con
->filename
);
2157 cupsdClearString(&con
->filename
);
2166 break; /* Anti-compiler-warning-code */
2169 if (con
->http
.state
== HTTP_WAITING
)
2171 if (!con
->http
.keep_alive
)
2172 cupsdCloseClient(con
);
2175 cupsArrayRemove(ActiveClients
, con
);
2176 cupsdSetBusyState();
2183 * 'cupsdSendCommand()' - Send output from a command via HTTP.
2186 int /* O - 1 on success, 0 on failure */
2188 cupsd_client_t
*con
, /* I - Client connection */
2189 char *command
, /* I - Command to run */
2190 char *options
, /* I - Command-line options */
2191 int root
) /* I - Run as root? */
2193 int fd
; /* Standard input file descriptor */
2198 fd
= open(con
->filename
, O_RDONLY
);
2202 cupsdLogMessage(CUPSD_LOG_ERROR
,
2203 "cupsdSendCommand: %d Unable to open \"%s\" for reading: %s",
2204 con
->http
.fd
, con
->filename
? con
->filename
: "/dev/null",
2209 fcntl(fd
, F_SETFD
, fcntl(fd
, F_GETFD
) | FD_CLOEXEC
);
2214 con
->pipe_pid
= pipe_command(con
, fd
, &(con
->file
), command
, options
, root
);
2219 cupsdLogMessage(CUPSD_LOG_INFO
, "Started \"%s\" (pid=%d)", command
,
2222 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendCommand: %d file=%d",
2223 con
->http
.fd
, con
->file
);
2225 if (con
->pipe_pid
== 0)
2228 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2230 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2232 con
->sent_header
= 0;
2233 con
->file_ready
= 0;
2234 con
->got_fields
= 0;
2242 * 'cupsdSendError()' - Send an error message via HTTP.
2245 int /* O - 1 if successful, 0 otherwise */
2246 cupsdSendError(cupsd_client_t
*con
, /* I - Connection */
2247 http_status_t code
, /* I - Error code */
2248 int auth_type
)/* I - Authentication type */
2250 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2251 "cupsdSendError(con=%p(%d), code=%d, auth_type=%d", con
,
2252 con
->http
.fd
, code
, auth_type
);
2256 * Force client to upgrade for authentication if that is how the
2257 * server is configured...
2260 if (code
== HTTP_UNAUTHORIZED
&&
2261 DefaultEncryption
== HTTP_ENCRYPT_REQUIRED
&&
2262 strcasecmp(con
->http
.hostname
, "localhost") &&
2265 code
= HTTP_UPGRADE_REQUIRED
;
2267 #endif /* HAVE_SSL */
2270 * Put the request in the access_log file...
2273 cupsdLogRequest(con
, code
);
2276 * To work around bugs in some proxies, don't use Keep-Alive for some
2279 * Kerberos authentication doesn't work without Keep-Alive, so
2280 * never disable it in that case.
2283 if (code
>= HTTP_BAD_REQUEST
&& con
->http
.auth_type
!= CUPSD_AUTH_NEGOTIATE
)
2284 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
2287 * Send an error message back to the client. If the error code is a
2288 * 400 or 500 series, make sure the message contains some text, too!
2291 if (!cupsdSendHeader(con
, code
, NULL
, auth_type
))
2295 if (code
== HTTP_UPGRADE_REQUIRED
)
2296 if (httpPrintf(HTTP(con
), "Connection: Upgrade\r\n") < 0)
2299 if (httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n") < 0)
2301 #endif /* HAVE_SSL */
2303 if (con
->http
.version
>= HTTP_1_1
&&
2304 con
->http
.keep_alive
== HTTP_KEEPALIVE_OFF
)
2306 if (httpPrintf(HTTP(con
), "Connection: close\r\n") < 0)
2310 if (code
>= HTTP_BAD_REQUEST
)
2313 * Send a human-readable error message.
2316 char message
[4096], /* Message for user */
2317 urltext
[1024], /* URL redirection text */
2318 redirect
[1024]; /* Redirection link */
2319 const char *text
; /* Status-specific text */
2324 if (code
== HTTP_UNAUTHORIZED
)
2325 text
= _cupsLangString(con
->language
,
2326 _("Enter your username and password or the "
2327 "root username and password to access this "
2328 "page. If you are using Kerberos authentication, "
2329 "make sure you have a valid Kerberos ticket."));
2330 else if (code
== HTTP_UPGRADE_REQUIRED
)
2334 snprintf(urltext
, sizeof(urltext
),
2335 _cupsLangString(con
->language
,
2336 _("You must access this page using the URL "
2337 "<A HREF=\"https://%s:%d%s\">"
2338 "https://%s:%d%s</A>.")),
2339 con
->servername
, con
->serverport
, con
->uri
,
2340 con
->servername
, con
->serverport
, con
->uri
);
2342 snprintf(redirect
, sizeof(redirect
),
2343 "<META HTTP-EQUIV=\"Refresh\" "
2344 "CONTENT=\"3;URL=https://%s:%d%s\">\n",
2345 con
->servername
, con
->serverport
, con
->uri
);
2350 snprintf(message
, sizeof(message
),
2351 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" "
2352 "\"http://www.w3.org/TR/html4/loose.dtd\">\n"
2355 "\t<META HTTP-EQUIV=\"Content-Type\" "
2356 "CONTENT=\"text/html; charset=utf-8\">\n"
2357 "\t<TITLE>%d %s</TITLE>\n"
2358 "\t<LINK REL=\"STYLESHEET\" TYPE=\"text/css\" "
2359 "HREF=\"/cups.css\">\n"
2367 code
, httpStatus(code
), redirect
, code
, httpStatus(code
), text
);
2369 if (httpPrintf(HTTP(con
), "Content-Type: text/html; charset=utf-8\r\n") < 0)
2371 if (httpPrintf(HTTP(con
), "Content-Length: %d\r\n",
2372 (int)strlen(message
)) < 0)
2374 if (httpPrintf(HTTP(con
), "\r\n") < 0)
2376 if (httpPrintf(HTTP(con
), "%s", message
) < 0)
2379 else if (httpPrintf(HTTP(con
), "\r\n") < 0)
2382 if (cupsdFlushHeader(con
) < 0)
2385 con
->http
.state
= HTTP_WAITING
;
2392 * 'cupsdSendHeader()' - Send an HTTP request.
2395 int /* O - 1 on success, 0 on failure */
2397 cupsd_client_t
*con
, /* I - Client to send to */
2398 http_status_t code
, /* I - HTTP status code */
2399 char *type
, /* I - MIME type of document */
2400 int auth_type
) /* I - Type of authentication */
2402 char auth_str
[1024]; /* Authorization string */
2404 static char *gss_buf
= NULL
; /* Kerberos auth data buffer */
2405 static int gss_bufsize
= 0; /* Size of Kerberos auth data buffer */
2406 #endif /* HAVE_GSSAPI */
2410 * Send the HTTP status header...
2413 if (code
== HTTP_CONTINUE
)
2416 * 100-continue doesn't send any headers...
2419 return (httpPrintf(HTTP(con
), "HTTP/%d.%d 100 Continue\r\n\r\n",
2420 con
->http
.version
/ 100, con
->http
.version
% 100) > 0);
2423 httpFlushWrite(HTTP(con
));
2425 con
->http
.data_encoding
= HTTP_ENCODE_FIELDS
;
2427 if (httpPrintf(HTTP(con
), "HTTP/%d.%d %d %s\r\n", con
->http
.version
/ 100,
2428 con
->http
.version
% 100, code
, httpStatus(code
)) < 0)
2430 if (httpPrintf(HTTP(con
), "Date: %s\r\n", httpGetDateString(time(NULL
))) < 0)
2433 if (httpPrintf(HTTP(con
), "Server: %s\r\n", ServerHeader
) < 0)
2435 if (con
->http
.keep_alive
&& con
->http
.version
>= HTTP_1_0
)
2437 if (httpPrintf(HTTP(con
), "Connection: Keep-Alive\r\n") < 0)
2439 if (httpPrintf(HTTP(con
), "Keep-Alive: timeout=%d\r\n",
2440 KeepAliveTimeout
) < 0)
2443 if (code
== HTTP_METHOD_NOT_ALLOWED
)
2444 if (httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n") < 0)
2447 if (code
== HTTP_UNAUTHORIZED
)
2449 if (auth_type
== CUPSD_AUTH_NONE
)
2451 if (!con
->best
|| con
->best
->type
<= CUPSD_AUTH_NONE
)
2452 auth_type
= DefaultAuthType
;
2454 auth_type
= con
->best
->type
;
2459 if (auth_type
== CUPSD_AUTH_BASIC
|| auth_type
== CUPSD_AUTH_BASICDIGEST
)
2460 strlcpy(auth_str
, "Basic realm=\"CUPS\"", sizeof(auth_str
));
2461 else if (auth_type
== CUPSD_AUTH_DIGEST
)
2462 snprintf(auth_str
, sizeof(auth_str
), "Digest realm=\"CUPS\", nonce=\"%s\"",
2463 con
->http
.hostname
);
2465 else if (auth_type
== CUPSD_AUTH_NEGOTIATE
&& con
->gss_output_token
.length
== 0)
2466 strlcpy(auth_str
, "Negotiate", sizeof(auth_str
));
2467 #endif /* HAVE_GSSAPI */
2469 #ifdef HAVE_AUTHORIZATION_H
2470 if (con
->best
&& auth_type
!= CUPSD_AUTH_NEGOTIATE
)
2472 int i
; /* Looping var */
2473 char *auth_key
; /* Auth key buffer */
2474 size_t auth_size
; /* Size of remaining buffer */
2477 auth_key
= auth_str
+ strlen(auth_str
);
2478 auth_size
= sizeof(auth_str
) - (auth_key
- auth_str
);
2480 for (i
= 0; i
< con
->best
->num_names
; i
++)
2482 if (!strncasecmp(con
->best
->names
[i
], "@AUTHKEY(", 9))
2484 snprintf(auth_key
, auth_size
, ", authkey=\"%s\"",
2485 con
->best
->names
[i
] + 9);
2486 /* end parenthesis is stripped in conf.c */
2489 else if (!strcasecmp(con
->best
->names
[i
], "@SYSTEM") &&
2492 snprintf(auth_key
, auth_size
, ", authkey=\"%s\"", SystemGroupAuthKey
);
2497 #endif /* HAVE_AUTHORIZATION_H */
2501 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendHeader: WWW-Authenticate: %s",
2504 if (httpPrintf(HTTP(con
), "WWW-Authenticate: %s\r\n", auth_str
) < 0)
2511 * WWW-Authenticate: Negotiate can be included even for
2512 * non-401 replies...
2515 if (con
->gss_output_token
.length
> 0 && con
->gss_output_token
.length
<= 65536)
2517 OM_uint32 minor_status
; /* Minor status code */
2518 int bufsize
; /* Size of output token buffer */
2521 bufsize
= con
->gss_output_token
.length
* 4 / 3 + 2;
2523 if (bufsize
> gss_bufsize
)
2525 char *buf
; /* New buffer */
2528 bufsize
= (bufsize
+ 1023) & 1023;/* Round up */
2531 buf
= realloc(gss_buf
, bufsize
);
2533 buf
= malloc(bufsize
);
2537 cupsdLogMessage(CUPSD_LOG_ERROR
,
2538 "Unable to allocate %d bytes for Kerberos credentials!",
2544 gss_bufsize
= bufsize
;
2547 httpEncode64_2(gss_buf
, gss_bufsize
,
2548 con
->gss_output_token
.value
,
2549 con
->gss_output_token
.length
);
2550 gss_release_buffer(&minor_status
, &con
->gss_output_token
);
2552 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2553 "cupsdSendHeader: WWW-Authenticate: Negotiate %s", gss_buf
);
2555 if (httpPrintf(HTTP(con
), "WWW-Authenticate: Negotiate %s\r\n",
2559 else if (con
->gss_output_token
.length
> 65536)
2561 cupsdLogMessage(CUPSD_LOG_ERROR
,
2562 "Kerberos credentials larger than 64k (%d)!",
2563 (int)con
->gss_output_token
.length
);
2566 #endif /* HAVE_GSSAPI */
2568 if (con
->language
&& strcmp(con
->language
->language
, "C"))
2570 if (httpPrintf(HTTP(con
), "Content-Language: %s\r\n",
2571 con
->language
->language
) < 0)
2577 if (!strcmp(type
, "text/html"))
2579 if (httpPrintf(HTTP(con
),
2580 "Content-Type: text/html; charset=utf-8\r\n") < 0)
2583 else if (httpPrintf(HTTP(con
), "Content-Type: %s\r\n", type
) < 0)
2592 * 'cupsdUpdateCGI()' - Read status messages from CGI scripts and programs.
2596 cupsdUpdateCGI(void)
2598 char *ptr
, /* Pointer to end of line in buffer */
2599 message
[1024]; /* Pointer to message text */
2600 int loglevel
; /* Log level for message */
2603 while ((ptr
= cupsdStatBufUpdate(CGIStatusBuffer
, &loglevel
,
2604 message
, sizeof(message
))) != NULL
)
2606 if (loglevel
== CUPSD_LOG_INFO
)
2607 cupsdLogMessage(CUPSD_LOG_INFO
, "%s", message
);
2609 if (!strchr(CGIStatusBuffer
->buffer
, '\n'))
2613 if (ptr
== NULL
&& !CGIStatusBuffer
->bufused
)
2616 * Fatal error on pipe - should never happen!
2619 cupsdLogMessage(CUPSD_LOG_CRIT
,
2620 "cupsdUpdateCGI: error reading from CGI error pipe - %s",
2627 * 'cupsdWriteClient()' - Write data to a client as needed.
2631 cupsdWriteClient(cupsd_client_t
*con
) /* I - Client connection */
2633 int bytes
; /* Number of bytes written */
2634 char buf
[16385]; /* Data buffer */
2635 char *bufptr
; /* Pointer into buffer */
2636 ipp_state_t ipp_state
; /* IPP state value */
2639 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2640 "cupsdWriteClient(con=%p(%d)) response=%p(%d), file=%d "
2641 "pipe_pid=%d state=%d",
2642 con
, con
->http
.fd
, con
->response
,
2643 con
->response
? con
->response
->state
: -1,
2644 con
->file
, con
->pipe_pid
, con
->http
.state
);
2646 if (con
->http
.state
!= HTTP_GET_SEND
&&
2647 con
->http
.state
!= HTTP_POST_SEND
)
2653 * Make sure we select on the CGI output...
2656 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2658 if (!con
->file_ready
)
2661 * Try again later when there is CGI output available...
2664 cupsdRemoveSelect(con
->http
.fd
);
2668 con
->file_ready
= 0;
2671 if (con
->response
&& con
->response
->state
!= IPP_DATA
)
2673 ipp_state
= ippWrite(HTTP(con
), con
->response
);
2674 bytes
= ipp_state
!= IPP_ERROR
&&
2675 (con
->file
>= 0 || ipp_state
!= IPP_DATA
);
2677 else if ((bytes
= read(con
->file
, buf
, sizeof(buf
) - 1)) > 0)
2679 if (con
->pipe_pid
&& !con
->got_fields
)
2682 * Inspect the data for Content-Type and other fields.
2687 for (bufptr
= buf
; !con
->got_fields
&& *bufptr
; bufptr
++)
2689 if (*bufptr
== '\n')
2692 * Send line to client...
2695 if (bufptr
> buf
&& bufptr
[-1] == '\r')
2699 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Script header: %s", buf
);
2701 if (!con
->sent_header
)
2704 * Handle redirection and CGI status codes...
2707 if (!strncasecmp(buf
, "Location:", 9))
2709 cupsdSendHeader(con
, HTTP_SEE_OTHER
, NULL
, CUPSD_AUTH_NONE
);
2710 con
->sent_header
= 2;
2712 if (httpPrintf(HTTP(con
), "Content-Length: 0\r\n") < 0)
2715 else if (!strncasecmp(buf
, "Status:", 7))
2717 cupsdSendError(con
, (http_status_t
)atoi(buf
+ 7), CUPSD_AUTH_NONE
);
2718 con
->sent_header
= 2;
2722 cupsdSendHeader(con
, HTTP_OK
, NULL
, CUPSD_AUTH_NONE
);
2723 con
->sent_header
= 1;
2725 if (con
->http
.version
== HTTP_1_1
)
2727 if (httpPrintf(HTTP(con
), "Transfer-Encoding: chunked\r\n") < 0)
2733 if (strncasecmp(buf
, "Status:", 7))
2734 httpPrintf(HTTP(con
), "%s\r\n", buf
);
2740 bytes
-= (bufptr
- buf
);
2743 memmove(buf
, bufptr
, bytes
+ 1);
2750 * See if the line was empty...
2753 if (con
->field_col
== 0)
2755 con
->got_fields
= 1;
2757 if (cupsdFlushHeader(con
) < 0)
2759 cupsdCloseClient(con
);
2763 if (con
->http
.version
== HTTP_1_1
)
2764 con
->http
.data_encoding
= HTTP_ENCODE_CHUNKED
;
2769 else if (*bufptr
!= '\r')
2773 if (bytes
> 0 && !con
->got_fields
)
2776 * Remaining text needs to go out...
2779 httpPrintf(HTTP(con
), "%s", buf
);
2781 con
->http
.activity
= time(NULL
);
2784 else if (bytes
== 0)
2786 con
->http
.activity
= time(NULL
);
2793 if (httpWrite2(HTTP(con
), buf
, bytes
) < 0)
2795 cupsdCloseClient(con
);
2799 if (con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
)
2800 httpFlushWrite(HTTP(con
));
2802 con
->bytes
+= bytes
;
2804 if (con
->http
.state
== HTTP_WAITING
)
2811 cupsdLogRequest(con
, HTTP_OK
);
2813 httpFlushWrite(HTTP(con
));
2815 if (con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
&& con
->sent_header
== 1)
2817 if (httpWrite2(HTTP(con
), "", 0) < 0)
2819 cupsdCloseClient(con
);
2824 con
->http
.state
= HTTP_WAITING
;
2826 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
2830 cupsdRemoveSelect(con
->file
);
2833 cupsdEndProcess(con
->pipe_pid
, 0);
2842 unlink(con
->filename
);
2843 cupsdClearString(&con
->filename
);
2848 ippDelete(con
->request
);
2849 con
->request
= NULL
;
2854 ippDelete(con
->response
);
2855 con
->response
= NULL
;
2858 cupsdClearString(&con
->command
);
2859 cupsdClearString(&con
->options
);
2860 cupsdClearString(&con
->query_string
);
2862 if (!con
->http
.keep_alive
)
2864 cupsdCloseClient(con
);
2869 con
->http
.activity
= time(NULL
);
2874 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
2877 static int /* O - 1 if modified since */
2879 cupsd_client_t
*con
, /* I - Client connection */
2880 struct stat
*filestats
) /* I - File information */
2882 char *ptr
; /* Pointer into field */
2883 time_t date
; /* Time/date value */
2884 off_t size
; /* Size/length value */
2889 ptr
= con
->http
.fields
[HTTP_FIELD_IF_MODIFIED_SINCE
];
2894 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2895 "check_if_modified(con=%p(%d), "
2896 "filestats=%p(" CUPS_LLFMT
", %d)) If-Modified-Since=\"%s\"",
2897 con
, con
->http
.fd
, filestats
, CUPS_LLCAST filestats
->st_size
,
2898 (int)filestats
->st_mtime
, ptr
);
2900 while (*ptr
!= '\0')
2902 while (isspace(*ptr
) || *ptr
== ';')
2905 if (strncasecmp(ptr
, "length=", 7) == 0)
2908 size
= strtoll(ptr
, NULL
, 10);
2910 while (isdigit(*ptr
))
2913 else if (isalpha(*ptr
))
2915 date
= httpGetDateTime(ptr
);
2916 while (*ptr
!= '\0' && *ptr
!= ';')
2923 return ((size
!= filestats
->st_size
&& size
!= 0) ||
2924 (date
< filestats
->st_mtime
&& date
!= 0) ||
2925 (size
== 0 && date
== 0));
2930 * 'compare_clients()' - Compare two client connections.
2933 static int /* O - Result of comparison */
2934 compare_clients(cupsd_client_t
*a
, /* I - First client */
2935 cupsd_client_t
*b
, /* I - Second client */
2936 void *data
) /* I - User data (not used) */
2950 * 'data_ready()' - Check whether data is available from a client.
2953 static int /* O - 1 if data is ready, 0 otherwise */
2954 data_ready(cupsd_client_t
*con
) /* I - Client */
2956 if (con
->http
.used
> 0)
2959 else if (con
->http
.tls
)
2962 if (SSL_pending((SSL
*)(con
->http
.tls
)))
2964 # elif defined(HAVE_GNUTLS)
2965 if (gnutls_record_check_pending(((http_tls_t
*)(con
->http
.tls
))->session
))
2967 # elif defined(HAVE_CDSASSL)
2968 size_t bytes
; /* Bytes that are available */
2970 if (!SSLGetBufferedReadSize(((http_tls_t
*)(con
->http
.tls
))->session
,
2971 &bytes
) && bytes
> 0)
2973 # endif /* HAVE_LIBSSL */
2975 #endif /* HAVE_SSL */
2983 * 'encrypt_client()' - Enable encryption for the client...
2986 static int /* O - 1 on success, 0 on error */
2987 encrypt_client(cupsd_client_t
*con
) /* I - Client to encrypt */
2990 SSL_CTX
*context
; /* Context for encryption */
2991 SSL
*conn
; /* Connection for encryption */
2992 BIO
*bio
; /* BIO data */
2993 unsigned long error
; /* Error code */
2996 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "encrypt_client(con=%p(%d))", con
,
3000 * Verify that we have a certificate...
3003 if (access(ServerKey
, 0) || access(ServerCertificate
, 0))
3006 * Nope, make a self-signed certificate...
3009 if (!make_certificate(con
))
3014 * Create the SSL context and accept the connection...
3017 context
= SSL_CTX_new(SSLv23_server_method());
3019 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
3020 if (SSLOptions
& CUPSD_SSL_NOEMPTY
)
3021 SSL_CTX_set_options(context
, SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
);
3022 SSL_CTX_use_PrivateKey_file(context
, ServerKey
, SSL_FILETYPE_PEM
);
3023 SSL_CTX_use_certificate_chain_file(context
, ServerCertificate
);
3025 bio
= BIO_new(_httpBIOMethods());
3026 BIO_ctrl(bio
, BIO_C_SET_FILE_PTR
, 0, (char *)HTTP(con
));
3028 conn
= SSL_new(context
);
3029 SSL_set_bio(conn
, bio
, bio
);
3031 if (SSL_accept(conn
) != 1)
3033 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to encrypt connection from %s!",
3034 con
->http
.hostname
);
3036 while ((error
= ERR_get_error()) != 0)
3037 cupsdLogMessage(CUPSD_LOG_ERROR
, "%s", ERR_error_string(error
, NULL
));
3039 SSL_CTX_free(context
);
3044 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Connection from %s now encrypted.",
3045 con
->http
.hostname
);
3047 con
->http
.tls
= conn
;
3050 # elif defined(HAVE_GNUTLS)
3051 http_tls_t
*conn
; /* TLS session object */
3052 int error
; /* Error code */
3053 gnutls_certificate_server_credentials
*credentials
;
3054 /* TLS credentials */
3057 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "encrypt_client(con=%p(%d))", con
,
3061 * Verify that we have a certificate...
3064 if (access(ServerKey
, 0) || access(ServerCertificate
, 0))
3067 * Nope, make a self-signed certificate...
3070 if (!make_certificate(con
))
3075 * Create the SSL object and perform the SSL handshake...
3078 conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
));
3083 credentials
= (gnutls_certificate_server_credentials
*)
3084 malloc(sizeof(gnutls_certificate_server_credentials
));
3085 if (credentials
== NULL
)
3087 cupsdLogMessage(CUPSD_LOG_ERROR
,
3088 "Unable to encrypt connection from %s - %s",
3089 con
->http
.hostname
, strerror(errno
));
3095 gnutls_certificate_allocate_credentials(credentials
);
3096 gnutls_certificate_set_x509_key_file(*credentials
, ServerCertificate
,
3097 ServerKey
, GNUTLS_X509_FMT_PEM
);
3099 gnutls_init(&(conn
->session
), GNUTLS_SERVER
);
3100 gnutls_set_default_priority(conn
->session
);
3101 gnutls_credentials_set(conn
->session
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
3102 gnutls_transport_set_ptr(conn
->session
, (gnutls_transport_ptr
)HTTP(con
));
3103 gnutls_transport_set_pull_function(conn
->session
, _httpReadGNUTLS
);
3104 gnutls_transport_set_push_function(conn
->session
, _httpWriteGNUTLS
);
3106 error
= gnutls_handshake(conn
->session
);
3108 if (error
!= GNUTLS_E_SUCCESS
)
3110 cupsdLogMessage(CUPSD_LOG_ERROR
,
3111 "Unable to encrypt connection from %s - %s",
3112 con
->http
.hostname
, gnutls_strerror(error
));
3114 gnutls_deinit(conn
->session
);
3115 gnutls_certificate_free_credentials(*credentials
);
3121 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Connection from %s now encrypted.",
3122 con
->http
.hostname
);
3124 conn
->credentials
= credentials
;
3125 con
->http
.tls
= conn
;
3128 # elif defined(HAVE_CDSASSL)
3129 OSStatus error
; /* Error code */
3130 http_tls_t
*conn
; /* CDSA connection information */
3133 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "encrypt_client(con=%p(%d))", con
,
3136 if ((conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
))) == NULL
)
3140 conn
->session
= NULL
;
3141 conn
->certsArray
= get_cdsa_certificate(con
);
3143 if (!conn
->certsArray
)
3146 * No keychain (yet), make a self-signed certificate...
3149 if (make_certificate(con
))
3150 conn
->certsArray
= get_cdsa_certificate(con
);
3153 if (!conn
->certsArray
)
3155 cupsdLogMessage(CUPSD_LOG_ERROR
,
3156 "Could not find signing key in keychain \"%s\"",
3158 error
= errSSLBadCert
; /* errSSLBadConfiguration is a better choice, but not available on 10.2.x */
3162 error
= SSLNewContext(true, &conn
->session
);
3165 error
= SSLSetIOFuncs(conn
->session
, _httpReadCDSA
, _httpWriteCDSA
);
3168 error
= SSLSetProtocolVersionEnabled(conn
->session
, kSSLProtocol2
, false);
3171 error
= SSLSetConnection(conn
->session
, HTTP(con
));
3174 error
= SSLSetAllowsExpiredCerts(conn
->session
, true);
3177 error
= SSLSetAllowsAnyRoot(conn
->session
, true);
3180 error
= SSLSetCertificate(conn
->session
, conn
->certsArray
);
3185 * Perform SSL/TLS handshake
3188 while ((error
= SSLHandshake(conn
->session
)) == errSSLWouldBlock
)
3194 cupsdLogMessage(CUPSD_LOG_ERROR
,
3195 "Unable to encrypt connection from %s - %s (%d)",
3196 con
->http
.hostname
, cssmErrorString(error
), (int)error
);
3198 con
->http
.error
= error
;
3199 con
->http
.status
= HTTP_ERROR
;
3202 SSLDisposeContext(conn
->session
);
3204 if (conn
->certsArray
)
3205 CFRelease(conn
->certsArray
);
3212 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Connection from %s now encrypted.",
3213 con
->http
.hostname
);
3215 con
->http
.tls
= conn
;
3218 # endif /* HAVE_LIBSSL */
3220 #endif /* HAVE_SSL */
3225 * 'get_cdsa_certificate()' - Get a SSL/TLS certificate from the System keychain.
3228 static CFArrayRef
/* O - Array of certificates */
3229 get_cdsa_certificate(cupsd_client_t
*con
) /* I - Client connection */
3231 OSStatus err
; /* Error info */
3232 SecKeychainRef keychain
; /* Keychain reference */
3233 SecIdentitySearchRef search
; /* Search reference */
3234 SecIdentityRef identity
; /* Identity */
3235 CFArrayRef certificates
= NULL
;
3236 /* Certificate array */
3239 if ((err
= SecKeychainOpen(ServerCertificate
, &keychain
)))
3241 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot open keychain \"%s\" - %s (%d)",
3242 ServerCertificate
, cssmErrorString(err
), (int)err
);
3246 # if HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY
3248 * Use a policy to search for valid certificates who's common name matches the
3252 SecPolicySearchRef policy_search
; /* Policy search ref */
3253 SecPolicyRef policy
; /* Policy ref */
3254 CSSM_DATA options
; /* Policy options */
3255 CSSM_APPLE_TP_SSL_OPTIONS
3256 ssl_options
; /* SSL Option for hostname */
3259 if (SecPolicySearchCreate(CSSM_CERT_X_509v3
, &CSSMOID_APPLE_TP_SSL
,
3260 NULL
, &policy_search
))
3262 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot create a policy search reference");
3263 CFRelease(keychain
);
3267 if (SecPolicySearchCopyNext(policy_search
, &policy
))
3269 cupsdLogMessage(CUPSD_LOG_ERROR
,
3270 "Cannot find a policy to use for searching");
3271 CFRelease(keychain
);
3272 CFRelease(policy_search
);
3276 memset(&ssl_options
, 0, sizeof(ssl_options
));
3277 ssl_options
.Version
= CSSM_APPLE_TP_SSL_OPTS_VERSION
;
3278 ssl_options
.ServerName
= con
->servername
;
3279 ssl_options
.ServerNameLen
= strlen(con
->servername
);
3281 options
.Data
= (uint8
*)&ssl_options
;
3282 options
.Length
= sizeof(ssl_options
);
3284 if (SecPolicySetValue(policy
, &options
))
3286 cupsdLogMessage(CUPSD_LOG_ERROR
,
3287 "Cannot set policy value to use for searching");
3288 CFRelease(keychain
);
3289 CFRelease(policy_search
);
3293 err
= SecIdentitySearchCreateWithPolicy(policy
, NULL
, CSSM_KEYUSE_SIGN
,
3294 keychain
, FALSE
, &search
);
3297 * Assume there is exactly one SecIdentity in the keychain...
3300 err
= SecIdentitySearchCreate(keychain
, CSSM_KEYUSE_SIGN
, &search
);
3301 # endif /* HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY */
3304 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3305 "Cannot create keychain search reference: %s (%d)",
3306 cssmErrorString(err
), (int)err
);
3309 if ((err
= SecIdentitySearchCopyNext(search
, &identity
)))
3311 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3312 "Cannot find signing key in keychain \"%s\": %s (%d)",
3313 ServerCertificate
, cssmErrorString(err
), (int)err
);
3317 if (CFGetTypeID(identity
) != SecIdentityGetTypeID())
3318 cupsdLogMessage(CUPSD_LOG_ERROR
,
3319 "SecIdentitySearchCopyNext CFTypeID failure!");
3322 if ((certificates
= CFArrayCreate(NULL
, (const void **)&identity
,
3323 1, &kCFTypeArrayCallBacks
)) == NULL
)
3324 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot create certificate array");
3327 CFRelease(identity
);
3333 # if HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY
3335 CFRelease(policy_search
);
3336 # endif /* HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY */
3338 return (certificates
);
3340 #endif /* HAVE_CDSASSL */
3344 * 'get_file()' - Get a filename and state info.
3347 static char * /* O - Real filename */
3348 get_file(cupsd_client_t
*con
, /* I - Client connection */
3349 struct stat
*filestats
, /* O - File information */
3350 char *filename
, /* IO - Filename buffer */
3351 int len
) /* I - Buffer length */
3353 int status
; /* Status of filesystem calls */
3354 char *ptr
; /* Pointer info filename */
3355 int plen
; /* Remaining length after pointer */
3356 char language
[7]; /* Language subdirectory, if any */
3360 * Figure out the real filename...
3365 if (!strncmp(con
->uri
, "/ppd/", 5))
3366 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
);
3367 else if (!strncmp(con
->uri
, "/rss/", 5) && !strchr(con
->uri
+ 5, '/'))
3368 snprintf(filename
, len
, "%s/rss/%s", CacheDir
, con
->uri
+ 5);
3369 else if (!strncmp(con
->uri
, "/admin/conf/", 12))
3370 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
+ 11);
3371 else if (!strncmp(con
->uri
, "/admin/log/", 11))
3373 if (!strncmp(con
->uri
+ 11, "access_log", 10) && AccessLog
[0] == '/')
3374 strlcpy(filename
, AccessLog
, len
);
3375 else if (!strncmp(con
->uri
+ 11, "error_log", 9) && ErrorLog
[0] == '/')
3376 strlcpy(filename
, ErrorLog
, len
);
3377 else if (!strncmp(con
->uri
+ 11, "page_log", 8) && PageLog
[0] == '/')
3378 strlcpy(filename
, PageLog
, len
);
3382 else if (con
->language
)
3384 snprintf(language
, sizeof(language
), "/%s", con
->language
->language
);
3385 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3388 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3390 if ((ptr
= strchr(filename
, '?')) != NULL
)
3394 * Grab the status for this language; if there isn't a language-specific file
3395 * then fallback to the default one...
3398 if ((status
= stat(filename
, filestats
)) != 0 && language
[0] &&
3399 strncmp(con
->uri
, "/ppd/", 5) &&
3400 strncmp(con
->uri
, "/admin/conf/", 12) &&
3401 strncmp(con
->uri
, "/admin/log/", 11))
3404 * Drop the country code...
3408 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3410 if ((ptr
= strchr(filename
, '?')) != NULL
)
3413 if ((status
= stat(filename
, filestats
)) != 0)
3416 * Drop the language prefix and try the root directory...
3420 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3422 if ((ptr
= strchr(filename
, '?')) != NULL
)
3425 status
= stat(filename
, filestats
);
3430 * If we're found a directory, get the index.html file instead...
3433 if (!status
&& S_ISDIR(filestats
->st_mode
))
3436 * Make sure the URI ends with a slash...
3439 if (con
->uri
[strlen(con
->uri
) - 1] != '/')
3440 strlcat(con
->uri
, "/", sizeof(con
->uri
));
3443 * Find the directory index file, trying every language...
3448 if (status
&& language
[0])
3451 * Try a different language subset...
3455 language
[0] = '\0'; /* Strip country code */
3457 language
[0] = '\0'; /* Strip language */
3461 * Look for the index file...
3464 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3466 if ((ptr
= strchr(filename
, '?')) != NULL
)
3469 ptr
= filename
+ strlen(filename
);
3470 plen
= len
- (ptr
- filename
);
3472 strlcpy(ptr
, "index.html", plen
);
3473 status
= stat(filename
, filestats
);
3478 strlcpy(ptr
, "index.class", plen
);
3479 status
= stat(filename
, filestats
);
3481 #endif /* HAVE_JAVA */
3486 strlcpy(ptr
, "index.pl", plen
);
3487 status
= stat(filename
, filestats
);
3489 #endif /* HAVE_PERL */
3494 strlcpy(ptr
, "index.php", plen
);
3495 status
= stat(filename
, filestats
);
3497 #endif /* HAVE_PHP */
3502 strlcpy(ptr
, "index.pyc", plen
);
3503 status
= stat(filename
, filestats
);
3508 strlcpy(ptr
, "index.py", plen
);
3509 status
= stat(filename
, filestats
);
3511 #endif /* HAVE_PYTHON */
3514 while (status
&& language
[0]);
3517 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3518 "get_file(con=%p(%d), filestats=%p, filename=%p, len=%d) = "
3519 "%s", con
, con
->http
.fd
, filestats
, filename
, len
,
3520 status
? "(null)" : filename
);
3523 con
->http
.data_remaining
= (int)filestats
->st_size
;
3533 * 'install_conf_file()' - Install a configuration file.
3536 static http_status_t
/* O - Status */
3537 install_conf_file(cupsd_client_t
*con
) /* I - Connection */
3539 cups_file_t
*in
, /* Input file */
3540 *out
; /* Output file */
3541 char buffer
[1024]; /* Copy buffer */
3542 int bytes
; /* Number of bytes */
3543 char conffile
[1024], /* Configuration filename */
3544 newfile
[1024], /* New config filename */
3545 oldfile
[1024]; /* Old config filename */
3546 struct stat confinfo
; /* Config file info */
3550 * First construct the filenames...
3553 snprintf(conffile
, sizeof(conffile
), "%s%s", ServerRoot
, con
->uri
+ 11);
3554 snprintf(newfile
, sizeof(newfile
), "%s%s.N", ServerRoot
, con
->uri
+ 11);
3555 snprintf(oldfile
, sizeof(oldfile
), "%s%s.O", ServerRoot
, con
->uri
+ 11);
3557 cupsdLogMessage(CUPSD_LOG_INFO
, "Installing config file \"%s\"...", conffile
);
3560 * Get the owner, group, and permissions of the configuration file.
3561 * If it doesn't exist, assign it to the User and Group in the
3562 * cupsd.conf file with mode 0640 permissions.
3565 if (stat(conffile
, &confinfo
))
3567 confinfo
.st_uid
= User
;
3568 confinfo
.st_gid
= Group
;
3569 confinfo
.st_mode
= ConfigFilePerm
;
3573 * Open the request file and new config file...
3576 if ((in
= cupsFileOpen(con
->filename
, "rb")) == NULL
)
3578 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open request file \"%s\" - %s",
3579 con
->filename
, strerror(errno
));
3580 return (HTTP_SERVER_ERROR
);
3583 if ((out
= cupsFileOpen(newfile
, "wb")) == NULL
)
3586 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open config file \"%s\" - %s",
3587 newfile
, strerror(errno
));
3588 return (HTTP_SERVER_ERROR
);
3591 fchmod(cupsFileNumber(out
), confinfo
.st_mode
);
3592 fchown(cupsFileNumber(out
), confinfo
.st_uid
, confinfo
.st_gid
);
3595 * Copy from the request to the new config file...
3598 while ((bytes
= cupsFileRead(in
, buffer
, sizeof(buffer
))) > 0)
3599 if (cupsFileWrite(out
, buffer
, bytes
) < bytes
)
3601 cupsdLogMessage(CUPSD_LOG_ERROR
,
3602 "Unable to copy to config file \"%s\" - %s",
3603 newfile
, strerror(errno
));
3609 return (HTTP_SERVER_ERROR
);
3613 * Close the files...
3617 if (cupsFileClose(out
))
3619 cupsdLogMessage(CUPSD_LOG_ERROR
,
3620 "Error file closing config file \"%s\" - %s",
3621 newfile
, strerror(errno
));
3625 return (HTTP_SERVER_ERROR
);
3629 * Remove the request file...
3632 unlink(con
->filename
);
3633 cupsdClearString(&con
->filename
);
3636 * Unlink the old backup, rename the current config file to the backup
3637 * filename, and rename the new config file to the config file name...
3640 if (unlink(oldfile
))
3641 if (errno
!= ENOENT
)
3643 cupsdLogMessage(CUPSD_LOG_ERROR
,
3644 "Unable to remove backup config file \"%s\" - %s",
3645 oldfile
, strerror(errno
));
3649 return (HTTP_SERVER_ERROR
);
3652 if (rename(conffile
, oldfile
))
3653 if (errno
!= ENOENT
)
3655 cupsdLogMessage(CUPSD_LOG_ERROR
,
3656 "Unable to rename old config file \"%s\" - %s",
3657 conffile
, strerror(errno
));
3661 return (HTTP_SERVER_ERROR
);
3664 if (rename(newfile
, conffile
))
3666 cupsdLogMessage(CUPSD_LOG_ERROR
,
3667 "Unable to rename new config file \"%s\" - %s",
3668 newfile
, strerror(errno
));
3670 rename(oldfile
, conffile
);
3673 return (HTTP_SERVER_ERROR
);
3677 * If the cupsd.conf file was updated, set the NeedReload flag...
3680 if (!strcmp(con
->uri
, "/admin/conf/cupsd.conf"))
3681 NeedReload
= RELOAD_CUPSD
;
3683 NeedReload
= RELOAD_ALL
;
3685 ReloadTime
= time(NULL
);
3688 * Return that the file was created successfully...
3691 return (HTTP_CREATED
);
3696 * 'is_cgi()' - Is the resource a CGI script/program?
3699 static int /* O - 1 = CGI, 0 = file */
3700 is_cgi(cupsd_client_t
*con
, /* I - Client connection */
3701 const char *filename
, /* I - Real filename */
3702 struct stat
*filestats
, /* I - File information */
3703 mime_type_t
*type
) /* I - MIME type */
3705 const char *options
; /* Options on URL */
3709 * Get the options, if any...
3712 if ((options
= strchr(con
->uri
, '?')) != NULL
)
3715 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", options
);
3719 * Check for known types...
3722 if (!type
|| strcasecmp(type
->super
, "application"))
3724 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3725 "is_cgi(con=%p(%d), filename=\"%s\", filestats=%p, "
3726 "type=%s/%s) = 0", con
, con
->http
.fd
, filename
, filestats
,
3727 type
? type
->super
: "unknown",
3728 type
? type
->type
: "unknown");
3732 if (!strcasecmp(type
->type
, "x-httpd-cgi") &&
3733 (filestats
->st_mode
& 0111))
3736 * "application/x-httpd-cgi" is a CGI script.
3739 cupsdSetString(&con
->command
, filename
);
3742 cupsdSetStringf(&con
->options
, " %s", options
);
3744 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3745 "is_cgi(con=%p(%d), filename=\"%s\", filestats=%p, "
3746 "type=%s/%s) = 1", con
, con
->http
.fd
, filename
, filestats
,
3747 type
? type
->super
: "unknown",
3748 type
? type
->type
: "unknown");
3752 else if (!strcasecmp(type
->type
, "x-httpd-java"))
3755 * "application/x-httpd-java" is a Java servlet.
3758 cupsdSetString(&con
->command
, CUPS_JAVA
);
3761 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3763 cupsdSetStringf(&con
->options
, " %s", filename
);
3765 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3766 "is_cgi(con=%p(%d), filename=\"%s\", filestats=%p, "
3767 "type=%s/%s) = 1", con
, con
->http
.fd
, filename
, filestats
,
3768 type
? type
->super
: "unknown",
3769 type
? type
->type
: "unknown");
3772 #endif /* HAVE_JAVA */
3774 else if (!strcasecmp(type
->type
, "x-httpd-perl"))
3777 * "application/x-httpd-perl" is a Perl page.
3780 cupsdSetString(&con
->command
, CUPS_PERL
);
3783 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3785 cupsdSetStringf(&con
->options
, " %s", filename
);
3787 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3788 "is_cgi(con=%p(%d), filename=\"%s\", filestats=%p, "
3789 "type=%s/%s) = 1", con
, con
->http
.fd
, filename
, filestats
,
3790 type
? type
->super
: "unknown",
3791 type
? type
->type
: "unknown");
3794 #endif /* HAVE_PERL */
3796 else if (!strcasecmp(type
->type
, "x-httpd-php"))
3799 * "application/x-httpd-php" is a PHP page.
3802 cupsdSetString(&con
->command
, CUPS_PHP
);
3805 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3807 cupsdSetStringf(&con
->options
, " %s", filename
);
3809 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3810 "is_cgi(con=%p(%d), filename=\"%s\", filestats=%p, "
3811 "type=%s/%s) = 1", con
, con
->http
.fd
, filename
, filestats
,
3812 type
? type
->super
: "unknown",
3813 type
? type
->type
: "unknown");
3816 #endif /* HAVE_PHP */
3818 else if (!strcasecmp(type
->type
, "x-httpd-python"))
3821 * "application/x-httpd-python" is a Python page.
3824 cupsdSetString(&con
->command
, CUPS_PYTHON
);
3827 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3829 cupsdSetStringf(&con
->options
, " %s", filename
);
3831 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3832 "is_cgi(con=%p(%d), filename=\"%s\", filestats=%p, "
3833 "type=%s/%s) = 1", con
, con
->http
.fd
, filename
, filestats
,
3834 type
? type
->super
: "unknown",
3835 type
? type
->type
: "unknown");
3838 #endif /* HAVE_PYTHON */
3840 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3841 "is_cgi(con=%p(%d), filename=\"%s\", filestats=%p, "
3842 "type=%s/%s) = 0", con
, con
->http
.fd
, filename
, filestats
,
3843 type
? type
->super
: "unknown",
3844 type
? type
->type
: "unknown");
3850 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
3853 static int /* O - 0 if relative, 1 if absolute */
3854 is_path_absolute(const char *path
) /* I - Input path */
3857 * Check for a leading slash...
3864 * Check for "/.." in the path...
3867 while ((path
= strstr(path
, "/..")) != NULL
)
3869 if (!path
[3] || path
[3] == '/')
3876 * If we haven't found any relative paths, return 1 indicating an
3886 * 'make_certificate()' - Make a self-signed SSL/TLS certificate.
3889 static int /* O - 1 on success, 0 on failure */
3890 make_certificate(cupsd_client_t
*con
) /* I - Client connection */
3892 #if defined(HAVE_LIBSSL) && defined(HAVE_WAITPID)
3893 int pid
, /* Process ID of command */
3894 status
; /* Status of command */
3895 char command
[1024], /* Command */
3896 *argv
[12], /* Command-line arguments */
3897 *envp
[MAX_ENV
+ 1], /* Environment variables */
3898 home
[1024], /* HOME environment variable */
3899 infofile
[1024], /* Type-in information for cert */
3900 seedfile
[1024]; /* Random number seed file */
3901 int envc
, /* Number of environment variables */
3902 bytes
; /* Bytes written */
3903 cups_file_t
*fp
; /* Seed/info file */
3904 int infofd
; /* Info file descriptor */
3908 * Run the "openssl" command to seed the random number generator and
3909 * generate a self-signed certificate that is good for 10 years:
3911 * openssl rand -rand seedfile 1
3913 * openssl req -new -x509 -keyout ServerKey \
3914 * -out ServerCertificate -days 3650 -nodes
3916 * The seeding step is crucial in ensuring that the openssl command
3917 * does not block on systems without sufficient entropy...
3920 if (!cupsFileFind("openssl", getenv("PATH"), 1, command
, sizeof(command
)))
3922 cupsdLogMessage(CUPSD_LOG_ERROR
,
3923 "No SSL certificate and openssl command not found!");
3927 if (access("/dev/urandom", 0))
3930 * If the system doesn't provide /dev/urandom, then any random source
3931 * will probably be blocking-style, so generate some random data to
3932 * use as a seed for the certificate. Note that we have already
3933 * seeded the random number generator in cupsdInitCerts()...
3936 cupsdLogMessage(CUPSD_LOG_INFO
,
3937 "Seeding the random number generator...");
3939 snprintf(home
, sizeof(home
), "HOME=%s", TempDir
);
3942 * Write the seed file...
3945 if ((fp
= cupsTempFile2(seedfile
, sizeof(seedfile
))) == NULL
)
3947 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to create seed file %s - %s",
3948 seedfile
, strerror(errno
));
3952 for (bytes
= 0; bytes
< 262144; bytes
++)
3953 cupsFilePutChar(fp
, random());
3958 * Run the openssl command to seed its random number generator...
3961 argv
[0] = "openssl";
3968 envc
= cupsdLoadEnv(envp
, MAX_ENV
);
3969 envp
[envc
++] = home
;
3972 if (!cupsdStartProcess(command
, argv
, envp
, -1, -1, -1, -1, -1, 1, NULL
, 0,
3979 while (waitpid(pid
, &status
, 0) < 0)
3986 cupsdFinishProcess(pid
, command
, sizeof(command
), NULL
);
3989 * Remove the seed file, as it is no longer needed...
3996 if (WIFEXITED(status
))
3997 cupsdLogMessage(CUPSD_LOG_ERROR
,
3998 "Unable to seed random number generator - "
3999 "the openssl command stopped with status %d!",
4000 WEXITSTATUS(status
));
4002 cupsdLogMessage(CUPSD_LOG_ERROR
,
4003 "Unable to seed random number generator - "
4004 "the openssl command crashed on signal %d!",
4012 * Create a file with the certificate information fields...
4014 * Note: This assumes that the default questions are asked by the openssl
4018 if ((fp
= cupsTempFile2(infofile
, sizeof(infofile
))) == NULL
)
4020 cupsdLogMessage(CUPSD_LOG_ERROR
,
4021 "Unable to create certificate information file %s - %s",
4022 infofile
, strerror(errno
));
4026 cupsFilePrintf(fp
, ".\n.\n.\n%s\n.\n%s\n%s\n",
4027 ServerName
, ServerName
, ServerAdmin
);
4030 cupsdLogMessage(CUPSD_LOG_INFO
,
4031 "Generating SSL server key and certificate...");
4033 argv
[0] = "openssl";
4037 argv
[4] = "-keyout";
4038 argv
[5] = ServerKey
;
4040 argv
[7] = ServerCertificate
;
4043 argv
[10] = "-nodes";
4046 cupsdLoadEnv(envp
, MAX_ENV
);
4048 infofd
= open(infofile
, O_RDONLY
);
4050 if (!cupsdStartProcess(command
, argv
, envp
, infofd
, -1, -1, -1, -1, 1, NULL
,
4061 while (waitpid(pid
, &status
, 0) < 0)
4068 cupsdFinishProcess(pid
, command
, sizeof(command
), NULL
);
4072 if (WIFEXITED(status
))
4073 cupsdLogMessage(CUPSD_LOG_ERROR
,
4074 "Unable to create SSL server key and certificate - "
4075 "the openssl command stopped with status %d!",
4076 WEXITSTATUS(status
));
4078 cupsdLogMessage(CUPSD_LOG_ERROR
,
4079 "Unable to create SSL server key and certificate - "
4080 "the openssl command crashed on signal %d!",
4085 cupsdLogMessage(CUPSD_LOG_INFO
, "Created SSL server key file \"%s\"...",
4087 cupsdLogMessage(CUPSD_LOG_INFO
,
4088 "Created SSL server certificate file \"%s\"...",
4094 #elif defined(HAVE_GNUTLS)
4095 gnutls_x509_crt crt
; /* Self-signed certificate */
4096 gnutls_x509_privkey key
; /* Encryption key */
4097 cups_lang_t
*language
; /* Default language info */
4098 cups_file_t
*fp
; /* Key/cert file */
4099 unsigned char buffer
[8192]; /* Buffer for x509 data */
4100 size_t bytes
; /* Number of bytes of data */
4101 unsigned char serial
[4]; /* Serial number buffer */
4102 time_t curtime
; /* Current time */
4103 int result
; /* Result of GNU TLS calls */
4107 * Create the encryption key...
4110 cupsdLogMessage(CUPSD_LOG_INFO
, "Generating SSL server key...");
4112 gnutls_x509_privkey_init(&key
);
4113 gnutls_x509_privkey_generate(key
, GNUTLS_PK_RSA
, 2048, 0);
4119 bytes
= sizeof(buffer
);
4121 if ((result
= gnutls_x509_privkey_export(key
, GNUTLS_X509_FMT_PEM
,
4122 buffer
, &bytes
)) < 0)
4124 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to export SSL server key - %s",
4125 gnutls_strerror(result
));
4126 gnutls_x509_privkey_deinit(key
);
4129 else if ((fp
= cupsFileOpen(ServerKey
, "w")) != NULL
)
4131 cupsFileWrite(fp
, (char *)buffer
, bytes
);
4134 cupsdLogMessage(CUPSD_LOG_INFO
, "Created SSL server key file \"%s\"...",
4139 cupsdLogMessage(CUPSD_LOG_ERROR
,
4140 "Unable to create SSL server key file \"%s\" - %s",
4141 ServerKey
, strerror(errno
));
4142 gnutls_x509_privkey_deinit(key
);
4147 * Create the self-signed certificate...
4150 cupsdLogMessage(CUPSD_LOG_INFO
, "Generating self-signed SSL certificate...");
4152 language
= cupsLangDefault();
4153 curtime
= time(NULL
);
4154 serial
[0] = curtime
>> 24;
4155 serial
[1] = curtime
>> 16;
4156 serial
[2] = curtime
>> 8;
4157 serial
[3] = curtime
;
4159 gnutls_x509_crt_init(&crt
);
4160 if (strlen(language
->language
) == 5)
4161 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
4162 language
->language
+ 3, 2);
4164 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
4166 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COMMON_NAME
, 0,
4167 ServerName
, strlen(ServerName
));
4168 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATION_NAME
, 0,
4169 ServerName
, strlen(ServerName
));
4170 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATIONAL_UNIT_NAME
,
4172 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_STATE_OR_PROVINCE_NAME
, 0,
4174 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_LOCALITY_NAME
, 0,
4176 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_PKCS9_EMAIL
, 0,
4177 ServerAdmin
, strlen(ServerAdmin
));
4178 gnutls_x509_crt_set_key(crt
, key
);
4179 gnutls_x509_crt_set_serial(crt
, serial
, sizeof(serial
));
4180 gnutls_x509_crt_set_activation_time(crt
, curtime
);
4181 gnutls_x509_crt_set_expiration_time(crt
, curtime
+ 10 * 365 * 86400);
4182 gnutls_x509_crt_set_ca_status(crt
, 0);
4183 gnutls_x509_crt_set_subject_alternative_name(crt
, GNUTLS_SAN_DNSNAME
,
4185 gnutls_x509_crt_set_key_purpose_oid(crt
, GNUTLS_KP_TLS_WWW_SERVER
, 0);
4186 gnutls_x509_crt_set_key_usage(crt
, GNUTLS_KEY_KEY_ENCIPHERMENT
);
4187 gnutls_x509_crt_set_version(crt
, 3);
4189 bytes
= sizeof(buffer
);
4190 if (gnutls_x509_crt_get_key_id(crt
, 0, buffer
, &bytes
) >= 0)
4191 gnutls_x509_crt_set_subject_key_id(crt
, buffer
, bytes
);
4193 gnutls_x509_crt_sign(crt
, crt
, key
);
4199 bytes
= sizeof(buffer
);
4200 if ((result
= gnutls_x509_crt_export(crt
, GNUTLS_X509_FMT_PEM
,
4201 buffer
, &bytes
)) < 0)
4202 cupsdLogMessage(CUPSD_LOG_ERROR
,
4203 "Unable to export SSL server certificate - %s",
4204 gnutls_strerror(result
));
4205 else if ((fp
= cupsFileOpen(ServerCertificate
, "w")) != NULL
)
4207 cupsFileWrite(fp
, (char *)buffer
, bytes
);
4210 cupsdLogMessage(CUPSD_LOG_INFO
,
4211 "Created SSL server certificate file \"%s\"...",
4215 cupsdLogMessage(CUPSD_LOG_ERROR
,
4216 "Unable to create SSL server certificate file \"%s\" - %s",
4217 ServerCertificate
, strerror(errno
));
4223 gnutls_x509_crt_deinit(crt
);
4224 gnutls_x509_privkey_deinit(key
);
4228 #elif defined(HAVE_CDSASSL) && defined(HAVE_WAITPID)
4229 int pid
, /* Process ID of command */
4230 status
; /* Status of command */
4231 char command
[1024], /* Command */
4232 *argv
[4], /* Command-line arguments */
4233 *envp
[MAX_ENV
+ 1], /* Environment variables */
4234 keychain
[1024], /* Keychain argument */
4235 infofile
[1024]; /* Type-in information for cert */
4236 cups_file_t
*fp
; /* Seed/info file */
4237 int infofd
; /* Info file descriptor */
4241 * Run the "certtool" command to generate a self-signed certificate...
4244 if (!cupsFileFind("certtool", getenv("PATH"), 1, command
, sizeof(command
)))
4246 cupsdLogMessage(CUPSD_LOG_ERROR
,
4247 "No SSL certificate and certtool command not found!");
4252 * Create a file with the certificate information fields...
4254 * Note: This assumes that the default questions are asked by the certtool
4258 if ((fp
= cupsTempFile2(infofile
, sizeof(infofile
))) == NULL
)
4260 cupsdLogMessage(CUPSD_LOG_ERROR
,
4261 "Unable to create certificate information file %s - %s",
4262 infofile
, strerror(errno
));
4266 cupsFilePrintf(fp
, "%s\nr\n\ny\nb\ns\ny\n%s\n\n\n\n\n%s\ny\n",
4267 con
->servername
, con
->servername
, ServerAdmin
);
4270 cupsdLogMessage(CUPSD_LOG_INFO
,
4271 "Generating SSL server key and certificate...");
4273 snprintf(keychain
, sizeof(keychain
), "k=%s", ServerCertificate
);
4275 argv
[0] = "certtool";
4280 cupsdLoadEnv(envp
, MAX_ENV
);
4282 infofd
= open(infofile
, O_RDONLY
);
4284 if (!cupsdStartProcess(command
, argv
, envp
, infofd
, -1, -1, -1, -1, 1, NULL
,
4295 while (waitpid(pid
, &status
, 0) < 0)
4302 cupsdFinishProcess(pid
, command
, sizeof(command
), NULL
);
4306 if (WIFEXITED(status
))
4307 cupsdLogMessage(CUPSD_LOG_ERROR
,
4308 "Unable to create SSL server key and certificate - "
4309 "the certtool command stopped with status %d!",
4310 WEXITSTATUS(status
));
4312 cupsdLogMessage(CUPSD_LOG_ERROR
,
4313 "Unable to create SSL server key and certificate - "
4314 "the certtool command crashed on signal %d!",
4319 cupsdLogMessage(CUPSD_LOG_INFO
,
4320 "Created SSL server certificate file \"%s\"...",
4328 #endif /* HAVE_LIBSSL && HAVE_WAITPID */
4330 #endif /* HAVE_SSL */
4334 * 'pipe_command()' - Pipe the output of a command to the remote client.
4337 static int /* O - Process ID */
4338 pipe_command(cupsd_client_t
*con
, /* I - Client connection */
4339 int infile
, /* I - Standard input for command */
4340 int *outfile
, /* O - Standard output for command */
4341 char *command
, /* I - Command to run */
4342 char *options
, /* I - Options for command */
4343 int root
) /* I - Run as root? */
4345 int i
; /* Looping var */
4346 int pid
; /* Process ID */
4347 char *commptr
, /* Command string pointer */
4348 commch
; /* Command string character */
4349 char *uriptr
; /* URI string pointer */
4350 int fds
[2]; /* Pipe FDs */
4351 int argc
; /* Number of arguments */
4352 int envc
; /* Number of environment variables */
4353 char argbuf
[10240], /* Argument buffer */
4354 *argv
[100], /* Argument strings */
4355 *envp
[MAX_ENV
+ 20]; /* Environment variables */
4356 char auth_type
[256], /* CUPSD_AUTH_TYPE environment variable */
4357 content_length
[1024], /* CONTENT_LENGTH environment variable */
4358 content_type
[1024], /* CONTENT_TYPE environment variable */
4359 http_cookie
[32768], /* HTTP_COOKIE environment variable */
4360 http_referer
[1024], /* HTTP_REFERER environment variable */
4361 http_user_agent
[1024], /* HTTP_USER_AGENT environment variable */
4362 lang
[1024], /* LANG environment variable */
4363 path_info
[1024], /* PATH_INFO environment variable */
4364 remote_addr
[1024], /* REMOTE_ADDR environment variable */
4365 remote_host
[1024], /* REMOTE_HOST environment variable */
4366 remote_user
[1024], /* REMOTE_USER environment variable */
4367 script_filename
[1024], /* SCRIPT_FILENAME environment variable */
4368 script_name
[1024], /* SCRIPT_NAME environment variable */
4369 server_name
[1024], /* SERVER_NAME environment variable */
4370 server_port
[1024]; /* SERVER_PORT environment variable */
4371 ipp_attribute_t
*attr
; /* attributes-natural-language attribute */
4373 krb5_ccache ccache
= NULL
; /* Kerberos credentials */
4374 # if defined(HAVE_KRB5_CC_NEW_UNIQUE) || defined(HAVE_HEIMDAL)
4375 char krb5ccname
[1024]; /* KRB5CCNAME environment variable */
4376 # endif /* HAVE_KRB5_CC_NEW_UNIQUE || HAVE_HEIMDAL */
4377 #endif /* HAVE_GSSAPI */
4381 * Parse a copy of the options string, which is of the form:
4383 * argument+argument+argument
4384 * ?argument+argument+argument
4385 * param=value¶m=value
4386 * ?param=value¶m=value
4387 * /name?argument+argument+argument
4388 * /name?param=value¶m=value
4390 * If the string contains an "=" character after the initial name,
4391 * then we treat it as a HTTP GET form request and make a copy of
4392 * the remaining string for the environment variable.
4394 * The string is always parsed out as command-line arguments, to
4395 * be consistent with Apache...
4398 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4399 "pipe_command(con=%p(%d), infile=%d, outfile=%p, "
4400 "command=\"%s\", options=\"%s\", root=%d)",
4401 con
, con
->http
.fd
, infile
, outfile
, command
,
4402 options
? options
: "(null)", root
);
4407 strlcpy(argbuf
, options
, sizeof(argbuf
));
4411 if (argbuf
[0] == '/')
4414 * Found some trailing path information, set PATH_INFO...
4417 if ((commptr
= strchr(argbuf
, '?')) == NULL
)
4418 commptr
= argbuf
+ strlen(argbuf
);
4422 snprintf(path_info
, sizeof(path_info
), "PATH_INFO=%s", argbuf
);
4428 path_info
[0] = '\0';
4430 if (*commptr
== ' ')
4434 if (*commptr
== '?' && con
->operation
== HTTP_GET
&& !con
->query_string
)
4437 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", commptr
);
4444 argv
[argc
++] = commptr
;
4446 for (; *commptr
&& argc
< 99; commptr
++)
4449 * Break arguments whenever we see a + or space...
4452 if (*commptr
== ' ' || *commptr
== '+')
4454 while (*commptr
== ' ' || *commptr
== '+')
4458 * If we don't have a blank string, save it as another argument...
4463 argv
[argc
] = commptr
;
4469 else if (*commptr
== '%' && isxdigit(commptr
[1] & 255) &&
4470 isxdigit(commptr
[2] & 255))
4473 * Convert the %xx notation to the individual character.
4476 if (commptr
[1] >= '0' && commptr
[1] <= '9')
4477 *commptr
= (commptr
[1] - '0') << 4;
4479 *commptr
= (tolower(commptr
[1]) - 'a' + 10) << 4;
4481 if (commptr
[2] >= '0' && commptr
[2] <= '9')
4482 *commptr
|= commptr
[2] - '0';
4484 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
4486 _cups_strcpy(commptr
+ 1, commptr
+ 3);
4489 * Check for a %00 and break if that is the case...
4501 * Setup the environment variables as needed...
4504 if (con
->username
[0])
4506 snprintf(auth_type
, sizeof(auth_type
), "CUPSD_AUTH_TYPE=%s",
4507 httpGetField(HTTP(con
), HTTP_FIELD_AUTHORIZATION
));
4509 if ((uriptr
= strchr(auth_type
+ 10, ' ')) != NULL
)
4513 auth_type
[0] = '\0';
4516 (attr
= ippFindAttribute(con
->request
, "attributes-natural-language",
4517 IPP_TAG_LANGUAGE
)) != NULL
)
4519 switch (strlen(attr
->values
[0].string
.text
))
4523 * This is an unknown or badly formatted language code; use
4524 * the POSIX locale...
4527 strcpy(lang
, "LANG=C");
4532 * Just the language code (ll)...
4535 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8",
4536 attr
->values
[0].string
.text
);
4541 * Language and country code (ll-cc)...
4544 snprintf(lang
, sizeof(lang
), "LANG=%c%c_%c%c.UTF8",
4545 attr
->values
[0].string
.text
[0],
4546 attr
->values
[0].string
.text
[1],
4547 toupper(attr
->values
[0].string
.text
[3] & 255),
4548 toupper(attr
->values
[0].string
.text
[4] & 255));
4552 else if (con
->language
)
4553 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8", con
->language
->language
);
4555 strcpy(lang
, "LANG=C");
4557 strcpy(remote_addr
, "REMOTE_ADDR=");
4558 httpAddrString(con
->http
.hostaddr
, remote_addr
+ 12,
4559 sizeof(remote_addr
) - 12);
4561 snprintf(remote_host
, sizeof(remote_host
), "REMOTE_HOST=%s",
4562 con
->http
.hostname
);
4564 snprintf(script_name
, sizeof(script_name
), "SCRIPT_NAME=%s", con
->uri
);
4565 if ((uriptr
= strchr(script_name
, '?')) != NULL
)
4568 snprintf(script_filename
, sizeof(script_filename
), "SCRIPT_FILENAME=%s%s",
4569 DocumentRoot
, script_name
+ 12);
4571 sprintf(server_port
, "SERVER_PORT=%d", con
->serverport
);
4573 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
4576 envc
= cupsdLoadEnv(envp
, (int)(sizeof(envp
) / sizeof(envp
[0])));
4579 envp
[envc
++] = auth_type
;
4581 envp
[envc
++] = lang
;
4582 envp
[envc
++] = "REDIRECT_STATUS=1";
4583 envp
[envc
++] = "GATEWAY_INTERFACE=CGI/1.1";
4584 envp
[envc
++] = server_name
;
4585 envp
[envc
++] = server_port
;
4586 envp
[envc
++] = remote_addr
;
4587 envp
[envc
++] = remote_host
;
4588 envp
[envc
++] = script_name
;
4589 envp
[envc
++] = script_filename
;
4592 envp
[envc
++] = path_info
;
4594 if (con
->username
[0])
4596 snprintf(remote_user
, sizeof(remote_user
), "REMOTE_USER=%s", con
->username
);
4598 envp
[envc
++] = remote_user
;
4601 * Save Kerberos credentials, if any...
4605 if (con
->gss_have_creds
)
4607 # if !defined(HAVE_KRB5_CC_NEW_UNIQUE) && !defined(HAVE_HEIMDAL)
4608 cupsdLogMessage(CUPSD_LOG_INFO
,
4609 "Sorry, your version of Kerberos does not support "
4610 "delegated credentials!");
4613 krb5_error_code error
; /* Kerberos error code */
4614 OM_uint32 major_status
, /* Major status code */
4615 minor_status
; /* Minor status code */
4616 krb5_principal principal
; /* Kerberos principal */
4621 * If the weak-linked GSSAPI/Kerberos library is not present, don't try
4625 if (krb5_init_context
!= NULL
)
4627 # endif /* __APPLE__ */
4629 if (!KerberosInitialized
)
4632 * Setup a Kerberos context for the scheduler to use...
4635 KerberosInitialized
= 1;
4637 if (krb5_init_context(&KerberosContext
))
4639 KerberosContext
= NULL
;
4641 cupsdLogMessage(CUPSD_LOG_ERROR
,
4642 "Unable to initialize Kerberos context");
4647 * We MUST create a file-based cache because memory-based caches are
4648 * only valid for the current process/address space.
4650 * Due to various bugs/features in different versions of Kerberos, we
4651 * need either the krb5_cc_new_unique() function or Heimdal's version
4652 * of krb5_cc_gen_new() to create a new FILE: credential cache that
4653 * can be passed to the backend. These functions create a temporary
4654 * file (typically in /tmp) containing the cached credentials, which
4655 * are removed when we have successfully printed a job.
4658 if (KerberosContext
)
4660 # ifdef HAVE_KRB5_CC_NEW_UNIQUE
4661 if ((error
= krb5_cc_new_unique(KerberosContext
, "FILE", NULL
,
4663 # else /* HAVE_HEIMDAL */
4664 if ((error
= krb5_cc_gen_new(KerberosContext
, &krb5_fcc_ops
,
4666 # endif /* HAVE_KRB5_CC_NEW_UNIQUE */
4668 cupsdLogMessage(CUPSD_LOG_ERROR
,
4669 "Unable to create new credentials cache (%d/%s)",
4670 error
, strerror(errno
));
4673 else if ((error
= krb5_parse_name(KerberosContext
, con
->username
,
4676 cupsdLogMessage(CUPSD_LOG_ERROR
,
4677 "Unable to parse kerberos username (%d/%s)", error
,
4679 krb5_cc_destroy(KerberosContext
, ccache
);
4682 else if ((error
= krb5_cc_initialize(KerberosContext
, ccache
,
4685 cupsdLogMessage(CUPSD_LOG_ERROR
,
4686 "Unable to initialize credentials cache (%d/%s)",
4687 error
, strerror(errno
));
4688 krb5_cc_destroy(KerberosContext
, ccache
);
4689 krb5_free_principal(KerberosContext
, principal
);
4694 krb5_free_principal(KerberosContext
, principal
);
4697 * Copy the user's credentials to the new cache file...
4700 major_status
= gss_krb5_copy_ccache(&minor_status
,
4701 con
->gss_delegated_cred
, ccache
);
4703 if (GSS_ERROR(major_status
))
4705 cupsdLogGSSMessage(CUPSD_LOG_ERROR
, major_status
, minor_status
,
4706 "Unable to import client credentials cache");
4707 krb5_cc_destroy(KerberosContext
, ccache
);
4713 * Add the KRB5CCNAME environment variable to the job so that the
4714 * backend can use the credentials when printing.
4717 snprintf(krb5ccname
, sizeof(krb5ccname
), "KRB5CCNAME=FILE:%s",
4718 krb5_cc_get_name(KerberosContext
, ccache
));
4719 envp
[envc
++] = krb5ccname
;
4722 chown(krb5_cc_get_name(KerberosContext
, ccache
), User
, Group
);
4728 # endif /* __APPLE__ */
4729 # endif /* HAVE_KRB5_CC_NEW_UNIQUE || HAVE_HEIMDAL */
4731 #endif /* HAVE_GSSAPI */
4734 if (con
->http
.version
== HTTP_1_1
)
4735 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.1";
4736 else if (con
->http
.version
== HTTP_1_0
)
4737 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.0";
4739 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/0.9";
4741 if (con
->http
.cookie
)
4743 snprintf(http_cookie
, sizeof(http_cookie
), "HTTP_COOKIE=%s",
4745 envp
[envc
++] = http_cookie
;
4748 if (con
->http
.fields
[HTTP_FIELD_USER_AGENT
][0])
4750 snprintf(http_user_agent
, sizeof(http_user_agent
), "HTTP_USER_AGENT=%s",
4751 con
->http
.fields
[HTTP_FIELD_USER_AGENT
]);
4752 envp
[envc
++] = http_user_agent
;
4755 if (con
->http
.fields
[HTTP_FIELD_REFERER
][0])
4757 snprintf(http_referer
, sizeof(http_referer
), "HTTP_REFERER=%s",
4758 con
->http
.fields
[HTTP_FIELD_REFERER
]);
4759 envp
[envc
++] = http_referer
;
4762 if (con
->operation
== HTTP_GET
)
4764 envp
[envc
++] = "REQUEST_METHOD=GET";
4766 if (con
->query_string
)
4769 * Add GET form variables after ?...
4772 envp
[envc
++] = con
->query_string
;
4775 envp
[envc
++] = "QUERY_STRING=";
4779 sprintf(content_length
, "CONTENT_LENGTH=" CUPS_LLFMT
,
4780 CUPS_LLCAST con
->bytes
);
4781 snprintf(content_type
, sizeof(content_type
), "CONTENT_TYPE=%s",
4782 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
4784 envp
[envc
++] = "REQUEST_METHOD=POST";
4785 envp
[envc
++] = content_length
;
4786 envp
[envc
++] = content_type
;
4790 * Tell the CGI if we are using encryption...
4794 envp
[envc
++] = "HTTPS=ON";
4797 * Terminate the environment array...
4802 if (LogLevel
== CUPSD_LOG_DEBUG2
)
4804 for (i
= 0; i
< argc
; i
++)
4805 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4806 "pipe_command: argv[%d] = \"%s\"", i
, argv
[i
]);
4807 for (i
= 0; i
< envc
; i
++)
4808 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4809 "pipe_command: envp[%d] = \"%s\"", i
, envp
[i
]);
4813 * Create a pipe for the output...
4816 if (cupsdOpenPipe(fds
))
4818 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to create pipes for CGI %s - %s",
4819 argv
[0], strerror(errno
));
4824 * Then execute the command...
4827 if (cupsdStartProcess(command
, argv
, envp
, infile
, fds
[1], CGIPipes
[1],
4828 -1, -1, root
, DefaultProfile
, 0, &pid
) < 0)
4831 * Error - can't fork!
4834 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to fork for CGI %s - %s", argv
[0],
4837 cupsdClosePipe(fds
);
4843 * Fork successful - return the PID...
4846 if (con
->username
[0])
4848 cupsdAddCert(pid
, con
->username
, ccache
);
4850 cupsdAddCert(pid
, con
->username
, NULL
);
4851 #endif /* HAVE_GSSAPI */
4853 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[CGI] %s started - PID = %d",
4865 * 'write_file()' - Send a file via HTTP.
4868 static int /* O - 0 on failure, 1 on success */
4869 write_file(cupsd_client_t
*con
, /* I - Client connection */
4870 http_status_t code
, /* I - HTTP status */
4871 char *filename
, /* I - Filename */
4872 char *type
, /* I - File type */
4873 struct stat
*filestats
) /* O - File information */
4875 con
->file
= open(filename
, O_RDONLY
);
4877 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4878 "write_file(con=%p(%d), code=%d, filename=\"%s\" (%d), "
4879 "type=\"%s\", filestats=%p)", con
, con
->http
.fd
,
4880 code
, filename
, con
->file
, type
? type
: "(null)", filestats
);
4885 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
4889 if (!cupsdSendHeader(con
, code
, type
, CUPSD_AUTH_NONE
))
4892 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
4893 httpGetDateString(filestats
->st_mtime
)) < 0)
4895 if (httpPrintf(HTTP(con
), "Content-Length: " CUPS_LLFMT
"\r\n",
4896 CUPS_LLCAST filestats
->st_size
) < 0)
4898 if (httpPrintf(HTTP(con
), "\r\n") < 0)
4901 if (cupsdFlushHeader(con
) < 0)
4904 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
4905 con
->http
.data_remaining
= filestats
->st_size
;
4907 if (con
->http
.data_remaining
<= INT_MAX
)
4908 con
->http
._data_remaining
= con
->http
.data_remaining
;
4910 con
->http
._data_remaining
= INT_MAX
;
4912 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
,
4913 (cupsd_selfunc_t
)cupsdWriteClient
, con
);
4920 * 'write_pipe()' - Flag that data is available on the CGI pipe.
4924 write_pipe(cupsd_client_t
*con
) /* I - Client connection */
4926 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4927 "write_pipe(con=%p(%d)) CGI output on fd %d",
4928 con
, con
->http
.fd
, con
->file
);
4930 con
->file_ready
= 1;
4932 cupsdRemoveSelect(con
->file
);
4933 cupsdAddSelect(con
->http
.fd
, NULL
, (cupsd_selfunc_t
)cupsdWriteClient
, con
);
4938 * End of "$Id: client.c 7950 2008-09-17 00:21:59Z mike $".