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
)
2650 * If we get called in the wrong state, then something went wrong with the
2651 * connection and we need to shut it down...
2654 cupsdCloseClient(con
);
2661 * Make sure we select on the CGI output...
2664 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2666 if (!con
->file_ready
)
2669 * Try again later when there is CGI output available...
2672 cupsdRemoveSelect(con
->http
.fd
);
2676 con
->file_ready
= 0;
2679 if (con
->response
&& con
->response
->state
!= IPP_DATA
)
2681 ipp_state
= ippWrite(HTTP(con
), con
->response
);
2682 bytes
= ipp_state
!= IPP_ERROR
&&
2683 (con
->file
>= 0 || ipp_state
!= IPP_DATA
);
2685 else if ((bytes
= read(con
->file
, buf
, sizeof(buf
) - 1)) > 0)
2687 if (con
->pipe_pid
&& !con
->got_fields
)
2690 * Inspect the data for Content-Type and other fields.
2695 for (bufptr
= buf
; !con
->got_fields
&& *bufptr
; bufptr
++)
2697 if (*bufptr
== '\n')
2700 * Send line to client...
2703 if (bufptr
> buf
&& bufptr
[-1] == '\r')
2707 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Script header: %s", buf
);
2709 if (!con
->sent_header
)
2712 * Handle redirection and CGI status codes...
2715 if (!strncasecmp(buf
, "Location:", 9))
2717 cupsdSendHeader(con
, HTTP_SEE_OTHER
, NULL
, CUPSD_AUTH_NONE
);
2718 con
->sent_header
= 2;
2720 if (httpPrintf(HTTP(con
), "Content-Length: 0\r\n") < 0)
2723 else if (!strncasecmp(buf
, "Status:", 7))
2725 cupsdSendError(con
, (http_status_t
)atoi(buf
+ 7), CUPSD_AUTH_NONE
);
2726 con
->sent_header
= 2;
2730 cupsdSendHeader(con
, HTTP_OK
, NULL
, CUPSD_AUTH_NONE
);
2731 con
->sent_header
= 1;
2733 if (con
->http
.version
== HTTP_1_1
)
2735 if (httpPrintf(HTTP(con
), "Transfer-Encoding: chunked\r\n") < 0)
2741 if (strncasecmp(buf
, "Status:", 7))
2742 httpPrintf(HTTP(con
), "%s\r\n", buf
);
2748 bytes
-= (bufptr
- buf
);
2751 memmove(buf
, bufptr
, bytes
+ 1);
2758 * See if the line was empty...
2761 if (con
->field_col
== 0)
2763 con
->got_fields
= 1;
2765 if (cupsdFlushHeader(con
) < 0)
2767 cupsdCloseClient(con
);
2771 if (con
->http
.version
== HTTP_1_1
)
2772 con
->http
.data_encoding
= HTTP_ENCODE_CHUNKED
;
2777 else if (*bufptr
!= '\r')
2781 if (bytes
> 0 && !con
->got_fields
)
2784 * Remaining text needs to go out...
2787 httpPrintf(HTTP(con
), "%s", buf
);
2789 con
->http
.activity
= time(NULL
);
2792 else if (bytes
== 0)
2794 con
->http
.activity
= time(NULL
);
2801 if (httpWrite2(HTTP(con
), buf
, bytes
) < 0)
2803 cupsdCloseClient(con
);
2807 if (con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
)
2808 httpFlushWrite(HTTP(con
));
2810 con
->bytes
+= bytes
;
2812 if (con
->http
.state
== HTTP_WAITING
)
2818 (con
->http
.state
!= HTTP_GET_SEND
&& con
->http
.state
!= HTTP_POST_SEND
))
2820 cupsdLogRequest(con
, HTTP_OK
);
2822 httpFlushWrite(HTTP(con
));
2824 if (con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
&& con
->sent_header
== 1)
2826 if (httpWrite2(HTTP(con
), "", 0) < 0)
2828 cupsdCloseClient(con
);
2833 con
->http
.state
= HTTP_WAITING
;
2835 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
2839 cupsdRemoveSelect(con
->file
);
2842 cupsdEndProcess(con
->pipe_pid
, 0);
2851 unlink(con
->filename
);
2852 cupsdClearString(&con
->filename
);
2857 ippDelete(con
->request
);
2858 con
->request
= NULL
;
2863 ippDelete(con
->response
);
2864 con
->response
= NULL
;
2867 cupsdClearString(&con
->command
);
2868 cupsdClearString(&con
->options
);
2869 cupsdClearString(&con
->query_string
);
2871 if (!con
->http
.keep_alive
)
2873 cupsdCloseClient(con
);
2878 con
->http
.activity
= time(NULL
);
2883 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
2886 static int /* O - 1 if modified since */
2888 cupsd_client_t
*con
, /* I - Client connection */
2889 struct stat
*filestats
) /* I - File information */
2891 char *ptr
; /* Pointer into field */
2892 time_t date
; /* Time/date value */
2893 off_t size
; /* Size/length value */
2898 ptr
= con
->http
.fields
[HTTP_FIELD_IF_MODIFIED_SINCE
];
2903 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2904 "check_if_modified(con=%p(%d), "
2905 "filestats=%p(" CUPS_LLFMT
", %d)) If-Modified-Since=\"%s\"",
2906 con
, con
->http
.fd
, filestats
, CUPS_LLCAST filestats
->st_size
,
2907 (int)filestats
->st_mtime
, ptr
);
2909 while (*ptr
!= '\0')
2911 while (isspace(*ptr
) || *ptr
== ';')
2914 if (strncasecmp(ptr
, "length=", 7) == 0)
2917 size
= strtoll(ptr
, NULL
, 10);
2919 while (isdigit(*ptr
))
2922 else if (isalpha(*ptr
))
2924 date
= httpGetDateTime(ptr
);
2925 while (*ptr
!= '\0' && *ptr
!= ';')
2932 return ((size
!= filestats
->st_size
&& size
!= 0) ||
2933 (date
< filestats
->st_mtime
&& date
!= 0) ||
2934 (size
== 0 && date
== 0));
2939 * 'compare_clients()' - Compare two client connections.
2942 static int /* O - Result of comparison */
2943 compare_clients(cupsd_client_t
*a
, /* I - First client */
2944 cupsd_client_t
*b
, /* I - Second client */
2945 void *data
) /* I - User data (not used) */
2959 * 'data_ready()' - Check whether data is available from a client.
2962 static int /* O - 1 if data is ready, 0 otherwise */
2963 data_ready(cupsd_client_t
*con
) /* I - Client */
2965 if (con
->http
.used
> 0)
2968 else if (con
->http
.tls
)
2971 if (SSL_pending((SSL
*)(con
->http
.tls
)))
2973 # elif defined(HAVE_GNUTLS)
2974 if (gnutls_record_check_pending(((http_tls_t
*)(con
->http
.tls
))->session
))
2976 # elif defined(HAVE_CDSASSL)
2977 size_t bytes
; /* Bytes that are available */
2979 if (!SSLGetBufferedReadSize(((http_tls_t
*)(con
->http
.tls
))->session
,
2980 &bytes
) && bytes
> 0)
2982 # endif /* HAVE_LIBSSL */
2984 #endif /* HAVE_SSL */
2992 * 'encrypt_client()' - Enable encryption for the client...
2995 static int /* O - 1 on success, 0 on error */
2996 encrypt_client(cupsd_client_t
*con
) /* I - Client to encrypt */
2999 SSL_CTX
*context
; /* Context for encryption */
3000 SSL
*conn
; /* Connection for encryption */
3001 BIO
*bio
; /* BIO data */
3002 unsigned long error
; /* Error code */
3005 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "encrypt_client(con=%p(%d))", con
,
3009 * Verify that we have a certificate...
3012 if (access(ServerKey
, 0) || access(ServerCertificate
, 0))
3015 * Nope, make a self-signed certificate...
3018 if (!make_certificate(con
))
3023 * Create the SSL context and accept the connection...
3026 context
= SSL_CTX_new(SSLv23_server_method());
3028 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
3029 if (SSLOptions
& CUPSD_SSL_NOEMPTY
)
3030 SSL_CTX_set_options(context
, SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
);
3031 SSL_CTX_use_PrivateKey_file(context
, ServerKey
, SSL_FILETYPE_PEM
);
3032 SSL_CTX_use_certificate_chain_file(context
, ServerCertificate
);
3034 bio
= BIO_new(_httpBIOMethods());
3035 BIO_ctrl(bio
, BIO_C_SET_FILE_PTR
, 0, (char *)HTTP(con
));
3037 conn
= SSL_new(context
);
3038 SSL_set_bio(conn
, bio
, bio
);
3040 if (SSL_accept(conn
) != 1)
3042 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to encrypt connection from %s!",
3043 con
->http
.hostname
);
3045 while ((error
= ERR_get_error()) != 0)
3046 cupsdLogMessage(CUPSD_LOG_ERROR
, "%s", ERR_error_string(error
, NULL
));
3048 SSL_CTX_free(context
);
3053 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Connection from %s now encrypted.",
3054 con
->http
.hostname
);
3056 con
->http
.tls
= conn
;
3059 # elif defined(HAVE_GNUTLS)
3060 http_tls_t
*conn
; /* TLS session object */
3061 int error
; /* Error code */
3062 gnutls_certificate_server_credentials
*credentials
;
3063 /* TLS credentials */
3066 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "encrypt_client(con=%p(%d))", con
,
3070 * Verify that we have a certificate...
3073 if (access(ServerKey
, 0) || access(ServerCertificate
, 0))
3076 * Nope, make a self-signed certificate...
3079 if (!make_certificate(con
))
3084 * Create the SSL object and perform the SSL handshake...
3087 conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
));
3092 credentials
= (gnutls_certificate_server_credentials
*)
3093 malloc(sizeof(gnutls_certificate_server_credentials
));
3094 if (credentials
== NULL
)
3096 cupsdLogMessage(CUPSD_LOG_ERROR
,
3097 "Unable to encrypt connection from %s - %s",
3098 con
->http
.hostname
, strerror(errno
));
3104 gnutls_certificate_allocate_credentials(credentials
);
3105 gnutls_certificate_set_x509_key_file(*credentials
, ServerCertificate
,
3106 ServerKey
, GNUTLS_X509_FMT_PEM
);
3108 gnutls_init(&(conn
->session
), GNUTLS_SERVER
);
3109 gnutls_set_default_priority(conn
->session
);
3110 gnutls_credentials_set(conn
->session
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
3111 gnutls_transport_set_ptr(conn
->session
, (gnutls_transport_ptr
)HTTP(con
));
3112 gnutls_transport_set_pull_function(conn
->session
, _httpReadGNUTLS
);
3113 gnutls_transport_set_push_function(conn
->session
, _httpWriteGNUTLS
);
3115 error
= gnutls_handshake(conn
->session
);
3117 if (error
!= GNUTLS_E_SUCCESS
)
3119 cupsdLogMessage(CUPSD_LOG_ERROR
,
3120 "Unable to encrypt connection from %s - %s",
3121 con
->http
.hostname
, gnutls_strerror(error
));
3123 gnutls_deinit(conn
->session
);
3124 gnutls_certificate_free_credentials(*credentials
);
3130 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Connection from %s now encrypted.",
3131 con
->http
.hostname
);
3133 conn
->credentials
= credentials
;
3134 con
->http
.tls
= conn
;
3137 # elif defined(HAVE_CDSASSL)
3138 OSStatus error
; /* Error code */
3139 http_tls_t
*conn
; /* CDSA connection information */
3142 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "encrypt_client(con=%p(%d))", con
,
3145 if ((conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
))) == NULL
)
3149 conn
->session
= NULL
;
3150 conn
->certsArray
= get_cdsa_certificate(con
);
3152 if (!conn
->certsArray
)
3155 * No keychain (yet), make a self-signed certificate...
3158 if (make_certificate(con
))
3159 conn
->certsArray
= get_cdsa_certificate(con
);
3162 if (!conn
->certsArray
)
3164 cupsdLogMessage(CUPSD_LOG_ERROR
,
3165 "Could not find signing key in keychain \"%s\"",
3167 error
= errSSLBadCert
; /* errSSLBadConfiguration is a better choice, but not available on 10.2.x */
3171 error
= SSLNewContext(true, &conn
->session
);
3174 error
= SSLSetIOFuncs(conn
->session
, _httpReadCDSA
, _httpWriteCDSA
);
3177 error
= SSLSetProtocolVersionEnabled(conn
->session
, kSSLProtocol2
, false);
3180 error
= SSLSetConnection(conn
->session
, HTTP(con
));
3183 error
= SSLSetAllowsExpiredCerts(conn
->session
, true);
3186 error
= SSLSetAllowsAnyRoot(conn
->session
, true);
3189 error
= SSLSetCertificate(conn
->session
, conn
->certsArray
);
3194 * Perform SSL/TLS handshake
3197 while ((error
= SSLHandshake(conn
->session
)) == errSSLWouldBlock
)
3203 cupsdLogMessage(CUPSD_LOG_ERROR
,
3204 "Unable to encrypt connection from %s - %s (%d)",
3205 con
->http
.hostname
, cssmErrorString(error
), (int)error
);
3207 con
->http
.error
= error
;
3208 con
->http
.status
= HTTP_ERROR
;
3211 SSLDisposeContext(conn
->session
);
3213 if (conn
->certsArray
)
3214 CFRelease(conn
->certsArray
);
3221 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Connection from %s now encrypted.",
3222 con
->http
.hostname
);
3224 con
->http
.tls
= conn
;
3227 # endif /* HAVE_LIBSSL */
3229 #endif /* HAVE_SSL */
3234 * 'get_cdsa_certificate()' - Get a SSL/TLS certificate from the System keychain.
3237 static CFArrayRef
/* O - Array of certificates */
3238 get_cdsa_certificate(cupsd_client_t
*con
) /* I - Client connection */
3240 OSStatus err
; /* Error info */
3241 SecKeychainRef keychain
; /* Keychain reference */
3242 SecIdentitySearchRef search
; /* Search reference */
3243 SecIdentityRef identity
; /* Identity */
3244 CFArrayRef certificates
= NULL
;
3245 /* Certificate array */
3248 if ((err
= SecKeychainOpen(ServerCertificate
, &keychain
)))
3250 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot open keychain \"%s\" - %s (%d)",
3251 ServerCertificate
, cssmErrorString(err
), (int)err
);
3255 # if HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY
3257 * Use a policy to search for valid certificates who's common name matches the
3261 SecPolicySearchRef policy_search
; /* Policy search ref */
3262 SecPolicyRef policy
; /* Policy ref */
3263 CSSM_DATA options
; /* Policy options */
3264 CSSM_APPLE_TP_SSL_OPTIONS
3265 ssl_options
; /* SSL Option for hostname */
3268 if (SecPolicySearchCreate(CSSM_CERT_X_509v3
, &CSSMOID_APPLE_TP_SSL
,
3269 NULL
, &policy_search
))
3271 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot create a policy search reference");
3272 CFRelease(keychain
);
3276 if (SecPolicySearchCopyNext(policy_search
, &policy
))
3278 cupsdLogMessage(CUPSD_LOG_ERROR
,
3279 "Cannot find a policy to use for searching");
3280 CFRelease(keychain
);
3281 CFRelease(policy_search
);
3285 memset(&ssl_options
, 0, sizeof(ssl_options
));
3286 ssl_options
.Version
= CSSM_APPLE_TP_SSL_OPTS_VERSION
;
3287 ssl_options
.ServerName
= con
->servername
;
3288 ssl_options
.ServerNameLen
= strlen(con
->servername
);
3290 options
.Data
= (uint8
*)&ssl_options
;
3291 options
.Length
= sizeof(ssl_options
);
3293 if (SecPolicySetValue(policy
, &options
))
3295 cupsdLogMessage(CUPSD_LOG_ERROR
,
3296 "Cannot set policy value to use for searching");
3297 CFRelease(keychain
);
3298 CFRelease(policy_search
);
3302 err
= SecIdentitySearchCreateWithPolicy(policy
, NULL
, CSSM_KEYUSE_SIGN
,
3303 keychain
, FALSE
, &search
);
3306 * Assume there is exactly one SecIdentity in the keychain...
3309 err
= SecIdentitySearchCreate(keychain
, CSSM_KEYUSE_SIGN
, &search
);
3310 # endif /* HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY */
3313 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3314 "Cannot create keychain search reference: %s (%d)",
3315 cssmErrorString(err
), (int)err
);
3318 if ((err
= SecIdentitySearchCopyNext(search
, &identity
)))
3320 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3321 "Cannot find signing key in keychain \"%s\": %s (%d)",
3322 ServerCertificate
, cssmErrorString(err
), (int)err
);
3326 if (CFGetTypeID(identity
) != SecIdentityGetTypeID())
3327 cupsdLogMessage(CUPSD_LOG_ERROR
,
3328 "SecIdentitySearchCopyNext CFTypeID failure!");
3331 if ((certificates
= CFArrayCreate(NULL
, (const void **)&identity
,
3332 1, &kCFTypeArrayCallBacks
)) == NULL
)
3333 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot create certificate array");
3336 CFRelease(identity
);
3342 # if HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY
3344 CFRelease(policy_search
);
3345 # endif /* HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY */
3347 return (certificates
);
3349 #endif /* HAVE_CDSASSL */
3353 * 'get_file()' - Get a filename and state info.
3356 static char * /* O - Real filename */
3357 get_file(cupsd_client_t
*con
, /* I - Client connection */
3358 struct stat
*filestats
, /* O - File information */
3359 char *filename
, /* IO - Filename buffer */
3360 int len
) /* I - Buffer length */
3362 int status
; /* Status of filesystem calls */
3363 char *ptr
; /* Pointer info filename */
3364 int plen
; /* Remaining length after pointer */
3365 char language
[7]; /* Language subdirectory, if any */
3369 * Figure out the real filename...
3374 if (!strncmp(con
->uri
, "/ppd/", 5))
3375 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
);
3376 else if (!strncmp(con
->uri
, "/rss/", 5) && !strchr(con
->uri
+ 5, '/'))
3377 snprintf(filename
, len
, "%s/rss/%s", CacheDir
, con
->uri
+ 5);
3378 else if (!strncmp(con
->uri
, "/admin/conf/", 12))
3379 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
+ 11);
3380 else if (!strncmp(con
->uri
, "/admin/log/", 11))
3382 if (!strncmp(con
->uri
+ 11, "access_log", 10) && AccessLog
[0] == '/')
3383 strlcpy(filename
, AccessLog
, len
);
3384 else if (!strncmp(con
->uri
+ 11, "error_log", 9) && ErrorLog
[0] == '/')
3385 strlcpy(filename
, ErrorLog
, len
);
3386 else if (!strncmp(con
->uri
+ 11, "page_log", 8) && PageLog
[0] == '/')
3387 strlcpy(filename
, PageLog
, len
);
3391 else if (con
->language
)
3393 snprintf(language
, sizeof(language
), "/%s", con
->language
->language
);
3394 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3397 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3399 if ((ptr
= strchr(filename
, '?')) != NULL
)
3403 * Grab the status for this language; if there isn't a language-specific file
3404 * then fallback to the default one...
3407 if ((status
= stat(filename
, filestats
)) != 0 && language
[0] &&
3408 strncmp(con
->uri
, "/ppd/", 5) &&
3409 strncmp(con
->uri
, "/admin/conf/", 12) &&
3410 strncmp(con
->uri
, "/admin/log/", 11))
3413 * Drop the country code...
3417 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3419 if ((ptr
= strchr(filename
, '?')) != NULL
)
3422 if ((status
= stat(filename
, filestats
)) != 0)
3425 * Drop the language prefix and try the root directory...
3429 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3431 if ((ptr
= strchr(filename
, '?')) != NULL
)
3434 status
= stat(filename
, filestats
);
3439 * If we're found a directory, get the index.html file instead...
3442 if (!status
&& S_ISDIR(filestats
->st_mode
))
3445 * Make sure the URI ends with a slash...
3448 if (con
->uri
[strlen(con
->uri
) - 1] != '/')
3449 strlcat(con
->uri
, "/", sizeof(con
->uri
));
3452 * Find the directory index file, trying every language...
3457 if (status
&& language
[0])
3460 * Try a different language subset...
3464 language
[0] = '\0'; /* Strip country code */
3466 language
[0] = '\0'; /* Strip language */
3470 * Look for the index file...
3473 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3475 if ((ptr
= strchr(filename
, '?')) != NULL
)
3478 ptr
= filename
+ strlen(filename
);
3479 plen
= len
- (ptr
- filename
);
3481 strlcpy(ptr
, "index.html", plen
);
3482 status
= stat(filename
, filestats
);
3487 strlcpy(ptr
, "index.class", plen
);
3488 status
= stat(filename
, filestats
);
3490 #endif /* HAVE_JAVA */
3495 strlcpy(ptr
, "index.pl", plen
);
3496 status
= stat(filename
, filestats
);
3498 #endif /* HAVE_PERL */
3503 strlcpy(ptr
, "index.php", plen
);
3504 status
= stat(filename
, filestats
);
3506 #endif /* HAVE_PHP */
3511 strlcpy(ptr
, "index.pyc", plen
);
3512 status
= stat(filename
, filestats
);
3517 strlcpy(ptr
, "index.py", plen
);
3518 status
= stat(filename
, filestats
);
3520 #endif /* HAVE_PYTHON */
3523 while (status
&& language
[0]);
3526 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3527 "get_file(con=%p(%d), filestats=%p, filename=%p, len=%d) = "
3528 "%s", con
, con
->http
.fd
, filestats
, filename
, len
,
3529 status
? "(null)" : filename
);
3532 con
->http
.data_remaining
= (int)filestats
->st_size
;
3542 * 'install_conf_file()' - Install a configuration file.
3545 static http_status_t
/* O - Status */
3546 install_conf_file(cupsd_client_t
*con
) /* I - Connection */
3548 cups_file_t
*in
, /* Input file */
3549 *out
; /* Output file */
3550 char buffer
[1024]; /* Copy buffer */
3551 int bytes
; /* Number of bytes */
3552 char conffile
[1024], /* Configuration filename */
3553 newfile
[1024], /* New config filename */
3554 oldfile
[1024]; /* Old config filename */
3555 struct stat confinfo
; /* Config file info */
3559 * First construct the filenames...
3562 snprintf(conffile
, sizeof(conffile
), "%s%s", ServerRoot
, con
->uri
+ 11);
3563 snprintf(newfile
, sizeof(newfile
), "%s%s.N", ServerRoot
, con
->uri
+ 11);
3564 snprintf(oldfile
, sizeof(oldfile
), "%s%s.O", ServerRoot
, con
->uri
+ 11);
3566 cupsdLogMessage(CUPSD_LOG_INFO
, "Installing config file \"%s\"...", conffile
);
3569 * Get the owner, group, and permissions of the configuration file.
3570 * If it doesn't exist, assign it to the User and Group in the
3571 * cupsd.conf file with mode 0640 permissions.
3574 if (stat(conffile
, &confinfo
))
3576 confinfo
.st_uid
= User
;
3577 confinfo
.st_gid
= Group
;
3578 confinfo
.st_mode
= ConfigFilePerm
;
3582 * Open the request file and new config file...
3585 if ((in
= cupsFileOpen(con
->filename
, "rb")) == NULL
)
3587 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open request file \"%s\" - %s",
3588 con
->filename
, strerror(errno
));
3589 return (HTTP_SERVER_ERROR
);
3592 if ((out
= cupsFileOpen(newfile
, "wb")) == NULL
)
3595 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open config file \"%s\" - %s",
3596 newfile
, strerror(errno
));
3597 return (HTTP_SERVER_ERROR
);
3600 fchmod(cupsFileNumber(out
), confinfo
.st_mode
);
3601 fchown(cupsFileNumber(out
), confinfo
.st_uid
, confinfo
.st_gid
);
3604 * Copy from the request to the new config file...
3607 while ((bytes
= cupsFileRead(in
, buffer
, sizeof(buffer
))) > 0)
3608 if (cupsFileWrite(out
, buffer
, bytes
) < bytes
)
3610 cupsdLogMessage(CUPSD_LOG_ERROR
,
3611 "Unable to copy to config file \"%s\" - %s",
3612 newfile
, strerror(errno
));
3618 return (HTTP_SERVER_ERROR
);
3622 * Close the files...
3626 if (cupsFileClose(out
))
3628 cupsdLogMessage(CUPSD_LOG_ERROR
,
3629 "Error file closing config file \"%s\" - %s",
3630 newfile
, strerror(errno
));
3634 return (HTTP_SERVER_ERROR
);
3638 * Remove the request file...
3641 unlink(con
->filename
);
3642 cupsdClearString(&con
->filename
);
3645 * Unlink the old backup, rename the current config file to the backup
3646 * filename, and rename the new config file to the config file name...
3649 if (unlink(oldfile
))
3650 if (errno
!= ENOENT
)
3652 cupsdLogMessage(CUPSD_LOG_ERROR
,
3653 "Unable to remove backup config file \"%s\" - %s",
3654 oldfile
, strerror(errno
));
3658 return (HTTP_SERVER_ERROR
);
3661 if (rename(conffile
, oldfile
))
3662 if (errno
!= ENOENT
)
3664 cupsdLogMessage(CUPSD_LOG_ERROR
,
3665 "Unable to rename old config file \"%s\" - %s",
3666 conffile
, strerror(errno
));
3670 return (HTTP_SERVER_ERROR
);
3673 if (rename(newfile
, conffile
))
3675 cupsdLogMessage(CUPSD_LOG_ERROR
,
3676 "Unable to rename new config file \"%s\" - %s",
3677 newfile
, strerror(errno
));
3679 rename(oldfile
, conffile
);
3682 return (HTTP_SERVER_ERROR
);
3686 * If the cupsd.conf file was updated, set the NeedReload flag...
3689 if (!strcmp(con
->uri
, "/admin/conf/cupsd.conf"))
3690 NeedReload
= RELOAD_CUPSD
;
3692 NeedReload
= RELOAD_ALL
;
3694 ReloadTime
= time(NULL
);
3697 * Return that the file was created successfully...
3700 return (HTTP_CREATED
);
3705 * 'is_cgi()' - Is the resource a CGI script/program?
3708 static int /* O - 1 = CGI, 0 = file */
3709 is_cgi(cupsd_client_t
*con
, /* I - Client connection */
3710 const char *filename
, /* I - Real filename */
3711 struct stat
*filestats
, /* I - File information */
3712 mime_type_t
*type
) /* I - MIME type */
3714 const char *options
; /* Options on URL */
3718 * Get the options, if any...
3721 if ((options
= strchr(con
->uri
, '?')) != NULL
)
3724 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", options
);
3728 * Check for known types...
3731 if (!type
|| strcasecmp(type
->super
, "application"))
3733 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3734 "is_cgi(con=%p(%d), filename=\"%s\", filestats=%p, "
3735 "type=%s/%s) = 0", con
, con
->http
.fd
, filename
, filestats
,
3736 type
? type
->super
: "unknown",
3737 type
? type
->type
: "unknown");
3741 if (!strcasecmp(type
->type
, "x-httpd-cgi") &&
3742 (filestats
->st_mode
& 0111))
3745 * "application/x-httpd-cgi" is a CGI script.
3748 cupsdSetString(&con
->command
, filename
);
3751 cupsdSetStringf(&con
->options
, " %s", options
);
3753 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3754 "is_cgi(con=%p(%d), filename=\"%s\", filestats=%p, "
3755 "type=%s/%s) = 1", con
, con
->http
.fd
, filename
, filestats
,
3756 type
? type
->super
: "unknown",
3757 type
? type
->type
: "unknown");
3761 else if (!strcasecmp(type
->type
, "x-httpd-java"))
3764 * "application/x-httpd-java" is a Java servlet.
3767 cupsdSetString(&con
->command
, CUPS_JAVA
);
3770 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3772 cupsdSetStringf(&con
->options
, " %s", filename
);
3774 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3775 "is_cgi(con=%p(%d), filename=\"%s\", filestats=%p, "
3776 "type=%s/%s) = 1", con
, con
->http
.fd
, filename
, filestats
,
3777 type
? type
->super
: "unknown",
3778 type
? type
->type
: "unknown");
3781 #endif /* HAVE_JAVA */
3783 else if (!strcasecmp(type
->type
, "x-httpd-perl"))
3786 * "application/x-httpd-perl" is a Perl page.
3789 cupsdSetString(&con
->command
, CUPS_PERL
);
3792 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3794 cupsdSetStringf(&con
->options
, " %s", filename
);
3796 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3797 "is_cgi(con=%p(%d), filename=\"%s\", filestats=%p, "
3798 "type=%s/%s) = 1", con
, con
->http
.fd
, filename
, filestats
,
3799 type
? type
->super
: "unknown",
3800 type
? type
->type
: "unknown");
3803 #endif /* HAVE_PERL */
3805 else if (!strcasecmp(type
->type
, "x-httpd-php"))
3808 * "application/x-httpd-php" is a PHP page.
3811 cupsdSetString(&con
->command
, CUPS_PHP
);
3814 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3816 cupsdSetStringf(&con
->options
, " %s", filename
);
3818 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3819 "is_cgi(con=%p(%d), filename=\"%s\", filestats=%p, "
3820 "type=%s/%s) = 1", con
, con
->http
.fd
, filename
, filestats
,
3821 type
? type
->super
: "unknown",
3822 type
? type
->type
: "unknown");
3825 #endif /* HAVE_PHP */
3827 else if (!strcasecmp(type
->type
, "x-httpd-python"))
3830 * "application/x-httpd-python" is a Python page.
3833 cupsdSetString(&con
->command
, CUPS_PYTHON
);
3836 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3838 cupsdSetStringf(&con
->options
, " %s", filename
);
3840 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3841 "is_cgi(con=%p(%d), filename=\"%s\", filestats=%p, "
3842 "type=%s/%s) = 1", con
, con
->http
.fd
, filename
, filestats
,
3843 type
? type
->super
: "unknown",
3844 type
? type
->type
: "unknown");
3847 #endif /* HAVE_PYTHON */
3849 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3850 "is_cgi(con=%p(%d), filename=\"%s\", filestats=%p, "
3851 "type=%s/%s) = 0", con
, con
->http
.fd
, filename
, filestats
,
3852 type
? type
->super
: "unknown",
3853 type
? type
->type
: "unknown");
3859 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
3862 static int /* O - 0 if relative, 1 if absolute */
3863 is_path_absolute(const char *path
) /* I - Input path */
3866 * Check for a leading slash...
3873 * Check for "/.." in the path...
3876 while ((path
= strstr(path
, "/..")) != NULL
)
3878 if (!path
[3] || path
[3] == '/')
3885 * If we haven't found any relative paths, return 1 indicating an
3895 * 'make_certificate()' - Make a self-signed SSL/TLS certificate.
3898 static int /* O - 1 on success, 0 on failure */
3899 make_certificate(cupsd_client_t
*con
) /* I - Client connection */
3901 #if defined(HAVE_LIBSSL) && defined(HAVE_WAITPID)
3902 int pid
, /* Process ID of command */
3903 status
; /* Status of command */
3904 char command
[1024], /* Command */
3905 *argv
[12], /* Command-line arguments */
3906 *envp
[MAX_ENV
+ 1], /* Environment variables */
3907 home
[1024], /* HOME environment variable */
3908 infofile
[1024], /* Type-in information for cert */
3909 seedfile
[1024]; /* Random number seed file */
3910 int envc
, /* Number of environment variables */
3911 bytes
; /* Bytes written */
3912 cups_file_t
*fp
; /* Seed/info file */
3913 int infofd
; /* Info file descriptor */
3917 * Run the "openssl" command to seed the random number generator and
3918 * generate a self-signed certificate that is good for 10 years:
3920 * openssl rand -rand seedfile 1
3922 * openssl req -new -x509 -keyout ServerKey \
3923 * -out ServerCertificate -days 3650 -nodes
3925 * The seeding step is crucial in ensuring that the openssl command
3926 * does not block on systems without sufficient entropy...
3929 if (!cupsFileFind("openssl", getenv("PATH"), 1, command
, sizeof(command
)))
3931 cupsdLogMessage(CUPSD_LOG_ERROR
,
3932 "No SSL certificate and openssl command not found!");
3936 if (access("/dev/urandom", 0))
3939 * If the system doesn't provide /dev/urandom, then any random source
3940 * will probably be blocking-style, so generate some random data to
3941 * use as a seed for the certificate. Note that we have already
3942 * seeded the random number generator in cupsdInitCerts()...
3945 cupsdLogMessage(CUPSD_LOG_INFO
,
3946 "Seeding the random number generator...");
3948 snprintf(home
, sizeof(home
), "HOME=%s", TempDir
);
3951 * Write the seed file...
3954 if ((fp
= cupsTempFile2(seedfile
, sizeof(seedfile
))) == NULL
)
3956 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to create seed file %s - %s",
3957 seedfile
, strerror(errno
));
3961 for (bytes
= 0; bytes
< 262144; bytes
++)
3962 cupsFilePutChar(fp
, random());
3967 * Run the openssl command to seed its random number generator...
3970 argv
[0] = "openssl";
3977 envc
= cupsdLoadEnv(envp
, MAX_ENV
);
3978 envp
[envc
++] = home
;
3981 if (!cupsdStartProcess(command
, argv
, envp
, -1, -1, -1, -1, -1, 1, NULL
, 0,
3988 while (waitpid(pid
, &status
, 0) < 0)
3995 cupsdFinishProcess(pid
, command
, sizeof(command
), NULL
);
3998 * Remove the seed file, as it is no longer needed...
4005 if (WIFEXITED(status
))
4006 cupsdLogMessage(CUPSD_LOG_ERROR
,
4007 "Unable to seed random number generator - "
4008 "the openssl command stopped with status %d!",
4009 WEXITSTATUS(status
));
4011 cupsdLogMessage(CUPSD_LOG_ERROR
,
4012 "Unable to seed random number generator - "
4013 "the openssl command crashed on signal %d!",
4021 * Create a file with the certificate information fields...
4023 * Note: This assumes that the default questions are asked by the openssl
4027 if ((fp
= cupsTempFile2(infofile
, sizeof(infofile
))) == NULL
)
4029 cupsdLogMessage(CUPSD_LOG_ERROR
,
4030 "Unable to create certificate information file %s - %s",
4031 infofile
, strerror(errno
));
4035 cupsFilePrintf(fp
, ".\n.\n.\n%s\n.\n%s\n%s\n",
4036 ServerName
, ServerName
, ServerAdmin
);
4039 cupsdLogMessage(CUPSD_LOG_INFO
,
4040 "Generating SSL server key and certificate...");
4042 argv
[0] = "openssl";
4046 argv
[4] = "-keyout";
4047 argv
[5] = ServerKey
;
4049 argv
[7] = ServerCertificate
;
4052 argv
[10] = "-nodes";
4055 cupsdLoadEnv(envp
, MAX_ENV
);
4057 infofd
= open(infofile
, O_RDONLY
);
4059 if (!cupsdStartProcess(command
, argv
, envp
, infofd
, -1, -1, -1, -1, 1, NULL
,
4070 while (waitpid(pid
, &status
, 0) < 0)
4077 cupsdFinishProcess(pid
, command
, sizeof(command
), NULL
);
4081 if (WIFEXITED(status
))
4082 cupsdLogMessage(CUPSD_LOG_ERROR
,
4083 "Unable to create SSL server key and certificate - "
4084 "the openssl command stopped with status %d!",
4085 WEXITSTATUS(status
));
4087 cupsdLogMessage(CUPSD_LOG_ERROR
,
4088 "Unable to create SSL server key and certificate - "
4089 "the openssl command crashed on signal %d!",
4094 cupsdLogMessage(CUPSD_LOG_INFO
, "Created SSL server key file \"%s\"...",
4096 cupsdLogMessage(CUPSD_LOG_INFO
,
4097 "Created SSL server certificate file \"%s\"...",
4103 #elif defined(HAVE_GNUTLS)
4104 gnutls_x509_crt crt
; /* Self-signed certificate */
4105 gnutls_x509_privkey key
; /* Encryption key */
4106 cups_lang_t
*language
; /* Default language info */
4107 cups_file_t
*fp
; /* Key/cert file */
4108 unsigned char buffer
[8192]; /* Buffer for x509 data */
4109 size_t bytes
; /* Number of bytes of data */
4110 unsigned char serial
[4]; /* Serial number buffer */
4111 time_t curtime
; /* Current time */
4112 int result
; /* Result of GNU TLS calls */
4116 * Create the encryption key...
4119 cupsdLogMessage(CUPSD_LOG_INFO
, "Generating SSL server key...");
4121 gnutls_x509_privkey_init(&key
);
4122 gnutls_x509_privkey_generate(key
, GNUTLS_PK_RSA
, 2048, 0);
4128 bytes
= sizeof(buffer
);
4130 if ((result
= gnutls_x509_privkey_export(key
, GNUTLS_X509_FMT_PEM
,
4131 buffer
, &bytes
)) < 0)
4133 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to export SSL server key - %s",
4134 gnutls_strerror(result
));
4135 gnutls_x509_privkey_deinit(key
);
4138 else if ((fp
= cupsFileOpen(ServerKey
, "w")) != NULL
)
4140 cupsFileWrite(fp
, (char *)buffer
, bytes
);
4143 cupsdLogMessage(CUPSD_LOG_INFO
, "Created SSL server key file \"%s\"...",
4148 cupsdLogMessage(CUPSD_LOG_ERROR
,
4149 "Unable to create SSL server key file \"%s\" - %s",
4150 ServerKey
, strerror(errno
));
4151 gnutls_x509_privkey_deinit(key
);
4156 * Create the self-signed certificate...
4159 cupsdLogMessage(CUPSD_LOG_INFO
, "Generating self-signed SSL certificate...");
4161 language
= cupsLangDefault();
4162 curtime
= time(NULL
);
4163 serial
[0] = curtime
>> 24;
4164 serial
[1] = curtime
>> 16;
4165 serial
[2] = curtime
>> 8;
4166 serial
[3] = curtime
;
4168 gnutls_x509_crt_init(&crt
);
4169 if (strlen(language
->language
) == 5)
4170 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
4171 language
->language
+ 3, 2);
4173 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
4175 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COMMON_NAME
, 0,
4176 ServerName
, strlen(ServerName
));
4177 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATION_NAME
, 0,
4178 ServerName
, strlen(ServerName
));
4179 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATIONAL_UNIT_NAME
,
4181 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_STATE_OR_PROVINCE_NAME
, 0,
4183 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_LOCALITY_NAME
, 0,
4185 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_PKCS9_EMAIL
, 0,
4186 ServerAdmin
, strlen(ServerAdmin
));
4187 gnutls_x509_crt_set_key(crt
, key
);
4188 gnutls_x509_crt_set_serial(crt
, serial
, sizeof(serial
));
4189 gnutls_x509_crt_set_activation_time(crt
, curtime
);
4190 gnutls_x509_crt_set_expiration_time(crt
, curtime
+ 10 * 365 * 86400);
4191 gnutls_x509_crt_set_ca_status(crt
, 0);
4192 gnutls_x509_crt_set_subject_alternative_name(crt
, GNUTLS_SAN_DNSNAME
,
4194 gnutls_x509_crt_set_key_purpose_oid(crt
, GNUTLS_KP_TLS_WWW_SERVER
, 0);
4195 gnutls_x509_crt_set_key_usage(crt
, GNUTLS_KEY_KEY_ENCIPHERMENT
);
4196 gnutls_x509_crt_set_version(crt
, 3);
4198 bytes
= sizeof(buffer
);
4199 if (gnutls_x509_crt_get_key_id(crt
, 0, buffer
, &bytes
) >= 0)
4200 gnutls_x509_crt_set_subject_key_id(crt
, buffer
, bytes
);
4202 gnutls_x509_crt_sign(crt
, crt
, key
);
4208 bytes
= sizeof(buffer
);
4209 if ((result
= gnutls_x509_crt_export(crt
, GNUTLS_X509_FMT_PEM
,
4210 buffer
, &bytes
)) < 0)
4211 cupsdLogMessage(CUPSD_LOG_ERROR
,
4212 "Unable to export SSL server certificate - %s",
4213 gnutls_strerror(result
));
4214 else if ((fp
= cupsFileOpen(ServerCertificate
, "w")) != NULL
)
4216 cupsFileWrite(fp
, (char *)buffer
, bytes
);
4219 cupsdLogMessage(CUPSD_LOG_INFO
,
4220 "Created SSL server certificate file \"%s\"...",
4224 cupsdLogMessage(CUPSD_LOG_ERROR
,
4225 "Unable to create SSL server certificate file \"%s\" - %s",
4226 ServerCertificate
, strerror(errno
));
4232 gnutls_x509_crt_deinit(crt
);
4233 gnutls_x509_privkey_deinit(key
);
4237 #elif defined(HAVE_CDSASSL) && defined(HAVE_WAITPID)
4238 int pid
, /* Process ID of command */
4239 status
; /* Status of command */
4240 char command
[1024], /* Command */
4241 *argv
[4], /* Command-line arguments */
4242 *envp
[MAX_ENV
+ 1], /* Environment variables */
4243 keychain
[1024], /* Keychain argument */
4244 infofile
[1024]; /* Type-in information for cert */
4245 cups_file_t
*fp
; /* Seed/info file */
4246 int infofd
; /* Info file descriptor */
4250 * Run the "certtool" command to generate a self-signed certificate...
4253 if (!cupsFileFind("certtool", getenv("PATH"), 1, command
, sizeof(command
)))
4255 cupsdLogMessage(CUPSD_LOG_ERROR
,
4256 "No SSL certificate and certtool command not found!");
4261 * Create a file with the certificate information fields...
4263 * Note: This assumes that the default questions are asked by the certtool
4267 if ((fp
= cupsTempFile2(infofile
, sizeof(infofile
))) == NULL
)
4269 cupsdLogMessage(CUPSD_LOG_ERROR
,
4270 "Unable to create certificate information file %s - %s",
4271 infofile
, strerror(errno
));
4275 cupsFilePrintf(fp
, "%s\nr\n\ny\nb\ns\ny\n%s\n\n\n\n\n%s\ny\n",
4276 con
->servername
, con
->servername
, ServerAdmin
);
4279 cupsdLogMessage(CUPSD_LOG_INFO
,
4280 "Generating SSL server key and certificate...");
4282 snprintf(keychain
, sizeof(keychain
), "k=%s", ServerCertificate
);
4284 argv
[0] = "certtool";
4289 cupsdLoadEnv(envp
, MAX_ENV
);
4291 infofd
= open(infofile
, O_RDONLY
);
4293 if (!cupsdStartProcess(command
, argv
, envp
, infofd
, -1, -1, -1, -1, 1, NULL
,
4304 while (waitpid(pid
, &status
, 0) < 0)
4311 cupsdFinishProcess(pid
, command
, sizeof(command
), NULL
);
4315 if (WIFEXITED(status
))
4316 cupsdLogMessage(CUPSD_LOG_ERROR
,
4317 "Unable to create SSL server key and certificate - "
4318 "the certtool command stopped with status %d!",
4319 WEXITSTATUS(status
));
4321 cupsdLogMessage(CUPSD_LOG_ERROR
,
4322 "Unable to create SSL server key and certificate - "
4323 "the certtool command crashed on signal %d!",
4328 cupsdLogMessage(CUPSD_LOG_INFO
,
4329 "Created SSL server certificate file \"%s\"...",
4337 #endif /* HAVE_LIBSSL && HAVE_WAITPID */
4339 #endif /* HAVE_SSL */
4343 * 'pipe_command()' - Pipe the output of a command to the remote client.
4346 static int /* O - Process ID */
4347 pipe_command(cupsd_client_t
*con
, /* I - Client connection */
4348 int infile
, /* I - Standard input for command */
4349 int *outfile
, /* O - Standard output for command */
4350 char *command
, /* I - Command to run */
4351 char *options
, /* I - Options for command */
4352 int root
) /* I - Run as root? */
4354 int i
; /* Looping var */
4355 int pid
; /* Process ID */
4356 char *commptr
, /* Command string pointer */
4357 commch
; /* Command string character */
4358 char *uriptr
; /* URI string pointer */
4359 int fds
[2]; /* Pipe FDs */
4360 int argc
; /* Number of arguments */
4361 int envc
; /* Number of environment variables */
4362 char argbuf
[10240], /* Argument buffer */
4363 *argv
[100], /* Argument strings */
4364 *envp
[MAX_ENV
+ 20]; /* Environment variables */
4365 char auth_type
[256], /* CUPSD_AUTH_TYPE environment variable */
4366 content_length
[1024], /* CONTENT_LENGTH environment variable */
4367 content_type
[1024], /* CONTENT_TYPE environment variable */
4368 http_cookie
[32768], /* HTTP_COOKIE environment variable */
4369 http_referer
[1024], /* HTTP_REFERER environment variable */
4370 http_user_agent
[1024], /* HTTP_USER_AGENT environment variable */
4371 lang
[1024], /* LANG environment variable */
4372 path_info
[1024], /* PATH_INFO environment variable */
4373 remote_addr
[1024], /* REMOTE_ADDR environment variable */
4374 remote_host
[1024], /* REMOTE_HOST environment variable */
4375 remote_user
[1024], /* REMOTE_USER environment variable */
4376 script_filename
[1024], /* SCRIPT_FILENAME environment variable */
4377 script_name
[1024], /* SCRIPT_NAME environment variable */
4378 server_name
[1024], /* SERVER_NAME environment variable */
4379 server_port
[1024]; /* SERVER_PORT environment variable */
4380 ipp_attribute_t
*attr
; /* attributes-natural-language attribute */
4382 krb5_ccache ccache
= NULL
; /* Kerberos credentials */
4383 # if defined(HAVE_KRB5_CC_NEW_UNIQUE) || defined(HAVE_HEIMDAL)
4384 char krb5ccname
[1024]; /* KRB5CCNAME environment variable */
4385 # endif /* HAVE_KRB5_CC_NEW_UNIQUE || HAVE_HEIMDAL */
4386 #endif /* HAVE_GSSAPI */
4390 * Parse a copy of the options string, which is of the form:
4392 * argument+argument+argument
4393 * ?argument+argument+argument
4394 * param=value¶m=value
4395 * ?param=value¶m=value
4396 * /name?argument+argument+argument
4397 * /name?param=value¶m=value
4399 * If the string contains an "=" character after the initial name,
4400 * then we treat it as a HTTP GET form request and make a copy of
4401 * the remaining string for the environment variable.
4403 * The string is always parsed out as command-line arguments, to
4404 * be consistent with Apache...
4407 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4408 "pipe_command(con=%p(%d), infile=%d, outfile=%p, "
4409 "command=\"%s\", options=\"%s\", root=%d)",
4410 con
, con
->http
.fd
, infile
, outfile
, command
,
4411 options
? options
: "(null)", root
);
4416 strlcpy(argbuf
, options
, sizeof(argbuf
));
4420 if (argbuf
[0] == '/')
4423 * Found some trailing path information, set PATH_INFO...
4426 if ((commptr
= strchr(argbuf
, '?')) == NULL
)
4427 commptr
= argbuf
+ strlen(argbuf
);
4431 snprintf(path_info
, sizeof(path_info
), "PATH_INFO=%s", argbuf
);
4437 path_info
[0] = '\0';
4439 if (*commptr
== ' ')
4443 if (*commptr
== '?' && con
->operation
== HTTP_GET
&& !con
->query_string
)
4446 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", commptr
);
4453 argv
[argc
++] = commptr
;
4455 for (; *commptr
&& argc
< 99; commptr
++)
4458 * Break arguments whenever we see a + or space...
4461 if (*commptr
== ' ' || *commptr
== '+')
4463 while (*commptr
== ' ' || *commptr
== '+')
4467 * If we don't have a blank string, save it as another argument...
4472 argv
[argc
] = commptr
;
4478 else if (*commptr
== '%' && isxdigit(commptr
[1] & 255) &&
4479 isxdigit(commptr
[2] & 255))
4482 * Convert the %xx notation to the individual character.
4485 if (commptr
[1] >= '0' && commptr
[1] <= '9')
4486 *commptr
= (commptr
[1] - '0') << 4;
4488 *commptr
= (tolower(commptr
[1]) - 'a' + 10) << 4;
4490 if (commptr
[2] >= '0' && commptr
[2] <= '9')
4491 *commptr
|= commptr
[2] - '0';
4493 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
4495 _cups_strcpy(commptr
+ 1, commptr
+ 3);
4498 * Check for a %00 and break if that is the case...
4510 * Setup the environment variables as needed...
4513 if (con
->username
[0])
4515 snprintf(auth_type
, sizeof(auth_type
), "CUPSD_AUTH_TYPE=%s",
4516 httpGetField(HTTP(con
), HTTP_FIELD_AUTHORIZATION
));
4518 if ((uriptr
= strchr(auth_type
+ 10, ' ')) != NULL
)
4522 auth_type
[0] = '\0';
4525 (attr
= ippFindAttribute(con
->request
, "attributes-natural-language",
4526 IPP_TAG_LANGUAGE
)) != NULL
)
4528 switch (strlen(attr
->values
[0].string
.text
))
4532 * This is an unknown or badly formatted language code; use
4533 * the POSIX locale...
4536 strcpy(lang
, "LANG=C");
4541 * Just the language code (ll)...
4544 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8",
4545 attr
->values
[0].string
.text
);
4550 * Language and country code (ll-cc)...
4553 snprintf(lang
, sizeof(lang
), "LANG=%c%c_%c%c.UTF8",
4554 attr
->values
[0].string
.text
[0],
4555 attr
->values
[0].string
.text
[1],
4556 toupper(attr
->values
[0].string
.text
[3] & 255),
4557 toupper(attr
->values
[0].string
.text
[4] & 255));
4561 else if (con
->language
)
4562 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8", con
->language
->language
);
4564 strcpy(lang
, "LANG=C");
4566 strcpy(remote_addr
, "REMOTE_ADDR=");
4567 httpAddrString(con
->http
.hostaddr
, remote_addr
+ 12,
4568 sizeof(remote_addr
) - 12);
4570 snprintf(remote_host
, sizeof(remote_host
), "REMOTE_HOST=%s",
4571 con
->http
.hostname
);
4573 snprintf(script_name
, sizeof(script_name
), "SCRIPT_NAME=%s", con
->uri
);
4574 if ((uriptr
= strchr(script_name
, '?')) != NULL
)
4577 snprintf(script_filename
, sizeof(script_filename
), "SCRIPT_FILENAME=%s%s",
4578 DocumentRoot
, script_name
+ 12);
4580 sprintf(server_port
, "SERVER_PORT=%d", con
->serverport
);
4582 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
4585 envc
= cupsdLoadEnv(envp
, (int)(sizeof(envp
) / sizeof(envp
[0])));
4588 envp
[envc
++] = auth_type
;
4590 envp
[envc
++] = lang
;
4591 envp
[envc
++] = "REDIRECT_STATUS=1";
4592 envp
[envc
++] = "GATEWAY_INTERFACE=CGI/1.1";
4593 envp
[envc
++] = server_name
;
4594 envp
[envc
++] = server_port
;
4595 envp
[envc
++] = remote_addr
;
4596 envp
[envc
++] = remote_host
;
4597 envp
[envc
++] = script_name
;
4598 envp
[envc
++] = script_filename
;
4601 envp
[envc
++] = path_info
;
4603 if (con
->username
[0])
4605 snprintf(remote_user
, sizeof(remote_user
), "REMOTE_USER=%s", con
->username
);
4607 envp
[envc
++] = remote_user
;
4610 * Save Kerberos credentials, if any...
4614 if (con
->gss_have_creds
)
4616 # if !defined(HAVE_KRB5_CC_NEW_UNIQUE) && !defined(HAVE_HEIMDAL)
4617 cupsdLogMessage(CUPSD_LOG_INFO
,
4618 "Sorry, your version of Kerberos does not support "
4619 "delegated credentials!");
4622 krb5_error_code error
; /* Kerberos error code */
4623 OM_uint32 major_status
, /* Major status code */
4624 minor_status
; /* Minor status code */
4625 krb5_principal principal
; /* Kerberos principal */
4630 * If the weak-linked GSSAPI/Kerberos library is not present, don't try
4634 if (krb5_init_context
!= NULL
)
4636 # endif /* __APPLE__ */
4638 if (!KerberosInitialized
)
4641 * Setup a Kerberos context for the scheduler to use...
4644 KerberosInitialized
= 1;
4646 if (krb5_init_context(&KerberosContext
))
4648 KerberosContext
= NULL
;
4650 cupsdLogMessage(CUPSD_LOG_ERROR
,
4651 "Unable to initialize Kerberos context");
4656 * We MUST create a file-based cache because memory-based caches are
4657 * only valid for the current process/address space.
4659 * Due to various bugs/features in different versions of Kerberos, we
4660 * need either the krb5_cc_new_unique() function or Heimdal's version
4661 * of krb5_cc_gen_new() to create a new FILE: credential cache that
4662 * can be passed to the backend. These functions create a temporary
4663 * file (typically in /tmp) containing the cached credentials, which
4664 * are removed when we have successfully printed a job.
4667 if (KerberosContext
)
4669 # ifdef HAVE_KRB5_CC_NEW_UNIQUE
4670 if ((error
= krb5_cc_new_unique(KerberosContext
, "FILE", NULL
,
4672 # else /* HAVE_HEIMDAL */
4673 if ((error
= krb5_cc_gen_new(KerberosContext
, &krb5_fcc_ops
,
4675 # endif /* HAVE_KRB5_CC_NEW_UNIQUE */
4677 cupsdLogMessage(CUPSD_LOG_ERROR
,
4678 "Unable to create new credentials cache (%d/%s)",
4679 error
, strerror(errno
));
4682 else if ((error
= krb5_parse_name(KerberosContext
, con
->username
,
4685 cupsdLogMessage(CUPSD_LOG_ERROR
,
4686 "Unable to parse kerberos username (%d/%s)", error
,
4688 krb5_cc_destroy(KerberosContext
, ccache
);
4691 else if ((error
= krb5_cc_initialize(KerberosContext
, ccache
,
4694 cupsdLogMessage(CUPSD_LOG_ERROR
,
4695 "Unable to initialize credentials cache (%d/%s)",
4696 error
, strerror(errno
));
4697 krb5_cc_destroy(KerberosContext
, ccache
);
4698 krb5_free_principal(KerberosContext
, principal
);
4703 krb5_free_principal(KerberosContext
, principal
);
4706 * Copy the user's credentials to the new cache file...
4709 major_status
= gss_krb5_copy_ccache(&minor_status
,
4710 con
->gss_delegated_cred
, ccache
);
4712 if (GSS_ERROR(major_status
))
4714 cupsdLogGSSMessage(CUPSD_LOG_ERROR
, major_status
, minor_status
,
4715 "Unable to import client credentials cache");
4716 krb5_cc_destroy(KerberosContext
, ccache
);
4722 * Add the KRB5CCNAME environment variable to the job so that the
4723 * backend can use the credentials when printing.
4726 snprintf(krb5ccname
, sizeof(krb5ccname
), "KRB5CCNAME=FILE:%s",
4727 krb5_cc_get_name(KerberosContext
, ccache
));
4728 envp
[envc
++] = krb5ccname
;
4731 chown(krb5_cc_get_name(KerberosContext
, ccache
), User
, Group
);
4737 # endif /* __APPLE__ */
4738 # endif /* HAVE_KRB5_CC_NEW_UNIQUE || HAVE_HEIMDAL */
4740 #endif /* HAVE_GSSAPI */
4743 if (con
->http
.version
== HTTP_1_1
)
4744 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.1";
4745 else if (con
->http
.version
== HTTP_1_0
)
4746 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.0";
4748 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/0.9";
4750 if (con
->http
.cookie
)
4752 snprintf(http_cookie
, sizeof(http_cookie
), "HTTP_COOKIE=%s",
4754 envp
[envc
++] = http_cookie
;
4757 if (con
->http
.fields
[HTTP_FIELD_USER_AGENT
][0])
4759 snprintf(http_user_agent
, sizeof(http_user_agent
), "HTTP_USER_AGENT=%s",
4760 con
->http
.fields
[HTTP_FIELD_USER_AGENT
]);
4761 envp
[envc
++] = http_user_agent
;
4764 if (con
->http
.fields
[HTTP_FIELD_REFERER
][0])
4766 snprintf(http_referer
, sizeof(http_referer
), "HTTP_REFERER=%s",
4767 con
->http
.fields
[HTTP_FIELD_REFERER
]);
4768 envp
[envc
++] = http_referer
;
4771 if (con
->operation
== HTTP_GET
)
4773 envp
[envc
++] = "REQUEST_METHOD=GET";
4775 if (con
->query_string
)
4778 * Add GET form variables after ?...
4781 envp
[envc
++] = con
->query_string
;
4784 envp
[envc
++] = "QUERY_STRING=";
4788 sprintf(content_length
, "CONTENT_LENGTH=" CUPS_LLFMT
,
4789 CUPS_LLCAST con
->bytes
);
4790 snprintf(content_type
, sizeof(content_type
), "CONTENT_TYPE=%s",
4791 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
4793 envp
[envc
++] = "REQUEST_METHOD=POST";
4794 envp
[envc
++] = content_length
;
4795 envp
[envc
++] = content_type
;
4799 * Tell the CGI if we are using encryption...
4803 envp
[envc
++] = "HTTPS=ON";
4806 * Terminate the environment array...
4811 if (LogLevel
== CUPSD_LOG_DEBUG2
)
4813 for (i
= 0; i
< argc
; i
++)
4814 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4815 "pipe_command: argv[%d] = \"%s\"", i
, argv
[i
]);
4816 for (i
= 0; i
< envc
; i
++)
4817 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4818 "pipe_command: envp[%d] = \"%s\"", i
, envp
[i
]);
4822 * Create a pipe for the output...
4825 if (cupsdOpenPipe(fds
))
4827 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to create pipes for CGI %s - %s",
4828 argv
[0], strerror(errno
));
4833 * Then execute the command...
4836 if (cupsdStartProcess(command
, argv
, envp
, infile
, fds
[1], CGIPipes
[1],
4837 -1, -1, root
, DefaultProfile
, 0, &pid
) < 0)
4840 * Error - can't fork!
4843 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to fork for CGI %s - %s", argv
[0],
4846 cupsdClosePipe(fds
);
4852 * Fork successful - return the PID...
4855 if (con
->username
[0])
4857 cupsdAddCert(pid
, con
->username
, ccache
);
4859 cupsdAddCert(pid
, con
->username
, NULL
);
4860 #endif /* HAVE_GSSAPI */
4862 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[CGI] %s started - PID = %d",
4874 * 'write_file()' - Send a file via HTTP.
4877 static int /* O - 0 on failure, 1 on success */
4878 write_file(cupsd_client_t
*con
, /* I - Client connection */
4879 http_status_t code
, /* I - HTTP status */
4880 char *filename
, /* I - Filename */
4881 char *type
, /* I - File type */
4882 struct stat
*filestats
) /* O - File information */
4884 con
->file
= open(filename
, O_RDONLY
);
4886 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4887 "write_file(con=%p(%d), code=%d, filename=\"%s\" (%d), "
4888 "type=\"%s\", filestats=%p)", con
, con
->http
.fd
,
4889 code
, filename
, con
->file
, type
? type
: "(null)", filestats
);
4894 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
4898 if (!cupsdSendHeader(con
, code
, type
, CUPSD_AUTH_NONE
))
4901 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
4902 httpGetDateString(filestats
->st_mtime
)) < 0)
4904 if (httpPrintf(HTTP(con
), "Content-Length: " CUPS_LLFMT
"\r\n",
4905 CUPS_LLCAST filestats
->st_size
) < 0)
4907 if (httpPrintf(HTTP(con
), "\r\n") < 0)
4910 if (cupsdFlushHeader(con
) < 0)
4913 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
4914 con
->http
.data_remaining
= filestats
->st_size
;
4916 if (con
->http
.data_remaining
<= INT_MAX
)
4917 con
->http
._data_remaining
= con
->http
.data_remaining
;
4919 con
->http
._data_remaining
= INT_MAX
;
4921 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
,
4922 (cupsd_selfunc_t
)cupsdWriteClient
, con
);
4929 * 'write_pipe()' - Flag that data is available on the CGI pipe.
4933 write_pipe(cupsd_client_t
*con
) /* I - Client connection */
4935 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4936 "write_pipe(con=%p(%d)) CGI output on fd %d",
4937 con
, con
->http
.fd
, con
->file
);
4939 con
->file_ready
= 1;
4941 cupsdRemoveSelect(con
->file
);
4942 cupsdAddSelect(con
->http
.fd
, NULL
, (cupsd_selfunc_t
)cupsdWriteClient
, con
);
4947 * End of "$Id: client.c 7950 2008-09-17 00:21:59Z mike $".