2 * "$Id: client.c 6999 2007-09-28 19:46:53Z mike $"
4 * Client routines for the Common UNIX Printing System (CUPS) scheduler.
6 * Copyright 2007-2008 by Apple Inc.
7 * Copyright 1997-2007 by Easy Software Products, all rights reserved.
9 * This file contains Kerberos support code, copyright 2006 by
12 * These coded instructions, statements, and computer programs are the
13 * property of Apple Inc. and are protected by Federal copyright
14 * law. Distribution and use rights are outlined in the file "LICENSE.txt"
15 * which should have been included with this file. If this file is
16 * file is missing or damaged, see the license at "http://www.cups.org/".
20 * cupsdAcceptClient() - Accept a new client.
21 * cupsdCloseAllClients() - Close all remote clients immediately.
22 * cupsdCloseClient() - Close a remote client.
23 * cupsdFlushHeader() - Flush the header fields to the client.
24 * cupsdReadClient() - Read data from a client.
25 * cupsdSendCommand() - Send output from a command via HTTP.
26 * cupsdSendError() - Send an error message via HTTP.
27 * cupsdSendHeader() - Send an HTTP request.
28 * cupsdUpdateCGI() - Read status messages from CGI scripts and programs.
29 * cupsdWriteClient() - Write data to a client as needed.
30 * check_if_modified() - Decode an "If-Modified-Since" line.
31 * encrypt_client() - Enable encryption for the client...
32 * get_cdsa_certificate() - Convert a keychain name into the CFArrayRef
33 * required by SSLSetCertificate.
34 * get_file() - Get a filename and state info.
35 * install_conf_file() - Install a configuration file.
36 * is_cgi() - Is the resource a CGI script/program?
37 * is_path_absolute() - Is a path absolute and free of relative elements.
38 * make_certificate() - Make a self-signed SSL/TLS certificate.
39 * pipe_command() - Pipe the output of a command to the remote client.
40 * write_file() - Send a file via HTTP.
41 * write_pipe() - Flag that data is available on the CGI pipe.
45 * Include necessary headers...
51 # include <Security/Security.h>
52 # ifdef HAVE_SECIDENTITYSEARCHPRIV_H
53 # include <Security/SecIdentitySearchPriv.h>
54 # else /* Declare prototype for function in that header... */
55 extern OSStatus
SecIdentitySearchCreateWithPolicy(SecPolicyRef policy
,
56 CFStringRef idString
, CSSM_KEYUSE keyUsage
,
57 CFTypeRef keychainOrArray
,
58 Boolean returnOnlyValidIdentities
,
59 SecIdentitySearchRef
* searchRef
);
60 # endif /* HAVE_SECIDENTITYSEARCHPRIV_H */
61 # ifdef HAVE_SECPOLICYPRIV_H
62 # include <Security/SecPolicyPriv.h>
63 # else /* Declare prototype for function in that header... */
64 extern OSStatus
SecPolicySetValue(SecPolicyRef policyRef
,
65 const CSSM_DATA
*value
);
66 # endif /* HAVE_SECPOLICYPRIV_H */
67 # ifdef HAVE_SECBASEPRIV_H
68 # include <Security/SecBasePriv.h>
69 # else /* Declare prototype for function in that header... */
70 extern const char *cssmErrorString(int error
);
71 # endif /* HAVE_SECBASEPRIV_H */
72 #endif /* HAVE_CDSASSL */
75 # include <gnutls/x509.h>
76 #endif /* HAVE_GNUTLS */
83 static int check_if_modified(cupsd_client_t
*con
,
84 struct stat
*filestats
);
86 static int encrypt_client(cupsd_client_t
*con
);
89 static CFArrayRef
get_cdsa_certificate(cupsd_client_t
*con
);
90 #endif /* HAVE_CDSASSL */
91 static char *get_file(cupsd_client_t
*con
, struct stat
*filestats
,
92 char *filename
, int len
);
93 static http_status_t
install_conf_file(cupsd_client_t
*con
);
94 static int is_cgi(cupsd_client_t
*con
, const char *filename
,
95 struct stat
*filestats
, mime_type_t
*type
);
96 static int is_path_absolute(const char *path
);
98 static int make_certificate(cupsd_client_t
*con
);
100 static int pipe_command(cupsd_client_t
*con
, int infile
, int *outfile
,
101 char *command
, char *options
, int root
);
102 static int write_file(cupsd_client_t
*con
, http_status_t code
,
103 char *filename
, char *type
,
104 struct stat
*filestats
);
105 static void write_pipe(cupsd_client_t
*con
);
109 * 'cupsdAcceptClient()' - Accept a new client.
113 cupsdAcceptClient(cupsd_listener_t
*lis
)/* I - Listener socket */
115 int count
; /* Count of connections on a host */
116 int val
; /* Parameter value */
117 cupsd_client_t
*con
, /* New client pointer */
118 *tempcon
; /* Temporary client pointer */
119 http_addrlist_t
*addrlist
, /* List of adddresses for host */
120 *addr
; /* Current address */
121 socklen_t addrlen
; /* Length of address */
122 char *hostname
; /* Hostname for address */
123 http_addr_t temp
; /* Temporary address variable */
124 static time_t last_dos
= 0; /* Time of last DoS attack */
127 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
128 "cupsdAcceptClient(lis=%p) %d Clients = %d",
129 lis
, lis
->fd
, cupsArrayCount(Clients
));
132 * Make sure we don't have a full set of clients already...
135 if (cupsArrayCount(Clients
) == MaxClients
)
139 * Get a pointer to the next available client...
143 Clients
= cupsArrayNew(NULL
, NULL
);
147 cupsdLogMessage(CUPSD_LOG_ERROR
,
148 "Unable to allocate memory for client array!");
149 cupsdPauseListening();
153 if ((con
= calloc(1, sizeof(cupsd_client_t
))) == NULL
)
155 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to allocate memory for client!");
156 cupsdPauseListening();
160 con
->http
.activity
= time(NULL
);
162 con
->http
.hostaddr
= &(con
->clientaddr
);
165 * Accept the client and get the remote address...
168 addrlen
= sizeof(http_addr_t
);
170 if ((con
->http
.fd
= accept(lis
->fd
, (struct sockaddr
*)con
->http
.hostaddr
,
173 if (errno
== ENFILE
|| errno
== EMFILE
)
174 cupsdPauseListening();
176 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to accept client connection - %s.",
184 if (lis
->address
.addr
.sa_family
== AF_INET6
)
187 * Save the connected port number...
190 con
->http
.hostaddr
->ipv6
.sin6_port
= lis
->address
.ipv6
.sin6_port
;
193 * Convert IPv4 over IPv6 addresses (::ffff:n.n.n.n) to IPv4 forms we
194 * can more easily use...
197 if (con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[0] == 0 &&
198 con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[1] == 0 &&
199 ntohl(con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[2]) == 0xffff)
200 con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[2] = 0;
203 #endif /* AF_INET6 */
204 if (lis
->address
.addr
.sa_family
== AF_INET
)
205 con
->http
.hostaddr
->ipv4
.sin_port
= lis
->address
.ipv4
.sin_port
;
208 * Check the number of clients on the same address...
211 for (count
= 0, tempcon
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
213 tempcon
= (cupsd_client_t
*)cupsArrayNext(Clients
))
214 if (httpAddrEqual(tempcon
->http
.hostaddr
, con
->http
.hostaddr
))
217 if (count
>= MaxClientsPerHost
)
221 if (count
>= MaxClientsPerHost
)
223 if ((time(NULL
) - last_dos
) >= 60)
225 last_dos
= time(NULL
);
226 cupsdLogMessage(CUPSD_LOG_WARN
,
227 "Possible DoS attack - more than %d clients connecting "
229 MaxClientsPerHost
, tempcon
->http
.hostname
);
233 closesocket(con
->http
.fd
);
243 * Get the hostname or format the IP address as needed...
246 if (httpAddrLocalhost(con
->http
.hostaddr
))
249 * Map accesses from the loopback interface to "localhost"...
252 strlcpy(con
->http
.hostname
, "localhost", sizeof(con
->http
.hostname
));
253 hostname
= con
->http
.hostname
;
258 * Map accesses from the same host to the server name.
261 for (addr
= ServerAddrs
; addr
; addr
= addr
->next
)
262 if (httpAddrEqual(con
->http
.hostaddr
, &(addr
->addr
)))
267 strlcpy(con
->http
.hostname
, ServerName
, sizeof(con
->http
.hostname
));
268 hostname
= con
->http
.hostname
;
270 else if (HostNameLookups
)
271 hostname
= httpAddrLookup(con
->http
.hostaddr
, con
->http
.hostname
,
272 sizeof(con
->http
.hostname
));
276 httpAddrString(con
->http
.hostaddr
, con
->http
.hostname
,
277 sizeof(con
->http
.hostname
));
281 if (hostname
== NULL
&& HostNameLookups
== 2)
284 * Can't have an unresolved IP address with double-lookups enabled...
287 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
288 "cupsdAcceptClient: Closing connection %d...",
292 closesocket(con
->http
.fd
);
297 cupsdLogMessage(CUPSD_LOG_WARN
,
298 "Name lookup failed - connection from %s closed!",
305 if (HostNameLookups
== 2)
308 * Do double lookups as needed...
311 if ((addrlist
= httpAddrGetList(con
->http
.hostname
, AF_UNSPEC
, NULL
)) != NULL
)
314 * See if the hostname maps to the same IP address...
317 for (addr
= addrlist
; addr
; addr
= addr
->next
)
318 if (httpAddrEqual(con
->http
.hostaddr
, &(addr
->addr
)))
324 httpAddrFreeList(addrlist
);
329 * Can't have a hostname that doesn't resolve to the same IP address
330 * with double-lookups enabled...
333 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
334 "cupsdAcceptClient: Closing connection %d...",
338 closesocket(con
->http
.fd
);
343 cupsdLogMessage(CUPSD_LOG_WARN
,
344 "IP lookup failed - connection from %s closed!",
352 if (con
->http
.hostaddr
->addr
.sa_family
== AF_INET6
)
353 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdAcceptClient: %d from %s:%d (IPv6)",
354 con
->http
.fd
, con
->http
.hostname
,
355 ntohs(con
->http
.hostaddr
->ipv6
.sin6_port
));
357 #endif /* AF_INET6 */
359 if (con
->http
.hostaddr
->addr
.sa_family
== AF_LOCAL
)
360 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdAcceptClient: %d from %s (Domain)",
361 con
->http
.fd
, con
->http
.hostname
);
363 #endif /* AF_LOCAL */
364 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdAcceptClient: %d from %s:%d (IPv4)",
365 con
->http
.fd
, con
->http
.hostname
,
366 ntohs(con
->http
.hostaddr
->ipv4
.sin_port
));
369 * Get the local address the client connected to...
372 addrlen
= sizeof(temp
);
373 if (getsockname(con
->http
.fd
, (struct sockaddr
*)&temp
, &addrlen
))
375 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to get local address - %s",
378 strcpy(con
->servername
, "localhost");
379 con
->serverport
= LocalPort
;
384 if (temp
.addr
.sa_family
== AF_INET6
)
386 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
387 con
->serverport
= ntohs(lis
->address
.ipv6
.sin6_port
);
390 #endif /* AF_INET6 */
391 if (temp
.addr
.sa_family
== AF_INET
)
393 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
394 con
->serverport
= ntohs(lis
->address
.ipv4
.sin_port
);
398 strcpy(con
->servername
, "localhost");
399 con
->serverport
= LocalPort
;
403 cupsArrayAdd(Clients
, con
);
405 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
406 "cupsdAcceptClient: %d connected to server on %s:%d",
407 con
->http
.fd
, con
->servername
, con
->serverport
);
410 * Using TCP_NODELAY improves responsiveness, especially on systems
411 * with a slow loopback interface... Since we write large buffers
412 * when sending print files and requests, there shouldn't be any
413 * performance penalty for this...
417 setsockopt(con
->http
.fd
, IPPROTO_TCP
, TCP_NODELAY
, &val
, sizeof(val
));
420 * Close this file on all execs...
423 fcntl(con
->http
.fd
, F_SETFD
, fcntl(con
->http
.fd
, F_GETFD
) | FD_CLOEXEC
);
426 * Add the socket to the select() input mask.
429 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
432 * Temporarily suspend accept()'s until we lose a client...
435 if (cupsArrayCount(Clients
) == MaxClients
)
436 cupsdPauseListening();
440 * See if we are connecting on a secure port...
443 if (lis
->encryption
== HTTP_ENCRYPT_ALWAYS
)
446 * https connection; go secure...
449 con
->http
.encryption
= HTTP_ENCRYPT_ALWAYS
;
451 if (!encrypt_client(con
))
452 cupsdCloseClient(con
);
456 #endif /* HAVE_SSL */
461 * 'cupsdCloseAllClients()' - Close all remote clients immediately.
465 cupsdCloseAllClients(void)
467 cupsd_client_t
*con
; /* Current client */
470 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
472 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
473 cupsdCloseClient(con
);
478 * 'cupsdCloseClient()' - Close a remote client.
481 int /* O - 1 if partial close, 0 if fully closed */
482 cupsdCloseClient(cupsd_client_t
*con
) /* I - Client to close */
484 int partial
; /* Do partial close for SSL? */
486 SSL_CTX
*context
; /* Context for encryption */
487 SSL
*conn
; /* Connection for encryption */
488 unsigned long error
; /* Error code */
489 #elif defined(HAVE_GNUTLS)
490 http_tls_t
*conn
; /* TLS connection information */
491 int error
; /* Error code */
492 gnutls_certificate_server_credentials
*credentials
;
493 /* TLS credentials */
494 # elif defined(HAVE_CDSASSL)
495 http_tls_t
*conn
; /* CDSA connection information */
496 #endif /* HAVE_LIBSSL */
499 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdCloseClient: %d", con
->http
.fd
);
502 * Flush pending writes before closing...
505 httpFlushWrite(HTTP(con
));
511 * Shutdown encryption as needed...
519 conn
= (SSL
*)(con
->http
.tls
);
520 context
= SSL_get_SSL_CTX(conn
);
522 switch (SSL_shutdown(conn
))
525 cupsdLogMessage(CUPSD_LOG_INFO
,
526 "cupsdCloseClient: SSL shutdown successful!");
529 cupsdLogMessage(CUPSD_LOG_ERROR
,
530 "cupsdCloseClient: Fatal error during SSL shutdown!");
532 while ((error
= ERR_get_error()) != 0)
533 cupsdLogMessage(CUPSD_LOG_ERROR
, "cupsdCloseClient: %s",
534 ERR_error_string(error
, NULL
));
538 SSL_CTX_free(context
);
541 # elif defined(HAVE_GNUTLS)
542 conn
= (http_tls_t
*)(con
->http
.tls
);
543 credentials
= (gnutls_certificate_server_credentials
*)(conn
->credentials
);
545 error
= gnutls_bye(conn
->session
, GNUTLS_SHUT_WR
);
548 case GNUTLS_E_SUCCESS
:
549 cupsdLogMessage(CUPSD_LOG_INFO
,
550 "cupsdCloseClient: SSL shutdown successful!");
553 cupsdLogMessage(CUPSD_LOG_ERROR
,
554 "cupsdCloseClient: %s", gnutls_strerror(error
));
558 gnutls_deinit(conn
->session
);
559 gnutls_certificate_free_credentials(*credentials
);
563 # elif defined(HAVE_CDSASSL)
564 conn
= (http_tls_t
*)(con
->http
.tls
);
566 while (SSLClose(conn
->session
) == errSSLWouldBlock
)
569 SSLDisposeContext(conn
->session
);
571 if (conn
->certsArray
)
572 CFRelease(conn
->certsArray
);
575 # endif /* HAVE_LIBSSL */
577 con
->http
.tls
= NULL
;
579 #endif /* HAVE_SSL */
581 if (con
->pipe_pid
!= 0)
584 * Stop any CGI process...
587 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
588 "cupsdCloseClient: %d Killing process ID %d...",
589 con
->http
.fd
, con
->pipe_pid
);
590 cupsdEndProcess(con
->pipe_pid
, 1);
596 cupsdRemoveSelect(con
->file
);
598 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
599 "cupsdCloseClient: %d Closing data file %d.",
600 con
->http
.fd
, con
->file
);
607 * Close the socket and clear the file from the input set for select()...
610 if (con
->http
.fd
> 0)
615 * Only do a partial close so that the encrypted client gets everything.
618 shutdown(con
->http
.fd
, 0);
619 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
624 * Shut the socket down fully...
627 cupsdRemoveSelect(con
->http
.fd
);
639 if (con
->http
.input_set
)
640 free(con
->http
.input_set
);
642 httpClearCookie(HTTP(con
));
644 cupsdClearString(&con
->filename
);
645 cupsdClearString(&con
->command
);
646 cupsdClearString(&con
->options
);
647 cupsdClearString(&con
->query_string
);
651 ippDelete(con
->request
);
657 ippDelete(con
->response
);
658 con
->response
= NULL
;
663 cupsLangFree(con
->language
);
664 con
->language
= NULL
;
667 #ifdef HAVE_AUTHORIZATION_H
670 AuthorizationFree(con
->authref
, kAuthorizationFlagDefaults
);
673 #endif /* HAVE_AUTHORIZATION_H */
676 * Re-enable new client connections if we are going back under the
680 if (cupsArrayCount(Clients
) == MaxClients
)
681 cupsdResumeListening();
684 * Compact the list of clients as necessary...
687 cupsArrayRemove(Clients
, con
);
697 * 'cupsdFlushHeader()' - Flush the header fields to the client.
700 int /* I - Bytes written or -1 on error */
701 cupsdFlushHeader(cupsd_client_t
*con
) /* I - Client to flush to */
703 int bytes
= httpFlushWrite(HTTP(con
));
705 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
712 * 'cupsdReadClient()' - Read data from a client.
716 cupsdReadClient(cupsd_client_t
*con
) /* I - Client to read from */
718 char line
[32768], /* Line from client... */
719 operation
[64], /* Operation code from socket */
720 version
[64], /* HTTP version number string */
721 locale
[64], /* Locale */
722 *ptr
; /* Pointer into strings */
723 int major
, minor
; /* HTTP version numbers */
724 http_status_t status
; /* Transfer status */
725 ipp_state_t ipp_state
; /* State of IPP transfer */
726 int bytes
; /* Number of bytes to POST */
727 char *filename
; /* Name of file for GET/HEAD */
728 char buf
[1024]; /* Buffer for real filename */
729 struct stat filestats
; /* File information */
730 mime_type_t
*type
; /* MIME type of file */
731 cupsd_printer_t
*p
; /* Printer */
732 static unsigned request_id
= 0; /* Request ID for temp files */
735 status
= HTTP_CONTINUE
;
737 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
738 "cupsdReadClient: %d, used=%d, file=%d state=%d",
739 con
->http
.fd
, con
->http
.used
, con
->file
, con
->http
.state
);
743 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdReadClient: http error seen...");
744 cupsdCloseClient(con
);
752 * Automatically check for a SSL/TLS handshake...
757 if (recv(con
->http
.fd
, buf
, 1, MSG_PEEK
) == 1 &&
758 (!buf
[0] || !strchr("DGHOPT", buf
[0])))
761 * Encrypt this connection...
764 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
765 "cupsdReadClient: Saw first byte %02X, auto-negotiating SSL/TLS session...",
768 if (!encrypt_client(con
))
769 cupsdCloseClient(con
);
774 #endif /* HAVE_SSL */
776 switch (con
->http
.state
)
780 * See if we've received a request line...
783 if (httpGets(line
, sizeof(line
) - 1, HTTP(con
)) == NULL
)
785 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
786 "cupsdReadClient: httpGets returned EOF...");
787 cupsdCloseClient(con
);
792 * Ignore blank request lines...
799 * Clear other state variables...
802 httpClearFields(HTTP(con
));
804 con
->http
.activity
= time(NULL
);
805 con
->http
.version
= HTTP_1_0
;
806 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
807 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
808 con
->http
.data_remaining
= 0;
809 con
->http
._data_remaining
= 0;
810 con
->operation
= HTTP_WAITING
;
815 con
->username
[0] = '\0';
816 con
->password
[0] = '\0';
819 cupsdClearString(&con
->command
);
820 cupsdClearString(&con
->options
);
821 cupsdClearString(&con
->query_string
);
825 ippDelete(con
->request
);
831 ippDelete(con
->response
);
832 con
->response
= NULL
;
837 cupsLangFree(con
->language
);
838 con
->language
= NULL
;
842 con
->gss_have_creds
= 0;
843 #endif /* HAVE_GSSAPI */
846 * Grab the request line...
849 switch (sscanf(line
, "%63s%1023s%63s", operation
, con
->uri
, version
))
852 cupsdLogMessage(CUPSD_LOG_ERROR
,
853 "Bad request line \"%s\" from %s!", line
,
855 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
856 cupsdCloseClient(con
);
859 con
->http
.version
= HTTP_0_9
;
862 if (sscanf(version
, "HTTP/%d.%d", &major
, &minor
) != 2)
864 cupsdLogMessage(CUPSD_LOG_ERROR
,
865 "Bad request line \"%s\" from %s!", line
,
867 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
868 cupsdCloseClient(con
);
874 con
->http
.version
= (http_version_t
)(major
* 100 + minor
);
875 if (con
->http
.version
== HTTP_1_1
&& KeepAlive
)
876 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
878 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
882 cupsdSendError(con
, HTTP_NOT_SUPPORTED
, CUPSD_AUTH_NONE
);
883 cupsdCloseClient(con
);
890 * Handle full URLs in the request line...
893 if (strcmp(con
->uri
, "*"))
895 char method
[HTTP_MAX_URI
], /* Method/scheme */
896 userpass
[HTTP_MAX_URI
], /* Username:password */
897 hostname
[HTTP_MAX_URI
], /* Hostname */
898 resource
[HTTP_MAX_URI
]; /* Resource path */
899 int port
; /* Port number */
903 * Separate the URI into its components...
906 httpSeparateURI(HTTP_URI_CODING_MOST
, con
->uri
,
907 method
, sizeof(method
),
908 userpass
, sizeof(userpass
),
909 hostname
, sizeof(hostname
), &port
,
910 resource
, sizeof(resource
));
913 * Only allow URIs with the servername, localhost, or an IP
917 if (strcmp(method
, "file") &&
918 strcasecmp(hostname
, ServerName
) &&
919 strcasecmp(hostname
, "localhost") &&
920 !isdigit(hostname
[0]))
923 * Nope, we don't do proxies...
926 cupsdLogMessage(CUPSD_LOG_ERROR
, "Bad URI \"%s\" in request!",
928 cupsdSendError(con
, HTTP_METHOD_NOT_ALLOWED
, CUPSD_AUTH_NONE
);
929 cupsdCloseClient(con
);
934 * Copy the resource portion back into the URI; both resource and
935 * con->uri are HTTP_MAX_URI bytes in size...
938 strcpy(con
->uri
, resource
);
942 * Process the request...
945 if (!strcmp(operation
, "GET"))
946 con
->http
.state
= HTTP_GET
;
947 else if (!strcmp(operation
, "PUT"))
948 con
->http
.state
= HTTP_PUT
;
949 else if (!strcmp(operation
, "POST"))
950 con
->http
.state
= HTTP_POST
;
951 else if (!strcmp(operation
, "DELETE"))
952 con
->http
.state
= HTTP_DELETE
;
953 else if (!strcmp(operation
, "TRACE"))
954 con
->http
.state
= HTTP_TRACE
;
955 else if (!strcmp(operation
, "OPTIONS"))
956 con
->http
.state
= HTTP_OPTIONS
;
957 else if (!strcmp(operation
, "HEAD"))
958 con
->http
.state
= HTTP_HEAD
;
961 cupsdLogMessage(CUPSD_LOG_ERROR
, "Bad operation \"%s\"!", operation
);
962 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
963 cupsdCloseClient(con
);
967 con
->start
= time(NULL
);
968 con
->operation
= con
->http
.state
;
970 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdReadClient: %d %s %s HTTP/%d.%d",
971 con
->http
.fd
, operation
, con
->uri
,
972 con
->http
.version
/ 100, con
->http
.version
% 100);
974 con
->http
.status
= HTTP_OK
;
984 * Parse incoming parameters until the status changes...
987 while ((status
= httpUpdate(HTTP(con
))) == HTTP_CONTINUE
)
988 if (con
->http
.used
== 0 ||
989 !memchr(con
->http
.buffer
, '\n', con
->http
.used
))
992 if (status
!= HTTP_OK
&& status
!= HTTP_CONTINUE
)
994 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
995 cupsdCloseClient(con
);
1001 break; /* Anti-compiler-warning-code */
1005 * Handle new transfers...
1008 if (status
== HTTP_OK
)
1010 if (con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
][0])
1013 * Figure out the locale from the Accept-Language and Content-Type
1017 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ',')) != NULL
)
1020 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ';')) != NULL
)
1023 if ((ptr
= strstr(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
], "charset=")) != NULL
)
1026 * Combine language and charset, and trim any extra params in the
1030 snprintf(locale
, sizeof(locale
), "%s.%s",
1031 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ptr
+ 8);
1033 if ((ptr
= strchr(locale
, ',')) != NULL
)
1037 snprintf(locale
, sizeof(locale
), "%s.%s",
1038 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], DefaultCharset
);
1040 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1041 "cupsdReadClient: %d Browser asked for language \"%s\"...",
1042 con
->http
.fd
, locale
);
1044 con
->language
= cupsLangGet(locale
);
1047 con
->language
= cupsLangGet(DefaultLocale
);
1049 cupsdAuthorize(con
);
1051 if (!strncmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Keep-Alive", 10) &&
1053 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
1055 if (!con
->http
.fields
[HTTP_FIELD_HOST
][0] &&
1056 con
->http
.version
>= HTTP_1_1
)
1059 * HTTP/1.1 and higher require the "Host:" field...
1062 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1064 cupsdCloseClient(con
);
1068 else if (con
->operation
== HTTP_OPTIONS
)
1071 * Do OPTIONS command...
1074 if (con
->best
&& con
->best
->type
!= CUPSD_AUTH_NONE
)
1076 if (!cupsdSendHeader(con
, HTTP_UNAUTHORIZED
, NULL
, CUPSD_AUTH_NONE
))
1078 cupsdCloseClient(con
);
1083 if (!strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") &&
1084 con
->http
.tls
== NULL
)
1088 * Do encryption stuff...
1091 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
, CUPSD_AUTH_NONE
))
1093 cupsdCloseClient(con
);
1097 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1098 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1099 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1100 httpPrintf(HTTP(con
), "\r\n");
1102 if (cupsdFlushHeader(con
) < 0)
1104 cupsdCloseClient(con
);
1108 if (!encrypt_client(con
))
1110 cupsdCloseClient(con
);
1114 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
1116 cupsdCloseClient(con
);
1119 #endif /* HAVE_SSL */
1122 if (!cupsdSendHeader(con
, HTTP_OK
, NULL
, CUPSD_AUTH_NONE
))
1124 cupsdCloseClient(con
);
1128 httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n");
1129 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1130 httpPrintf(HTTP(con
), "\r\n");
1132 if (cupsdFlushHeader(con
) < 0)
1134 cupsdCloseClient(con
);
1138 else if (!is_path_absolute(con
->uri
))
1141 * Protect against malicious users!
1144 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1146 cupsdCloseClient(con
);
1152 if (!strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") &&
1153 con
->http
.tls
== NULL
)
1157 * Do encryption stuff...
1160 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
, CUPSD_AUTH_NONE
))
1162 cupsdCloseClient(con
);
1166 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1167 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1168 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1169 httpPrintf(HTTP(con
), "\r\n");
1171 if (cupsdFlushHeader(con
) < 0)
1173 cupsdCloseClient(con
);
1177 if (!encrypt_client(con
))
1179 cupsdCloseClient(con
);
1183 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
1185 cupsdCloseClient(con
);
1188 #endif /* HAVE_SSL */
1191 if ((status
= cupsdIsAuthorized(con
, NULL
)) != HTTP_OK
)
1193 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1194 "cupsdReadClient: Unauthorized request for %s...\n",
1196 cupsdSendError(con
, status
, CUPSD_AUTH_NONE
);
1197 cupsdCloseClient(con
);
1201 if (con
->http
.expect
&&
1202 (con
->operation
== HTTP_POST
|| con
->operation
== HTTP_PUT
))
1204 if (con
->http
.expect
== HTTP_CONTINUE
)
1207 * Send 100-continue header...
1210 if (!cupsdSendHeader(con
, HTTP_CONTINUE
, NULL
, CUPSD_AUTH_NONE
))
1212 cupsdCloseClient(con
);
1219 * Send 417-expectation-failed header...
1222 if (!cupsdSendHeader(con
, HTTP_EXPECTATION_FAILED
, NULL
, CUPSD_AUTH_NONE
))
1224 cupsdCloseClient(con
);
1228 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1229 httpPrintf(HTTP(con
), "\r\n");
1231 if (cupsdFlushHeader(con
) < 0)
1233 cupsdCloseClient(con
);
1239 switch (con
->http
.state
)
1241 case HTTP_GET_SEND
:
1242 if (!strncmp(con
->uri
, "/printers/", 10) &&
1243 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1246 * Send PPD file - get the real printer name since printer
1247 * names are not case sensitive but filenames can be...
1250 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1252 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1253 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1256 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1258 cupsdCloseClient(con
);
1266 if ((!strncmp(con
->uri
, "/admin", 6) &&
1267 strncmp(con
->uri
, "/admin/conf/", 12) &&
1268 strncmp(con
->uri
, "/admin/log/", 11)) ||
1269 !strncmp(con
->uri
, "/printers", 9) ||
1270 !strncmp(con
->uri
, "/classes", 8) ||
1271 !strncmp(con
->uri
, "/help", 5) ||
1272 !strncmp(con
->uri
, "/jobs", 5))
1275 * Send CGI output...
1278 if (!strncmp(con
->uri
, "/admin", 6))
1280 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1283 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1285 else if (!strncmp(con
->uri
, "/printers", 9))
1287 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1290 if (con
->uri
[9] && con
->uri
[10])
1291 cupsdSetString(&con
->options
, con
->uri
+ 9);
1293 cupsdSetString(&con
->options
, NULL
);
1295 else if (!strncmp(con
->uri
, "/classes", 8))
1297 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1300 if (con
->uri
[8] && con
->uri
[9])
1301 cupsdSetString(&con
->options
, con
->uri
+ 8);
1303 cupsdSetString(&con
->options
, NULL
);
1305 else if (!strncmp(con
->uri
, "/jobs", 5))
1307 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1310 if (con
->uri
[5] && con
->uri
[6])
1311 cupsdSetString(&con
->options
, con
->uri
+ 5);
1313 cupsdSetString(&con
->options
, NULL
);
1317 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1320 if (con
->uri
[5] && con
->uri
[6])
1321 cupsdSetString(&con
->options
, con
->uri
+ 5);
1323 cupsdSetString(&con
->options
, NULL
);
1326 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1328 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1330 cupsdCloseClient(con
);
1335 cupsdLogRequest(con
, HTTP_OK
);
1337 if (con
->http
.version
<= HTTP_1_0
)
1338 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1340 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1341 (strchr(con
->uri
+ 12, '/') ||
1342 strlen(con
->uri
) == 12)) ||
1343 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1344 (strchr(con
->uri
+ 11, '/') ||
1345 strlen(con
->uri
) == 11)))
1348 * GET can only be done to configuration files under
1352 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1354 cupsdCloseClient(con
);
1366 if ((filename
= get_file(con
, &filestats
, buf
,
1367 sizeof(buf
))) == NULL
)
1369 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1371 cupsdCloseClient(con
);
1378 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1380 if (is_cgi(con
, filename
, &filestats
, type
))
1383 * Note: con->command and con->options were set by
1387 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1389 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1391 cupsdCloseClient(con
);
1396 cupsdLogRequest(con
, HTTP_OK
);
1398 if (con
->http
.version
<= HTTP_1_0
)
1399 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1403 if (!check_if_modified(con
, &filestats
))
1405 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1407 cupsdCloseClient(con
);
1414 strcpy(line
, "text/plain");
1416 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1418 if (!write_file(con
, HTTP_OK
, filename
, line
, &filestats
))
1420 cupsdCloseClient(con
);
1427 case HTTP_POST_RECV
:
1429 * See if the POST request includes a Content-Length field, and if
1430 * so check the length against any limits that are set...
1433 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "POST %s", con
->uri
);
1434 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "CONTENT_TYPE = %s",
1435 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
1437 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1438 MaxRequestSize
> 0 &&
1439 con
->http
.data_remaining
> MaxRequestSize
)
1442 * Request too large...
1445 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1447 cupsdCloseClient(con
);
1453 else if (con
->http
.data_remaining
< 0 ||
1454 (!con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1455 con
->http
.data_encoding
== HTTP_ENCODE_LENGTH
))
1458 * Negative content lengths are invalid!
1461 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1463 cupsdCloseClient(con
);
1471 * See what kind of POST request this is; for IPP requests the
1472 * content-type field will be "application/ipp"...
1475 if (!strcmp(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
],
1477 con
->request
= ippNew();
1478 else if ((!strncmp(con
->uri
, "/admin", 6) &&
1479 strncmp(con
->uri
, "/admin/conf/", 12) &&
1480 strncmp(con
->uri
, "/admin/log/", 11)) ||
1481 !strncmp(con
->uri
, "/printers", 9) ||
1482 !strncmp(con
->uri
, "/classes", 8) ||
1483 !strncmp(con
->uri
, "/help", 5) ||
1484 !strncmp(con
->uri
, "/jobs", 5))
1490 if (!strncmp(con
->uri
, "/admin", 6))
1492 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1495 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1497 else if (!strncmp(con
->uri
, "/printers", 9))
1499 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1502 if (con
->uri
[9] && con
->uri
[10])
1503 cupsdSetString(&con
->options
, con
->uri
+ 9);
1505 cupsdSetString(&con
->options
, NULL
);
1507 else if (!strncmp(con
->uri
, "/classes", 8))
1509 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1512 if (con
->uri
[8] && con
->uri
[9])
1513 cupsdSetString(&con
->options
, con
->uri
+ 8);
1515 cupsdSetString(&con
->options
, NULL
);
1517 else if (!strncmp(con
->uri
, "/jobs", 5))
1519 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1522 if (con
->uri
[5] && con
->uri
[6])
1523 cupsdSetString(&con
->options
, con
->uri
+ 5);
1525 cupsdSetString(&con
->options
, NULL
);
1529 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1532 if (con
->uri
[5] && con
->uri
[6])
1533 cupsdSetString(&con
->options
, con
->uri
+ 5);
1535 cupsdSetString(&con
->options
, NULL
);
1538 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1539 "cupsdReadClient: %d command=\"%s\", "
1541 con
->http
.fd
, con
->command
,
1542 con
->options
? con
->options
: "(null)");
1544 if (con
->http
.version
<= HTTP_1_0
)
1545 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1553 if ((filename
= get_file(con
, &filestats
, buf
,
1554 sizeof(buf
))) == NULL
)
1556 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1558 cupsdCloseClient(con
);
1565 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1567 if (!is_cgi(con
, filename
, &filestats
, type
))
1570 * Only POST to CGI's...
1573 if (!cupsdSendError(con
, HTTP_UNAUTHORIZED
, CUPSD_AUTH_NONE
))
1575 cupsdCloseClient(con
);
1582 case HTTP_PUT_RECV
:
1584 * Validate the resource name...
1587 if (strncmp(con
->uri
, "/admin/conf/", 12) ||
1588 strchr(con
->uri
+ 12, '/') ||
1589 strlen(con
->uri
) == 12)
1592 * PUT can only be done to configuration files under
1596 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1598 cupsdCloseClient(con
);
1606 * See if the PUT request includes a Content-Length field, and if
1607 * so check the length against any limits that are set...
1610 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "PUT %s", con
->uri
);
1611 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "CONTENT_TYPE = %s",
1612 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
1614 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1615 MaxRequestSize
> 0 &&
1616 con
->http
.data_remaining
> MaxRequestSize
)
1619 * Request too large...
1622 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1624 cupsdCloseClient(con
);
1630 else if (con
->http
.data_remaining
< 0)
1633 * Negative content lengths are invalid!
1636 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1638 cupsdCloseClient(con
);
1646 * Open a temporary file to hold the request...
1649 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
1651 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1655 cupsdLogMessage(CUPSD_LOG_ERROR
,
1656 "Unable to create request file %s: %s",
1657 con
->filename
, strerror(errno
));
1659 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1661 cupsdCloseClient(con
);
1666 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1667 "cupsdReadClient: %d REQUEST %s=%d", con
->http
.fd
,
1668 con
->filename
, con
->file
);
1670 fchmod(con
->file
, 0640);
1671 fchown(con
->file
, RunUser
, Group
);
1672 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1677 cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
);
1678 cupsdCloseClient(con
);
1682 if (!strncmp(con
->uri
, "/printers/", 10) &&
1683 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1686 * Send PPD file - get the real printer name since printer
1687 * names are not case sensitive but filenames can be...
1690 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1692 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1693 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1696 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1698 cupsdCloseClient(con
);
1706 if ((!strncmp(con
->uri
, "/admin", 6) &&
1707 strncmp(con
->uri
, "/admin/conf/", 12) &&
1708 strncmp(con
->uri
, "/admin/log/", 11)) ||
1709 !strncmp(con
->uri
, "/printers", 9) ||
1710 !strncmp(con
->uri
, "/classes", 8) ||
1711 !strncmp(con
->uri
, "/help", 5) ||
1712 !strncmp(con
->uri
, "/jobs", 5))
1718 if (!cupsdSendHeader(con
, HTTP_OK
, "text/html", CUPSD_AUTH_NONE
))
1720 cupsdCloseClient(con
);
1724 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1726 cupsdCloseClient(con
);
1730 if (cupsdFlushHeader(con
) < 0)
1732 cupsdCloseClient(con
);
1736 cupsdLogRequest(con
, HTTP_OK
);
1738 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1739 (strchr(con
->uri
+ 12, '/') ||
1740 strlen(con
->uri
) == 12)) ||
1741 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1742 (strchr(con
->uri
+ 11, '/') ||
1743 strlen(con
->uri
) == 11)))
1746 * HEAD can only be done to configuration files under
1750 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1752 cupsdCloseClient(con
);
1758 else if ((filename
= get_file(con
, &filestats
, buf
,
1759 sizeof(buf
))) == NULL
)
1761 if (!cupsdSendHeader(con
, HTTP_NOT_FOUND
, "text/html", CUPSD_AUTH_NONE
))
1763 cupsdCloseClient(con
);
1767 cupsdLogRequest(con
, HTTP_NOT_FOUND
);
1769 else if (!check_if_modified(con
, &filestats
))
1771 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1773 cupsdCloseClient(con
);
1777 cupsdLogRequest(con
, HTTP_NOT_MODIFIED
);
1785 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1787 strcpy(line
, "text/plain");
1789 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1791 if (!cupsdSendHeader(con
, HTTP_OK
, line
, CUPSD_AUTH_NONE
))
1793 cupsdCloseClient(con
);
1797 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
1798 httpGetDateString(filestats
.st_mtime
)) < 0)
1800 cupsdCloseClient(con
);
1804 if (httpPrintf(HTTP(con
), "Content-Length: %lu\r\n",
1805 (unsigned long)filestats
.st_size
) < 0)
1807 cupsdCloseClient(con
);
1811 cupsdLogRequest(con
, HTTP_OK
);
1814 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1816 cupsdCloseClient(con
);
1820 if (cupsdFlushHeader(con
) < 0)
1822 cupsdCloseClient(con
);
1826 con
->http
.state
= HTTP_WAITING
;
1830 break; /* Anti-compiler-warning-code */
1836 * Handle any incoming data...
1839 switch (con
->http
.state
)
1841 case HTTP_PUT_RECV
:
1842 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1843 "cupsdReadClient: %d con->data_encoding=HTTP_ENCODE_%s, "
1844 "con->data_remaining=" CUPS_LLFMT
", con->file=%d",
1846 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
?
1847 "CHUNKED" : "LENGTH",
1848 CUPS_LLCAST con
->http
.data_remaining
, con
->file
);
1852 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
1854 cupsdCloseClient(con
);
1859 con
->bytes
+= bytes
;
1861 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1862 "cupsdReadClient: %d writing %d bytes to %d",
1863 con
->http
.fd
, bytes
, con
->file
);
1865 if (write(con
->file
, line
, bytes
) < bytes
)
1867 cupsdLogMessage(CUPSD_LOG_ERROR
,
1868 "cupsdReadClient: Unable to write %d bytes to %s: %s",
1869 bytes
, con
->filename
, strerror(errno
));
1871 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1872 "cupsdReadClient: Closing data file %d...",
1877 unlink(con
->filename
);
1878 cupsdClearString(&con
->filename
);
1880 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1882 cupsdCloseClient(con
);
1888 while (con
->http
.state
== HTTP_PUT_RECV
&& con
->http
.used
> 0);
1890 if (con
->http
.state
== HTTP_WAITING
)
1893 * End of file, see how big it is...
1896 fstat(con
->file
, &filestats
);
1898 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1899 "cupsdReadClient: %d Closing data file %d, size="
1901 con
->http
.fd
, con
->file
,
1902 CUPS_LLCAST filestats
.st_size
);
1907 if (filestats
.st_size
> MaxRequestSize
&&
1911 * Request is too big; remove it and send an error...
1914 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1915 "cupsdReadClient: %d Removing temp file %s",
1916 con
->http
.fd
, con
->filename
);
1917 unlink(con
->filename
);
1918 cupsdClearString(&con
->filename
);
1920 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1922 cupsdCloseClient(con
);
1928 * Install the configuration file...
1931 status
= install_conf_file(con
);
1934 * Return the status to the client...
1937 if (!cupsdSendError(con
, status
, CUPSD_AUTH_NONE
))
1939 cupsdCloseClient(con
);
1945 case HTTP_POST_RECV
:
1946 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1947 "cupsdReadClient: %d con->data_encoding=HTTP_ENCODE_"
1948 "%s, con->data_remaining=" CUPS_LLFMT
", con->file=%d",
1950 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
?
1951 "CHUNKED" : "LENGTH",
1952 CUPS_LLCAST con
->http
.data_remaining
, con
->file
);
1959 * Grab any request data from the connection...
1962 if ((ipp_state
= ippRead(&(con
->http
), con
->request
)) == IPP_ERROR
)
1964 cupsdLogMessage(CUPSD_LOG_ERROR
,
1965 "cupsdReadClient: %d IPP Read Error!",
1968 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
1969 cupsdCloseClient(con
);
1972 else if (ipp_state
!= IPP_DATA
)
1974 if (con
->http
.state
== HTTP_POST_SEND
)
1976 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
1977 cupsdCloseClient(con
);
1984 con
->bytes
+= ippLength(con
->request
);
1987 if (con
->file
< 0 && con
->http
.state
!= HTTP_POST_SEND
)
1990 * Create a file as needed for the request data...
1993 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
, request_id
++);
1994 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1998 cupsdLogMessage(CUPSD_LOG_ERROR
,
1999 "Unable to create request file %s: %s",
2000 con
->filename
, strerror(errno
));
2002 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2004 cupsdCloseClient(con
);
2009 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdReadClient: %d REQUEST %s=%d", con
->http
.fd
,
2010 con
->filename
, con
->file
);
2012 fchmod(con
->file
, 0640);
2013 fchown(con
->file
, RunUser
, Group
);
2014 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2017 if (con
->http
.state
!= HTTP_POST_SEND
)
2019 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
2021 cupsdCloseClient(con
);
2026 con
->bytes
+= bytes
;
2028 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2029 "cupsdReadClient: %d writing %d bytes to %d",
2030 con
->http
.fd
, bytes
, con
->file
);
2032 if (write(con
->file
, line
, bytes
) < bytes
)
2034 cupsdLogMessage(CUPSD_LOG_ERROR
,
2035 "cupsdReadClient: Unable to write %d bytes to %s: %s",
2036 bytes
, con
->filename
, strerror(errno
));
2038 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2039 "cupsdReadClient: Closing file %d...",
2044 unlink(con
->filename
);
2045 cupsdClearString(&con
->filename
);
2047 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2049 cupsdCloseClient(con
);
2054 else if (con
->http
.state
== HTTP_POST_RECV
)
2056 else if (con
->http
.state
!= HTTP_POST_SEND
)
2058 cupsdCloseClient(con
);
2063 while (con
->http
.state
== HTTP_POST_RECV
&& con
->http
.used
> 0);
2065 if (con
->http
.state
== HTTP_POST_SEND
)
2069 fstat(con
->file
, &filestats
);
2071 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2072 "cupsdReadClient: %d Closing data file %d, "
2073 "size=" CUPS_LLFMT
".",
2074 con
->http
.fd
, con
->file
,
2075 CUPS_LLCAST filestats
.st_size
);
2080 if (filestats
.st_size
> MaxRequestSize
&&
2084 * Request is too big; remove it and send an error...
2087 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2088 "cupsdReadClient: %d Removing temp file %s",
2089 con
->http
.fd
, con
->filename
);
2090 unlink(con
->filename
);
2091 cupsdClearString(&con
->filename
);
2096 * Delete any IPP request data...
2099 ippDelete(con
->request
);
2100 con
->request
= NULL
;
2103 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2105 cupsdCloseClient(con
);
2112 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
2114 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
2116 cupsdCloseClient(con
);
2121 cupsdLogRequest(con
, HTTP_OK
);
2127 cupsdProcessIPPRequest(con
);
2131 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2132 "cupsdReadClient: %d Removing temp file %s",
2133 con
->http
.fd
, con
->filename
);
2134 unlink(con
->filename
);
2135 cupsdClearString(&con
->filename
);
2144 break; /* Anti-compiler-warning-code */
2147 if (!con
->http
.keep_alive
&& con
->http
.state
== HTTP_WAITING
)
2148 cupsdCloseClient(con
);
2153 * 'cupsdSendCommand()' - Send output from a command via HTTP.
2156 int /* O - 1 on success, 0 on failure */
2158 cupsd_client_t
*con
, /* I - Client connection */
2159 char *command
, /* I - Command to run */
2160 char *options
, /* I - Command-line options */
2161 int root
) /* I - Run as root? */
2163 int fd
; /* Standard input file descriptor */
2168 fd
= open(con
->filename
, O_RDONLY
);
2172 cupsdLogMessage(CUPSD_LOG_ERROR
,
2173 "cupsdSendCommand: %d Unable to open \"%s\" for reading: %s",
2174 con
->http
.fd
, con
->filename
? con
->filename
: "/dev/null",
2179 fcntl(fd
, F_SETFD
, fcntl(fd
, F_GETFD
) | FD_CLOEXEC
);
2184 con
->pipe_pid
= pipe_command(con
, fd
, &(con
->file
), command
, options
, root
);
2189 cupsdLogMessage(CUPSD_LOG_INFO
, "Started \"%s\" (pid=%d)", command
,
2192 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendCommand: %d file=%d",
2193 con
->http
.fd
, con
->file
);
2195 if (con
->pipe_pid
== 0)
2198 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2200 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2202 con
->sent_header
= 0;
2203 con
->file_ready
= 0;
2204 con
->got_fields
= 0;
2212 * 'cupsdSendError()' - Send an error message via HTTP.
2215 int /* O - 1 if successful, 0 otherwise */
2216 cupsdSendError(cupsd_client_t
*con
, /* I - Connection */
2217 http_status_t code
, /* I - Error code */
2218 int auth_type
)/* I - Authentication type */
2222 * Force client to upgrade for authentication if that is how the
2223 * server is configured...
2226 if (code
== HTTP_UNAUTHORIZED
&&
2227 DefaultEncryption
== HTTP_ENCRYPT_REQUIRED
&&
2228 strcasecmp(con
->http
.hostname
, "localhost") &&
2231 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2232 "cupsdSendError: Encryption before authentication!");
2233 code
= HTTP_UPGRADE_REQUIRED
;
2235 #endif /* HAVE_SSL */
2238 * Put the request in the access_log file...
2241 cupsdLogRequest(con
, code
);
2243 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendError: %d code=%d (%s)",
2244 con
->http
.fd
, code
, httpStatus(code
));
2247 * To work around bugs in some proxies, don't use Keep-Alive for some
2250 * Kerberos authentication doesn't work without Keep-Alive, so
2251 * never disable it in that case.
2254 if (code
>= HTTP_BAD_REQUEST
&& con
->http
.auth_type
!= CUPSD_AUTH_NEGOTIATE
)
2255 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
2258 * Send an error message back to the client. If the error code is a
2259 * 400 or 500 series, make sure the message contains some text, too!
2262 if (!cupsdSendHeader(con
, code
, NULL
, auth_type
))
2266 if (code
== HTTP_UPGRADE_REQUIRED
)
2267 if (httpPrintf(HTTP(con
), "Connection: Upgrade\r\n") < 0)
2270 if (httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n") < 0)
2272 #endif /* HAVE_SSL */
2274 if (con
->http
.version
>= HTTP_1_1
&&
2275 con
->http
.keep_alive
== HTTP_KEEPALIVE_OFF
)
2277 if (httpPrintf(HTTP(con
), "Connection: close\r\n") < 0)
2281 if (code
>= HTTP_BAD_REQUEST
)
2284 * Send a human-readable error message.
2287 char message
[4096], /* Message for user */
2288 urltext
[1024], /* URL redirection text */
2289 redirect
[1024]; /* Redirection link */
2290 const char *text
; /* Status-specific text */
2295 if (code
== HTTP_UNAUTHORIZED
)
2296 text
= _cupsLangString(con
->language
,
2297 _("Enter your username and password or the "
2298 "root username and password to access this "
2299 "page. If you are using Kerberos authentication, "
2300 "make sure you have a valid Kerberos ticket."));
2301 else if (code
== HTTP_UPGRADE_REQUIRED
)
2305 snprintf(urltext
, sizeof(urltext
),
2306 _cupsLangString(con
->language
,
2307 _("You must access this page using the URL "
2308 "<A HREF=\"https://%s:%d%s\">"
2309 "https://%s:%d%s</A>.")),
2310 con
->servername
, con
->serverport
, con
->uri
,
2311 con
->servername
, con
->serverport
, con
->uri
);
2313 snprintf(redirect
, sizeof(redirect
),
2314 "<META HTTP-EQUIV=\"Refresh\" "
2315 "CONTENT=\"3;URL=https://%s:%d%s\">\n",
2316 con
->servername
, con
->serverport
, con
->uri
);
2321 snprintf(message
, sizeof(message
),
2322 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" "
2323 "\"http://www.w3.org/TR/REC-html40/loose.dtd\">\n"
2326 "\t<META HTTP-EQUIV=\"Content-Type\" "
2327 "CONTENT=\"text/html; charset=utf-8\">\n"
2328 "\t<TITLE>%d %s</TITLE>\n"
2329 "\t<LINK REL=\"STYLESHEET\" TYPE=\"text/css\" "
2330 "HREF=\"/cups.css\">\n"
2338 code
, httpStatus(code
), redirect
, code
, httpStatus(code
), text
);
2340 if (httpPrintf(HTTP(con
), "Content-Type: text/html; charset=utf-8\r\n") < 0)
2342 if (httpPrintf(HTTP(con
), "Content-Length: %d\r\n",
2343 (int)strlen(message
)) < 0)
2345 if (httpPrintf(HTTP(con
), "\r\n") < 0)
2347 if (httpPrintf(HTTP(con
), "%s", message
) < 0)
2350 else if (httpPrintf(HTTP(con
), "\r\n") < 0)
2353 if (cupsdFlushHeader(con
) < 0)
2356 con
->http
.state
= HTTP_WAITING
;
2363 * 'cupsdSendHeader()' - Send an HTTP request.
2366 int /* O - 1 on success, 0 on failure */
2368 cupsd_client_t
*con
, /* I - Client to send to */
2369 http_status_t code
, /* I - HTTP status code */
2370 char *type
, /* I - MIME type of document */
2371 int auth_type
) /* I - Type of authentication */
2373 char auth_str
[1024]; /* Authorization string */
2375 static char *gss_buf
= NULL
; /* Kerberos auth data buffer */
2376 static int gss_bufsize
= 0; /* Size of Kerberos auth data buffer */
2377 #endif /* HAVE_GSSAPI */
2381 * Send the HTTP status header...
2384 if (code
== HTTP_CONTINUE
)
2387 * 100-continue doesn't send any headers...
2390 return (httpPrintf(HTTP(con
), "HTTP/%d.%d 100 Continue\r\n\r\n",
2391 con
->http
.version
/ 100, con
->http
.version
% 100) > 0);
2394 httpFlushWrite(HTTP(con
));
2396 con
->http
.data_encoding
= HTTP_ENCODE_FIELDS
;
2398 if (httpPrintf(HTTP(con
), "HTTP/%d.%d %d %s\r\n", con
->http
.version
/ 100,
2399 con
->http
.version
% 100, code
, httpStatus(code
)) < 0)
2401 if (httpPrintf(HTTP(con
), "Date: %s\r\n", httpGetDateString(time(NULL
))) < 0)
2404 if (httpPrintf(HTTP(con
), "Server: %s\r\n", ServerHeader
) < 0)
2406 if (con
->http
.keep_alive
&& con
->http
.version
>= HTTP_1_0
)
2408 if (httpPrintf(HTTP(con
), "Connection: Keep-Alive\r\n") < 0)
2410 if (httpPrintf(HTTP(con
), "Keep-Alive: timeout=%d\r\n",
2411 KeepAliveTimeout
) < 0)
2414 if (code
== HTTP_METHOD_NOT_ALLOWED
)
2415 if (httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST\r\n") < 0)
2418 if (code
== HTTP_UNAUTHORIZED
)
2420 if (auth_type
== CUPSD_AUTH_NONE
)
2422 if (!con
->best
|| con
->best
->type
<= CUPSD_AUTH_NONE
)
2423 auth_type
= DefaultAuthType
;
2425 auth_type
= con
->best
->type
;
2430 if (auth_type
== CUPSD_AUTH_BASIC
|| auth_type
== CUPSD_AUTH_BASICDIGEST
)
2431 strlcpy(auth_str
, "Basic realm=\"CUPS\"", sizeof(auth_str
));
2432 else if (auth_type
== CUPSD_AUTH_DIGEST
)
2433 snprintf(auth_str
, sizeof(auth_str
), "Digest realm=\"CUPS\", nonce=\"%s\"",
2434 con
->http
.hostname
);
2436 else if (auth_type
== CUPSD_AUTH_NEGOTIATE
&& con
->gss_output_token
.length
== 0)
2437 strlcpy(auth_str
, "Negotiate", sizeof(auth_str
));
2438 #endif /* HAVE_GSSAPI */
2440 #ifdef HAVE_AUTHORIZATION_H
2441 if (con
->best
&& auth_type
!= CUPSD_AUTH_NEGOTIATE
)
2443 int i
; /* Looping var */
2444 char *auth_key
; /* Auth key buffer */
2445 size_t auth_size
; /* Size of remaining buffer */
2448 auth_key
= auth_str
+ strlen(auth_str
);
2449 auth_size
= sizeof(auth_str
) - (auth_key
- auth_str
);
2451 for (i
= 0; i
< con
->best
->num_names
; i
++)
2453 if (!strncasecmp(con
->best
->names
[i
], "@AUTHKEY(", 9))
2455 snprintf(auth_key
, auth_size
, ", authkey=\"%s\"",
2456 con
->best
->names
[i
] + 9);
2457 /* end parenthesis is stripped in conf.c */
2460 else if (!strcasecmp(con
->best
->names
[i
], "@SYSTEM") &&
2463 snprintf(auth_key
, auth_size
, ", authkey=\"%s\"", SystemGroupAuthKey
);
2468 #endif /* HAVE_AUTHORIZATION_H */
2472 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendHeader: WWW-Authenticate: %s",
2475 if (httpPrintf(HTTP(con
), "WWW-Authenticate: %s\r\n", auth_str
) < 0)
2482 * WWW-Authenticate: Negotiate can be included even for
2483 * non-401 replies...
2486 if (con
->gss_output_token
.length
> 0 && con
->gss_output_token
.length
<= 65536)
2488 OM_uint32 minor_status
; /* Minor status code */
2489 int bufsize
; /* Size of output token buffer */
2492 bufsize
= con
->gss_output_token
.length
* 4 / 3 + 2;
2494 if (bufsize
> gss_bufsize
)
2496 char *buf
; /* New buffer */
2499 bufsize
= (bufsize
+ 1023) & 1023;/* Round up */
2502 buf
= realloc(gss_buf
, bufsize
);
2504 buf
= malloc(bufsize
);
2508 cupsdLogMessage(CUPSD_LOG_ERROR
,
2509 "Unable to allocate %d bytes for Kerberos credentials!",
2515 gss_bufsize
= bufsize
;
2518 httpEncode64_2(gss_buf
, gss_bufsize
,
2519 con
->gss_output_token
.value
,
2520 con
->gss_output_token
.length
);
2521 gss_release_buffer(&minor_status
, &con
->gss_output_token
);
2523 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2524 "cupsdSendHeader: WWW-Authenticate: Negotiate %s", gss_buf
);
2526 if (httpPrintf(HTTP(con
), "WWW-Authenticate: Negotiate %s\r\n",
2530 else if (con
->gss_output_token
.length
> 65536)
2532 cupsdLogMessage(CUPSD_LOG_ERROR
,
2533 "Kerberos credentials larger than 64k (%d)!",
2534 (int)con
->gss_output_token
.length
);
2537 #endif /* HAVE_GSSAPI */
2539 if (con
->language
&& strcmp(con
->language
->language
, "C"))
2541 if (httpPrintf(HTTP(con
), "Content-Language: %s\r\n",
2542 con
->language
->language
) < 0)
2548 if (!strcmp(type
, "text/html"))
2550 if (httpPrintf(HTTP(con
),
2551 "Content-Type: text/html; charset=utf-8\r\n") < 0)
2554 else if (httpPrintf(HTTP(con
), "Content-Type: %s\r\n", type
) < 0)
2563 * 'cupsdUpdateCGI()' - Read status messages from CGI scripts and programs.
2567 cupsdUpdateCGI(void)
2569 char *ptr
, /* Pointer to end of line in buffer */
2570 message
[1024]; /* Pointer to message text */
2571 int loglevel
; /* Log level for message */
2574 while ((ptr
= cupsdStatBufUpdate(CGIStatusBuffer
, &loglevel
,
2575 message
, sizeof(message
))) != NULL
)
2576 if (!strchr(CGIStatusBuffer
->buffer
, '\n'))
2579 if (ptr
== NULL
&& !CGIStatusBuffer
->bufused
)
2582 * Fatal error on pipe - should never happen!
2585 cupsdLogMessage(CUPSD_LOG_CRIT
,
2586 "cupsdUpdateCGI: error reading from CGI error pipe - %s",
2593 * 'cupsdWriteClient()' - Write data to a client as needed.
2597 cupsdWriteClient(cupsd_client_t
*con
) /* I - Client connection */
2599 int bytes
; /* Number of bytes written */
2600 char buf
[16385]; /* Data buffer */
2601 char *bufptr
; /* Pointer into buffer */
2602 ipp_state_t ipp_state
; /* IPP state value */
2606 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2607 "cupsdWriteClient(con=%p) %d response=%p(%d), file=%d "
2608 "pipe_pid=%d state=%d",
2609 con
, con
->http
.fd
, con
->response
,
2610 con
->response
? con
->response
->state
: -1,
2611 con
->file
, con
->pipe_pid
, con
->http
.state
);
2614 if (con
->http
.state
!= HTTP_GET_SEND
&&
2615 con
->http
.state
!= HTTP_POST_SEND
)
2621 * Make sure we select on the CGI output...
2624 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2626 if (!con
->file_ready
)
2629 * Try again later when there is CGI output available...
2632 cupsdRemoveSelect(con
->http
.fd
);
2636 con
->file_ready
= 0;
2639 if (con
->response
&& con
->response
->state
!= IPP_DATA
)
2641 ipp_state
= ippWrite(HTTP(con
), con
->response
);
2642 bytes
= ipp_state
!= IPP_ERROR
&&
2643 (con
->file
>= 0 || ipp_state
!= IPP_DATA
);
2645 else if ((bytes
= read(con
->file
, buf
, sizeof(buf
) - 1)) > 0)
2647 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2648 "cupsdWriteClient: Read %d bytes from file %d...",
2651 if (con
->pipe_pid
&& !con
->got_fields
)
2654 * Inspect the data for Content-Type and other fields.
2659 for (bufptr
= buf
; !con
->got_fields
&& *bufptr
; bufptr
++)
2660 if (*bufptr
== '\n')
2663 * Send line to client...
2666 if (bufptr
> buf
&& bufptr
[-1] == '\r')
2670 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "Script header: %s", buf
);
2672 if (!con
->sent_header
)
2675 * Handle redirection and CGI status codes...
2678 if (!strncasecmp(buf
, "Location:", 9))
2680 cupsdSendHeader(con
, HTTP_SEE_OTHER
, NULL
, CUPSD_AUTH_NONE
);
2681 con
->sent_header
= 2;
2683 if (httpPrintf(HTTP(con
), "Content-Length: 0\r\n") < 0)
2686 else if (!strncasecmp(buf
, "Status:", 7))
2688 cupsdSendError(con
, (http_status_t
)atoi(buf
+ 7), CUPSD_AUTH_NONE
);
2689 con
->sent_header
= 2;
2693 cupsdSendHeader(con
, HTTP_OK
, NULL
, CUPSD_AUTH_NONE
);
2694 con
->sent_header
= 1;
2696 if (con
->http
.version
== HTTP_1_1
)
2698 if (httpPrintf(HTTP(con
), "Transfer-Encoding: chunked\r\n") < 0)
2704 if (strncasecmp(buf
, "Status:", 7))
2705 httpPrintf(HTTP(con
), "%s\r\n", buf
);
2707 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdWriteClient: %d %s",
2714 bytes
-= (bufptr
- buf
);
2715 memmove(buf
, bufptr
, bytes
+ 1);
2719 * See if the line was empty...
2722 if (con
->field_col
== 0)
2724 con
->got_fields
= 1;
2726 if (cupsdFlushHeader(con
) < 0)
2728 cupsdCloseClient(con
);
2732 if (con
->http
.version
== HTTP_1_1
)
2733 con
->http
.data_encoding
= HTTP_ENCODE_CHUNKED
;
2738 else if (*bufptr
!= '\r')
2741 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2742 "cupsdWriteClient: %d bytes=%d, got_fields=%d",
2743 con
->http
.fd
, bytes
, con
->got_fields
);
2745 if (bytes
> 0 && !con
->got_fields
)
2748 * Remaining text needs to go out...
2751 httpPrintf(HTTP(con
), "%s", buf
);
2753 con
->http
.activity
= time(NULL
);
2756 else if (bytes
== 0)
2757 con
->http
.activity
= time(NULL
);
2762 if (httpWrite2(HTTP(con
), buf
, bytes
) < 0)
2764 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2765 "cupsdWriteClient: %d Write of %d bytes failed!",
2766 con
->http
.fd
, bytes
);
2768 cupsdCloseClient(con
);
2772 httpFlushWrite(HTTP(con
));
2774 con
->bytes
+= bytes
;
2776 if (con
->http
.state
== HTTP_WAITING
)
2783 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdWriteClient: %d bytes < 0",
2786 cupsdLogRequest(con
, HTTP_OK
);
2788 httpFlushWrite(HTTP(con
));
2790 if (con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
&& con
->sent_header
== 1)
2792 if (httpWrite2(HTTP(con
), "", 0) < 0)
2794 cupsdCloseClient(con
);
2799 con
->http
.state
= HTTP_WAITING
;
2801 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
2805 cupsdRemoveSelect(con
->file
);
2808 cupsdEndProcess(con
->pipe_pid
, 0);
2810 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2811 "cupsdWriteClient: %d Closing data file %d.",
2812 con
->http
.fd
, con
->file
);
2821 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2822 "cupsdWriteClient: %d Removing temp file %s",
2823 con
->http
.fd
, con
->filename
);
2824 unlink(con
->filename
);
2825 cupsdClearString(&con
->filename
);
2830 ippDelete(con
->request
);
2831 con
->request
= NULL
;
2836 ippDelete(con
->response
);
2837 con
->response
= NULL
;
2840 cupsdClearString(&con
->command
);
2841 cupsdClearString(&con
->options
);
2842 cupsdClearString(&con
->query_string
);
2844 if (!con
->http
.keep_alive
)
2846 cupsdCloseClient(con
);
2851 con
->http
.activity
= time(NULL
);
2856 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
2859 static int /* O - 1 if modified since */
2861 cupsd_client_t
*con
, /* I - Client connection */
2862 struct stat
*filestats
) /* I - File information */
2864 char *ptr
; /* Pointer into field */
2865 time_t date
; /* Time/date value */
2866 off_t size
; /* Size/length value */
2871 ptr
= con
->http
.fields
[HTTP_FIELD_IF_MODIFIED_SINCE
];
2876 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2877 "check_if_modified: %d If-Modified-Since=\"%s\"",
2880 while (*ptr
!= '\0')
2882 while (isspace(*ptr
) || *ptr
== ';')
2885 if (strncasecmp(ptr
, "length=", 7) == 0)
2888 size
= strtoll(ptr
, NULL
, 10);
2890 while (isdigit(*ptr
))
2893 else if (isalpha(*ptr
))
2895 date
= httpGetDateTime(ptr
);
2896 while (*ptr
!= '\0' && *ptr
!= ';')
2903 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2904 "check_if_modified: %d sizes=" CUPS_LLFMT
","
2905 CUPS_LLFMT
" dates=%d,%d",
2906 con
->http
.fd
, CUPS_LLCAST size
,
2907 CUPS_LLCAST filestats
->st_size
, (int)date
,
2908 (int)filestats
->st_mtime
);
2910 return ((size
!= filestats
->st_size
&& size
!= 0) ||
2911 (date
< filestats
->st_mtime
&& date
!= 0) ||
2912 (size
== 0 && date
== 0));
2918 * 'encrypt_client()' - Enable encryption for the client...
2921 static int /* O - 1 on success, 0 on error */
2922 encrypt_client(cupsd_client_t
*con
) /* I - Client to encrypt */
2925 SSL_CTX
*context
; /* Context for encryption */
2926 SSL
*conn
; /* Connection for encryption */
2927 BIO
*bio
; /* BIO data */
2928 unsigned long error
; /* Error code */
2932 * Verify that we have a certificate...
2935 if (access(ServerKey
, 0) || access(ServerCertificate
, 0))
2938 * Nope, make a self-signed certificate...
2941 if (!make_certificate(con
))
2946 * Create the SSL context and accept the connection...
2949 context
= SSL_CTX_new(SSLv23_server_method());
2951 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
2952 SSL_CTX_use_PrivateKey_file(context
, ServerKey
, SSL_FILETYPE_PEM
);
2953 SSL_CTX_use_certificate_file(context
, ServerCertificate
, SSL_FILETYPE_PEM
);
2955 bio
= BIO_new(_httpBIOMethods());
2956 BIO_ctrl(bio
, BIO_C_SET_FILE_PTR
, 0, (char *)HTTP(con
));
2958 conn
= SSL_new(context
);
2959 SSL_set_bio(conn
, bio
, bio
);
2961 if (SSL_accept(conn
) != 1)
2963 cupsdLogMessage(CUPSD_LOG_ERROR
,
2964 "encrypt_client: Unable to encrypt connection from %s!",
2965 con
->http
.hostname
);
2967 while ((error
= ERR_get_error()) != 0)
2968 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s",
2969 ERR_error_string(error
, NULL
));
2971 SSL_CTX_free(context
);
2976 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2977 "encrypt_client: %d Connection from %s now encrypted.",
2978 con
->http
.fd
, con
->http
.hostname
);
2980 con
->http
.tls
= conn
;
2983 # elif defined(HAVE_GNUTLS)
2984 http_tls_t
*conn
; /* TLS session object */
2985 int error
; /* Error code */
2986 gnutls_certificate_server_credentials
*credentials
;
2987 /* TLS credentials */
2991 * Verify that we have a certificate...
2994 if (access(ServerKey
, 0) || access(ServerCertificate
, 0))
2997 * Nope, make a self-signed certificate...
3000 if (!make_certificate(con
))
3005 * Create the SSL object and perform the SSL handshake...
3008 conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
));
3013 credentials
= (gnutls_certificate_server_credentials
*)
3014 malloc(sizeof(gnutls_certificate_server_credentials
));
3015 if (credentials
== NULL
)
3017 cupsdLogMessage(CUPSD_LOG_ERROR
,
3018 "encrypt_client: Unable to encrypt connection from %s!",
3019 con
->http
.hostname
);
3020 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s", strerror(errno
));
3026 gnutls_certificate_allocate_credentials(credentials
);
3027 gnutls_certificate_set_x509_key_file(*credentials
, ServerCertificate
,
3028 ServerKey
, GNUTLS_X509_FMT_PEM
);
3030 gnutls_init(&(conn
->session
), GNUTLS_SERVER
);
3031 gnutls_set_default_priority(conn
->session
);
3032 gnutls_credentials_set(conn
->session
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
3033 gnutls_transport_set_ptr(conn
->session
, (gnutls_transport_ptr
)HTTP(con
));
3034 gnutls_transport_set_pull_function(conn
->session
, _httpReadGNUTLS
);
3035 gnutls_transport_set_push_function(conn
->session
, _httpWriteGNUTLS
);
3037 error
= gnutls_handshake(conn
->session
);
3039 if (error
!= GNUTLS_E_SUCCESS
)
3041 cupsdLogMessage(CUPSD_LOG_ERROR
,
3042 "encrypt_client: Unable to encrypt connection from %s!",
3043 con
->http
.hostname
);
3044 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s",
3045 gnutls_strerror(error
));
3047 gnutls_deinit(conn
->session
);
3048 gnutls_certificate_free_credentials(*credentials
);
3054 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3055 "encrypt_client: %d Connection from %s now encrypted.",
3056 con
->http
.fd
, con
->http
.hostname
);
3058 conn
->credentials
= credentials
;
3059 con
->http
.tls
= conn
;
3062 # elif defined(HAVE_CDSASSL)
3063 OSStatus error
; /* Error code */
3064 http_tls_t
*conn
; /* CDSA connection information */
3067 if ((conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
))) == NULL
)
3071 conn
->session
= NULL
;
3072 conn
->certsArray
= get_cdsa_certificate(con
);
3074 if (!conn
->certsArray
)
3077 * No keychain (yet), make a self-signed certificate...
3080 if (make_certificate(con
))
3081 conn
->certsArray
= get_cdsa_certificate(con
);
3084 if (!conn
->certsArray
)
3086 cupsdLogMessage(CUPSD_LOG_ERROR
,
3087 "encrypt_client: Could not find signing key in keychain "
3088 "\"%s\"", ServerCertificate
);
3089 error
= errSSLBadCert
; /* errSSLBadConfiguration is a better choice, but not available on 10.2.x */
3093 error
= SSLNewContext(true, &conn
->session
);
3096 error
= SSLSetIOFuncs(conn
->session
, _httpReadCDSA
, _httpWriteCDSA
);
3099 error
= SSLSetProtocolVersionEnabled(conn
->session
, kSSLProtocol2
, false);
3102 error
= SSLSetConnection(conn
->session
, HTTP(con
));
3105 error
= SSLSetAllowsExpiredCerts(conn
->session
, true);
3108 error
= SSLSetAllowsAnyRoot(conn
->session
, true);
3111 error
= SSLSetCertificate(conn
->session
, conn
->certsArray
);
3116 * Perform SSL/TLS handshake
3119 while ((error
= SSLHandshake(conn
->session
)) == errSSLWouldBlock
)
3125 cupsdLogMessage(CUPSD_LOG_ERROR
,
3126 "encrypt_client: Unable to encrypt connection from %s!",
3127 con
->http
.hostname
);
3129 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s (%d)",
3130 cssmErrorString(error
), (int)error
);
3132 con
->http
.error
= error
;
3133 con
->http
.status
= HTTP_ERROR
;
3136 SSLDisposeContext(conn
->session
);
3138 if (conn
->certsArray
)
3139 CFRelease(conn
->certsArray
);
3146 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3147 "encrypt_client: %d Connection from %s now encrypted.",
3148 con
->http
.fd
, con
->http
.hostname
);
3150 con
->http
.tls
= conn
;
3153 # endif /* HAVE_LIBSSL */
3155 #endif /* HAVE_SSL */
3160 * 'get_cdsa_certificate()' - Get a SSL/TLS certificate from the System keychain.
3163 static CFArrayRef
/* O - Array of certificates */
3164 get_cdsa_certificate(cupsd_client_t
*con
) /* I - Client connection */
3166 OSStatus err
; /* Error info */
3167 SecKeychainRef keychain
; /* Keychain reference */
3168 SecIdentitySearchRef search
; /* Search reference */
3169 SecIdentityRef identity
; /* Identity */
3170 CFArrayRef certificates
= NULL
;
3171 /* Certificate array */
3174 if ((err
= SecKeychainOpen(ServerCertificate
, &keychain
)))
3176 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot open keychain \"%s\", %s",
3177 ServerCertificate
, cssmErrorString(err
));
3181 # if HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY
3183 * Use a policy to search for valid certificates who's common name matches the
3187 SecPolicySearchRef policy_search
; /* Policy search ref */
3188 SecPolicyRef policy
; /* Policy ref */
3189 CSSM_DATA options
; /* Policy options */
3190 CSSM_APPLE_TP_SSL_OPTIONS
3191 ssl_options
; /* SSL Option for hostname */
3194 if ((err
= SecPolicySearchCreate(CSSM_CERT_X_509v3
, &CSSMOID_APPLE_TP_SSL
,
3195 NULL
, &policy_search
)))
3197 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot create a policy search reference");
3198 CFRelease(keychain
);
3202 if ((err
= SecPolicySearchCopyNext(policy_search
, &policy
)))
3204 cupsdLogMessage(CUPSD_LOG_ERROR
,
3205 "Cannot find a policy to use for searching");
3206 CFRelease(keychain
);
3207 CFRelease(policy_search
);
3211 memset(&ssl_options
, 0, sizeof(ssl_options
));
3212 ssl_options
.Version
= CSSM_APPLE_TP_SSL_OPTS_VERSION
;
3213 ssl_options
.ServerName
= con
->servername
;
3214 ssl_options
.ServerNameLen
= strlen(con
->servername
);
3216 options
.Data
= (uint8
*)&ssl_options
;
3217 options
.Length
= sizeof(ssl_options
);
3219 if ((err
= SecPolicySetValue(policy
, &options
)))
3221 cupsdLogMessage(CUPSD_LOG_ERROR
,
3222 "Cannot set policy value to use for searching");
3223 CFRelease(keychain
);
3224 CFRelease(policy_search
);
3228 err
= SecIdentitySearchCreateWithPolicy(policy
, NULL
, CSSM_KEYUSE_SIGN
,
3229 keychain
, FALSE
, &search
);
3232 * Assume there is exactly one SecIdentity in the keychain...
3235 err
= SecIdentitySearchCreate(keychain
, CSSM_KEYUSE_SIGN
, &search
);
3236 # endif /* HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY */
3239 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3240 "Cannot create keychain search reference: %s",
3241 cssmErrorString(err
));
3244 if ((err
= SecIdentitySearchCopyNext(search
, &identity
)))
3246 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3247 "Cannot find signing key in keychain \"%s\", error %d",
3248 ServerCertificate
, (int)err
);
3252 if (CFGetTypeID(identity
) != SecIdentityGetTypeID())
3253 cupsdLogMessage(CUPSD_LOG_ERROR
,
3254 "SecIdentitySearchCopyNext CFTypeID failure!");
3257 if ((certificates
= CFArrayCreate(NULL
, (const void **)&identity
,
3258 1, &kCFTypeArrayCallBacks
)) == NULL
)
3259 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot create certificate array");
3262 CFRelease(identity
);
3268 # if HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY
3270 CFRelease(policy_search
);
3271 # endif /* HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY */
3273 return (certificates
);
3275 #endif /* HAVE_CDSASSL */
3279 * 'get_file()' - Get a filename and state info.
3282 static char * /* O - Real filename */
3283 get_file(cupsd_client_t
*con
, /* I - Client connection */
3284 struct stat
*filestats
, /* O - File information */
3285 char *filename
, /* IO - Filename buffer */
3286 int len
) /* I - Buffer length */
3288 int status
; /* Status of filesystem calls */
3289 char *ptr
; /* Pointer info filename */
3290 int plen
; /* Remaining length after pointer */
3291 char language
[7]; /* Language subdirectory, if any */
3295 * Figure out the real filename...
3300 if (!strncmp(con
->uri
, "/ppd/", 5))
3301 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
);
3302 else if (!strncmp(con
->uri
, "/rss/", 5) && !strchr(con
->uri
+ 5, '/'))
3303 snprintf(filename
, len
, "%s/rss/%s", CacheDir
, con
->uri
+ 5);
3304 else if (!strncmp(con
->uri
, "/admin/conf/", 12))
3305 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
+ 11);
3306 else if (!strncmp(con
->uri
, "/admin/log/", 11))
3308 if (!strncmp(con
->uri
+ 11, "access_log", 10) && AccessLog
[0] == '/')
3309 strlcpy(filename
, AccessLog
, len
);
3310 else if (!strncmp(con
->uri
+ 11, "error_log", 9) && ErrorLog
[0] == '/')
3311 strlcpy(filename
, ErrorLog
, len
);
3312 else if (!strncmp(con
->uri
+ 11, "page_log", 8) && PageLog
[0] == '/')
3313 strlcpy(filename
, PageLog
, len
);
3317 else if (con
->language
)
3319 snprintf(language
, sizeof(language
), "/%s", con
->language
->language
);
3320 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3323 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3325 if ((ptr
= strchr(filename
, '?')) != NULL
)
3329 * Grab the status for this language; if there isn't a language-specific file
3330 * then fallback to the default one...
3333 if ((status
= stat(filename
, filestats
)) != 0 && language
[0] &&
3334 strncmp(con
->uri
, "/ppd/", 5) &&
3335 strncmp(con
->uri
, "/admin/conf/", 12) &&
3336 strncmp(con
->uri
, "/admin/log/", 11))
3339 * Drop the country code...
3343 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3345 if ((ptr
= strchr(filename
, '?')) != NULL
)
3348 if ((status
= stat(filename
, filestats
)) != 0)
3351 * Drop the language prefix and try the root directory...
3355 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3357 if ((ptr
= strchr(filename
, '?')) != NULL
)
3360 status
= stat(filename
, filestats
);
3365 * If we're found a directory, get the index.html file instead...
3368 if (!status
&& S_ISDIR(filestats
->st_mode
))
3371 * Make sure the URI ends with a slash...
3374 if (con
->uri
[strlen(con
->uri
) - 1] != '/')
3375 strlcat(con
->uri
, "/", sizeof(con
->uri
));
3378 * Find the directory index file, trying every language...
3383 if (status
&& language
[0])
3386 * Try a different language subset...
3390 language
[0] = '\0'; /* Strip country code */
3392 language
[0] = '\0'; /* Strip language */
3396 * Look for the index file...
3399 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3401 if ((ptr
= strchr(filename
, '?')) != NULL
)
3404 ptr
= filename
+ strlen(filename
);
3405 plen
= len
- (ptr
- filename
);
3407 strlcpy(ptr
, "index.html", plen
);
3408 status
= stat(filename
, filestats
);
3413 strlcpy(ptr
, "index.class", plen
);
3414 status
= stat(filename
, filestats
);
3416 #endif /* HAVE_JAVA */
3421 strlcpy(ptr
, "index.pl", plen
);
3422 status
= stat(filename
, filestats
);
3424 #endif /* HAVE_PERL */
3429 strlcpy(ptr
, "index.php", plen
);
3430 status
= stat(filename
, filestats
);
3432 #endif /* HAVE_PHP */
3437 strlcpy(ptr
, "index.pyc", plen
);
3438 status
= stat(filename
, filestats
);
3443 strlcpy(ptr
, "index.py", plen
);
3444 status
= stat(filename
, filestats
);
3446 #endif /* HAVE_PYTHON */
3449 while (status
&& language
[0]);
3452 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "get_file: %d filename=%s size=%d",
3453 con
->http
.fd
, filename
,
3454 status
? -1 : (int)filestats
->st_size
);
3457 con
->http
.data_remaining
= (int)filestats
->st_size
;
3467 * 'install_conf_file()' - Install a configuration file.
3470 static http_status_t
/* O - Status */
3471 install_conf_file(cupsd_client_t
*con
) /* I - Connection */
3473 cups_file_t
*in
, /* Input file */
3474 *out
; /* Output file */
3475 char buffer
[1024]; /* Copy buffer */
3476 int bytes
; /* Number of bytes */
3477 char conffile
[1024], /* Configuration filename */
3478 newfile
[1024], /* New config filename */
3479 oldfile
[1024]; /* Old config filename */
3480 struct stat confinfo
; /* Config file info */
3484 * First construct the filenames...
3487 snprintf(conffile
, sizeof(conffile
), "%s%s", ServerRoot
, con
->uri
+ 11);
3488 snprintf(newfile
, sizeof(newfile
), "%s%s.N", ServerRoot
, con
->uri
+ 11);
3489 snprintf(oldfile
, sizeof(oldfile
), "%s%s.O", ServerRoot
, con
->uri
+ 11);
3491 cupsdLogMessage(CUPSD_LOG_INFO
, "Installing config file \"%s\"...", conffile
);
3494 * Get the owner, group, and permissions of the configuration file.
3495 * If it doesn't exist, assign it to the User and Group in the
3496 * cupsd.conf file with mode 0640 permissions.
3499 if (stat(conffile
, &confinfo
))
3501 confinfo
.st_uid
= User
;
3502 confinfo
.st_gid
= Group
;
3503 confinfo
.st_mode
= ConfigFilePerm
;
3507 * Open the request file and new config file...
3510 if ((in
= cupsFileOpen(con
->filename
, "rb")) == NULL
)
3512 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open request file \"%s\" - %s",
3513 con
->filename
, strerror(errno
));
3514 return (HTTP_SERVER_ERROR
);
3517 if ((out
= cupsFileOpen(newfile
, "wb")) == NULL
)
3520 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open config file \"%s\" - %s",
3521 newfile
, strerror(errno
));
3522 return (HTTP_SERVER_ERROR
);
3525 fchmod(cupsFileNumber(out
), confinfo
.st_mode
);
3526 fchown(cupsFileNumber(out
), confinfo
.st_uid
, confinfo
.st_gid
);
3529 * Copy from the request to the new config file...
3532 while ((bytes
= cupsFileRead(in
, buffer
, sizeof(buffer
))) > 0)
3533 if (cupsFileWrite(out
, buffer
, bytes
) < bytes
)
3535 cupsdLogMessage(CUPSD_LOG_ERROR
,
3536 "Unable to copy to config file \"%s\" - %s",
3537 newfile
, strerror(errno
));
3543 return (HTTP_SERVER_ERROR
);
3547 * Close the files...
3551 if (cupsFileClose(out
))
3553 cupsdLogMessage(CUPSD_LOG_ERROR
,
3554 "Error file closing config file \"%s\" - %s",
3555 newfile
, strerror(errno
));
3559 return (HTTP_SERVER_ERROR
);
3563 * Remove the request file...
3566 unlink(con
->filename
);
3567 cupsdClearString(&con
->filename
);
3570 * Unlink the old backup, rename the current config file to the backup
3571 * filename, and rename the new config file to the config file name...
3574 if (unlink(oldfile
))
3575 if (errno
!= ENOENT
)
3577 cupsdLogMessage(CUPSD_LOG_ERROR
,
3578 "Unable to remove backup config file \"%s\" - %s",
3579 oldfile
, strerror(errno
));
3583 return (HTTP_SERVER_ERROR
);
3586 if (rename(conffile
, oldfile
))
3587 if (errno
!= ENOENT
)
3589 cupsdLogMessage(CUPSD_LOG_ERROR
,
3590 "Unable to rename old config file \"%s\" - %s",
3591 conffile
, strerror(errno
));
3595 return (HTTP_SERVER_ERROR
);
3598 if (rename(newfile
, conffile
))
3600 cupsdLogMessage(CUPSD_LOG_ERROR
,
3601 "Unable to rename new config file \"%s\" - %s",
3602 newfile
, strerror(errno
));
3604 rename(oldfile
, conffile
);
3607 return (HTTP_SERVER_ERROR
);
3611 * If the cupsd.conf file was updated, set the NeedReload flag...
3614 if (!strcmp(con
->uri
, "/admin/conf/cupsd.conf"))
3615 NeedReload
= RELOAD_CUPSD
;
3617 NeedReload
= RELOAD_ALL
;
3619 ReloadTime
= time(NULL
);
3622 * Return that the file was created successfully...
3625 return (HTTP_CREATED
);
3630 * 'is_cgi()' - Is the resource a CGI script/program?
3633 static int /* O - 1 = CGI, 0 = file */
3634 is_cgi(cupsd_client_t
*con
, /* I - Client connection */
3635 const char *filename
, /* I - Real filename */
3636 struct stat
*filestats
, /* I - File information */
3637 mime_type_t
*type
) /* I - MIME type */
3639 const char *options
; /* Options on URL */
3642 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3643 "is_cgi(con=%p, filename=\"%s\", filestats=%p, type=%s/%s)\n",
3644 con
, filename
, filestats
, type
? type
->super
: "unknown",
3645 type
? type
->type
: "unknown");
3648 * Get the options, if any...
3651 if ((options
= strchr(con
->uri
, '?')) != NULL
)
3655 if (strchr(options
, '='))
3656 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", options
);
3660 * Check for known types...
3663 if (!type
|| strcasecmp(type
->super
, "application"))
3665 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "is_cgi: Returning 0...");
3669 if (!strcasecmp(type
->type
, "x-httpd-cgi") &&
3670 (filestats
->st_mode
& 0111))
3673 * "application/x-httpd-cgi" is a CGI script.
3676 cupsdSetString(&con
->command
, filename
);
3678 filename
= strrchr(filename
, '/') + 1; /* Filename always absolute */
3680 cupsdSetString(&con
->options
, options
);
3682 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3683 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3684 con
->command
, con
->options
);
3689 else if (!strcasecmp(type
->type
, "x-httpd-java"))
3692 * "application/x-httpd-java" is a Java servlet.
3695 cupsdSetString(&con
->command
, CUPS_JAVA
);
3698 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3700 cupsdSetStringf(&con
->options
, " %s", filename
);
3702 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3703 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3704 con
->command
, con
->options
);
3708 #endif /* HAVE_JAVA */
3710 else if (!strcasecmp(type
->type
, "x-httpd-perl"))
3713 * "application/x-httpd-perl" is a Perl page.
3716 cupsdSetString(&con
->command
, CUPS_PERL
);
3719 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3721 cupsdSetStringf(&con
->options
, " %s", filename
);
3723 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3724 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3725 con
->command
, con
->options
);
3729 #endif /* HAVE_PERL */
3731 else if (!strcasecmp(type
->type
, "x-httpd-php"))
3734 * "application/x-httpd-php" is a PHP page.
3737 cupsdSetString(&con
->command
, CUPS_PHP
);
3740 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3742 cupsdSetStringf(&con
->options
, " %s", filename
);
3744 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3745 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3746 con
->command
, con
->options
);
3750 #endif /* HAVE_PHP */
3752 else if (!strcasecmp(type
->type
, "x-httpd-python"))
3755 * "application/x-httpd-python" is a Python page.
3758 cupsdSetString(&con
->command
, CUPS_PYTHON
);
3761 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3763 cupsdSetStringf(&con
->options
, " %s", filename
);
3765 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3766 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3767 con
->command
, con
->options
);
3771 #endif /* HAVE_PYTHON */
3773 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "is_cgi: Returning 0...");
3780 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
3783 static int /* O - 0 if relative, 1 if absolute */
3784 is_path_absolute(const char *path
) /* I - Input path */
3787 * Check for a leading slash...
3794 * Check for "/.." in the path...
3797 while ((path
= strstr(path
, "/..")) != NULL
)
3799 if (!path
[3] || path
[3] == '/')
3806 * If we haven't found any relative paths, return 1 indicating an
3816 * 'make_certificate()' - Make a self-signed SSL/TLS certificate.
3819 static int /* O - 1 on success, 0 on failure */
3820 make_certificate(cupsd_client_t
*con
) /* I - Client connection */
3822 #if defined(HAVE_LIBSSL) && defined(HAVE_WAITPID)
3823 int pid
, /* Process ID of command */
3824 status
; /* Status of command */
3825 char command
[1024], /* Command */
3826 *argv
[12], /* Command-line arguments */
3827 *envp
[MAX_ENV
+ 1], /* Environment variables */
3828 home
[1024], /* HOME environment variable */
3829 infofile
[1024], /* Type-in information for cert */
3830 seedfile
[1024]; /* Random number seed file */
3831 int envc
, /* Number of environment variables */
3832 bytes
; /* Bytes written */
3833 cups_file_t
*fp
; /* Seed/info file */
3834 int infofd
; /* Info file descriptor */
3838 * Run the "openssl" command to seed the random number generator and
3839 * generate a self-signed certificate that is good for 10 years:
3841 * openssl rand -rand seedfile 1
3843 * openssl req -new -x509 -keyout ServerKey \
3844 * -out ServerCertificate -days 3650 -nodes
3846 * The seeding step is crucial in ensuring that the openssl command
3847 * does not block on systems without sufficient entropy...
3850 if (!cupsFileFind("openssl", getenv("PATH"), 1, command
, sizeof(command
)))
3852 cupsdLogMessage(CUPSD_LOG_ERROR
,
3853 "No SSL certificate and openssl command not found!");
3857 if (access("/dev/urandom", 0))
3860 * If the system doesn't provide /dev/urandom, then any random source
3861 * will probably be blocking-style, so generate some random data to
3862 * use as a seed for the certificate. Note that we have already
3863 * seeded the random number generator in cupsdInitCerts()...
3866 cupsdLogMessage(CUPSD_LOG_INFO
,
3867 "Seeding the random number generator...");
3869 snprintf(home
, sizeof(home
), "HOME=%s", TempDir
);
3872 * Write the seed file...
3875 if ((fp
= cupsTempFile2(seedfile
, sizeof(seedfile
))) == NULL
)
3877 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to create seed file %s - %s",
3878 seedfile
, strerror(errno
));
3882 for (bytes
= 0; bytes
< 262144; bytes
++)
3883 cupsFilePutChar(fp
, random());
3888 * Run the openssl command to seed its random number generator...
3891 argv
[0] = "openssl";
3898 envc
= cupsdLoadEnv(envp
, MAX_ENV
);
3899 envp
[envc
++] = home
;
3902 if (!cupsdStartProcess(command
, argv
, envp
, -1, -1, -1, -1, -1, 1, NULL
,
3909 while (waitpid(pid
, &status
, 0) < 0)
3916 cupsdFinishProcess(pid
, command
, sizeof(command
));
3919 * Remove the seed file, as it is no longer needed...
3926 if (WIFEXITED(status
))
3927 cupsdLogMessage(CUPSD_LOG_ERROR
,
3928 "Unable to seed random number generator - "
3929 "the openssl command stopped with status %d!",
3930 WEXITSTATUS(status
));
3932 cupsdLogMessage(CUPSD_LOG_ERROR
,
3933 "Unable to seed random number generator - "
3934 "the openssl command crashed on signal %d!",
3942 * Create a file with the certificate information fields...
3944 * Note: This assumes that the default questions are asked by the openssl
3948 if ((fp
= cupsTempFile2(infofile
, sizeof(infofile
))) == NULL
)
3950 cupsdLogMessage(CUPSD_LOG_ERROR
,
3951 "Unable to create certificate information file %s - %s",
3952 infofile
, strerror(errno
));
3956 cupsFilePrintf(fp
, ".\n.\n.\n%s\n.\n%s\n%s\n",
3957 ServerName
, ServerName
, ServerAdmin
);
3960 cupsdLogMessage(CUPSD_LOG_INFO
,
3961 "Generating SSL server key and certificate...");
3963 argv
[0] = "openssl";
3967 argv
[4] = "-keyout";
3968 argv
[5] = ServerKey
;
3970 argv
[7] = ServerCertificate
;
3973 argv
[10] = "-nodes";
3976 cupsdLoadEnv(envp
, MAX_ENV
);
3978 infofd
= open(infofile
, O_RDONLY
);
3980 if (!cupsdStartProcess(command
, argv
, envp
, infofd
, -1, -1, -1, -1, 1, NULL
,
3991 while (waitpid(pid
, &status
, 0) < 0)
3998 cupsdFinishProcess(pid
, command
, sizeof(command
));
4002 if (WIFEXITED(status
))
4003 cupsdLogMessage(CUPSD_LOG_ERROR
,
4004 "Unable to create SSL server key and certificate - "
4005 "the openssl command stopped with status %d!",
4006 WEXITSTATUS(status
));
4008 cupsdLogMessage(CUPSD_LOG_ERROR
,
4009 "Unable to create SSL server key and certificate - "
4010 "the openssl command crashed on signal %d!",
4015 cupsdLogMessage(CUPSD_LOG_INFO
, "Created SSL server key file \"%s\"...",
4017 cupsdLogMessage(CUPSD_LOG_INFO
,
4018 "Created SSL server certificate file \"%s\"...",
4024 #elif defined(HAVE_GNUTLS)
4025 gnutls_x509_crt crt
; /* Self-signed certificate */
4026 gnutls_x509_privkey key
; /* Encryption key */
4027 cups_lang_t
*language
; /* Default language info */
4028 cups_file_t
*fp
; /* Key/cert file */
4029 unsigned char buffer
[8192]; /* Buffer for x509 data */
4030 size_t bytes
; /* Number of bytes of data */
4031 unsigned char serial
[4]; /* Serial number buffer */
4032 time_t curtime
; /* Current time */
4033 int result
; /* Result of GNU TLS calls */
4037 * Create the encryption key...
4040 cupsdLogMessage(CUPSD_LOG_INFO
, "Generating SSL server key...");
4042 gnutls_x509_privkey_init(&key
);
4043 gnutls_x509_privkey_generate(key
, GNUTLS_PK_RSA
, 2048, 0);
4049 bytes
= sizeof(buffer
);
4051 if ((result
= gnutls_x509_privkey_export(key
, GNUTLS_X509_FMT_PEM
,
4052 buffer
, &bytes
)) < 0)
4054 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to export SSL server key - %s",
4055 gnutls_strerror(result
));
4056 gnutls_x509_privkey_deinit(key
);
4059 else if ((fp
= cupsFileOpen(ServerKey
, "w")) != NULL
)
4061 cupsFileWrite(fp
, (char *)buffer
, bytes
);
4064 cupsdLogMessage(CUPSD_LOG_INFO
, "Created SSL server key file \"%s\"...",
4069 cupsdLogMessage(CUPSD_LOG_ERROR
,
4070 "Unable to create SSL server key file \"%s\" - %s",
4071 ServerKey
, strerror(errno
));
4072 gnutls_x509_privkey_deinit(key
);
4077 * Create the self-signed certificate...
4080 cupsdLogMessage(CUPSD_LOG_INFO
, "Generating self-signed SSL certificate...");
4082 language
= cupsLangDefault();
4083 curtime
= time(NULL
);
4084 serial
[0] = curtime
>> 24;
4085 serial
[1] = curtime
>> 16;
4086 serial
[2] = curtime
>> 8;
4087 serial
[3] = curtime
;
4089 gnutls_x509_crt_init(&crt
);
4090 if (strlen(language
->language
) == 5)
4091 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
4092 language
->language
+ 3, 2);
4094 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
4096 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COMMON_NAME
, 0,
4097 ServerName
, strlen(ServerName
));
4098 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATION_NAME
, 0,
4099 ServerName
, strlen(ServerName
));
4100 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATIONAL_UNIT_NAME
,
4102 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_STATE_OR_PROVINCE_NAME
, 0,
4104 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_LOCALITY_NAME
, 0,
4106 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_PKCS9_EMAIL
, 0,
4107 ServerAdmin
, strlen(ServerAdmin
));
4108 gnutls_x509_crt_set_key(crt
, key
);
4109 gnutls_x509_crt_set_serial(crt
, serial
, sizeof(serial
));
4110 gnutls_x509_crt_set_activation_time(crt
, curtime
);
4111 gnutls_x509_crt_set_expiration_time(crt
, curtime
+ 10 * 365 * 86400);
4112 gnutls_x509_crt_set_ca_status(crt
, 0);
4113 gnutls_x509_crt_set_subject_alternative_name(crt
, GNUTLS_SAN_DNSNAME
,
4115 gnutls_x509_crt_set_key_purpose_oid(crt
, GNUTLS_KP_TLS_WWW_SERVER
, 0);
4116 gnutls_x509_crt_set_key_usage(crt
, GNUTLS_KEY_KEY_ENCIPHERMENT
);
4117 gnutls_x509_crt_set_version(crt
, 3);
4119 bytes
= sizeof(buffer
);
4120 if (gnutls_x509_crt_get_key_id(crt
, 0, buffer
, &bytes
) >= 0)
4121 gnutls_x509_crt_set_subject_key_id(crt
, buffer
, bytes
);
4123 gnutls_x509_crt_sign(crt
, crt
, key
);
4129 bytes
= sizeof(buffer
);
4130 if ((result
= gnutls_x509_crt_export(crt
, GNUTLS_X509_FMT_PEM
,
4131 buffer
, &bytes
)) < 0)
4132 cupsdLogMessage(CUPSD_LOG_ERROR
,
4133 "Unable to export SSL server certificate - %s",
4134 gnutls_strerror(result
));
4135 else if ((fp
= cupsFileOpen(ServerCertificate
, "w")) != NULL
)
4137 cupsFileWrite(fp
, (char *)buffer
, bytes
);
4140 cupsdLogMessage(CUPSD_LOG_INFO
,
4141 "Created SSL server certificate file \"%s\"...",
4145 cupsdLogMessage(CUPSD_LOG_ERROR
,
4146 "Unable to create SSL server certificate file \"%s\" - %s",
4147 ServerCertificate
, strerror(errno
));
4153 gnutls_x509_crt_deinit(crt
);
4154 gnutls_x509_privkey_deinit(key
);
4158 #elif defined(HAVE_CDSASSL) && defined(HAVE_WAITPID)
4159 int pid
, /* Process ID of command */
4160 status
; /* Status of command */
4161 char command
[1024], /* Command */
4162 *argv
[4], /* Command-line arguments */
4163 *envp
[MAX_ENV
+ 1], /* Environment variables */
4164 keychain
[1024], /* Keychain argument */
4165 infofile
[1024]; /* Type-in information for cert */
4166 cups_file_t
*fp
; /* Seed/info file */
4167 int infofd
; /* Info file descriptor */
4171 * Run the "certtool" command to generate a self-signed certificate...
4174 if (!cupsFileFind("certtool", getenv("PATH"), 1, command
, sizeof(command
)))
4176 cupsdLogMessage(CUPSD_LOG_ERROR
,
4177 "No SSL certificate and certtool command not found!");
4182 * Create a file with the certificate information fields...
4184 * Note: This assumes that the default questions are asked by the certtool
4188 if ((fp
= cupsTempFile2(infofile
, sizeof(infofile
))) == NULL
)
4190 cupsdLogMessage(CUPSD_LOG_ERROR
,
4191 "Unable to create certificate information file %s - %s",
4192 infofile
, strerror(errno
));
4196 cupsFilePrintf(fp
, "%s\nr\n\ny\nb\ns\ny\n%s\n\n\n\n\n%s\ny\n",
4197 con
->servername
, con
->servername
, ServerAdmin
);
4200 cupsdLogMessage(CUPSD_LOG_INFO
,
4201 "Generating SSL server key and certificate...");
4203 snprintf(keychain
, sizeof(keychain
), "k=%s", ServerCertificate
);
4205 argv
[0] = "certtool";
4210 cupsdLoadEnv(envp
, MAX_ENV
);
4212 infofd
= open(infofile
, O_RDONLY
);
4214 if (!cupsdStartProcess(command
, argv
, envp
, infofd
, -1, -1, -1, -1, 1, NULL
,
4225 while (waitpid(pid
, &status
, 0) < 0)
4232 cupsdFinishProcess(pid
, command
, sizeof(command
));
4236 if (WIFEXITED(status
))
4237 cupsdLogMessage(CUPSD_LOG_ERROR
,
4238 "Unable to create SSL server key and certificate - "
4239 "the certtool command stopped with status %d!",
4240 WEXITSTATUS(status
));
4242 cupsdLogMessage(CUPSD_LOG_ERROR
,
4243 "Unable to create SSL server key and certificate - "
4244 "the certtool command crashed on signal %d!",
4249 cupsdLogMessage(CUPSD_LOG_INFO
,
4250 "Created SSL server certificate file \"%s\"...",
4258 #endif /* HAVE_LIBSSL && HAVE_WAITPID */
4260 #endif /* HAVE_SSL */
4264 * 'pipe_command()' - Pipe the output of a command to the remote client.
4267 static int /* O - Process ID */
4268 pipe_command(cupsd_client_t
*con
, /* I - Client connection */
4269 int infile
, /* I - Standard input for command */
4270 int *outfile
, /* O - Standard output for command */
4271 char *command
, /* I - Command to run */
4272 char *options
, /* I - Options for command */
4273 int root
) /* I - Run as root? */
4275 int i
; /* Looping var */
4276 int pid
; /* Process ID */
4277 char *commptr
, /* Command string pointer */
4278 commch
; /* Command string character */
4279 char *uriptr
; /* URI string pointer */
4280 int fds
[2]; /* Pipe FDs */
4281 int argc
; /* Number of arguments */
4282 int envc
; /* Number of environment variables */
4283 char argbuf
[10240], /* Argument buffer */
4284 *argv
[100], /* Argument strings */
4285 *envp
[MAX_ENV
+ 20]; /* Environment variables */
4286 char auth_type
[256], /* CUPSD_AUTH_TYPE environment variable */
4287 content_length
[1024], /* CONTENT_LENGTH environment variable */
4288 content_type
[1024], /* CONTENT_TYPE environment variable */
4289 http_cookie
[32768], /* HTTP_COOKIE environment variable */
4290 http_referer
[1024], /* HTTP_REFERER environment variable */
4291 http_user_agent
[1024], /* HTTP_USER_AGENT environment variable */
4292 lang
[1024], /* LANG environment variable */
4293 path_info
[1024], /* PATH_INFO environment variable */
4294 remote_addr
[1024], /* REMOTE_ADDR environment variable */
4295 remote_host
[1024], /* REMOTE_HOST environment variable */
4296 remote_user
[1024], /* REMOTE_USER environment variable */
4297 script_filename
[1024], /* SCRIPT_FILENAME environment variable */
4298 script_name
[1024], /* SCRIPT_NAME environment variable */
4299 server_name
[1024], /* SERVER_NAME environment variable */
4300 server_port
[1024]; /* SERVER_PORT environment variable */
4301 ipp_attribute_t
*attr
; /* attributes-natural-language attribute */
4303 krb5_ccache ccache
= NULL
; /* Kerberos credentials */
4304 char krb5ccname
[1024]; /* KRB5CCNAME environment variable */
4305 #endif /* HAVE_GSSAPI */
4309 * Parse a copy of the options string, which is of the form:
4311 * argument+argument+argument
4312 * ?argument+argument+argument
4313 * param=value¶m=value
4314 * ?param=value¶m=value
4315 * /name?argument+argument+argument
4316 * /name?param=value¶m=value
4318 * If the string contains an "=" character after the initial name,
4319 * then we treat it as a HTTP GET form request and make a copy of
4320 * the remaining string for the environment variable.
4322 * The string is always parsed out as command-line arguments, to
4323 * be consistent with Apache...
4326 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4327 "pipe_command: command=\"%s\", options=\"%s\"",
4328 command
, options
? options
: "(null)");
4333 strlcpy(argbuf
, options
, sizeof(argbuf
));
4337 if (argbuf
[0] == '/')
4340 * Found some trailing path information, set PATH_INFO...
4343 if ((commptr
= strchr(argbuf
, '?')) == NULL
)
4344 commptr
= argbuf
+ strlen(argbuf
);
4348 snprintf(path_info
, sizeof(path_info
), "PATH_INFO=%s", argbuf
);
4354 path_info
[0] = '\0';
4356 if (*commptr
== ' ')
4360 if (*commptr
== '?' && con
->operation
== HTTP_GET
&& !con
->query_string
)
4363 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", commptr
);
4370 argv
[argc
++] = commptr
;
4372 for (; *commptr
&& argc
< 99; commptr
++)
4375 * Break arguments whenever we see a + or space...
4378 if (*commptr
== ' ' || *commptr
== '+')
4380 while (*commptr
== ' ' || *commptr
== '+')
4384 * If we don't have a blank string, save it as another argument...
4389 argv
[argc
] = commptr
;
4395 else if (*commptr
== '%' && isxdigit(commptr
[1] & 255) &&
4396 isxdigit(commptr
[2] & 255))
4399 * Convert the %xx notation to the individual character.
4402 if (commptr
[1] >= '0' && commptr
[1] <= '9')
4403 *commptr
= (commptr
[1] - '0') << 4;
4405 *commptr
= (tolower(commptr
[1]) - 'a' + 10) << 4;
4407 if (commptr
[2] >= '0' && commptr
[2] <= '9')
4408 *commptr
|= commptr
[2] - '0';
4410 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
4412 _cups_strcpy(commptr
+ 1, commptr
+ 3);
4415 * Check for a %00 and break if that is the case...
4427 * Setup the environment variables as needed...
4430 if (con
->username
[0])
4432 snprintf(auth_type
, sizeof(auth_type
), "CUPSD_AUTH_TYPE=%s",
4433 httpGetField(HTTP(con
), HTTP_FIELD_AUTHORIZATION
));
4435 if ((uriptr
= strchr(auth_type
+ 10, ' ')) != NULL
)
4439 auth_type
[0] = '\0';
4442 (attr
= ippFindAttribute(con
->request
, "attributes-natural-language",
4443 IPP_TAG_LANGUAGE
)) != NULL
)
4445 switch (strlen(attr
->values
[0].string
.text
))
4449 * This is an unknown or badly formatted language code; use
4450 * the POSIX locale...
4453 strcpy(lang
, "LANG=C");
4458 * Just the language code (ll)...
4461 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8",
4462 attr
->values
[0].string
.text
);
4467 * Language and country code (ll-cc)...
4470 snprintf(lang
, sizeof(lang
), "LANG=%c%c_%c%c.UTF8",
4471 attr
->values
[0].string
.text
[0],
4472 attr
->values
[0].string
.text
[1],
4473 toupper(attr
->values
[0].string
.text
[3] & 255),
4474 toupper(attr
->values
[0].string
.text
[4] & 255));
4478 else if (con
->language
)
4479 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8", con
->language
->language
);
4481 strcpy(lang
, "LANG=C");
4483 strcpy(remote_addr
, "REMOTE_ADDR=");
4484 httpAddrString(con
->http
.hostaddr
, remote_addr
+ 12,
4485 sizeof(remote_addr
) - 12);
4487 snprintf(remote_host
, sizeof(remote_host
), "REMOTE_HOST=%s",
4488 con
->http
.hostname
);
4490 snprintf(script_name
, sizeof(script_name
), "SCRIPT_NAME=%s", con
->uri
);
4491 if ((uriptr
= strchr(script_name
, '?')) != NULL
)
4494 snprintf(script_filename
, sizeof(script_filename
), "SCRIPT_FILENAME=%s%s",
4495 DocumentRoot
, script_name
+ 12);
4497 sprintf(server_port
, "SERVER_PORT=%d", con
->serverport
);
4499 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
4502 envc
= cupsdLoadEnv(envp
, (int)(sizeof(envp
) / sizeof(envp
[0])));
4505 envp
[envc
++] = auth_type
;
4507 envp
[envc
++] = lang
;
4508 envp
[envc
++] = "REDIRECT_STATUS=1";
4509 envp
[envc
++] = "GATEWAY_INTERFACE=CGI/1.1";
4510 envp
[envc
++] = server_name
;
4511 envp
[envc
++] = server_port
;
4512 envp
[envc
++] = remote_addr
;
4513 envp
[envc
++] = remote_host
;
4514 envp
[envc
++] = script_name
;
4515 envp
[envc
++] = script_filename
;
4518 envp
[envc
++] = path_info
;
4520 if (con
->username
[0])
4522 snprintf(remote_user
, sizeof(remote_user
), "REMOTE_USER=%s", con
->username
);
4524 envp
[envc
++] = remote_user
;
4527 * Save Kerberos credentials, if any...
4531 if (con
->gss_have_creds
)
4533 # if !defined(HAVE_KRB5_CC_NEW_UNIQUE) && !defined(HAVE_HEIMDAL)
4534 cupsdLogMessage(CUPSD_LOG_INFO
,
4535 "Sorry, your version of Kerberos does not support "
4536 "delegated credentials!");
4539 krb5_error_code error
; /* Kerberos error code */
4540 OM_uint32 major_status
, /* Major status code */
4541 minor_status
; /* Minor status code */
4542 krb5_principal principal
; /* Kerberos principal */
4547 * If the weak-linked GSSAPI/Kerberos library is not present, don't try
4551 if (krb5_init_context
!= NULL
)
4553 # endif /* __APPLE__ */
4556 * We MUST create a file-based cache because memory-based caches are
4557 * only valid for the current process/address space.
4559 * Due to various bugs/features in different versions of Kerberos, we
4560 * need either the krb5_cc_new_unique() function or Heimdal's version
4561 * of krb5_cc_gen_new() to create a new FILE: credential cache that
4562 * can be passed to the backend. These functions create a temporary
4563 * file (typically in /tmp) containing the cached credentials, which
4564 * are removed when we have successfully printed a job.
4567 # ifdef HAVE_KRB5_CC_NEW_UNIQUE
4568 if ((error
= krb5_cc_new_unique(KerberosContext
, "FILE", NULL
,
4570 # else /* HAVE_HEIMDAL */
4571 if ((error
= krb5_cc_gen_new(KerberosContext
, &krb5_fcc_ops
,
4573 # endif /* HAVE_KRB5_CC_NEW_UNIQUE */
4575 cupsdLogMessage(CUPSD_LOG_ERROR
,
4576 "Unable to create new credentials cache (%d/%s)",
4577 error
, strerror(errno
));
4580 else if ((error
= krb5_parse_name(KerberosContext
, con
->username
,
4583 cupsdLogMessage(CUPSD_LOG_ERROR
,
4584 "Unable to parse kerberos username (%d/%s)", error
,
4586 krb5_cc_destroy(KerberosContext
, ccache
);
4589 else if ((error
= krb5_cc_initialize(KerberosContext
, ccache
,
4592 cupsdLogMessage(CUPSD_LOG_ERROR
,
4593 "Unable to initialize credentials cache (%d/%s)", error
,
4595 krb5_cc_destroy(KerberosContext
, ccache
);
4596 krb5_free_principal(KerberosContext
, principal
);
4601 krb5_free_principal(KerberosContext
, principal
);
4604 * Copy the user's credentials to the new cache file...
4607 major_status
= gss_krb5_copy_ccache(&minor_status
,
4608 con
->gss_delegated_cred
, ccache
);
4610 if (GSS_ERROR(major_status
))
4612 cupsdLogGSSMessage(CUPSD_LOG_ERROR
, major_status
, minor_status
,
4613 "Unable to import client credentials cache");
4614 krb5_cc_destroy(KerberosContext
, ccache
);
4620 * Add the KRB5CCNAME environment variable to the job so that the
4621 * backend can use the credentials when printing.
4624 snprintf(krb5ccname
, sizeof(krb5ccname
), "KRB5CCNAME=FILE:%s",
4625 krb5_cc_get_name(KerberosContext
, ccache
));
4626 envp
[envc
++] = krb5ccname
;
4629 chown(krb5_cc_get_name(KerberosContext
, ccache
), User
, Group
);
4634 # endif /* __APPLE__ */
4635 # endif /* HAVE_KRB5_CC_NEW_UNIQUE || HAVE_HEIMDAL */
4637 #endif /* HAVE_GSSAPI */
4641 if (con
->http
.version
== HTTP_1_1
)
4642 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.1";
4643 else if (con
->http
.version
== HTTP_1_0
)
4644 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.0";
4646 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/0.9";
4648 if (con
->http
.cookie
)
4650 snprintf(http_cookie
, sizeof(http_cookie
), "HTTP_COOKIE=%s",
4652 envp
[envc
++] = http_cookie
;
4655 if (con
->http
.fields
[HTTP_FIELD_USER_AGENT
][0])
4657 snprintf(http_user_agent
, sizeof(http_user_agent
), "HTTP_USER_AGENT=%s",
4658 con
->http
.fields
[HTTP_FIELD_USER_AGENT
]);
4659 envp
[envc
++] = http_user_agent
;
4662 if (con
->http
.fields
[HTTP_FIELD_REFERER
][0])
4664 snprintf(http_referer
, sizeof(http_referer
), "HTTP_REFERER=%s",
4665 con
->http
.fields
[HTTP_FIELD_REFERER
]);
4666 envp
[envc
++] = http_referer
;
4669 if (con
->operation
== HTTP_GET
)
4671 envp
[envc
++] = "REQUEST_METHOD=GET";
4673 if (con
->query_string
)
4676 * Add GET form variables after ?...
4679 envp
[envc
++] = con
->query_string
;
4684 sprintf(content_length
, "CONTENT_LENGTH=" CUPS_LLFMT
,
4685 CUPS_LLCAST con
->bytes
);
4686 snprintf(content_type
, sizeof(content_type
), "CONTENT_TYPE=%s",
4687 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
4689 envp
[envc
++] = "REQUEST_METHOD=POST";
4690 envp
[envc
++] = content_length
;
4691 envp
[envc
++] = content_type
;
4695 * Tell the CGI if we are using encryption...
4699 envp
[envc
++] = "HTTPS=ON";
4702 * Terminate the environment array...
4707 if (LogLevel
== CUPSD_LOG_DEBUG2
)
4709 for (i
= 0; i
< argc
; i
++)
4710 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4711 "pipe_command: argv[%d] = \"%s\"", i
, argv
[i
]);
4712 for (i
= 0; i
< envc
; i
++)
4713 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4714 "pipe_command: envp[%d] = \"%s\"", i
, envp
[i
]);
4718 * Create a pipe for the output...
4721 if (cupsdOpenPipe(fds
))
4723 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to create pipes for CGI %s - %s",
4724 argv
[0], strerror(errno
));
4729 * Then execute the command...
4732 if (cupsdStartProcess(command
, argv
, envp
, infile
, fds
[1], CGIPipes
[1],
4733 -1, -1, root
, DefaultProfile
, &pid
) < 0)
4736 * Error - can't fork!
4739 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to fork for CGI %s - %s", argv
[0],
4742 cupsdClosePipe(fds
);
4748 * Fork successful - return the PID...
4751 if (con
->username
[0])
4753 cupsdAddCert(pid
, con
->username
, ccache
);
4755 cupsdAddCert(pid
, con
->username
, NULL
);
4756 #endif /* HAVE_GSSAPI */
4758 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[CGI] %s started - PID = %d",
4770 * 'write_file()' - Send a file via HTTP.
4773 static int /* O - 0 on failure, 1 on success */
4774 write_file(cupsd_client_t
*con
, /* I - Client connection */
4775 http_status_t code
, /* I - HTTP status */
4776 char *filename
, /* I - Filename */
4777 char *type
, /* I - File type */
4778 struct stat
*filestats
) /* O - File information */
4780 con
->file
= open(filename
, O_RDONLY
);
4782 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "write_file: %d file=%d", con
->http
.fd
,
4788 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
4792 if (!cupsdSendHeader(con
, code
, type
, CUPSD_AUTH_NONE
))
4795 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
4796 httpGetDateString(filestats
->st_mtime
)) < 0)
4798 if (httpPrintf(HTTP(con
), "Content-Length: " CUPS_LLFMT
"\r\n",
4799 CUPS_LLCAST filestats
->st_size
) < 0)
4801 if (httpPrintf(HTTP(con
), "\r\n") < 0)
4804 if (cupsdFlushHeader(con
) < 0)
4807 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
4808 con
->http
.data_remaining
= filestats
->st_size
;
4810 if (con
->http
.data_remaining
<= INT_MAX
)
4811 con
->http
._data_remaining
= con
->http
.data_remaining
;
4813 con
->http
._data_remaining
= INT_MAX
;
4815 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
,
4816 (cupsd_selfunc_t
)cupsdWriteClient
, con
);
4823 * 'write_pipe()' - Flag that data is available on the CGI pipe.
4827 write_pipe(cupsd_client_t
*con
) /* I - Client connection */
4829 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "write_pipe: CGI output on fd %d...",
4832 con
->file_ready
= 1;
4834 cupsdRemoveSelect(con
->file
);
4835 cupsdAddSelect(con
->http
.fd
, NULL
, (cupsd_selfunc_t
)cupsdWriteClient
, con
);
4840 * End of "$Id: client.c 6999 2007-09-28 19:46:53Z mike $".