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 * compare_clients() - Compare two client connections.
32 * encrypt_client() - Enable encryption for the client...
33 * get_cdsa_certificate() - Convert a keychain name into the CFArrayRef
34 * required by SSLSetCertificate.
35 * get_file() - Get a filename and state info.
36 * install_conf_file() - Install a configuration file.
37 * is_cgi() - Is the resource a CGI script/program?
38 * is_path_absolute() - Is a path absolute and free of relative elements.
39 * make_certificate() - Make a self-signed SSL/TLS certificate.
40 * pipe_command() - Pipe the output of a command to the remote client.
41 * write_file() - Send a file via HTTP.
42 * write_pipe() - Flag that data is available on the CGI pipe.
46 * Include necessary headers...
52 # include <Security/Security.h>
53 # ifdef HAVE_SECIDENTITYSEARCHPRIV_H
54 # include <Security/SecIdentitySearchPriv.h>
55 # else /* Declare prototype for function in that header... */
56 extern OSStatus
SecIdentitySearchCreateWithPolicy(SecPolicyRef policy
,
57 CFStringRef idString
, CSSM_KEYUSE keyUsage
,
58 CFTypeRef keychainOrArray
,
59 Boolean returnOnlyValidIdentities
,
60 SecIdentitySearchRef
* searchRef
);
61 # endif /* HAVE_SECIDENTITYSEARCHPRIV_H */
62 # ifdef HAVE_SECPOLICYPRIV_H
63 # include <Security/SecPolicyPriv.h>
64 # else /* Declare prototype for function in that header... */
65 extern OSStatus
SecPolicySetValue(SecPolicyRef policyRef
,
66 const CSSM_DATA
*value
);
67 # endif /* HAVE_SECPOLICYPRIV_H */
68 # ifdef HAVE_SECBASEPRIV_H
69 # include <Security/SecBasePriv.h>
70 # else /* Declare prototype for function in that header... */
71 extern const char *cssmErrorString(int error
);
72 # endif /* HAVE_SECBASEPRIV_H */
73 #endif /* HAVE_CDSASSL */
76 # include <gnutls/x509.h>
77 #endif /* HAVE_GNUTLS */
84 static int check_if_modified(cupsd_client_t
*con
,
85 struct stat
*filestats
);
86 static int compare_clients(cupsd_client_t
*a
, cupsd_client_t
*b
,
89 static int encrypt_client(cupsd_client_t
*con
);
92 static CFArrayRef
get_cdsa_certificate(cupsd_client_t
*con
);
93 #endif /* HAVE_CDSASSL */
94 static char *get_file(cupsd_client_t
*con
, struct stat
*filestats
,
95 char *filename
, int len
);
96 static http_status_t
install_conf_file(cupsd_client_t
*con
);
97 static int is_cgi(cupsd_client_t
*con
, const char *filename
,
98 struct stat
*filestats
, mime_type_t
*type
);
99 static int is_path_absolute(const char *path
);
101 static int make_certificate(cupsd_client_t
*con
);
102 #endif /* HAVE_SSL */
103 static int pipe_command(cupsd_client_t
*con
, int infile
, int *outfile
,
104 char *command
, char *options
, int root
);
105 static int write_file(cupsd_client_t
*con
, http_status_t code
,
106 char *filename
, char *type
,
107 struct stat
*filestats
);
108 static void write_pipe(cupsd_client_t
*con
);
112 * 'cupsdAcceptClient()' - Accept a new client.
116 cupsdAcceptClient(cupsd_listener_t
*lis
)/* I - Listener socket */
118 int count
; /* Count of connections on a host */
119 int val
; /* Parameter value */
120 cupsd_client_t
*con
, /* New client pointer */
121 *tempcon
; /* Temporary client pointer */
122 http_addrlist_t
*addrlist
, /* List of adddresses for host */
123 *addr
; /* Current address */
124 socklen_t addrlen
; /* Length of address */
125 char *hostname
; /* Hostname for address */
126 http_addr_t temp
; /* Temporary address variable */
127 static time_t last_dos
= 0; /* Time of last DoS attack */
130 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
131 "cupsdAcceptClient(lis=%p) %d Clients = %d",
132 lis
, lis
->fd
, cupsArrayCount(Clients
));
135 * Make sure we don't have a full set of clients already...
138 if (cupsArrayCount(Clients
) == MaxClients
)
142 * Get a pointer to the next available client...
146 Clients
= cupsArrayNew(NULL
, NULL
);
150 cupsdLogMessage(CUPSD_LOG_ERROR
,
151 "Unable to allocate memory for clients array!");
152 cupsdPauseListening();
157 ActiveClients
= cupsArrayNew((cups_array_func_t
)compare_clients
, NULL
);
161 cupsdLogMessage(CUPSD_LOG_ERROR
,
162 "Unable to allocate memory for active clients array!");
163 cupsdPauseListening();
167 if ((con
= calloc(1, sizeof(cupsd_client_t
))) == NULL
)
169 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to allocate memory for client!");
170 cupsdPauseListening();
174 con
->http
.activity
= time(NULL
);
176 con
->http
.hostaddr
= &(con
->clientaddr
);
179 * Accept the client and get the remote address...
182 addrlen
= sizeof(http_addr_t
);
184 if ((con
->http
.fd
= accept(lis
->fd
, (struct sockaddr
*)con
->http
.hostaddr
,
187 if (errno
== ENFILE
|| errno
== EMFILE
)
188 cupsdPauseListening();
190 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to accept client connection - %s.",
198 if (lis
->address
.addr
.sa_family
== AF_INET6
)
201 * Save the connected port number...
204 con
->http
.hostaddr
->ipv6
.sin6_port
= lis
->address
.ipv6
.sin6_port
;
207 * Convert IPv4 over IPv6 addresses (::ffff:n.n.n.n) to IPv4 forms we
208 * can more easily use...
211 if (con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[0] == 0 &&
212 con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[1] == 0 &&
213 ntohl(con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[2]) == 0xffff)
214 con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[2] = 0;
217 #endif /* AF_INET6 */
218 if (lis
->address
.addr
.sa_family
== AF_INET
)
219 con
->http
.hostaddr
->ipv4
.sin_port
= lis
->address
.ipv4
.sin_port
;
222 * Check the number of clients on the same address...
225 for (count
= 0, tempcon
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
227 tempcon
= (cupsd_client_t
*)cupsArrayNext(Clients
))
228 if (httpAddrEqual(tempcon
->http
.hostaddr
, con
->http
.hostaddr
))
231 if (count
>= MaxClientsPerHost
)
235 if (count
>= MaxClientsPerHost
)
237 if ((time(NULL
) - last_dos
) >= 60)
239 last_dos
= time(NULL
);
240 cupsdLogMessage(CUPSD_LOG_WARN
,
241 "Possible DoS attack - more than %d clients connecting "
243 MaxClientsPerHost
, tempcon
->http
.hostname
);
247 closesocket(con
->http
.fd
);
257 * Get the hostname or format the IP address as needed...
260 if (httpAddrLocalhost(con
->http
.hostaddr
))
263 * Map accesses from the loopback interface to "localhost"...
266 strlcpy(con
->http
.hostname
, "localhost", sizeof(con
->http
.hostname
));
267 hostname
= con
->http
.hostname
;
272 * Map accesses from the same host to the server name.
275 for (addr
= ServerAddrs
; addr
; addr
= addr
->next
)
276 if (httpAddrEqual(con
->http
.hostaddr
, &(addr
->addr
)))
281 strlcpy(con
->http
.hostname
, ServerName
, sizeof(con
->http
.hostname
));
282 hostname
= con
->http
.hostname
;
284 else if (HostNameLookups
)
285 hostname
= httpAddrLookup(con
->http
.hostaddr
, con
->http
.hostname
,
286 sizeof(con
->http
.hostname
));
290 httpAddrString(con
->http
.hostaddr
, con
->http
.hostname
,
291 sizeof(con
->http
.hostname
));
295 if (hostname
== NULL
&& HostNameLookups
== 2)
298 * Can't have an unresolved IP address with double-lookups enabled...
301 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
302 "cupsdAcceptClient: Closing connection %d...",
306 closesocket(con
->http
.fd
);
311 cupsdLogMessage(CUPSD_LOG_WARN
,
312 "Name lookup failed - connection from %s closed!",
319 if (HostNameLookups
== 2)
322 * Do double lookups as needed...
325 if ((addrlist
= httpAddrGetList(con
->http
.hostname
, AF_UNSPEC
, NULL
)) != NULL
)
328 * See if the hostname maps to the same IP address...
331 for (addr
= addrlist
; addr
; addr
= addr
->next
)
332 if (httpAddrEqual(con
->http
.hostaddr
, &(addr
->addr
)))
338 httpAddrFreeList(addrlist
);
343 * Can't have a hostname that doesn't resolve to the same IP address
344 * with double-lookups enabled...
347 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
348 "cupsdAcceptClient: Closing connection %d...",
352 closesocket(con
->http
.fd
);
357 cupsdLogMessage(CUPSD_LOG_WARN
,
358 "IP lookup failed - connection from %s closed!",
366 if (con
->http
.hostaddr
->addr
.sa_family
== AF_INET6
)
367 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdAcceptClient: %d from %s:%d (IPv6)",
368 con
->http
.fd
, con
->http
.hostname
,
369 ntohs(con
->http
.hostaddr
->ipv6
.sin6_port
));
371 #endif /* AF_INET6 */
373 if (con
->http
.hostaddr
->addr
.sa_family
== AF_LOCAL
)
374 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdAcceptClient: %d from %s (Domain)",
375 con
->http
.fd
, con
->http
.hostname
);
377 #endif /* AF_LOCAL */
378 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdAcceptClient: %d from %s:%d (IPv4)",
379 con
->http
.fd
, con
->http
.hostname
,
380 ntohs(con
->http
.hostaddr
->ipv4
.sin_port
));
383 * Get the local address the client connected to...
386 addrlen
= sizeof(temp
);
387 if (getsockname(con
->http
.fd
, (struct sockaddr
*)&temp
, &addrlen
))
389 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to get local address - %s",
392 strcpy(con
->servername
, "localhost");
393 con
->serverport
= LocalPort
;
398 if (temp
.addr
.sa_family
== AF_INET6
)
400 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
401 con
->serverport
= ntohs(lis
->address
.ipv6
.sin6_port
);
404 #endif /* AF_INET6 */
405 if (temp
.addr
.sa_family
== AF_INET
)
407 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
408 con
->serverport
= ntohs(lis
->address
.ipv4
.sin_port
);
412 strcpy(con
->servername
, "localhost");
413 con
->serverport
= LocalPort
;
417 cupsArrayAdd(Clients
, con
);
419 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
420 "cupsdAcceptClient: %d connected to server on %s:%d",
421 con
->http
.fd
, con
->servername
, con
->serverport
);
424 * Using TCP_NODELAY improves responsiveness, especially on systems
425 * with a slow loopback interface... Since we write large buffers
426 * when sending print files and requests, there shouldn't be any
427 * performance penalty for this...
431 setsockopt(con
->http
.fd
, IPPROTO_TCP
, TCP_NODELAY
, &val
, sizeof(val
));
434 * Close this file on all execs...
437 fcntl(con
->http
.fd
, F_SETFD
, fcntl(con
->http
.fd
, F_GETFD
) | FD_CLOEXEC
);
440 * Add the socket to the select() input mask.
443 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
446 * Temporarily suspend accept()'s until we lose a client...
449 if (cupsArrayCount(Clients
) == MaxClients
)
450 cupsdPauseListening();
454 * See if we are connecting on a secure port...
457 if (lis
->encryption
== HTTP_ENCRYPT_ALWAYS
)
460 * https connection; go secure...
463 con
->http
.encryption
= HTTP_ENCRYPT_ALWAYS
;
465 if (!encrypt_client(con
))
466 cupsdCloseClient(con
);
470 #endif /* HAVE_SSL */
475 * 'cupsdCloseAllClients()' - Close all remote clients immediately.
479 cupsdCloseAllClients(void)
481 cupsd_client_t
*con
; /* Current client */
484 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
486 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
487 cupsdCloseClient(con
);
492 * 'cupsdCloseClient()' - Close a remote client.
495 int /* O - 1 if partial close, 0 if fully closed */
496 cupsdCloseClient(cupsd_client_t
*con
) /* I - Client to close */
498 int partial
; /* Do partial close for SSL? */
500 SSL_CTX
*context
; /* Context for encryption */
501 SSL
*conn
; /* Connection for encryption */
502 unsigned long error
; /* Error code */
503 #elif defined(HAVE_GNUTLS)
504 http_tls_t
*conn
; /* TLS connection information */
505 int error
; /* Error code */
506 gnutls_certificate_server_credentials
*credentials
;
507 /* TLS credentials */
508 # elif defined(HAVE_CDSASSL)
509 http_tls_t
*conn
; /* CDSA connection information */
510 #endif /* HAVE_LIBSSL */
513 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdCloseClient: %d", con
->http
.fd
);
516 * Flush pending writes before closing...
519 httpFlushWrite(HTTP(con
));
525 * Shutdown encryption as needed...
533 conn
= (SSL
*)(con
->http
.tls
);
534 context
= SSL_get_SSL_CTX(conn
);
536 switch (SSL_shutdown(conn
))
539 cupsdLogMessage(CUPSD_LOG_INFO
,
540 "cupsdCloseClient: SSL shutdown successful!");
543 cupsdLogMessage(CUPSD_LOG_ERROR
,
544 "cupsdCloseClient: Fatal error during SSL shutdown!");
546 while ((error
= ERR_get_error()) != 0)
547 cupsdLogMessage(CUPSD_LOG_ERROR
, "cupsdCloseClient: %s",
548 ERR_error_string(error
, NULL
));
552 SSL_CTX_free(context
);
555 # elif defined(HAVE_GNUTLS)
556 conn
= (http_tls_t
*)(con
->http
.tls
);
557 credentials
= (gnutls_certificate_server_credentials
*)(conn
->credentials
);
559 error
= gnutls_bye(conn
->session
, GNUTLS_SHUT_WR
);
562 case GNUTLS_E_SUCCESS
:
563 cupsdLogMessage(CUPSD_LOG_INFO
,
564 "cupsdCloseClient: SSL shutdown successful!");
567 cupsdLogMessage(CUPSD_LOG_ERROR
,
568 "cupsdCloseClient: %s", gnutls_strerror(error
));
572 gnutls_deinit(conn
->session
);
573 gnutls_certificate_free_credentials(*credentials
);
577 # elif defined(HAVE_CDSASSL)
578 conn
= (http_tls_t
*)(con
->http
.tls
);
580 while (SSLClose(conn
->session
) == errSSLWouldBlock
)
583 SSLDisposeContext(conn
->session
);
585 if (conn
->certsArray
)
586 CFRelease(conn
->certsArray
);
589 # endif /* HAVE_LIBSSL */
591 con
->http
.tls
= NULL
;
593 #endif /* HAVE_SSL */
595 if (con
->pipe_pid
!= 0)
598 * Stop any CGI process...
601 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
602 "cupsdCloseClient: %d Killing process ID %d...",
603 con
->http
.fd
, con
->pipe_pid
);
604 cupsdEndProcess(con
->pipe_pid
, 1);
610 cupsdRemoveSelect(con
->file
);
612 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
613 "cupsdCloseClient: %d Closing data file %d.",
614 con
->http
.fd
, con
->file
);
621 * Close the socket and clear the file from the input set for select()...
624 if (con
->http
.fd
>= 0)
626 cupsArrayRemove(ActiveClients
, con
);
632 * Only do a partial close so that the encrypted client gets everything.
635 shutdown(con
->http
.fd
, 0);
636 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
641 * Shut the socket down fully...
644 cupsdRemoveSelect(con
->http
.fd
);
656 if (con
->http
.input_set
)
657 free(con
->http
.input_set
);
659 httpClearCookie(HTTP(con
));
661 cupsdClearString(&con
->filename
);
662 cupsdClearString(&con
->command
);
663 cupsdClearString(&con
->options
);
664 cupsdClearString(&con
->query_string
);
668 ippDelete(con
->request
);
674 ippDelete(con
->response
);
675 con
->response
= NULL
;
680 cupsLangFree(con
->language
);
681 con
->language
= NULL
;
684 #ifdef HAVE_AUTHORIZATION_H
687 AuthorizationFree(con
->authref
, kAuthorizationFlagDefaults
);
690 #endif /* HAVE_AUTHORIZATION_H */
693 * Re-enable new client connections if we are going back under the
697 if (cupsArrayCount(Clients
) == MaxClients
)
698 cupsdResumeListening();
701 * Compact the list of clients as necessary...
704 cupsArrayRemove(Clients
, con
);
714 * 'cupsdFlushHeader()' - Flush the header fields to the client.
717 int /* I - Bytes written or -1 on error */
718 cupsdFlushHeader(cupsd_client_t
*con
) /* I - Client to flush to */
720 int bytes
= httpFlushWrite(HTTP(con
));
722 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
729 * 'cupsdReadClient()' - Read data from a client.
733 cupsdReadClient(cupsd_client_t
*con
) /* I - Client to read from */
735 char line
[32768], /* Line from client... */
736 operation
[64], /* Operation code from socket */
737 version
[64], /* HTTP version number string */
738 locale
[64], /* Locale */
739 *ptr
; /* Pointer into strings */
740 int major
, minor
; /* HTTP version numbers */
741 http_status_t status
; /* Transfer status */
742 ipp_state_t ipp_state
; /* State of IPP transfer */
743 int bytes
; /* Number of bytes to POST */
744 char *filename
; /* Name of file for GET/HEAD */
745 char buf
[1024]; /* Buffer for real filename */
746 struct stat filestats
; /* File information */
747 mime_type_t
*type
; /* MIME type of file */
748 cupsd_printer_t
*p
; /* Printer */
749 static unsigned request_id
= 0; /* Request ID for temp files */
752 status
= HTTP_CONTINUE
;
754 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
755 "cupsdReadClient: %d, used=%d, file=%d state=%d",
756 con
->http
.fd
, con
->http
.used
, con
->file
, con
->http
.state
);
760 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdReadClient: http error seen...");
761 cupsdCloseClient(con
);
769 * Automatically check for a SSL/TLS handshake...
774 if (recv(con
->http
.fd
, buf
, 1, MSG_PEEK
) == 1 &&
775 (!buf
[0] || !strchr("DGHOPT", buf
[0])))
778 * Encrypt this connection...
781 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
782 "cupsdReadClient: Saw first byte %02X, auto-negotiating SSL/TLS session...",
785 if (!encrypt_client(con
))
786 cupsdCloseClient(con
);
791 #endif /* HAVE_SSL */
793 switch (con
->http
.state
)
797 * See if we've received a request line...
800 if (httpGets(line
, sizeof(line
) - 1, HTTP(con
)) == NULL
)
802 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
803 "cupsdReadClient: httpGets returned EOF...");
804 cupsdCloseClient(con
);
809 * Ignore blank request lines...
816 * Clear other state variables...
819 httpClearFields(HTTP(con
));
821 con
->http
.activity
= time(NULL
);
822 con
->http
.version
= HTTP_1_0
;
823 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
824 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
825 con
->http
.data_remaining
= 0;
826 con
->http
._data_remaining
= 0;
827 con
->operation
= HTTP_WAITING
;
832 con
->username
[0] = '\0';
833 con
->password
[0] = '\0';
836 cupsdClearString(&con
->command
);
837 cupsdClearString(&con
->options
);
838 cupsdClearString(&con
->query_string
);
842 ippDelete(con
->request
);
848 ippDelete(con
->response
);
849 con
->response
= NULL
;
854 cupsLangFree(con
->language
);
855 con
->language
= NULL
;
859 con
->gss_have_creds
= 0;
860 #endif /* HAVE_GSSAPI */
863 * Grab the request line...
866 switch (sscanf(line
, "%63s%1023s%63s", operation
, con
->uri
, version
))
869 cupsdLogMessage(CUPSD_LOG_ERROR
,
870 "Bad request line \"%s\" from %s!", line
,
872 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
873 cupsdCloseClient(con
);
876 con
->http
.version
= HTTP_0_9
;
879 if (sscanf(version
, "HTTP/%d.%d", &major
, &minor
) != 2)
881 cupsdLogMessage(CUPSD_LOG_ERROR
,
882 "Bad request line \"%s\" from %s!", line
,
884 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
885 cupsdCloseClient(con
);
891 con
->http
.version
= (http_version_t
)(major
* 100 + minor
);
892 if (con
->http
.version
== HTTP_1_1
&& KeepAlive
)
893 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
895 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
899 cupsdSendError(con
, HTTP_NOT_SUPPORTED
, CUPSD_AUTH_NONE
);
900 cupsdCloseClient(con
);
907 * Handle full URLs in the request line...
910 if (strcmp(con
->uri
, "*"))
912 char method
[HTTP_MAX_URI
], /* Method/scheme */
913 userpass
[HTTP_MAX_URI
], /* Username:password */
914 hostname
[HTTP_MAX_URI
], /* Hostname */
915 resource
[HTTP_MAX_URI
]; /* Resource path */
916 int port
; /* Port number */
920 * Separate the URI into its components...
923 httpSeparateURI(HTTP_URI_CODING_MOST
, con
->uri
,
924 method
, sizeof(method
),
925 userpass
, sizeof(userpass
),
926 hostname
, sizeof(hostname
), &port
,
927 resource
, sizeof(resource
));
930 * Only allow URIs with the servername, localhost, or an IP
934 if (strcmp(method
, "file") &&
935 strcasecmp(hostname
, ServerName
) &&
936 strcasecmp(hostname
, "localhost") &&
937 !isdigit(hostname
[0]))
940 * Nope, we don't do proxies...
943 cupsdLogMessage(CUPSD_LOG_ERROR
, "Bad URI \"%s\" in request!",
945 cupsdSendError(con
, HTTP_METHOD_NOT_ALLOWED
, CUPSD_AUTH_NONE
);
946 cupsdCloseClient(con
);
951 * Copy the resource portion back into the URI; both resource and
952 * con->uri are HTTP_MAX_URI bytes in size...
955 strcpy(con
->uri
, resource
);
959 * Process the request...
962 if (!strcmp(operation
, "GET"))
963 con
->http
.state
= HTTP_GET
;
964 else if (!strcmp(operation
, "PUT"))
965 con
->http
.state
= HTTP_PUT
;
966 else if (!strcmp(operation
, "POST"))
967 con
->http
.state
= HTTP_POST
;
968 else if (!strcmp(operation
, "DELETE"))
969 con
->http
.state
= HTTP_DELETE
;
970 else if (!strcmp(operation
, "TRACE"))
971 con
->http
.state
= HTTP_TRACE
;
972 else if (!strcmp(operation
, "OPTIONS"))
973 con
->http
.state
= HTTP_OPTIONS
;
974 else if (!strcmp(operation
, "HEAD"))
975 con
->http
.state
= HTTP_HEAD
;
978 cupsdLogMessage(CUPSD_LOG_ERROR
, "Bad operation \"%s\"!", operation
);
979 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
980 cupsdCloseClient(con
);
984 con
->start
= time(NULL
);
985 con
->operation
= con
->http
.state
;
987 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdReadClient: %d %s %s HTTP/%d.%d",
988 con
->http
.fd
, operation
, con
->uri
,
989 con
->http
.version
/ 100, con
->http
.version
% 100);
991 con
->http
.status
= HTTP_OK
;
993 cupsArrayAdd(ActiveClients
, con
);
1004 * Parse incoming parameters until the status changes...
1007 while ((status
= httpUpdate(HTTP(con
))) == HTTP_CONTINUE
)
1008 if (con
->http
.used
== 0 ||
1009 !memchr(con
->http
.buffer
, '\n', con
->http
.used
))
1012 if (status
!= HTTP_OK
&& status
!= HTTP_CONTINUE
)
1014 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
1015 cupsdCloseClient(con
);
1021 break; /* Anti-compiler-warning-code */
1025 * Handle new transfers...
1028 if (status
== HTTP_OK
)
1030 if (con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
][0])
1033 * Figure out the locale from the Accept-Language and Content-Type
1037 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ',')) != NULL
)
1040 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ';')) != NULL
)
1043 if ((ptr
= strstr(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
], "charset=")) != NULL
)
1046 * Combine language and charset, and trim any extra params in the
1050 snprintf(locale
, sizeof(locale
), "%s.%s",
1051 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ptr
+ 8);
1053 if ((ptr
= strchr(locale
, ',')) != NULL
)
1057 snprintf(locale
, sizeof(locale
), "%s.%s",
1058 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], DefaultCharset
);
1060 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1061 "cupsdReadClient: %d Browser asked for language \"%s\"...",
1062 con
->http
.fd
, locale
);
1064 con
->language
= cupsLangGet(locale
);
1067 con
->language
= cupsLangGet(DefaultLocale
);
1069 cupsdAuthorize(con
);
1071 if (!strncmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Keep-Alive", 10) &&
1073 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
1075 if (!con
->http
.fields
[HTTP_FIELD_HOST
][0] &&
1076 con
->http
.version
>= HTTP_1_1
)
1079 * HTTP/1.1 and higher require the "Host:" field...
1082 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1084 cupsdCloseClient(con
);
1088 else if (con
->operation
== HTTP_OPTIONS
)
1091 * Do OPTIONS command...
1094 if (con
->best
&& con
->best
->type
!= CUPSD_AUTH_NONE
)
1096 if (!cupsdSendHeader(con
, HTTP_UNAUTHORIZED
, NULL
, CUPSD_AUTH_NONE
))
1098 cupsdCloseClient(con
);
1103 if (!strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") &&
1104 con
->http
.tls
== NULL
)
1108 * Do encryption stuff...
1111 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
, CUPSD_AUTH_NONE
))
1113 cupsdCloseClient(con
);
1117 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1118 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1119 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1120 httpPrintf(HTTP(con
), "\r\n");
1122 if (cupsdFlushHeader(con
) < 0)
1124 cupsdCloseClient(con
);
1128 if (!encrypt_client(con
))
1130 cupsdCloseClient(con
);
1134 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
1136 cupsdCloseClient(con
);
1139 #endif /* HAVE_SSL */
1142 if (!cupsdSendHeader(con
, HTTP_OK
, NULL
, CUPSD_AUTH_NONE
))
1144 cupsdCloseClient(con
);
1148 httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n");
1149 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1150 httpPrintf(HTTP(con
), "\r\n");
1152 if (cupsdFlushHeader(con
) < 0)
1154 cupsdCloseClient(con
);
1158 else if (!is_path_absolute(con
->uri
))
1161 * Protect against malicious users!
1164 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1166 cupsdCloseClient(con
);
1172 if (!strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") &&
1173 con
->http
.tls
== NULL
)
1177 * Do encryption stuff...
1180 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
, CUPSD_AUTH_NONE
))
1182 cupsdCloseClient(con
);
1186 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1187 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1188 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1189 httpPrintf(HTTP(con
), "\r\n");
1191 if (cupsdFlushHeader(con
) < 0)
1193 cupsdCloseClient(con
);
1197 if (!encrypt_client(con
))
1199 cupsdCloseClient(con
);
1203 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
1205 cupsdCloseClient(con
);
1208 #endif /* HAVE_SSL */
1211 if ((status
= cupsdIsAuthorized(con
, NULL
)) != HTTP_OK
)
1213 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1214 "cupsdReadClient: Unauthorized request for %s...\n",
1216 cupsdSendError(con
, status
, CUPSD_AUTH_NONE
);
1217 cupsdCloseClient(con
);
1221 if (con
->http
.expect
&&
1222 (con
->operation
== HTTP_POST
|| con
->operation
== HTTP_PUT
))
1224 if (con
->http
.expect
== HTTP_CONTINUE
)
1227 * Send 100-continue header...
1230 if (!cupsdSendHeader(con
, HTTP_CONTINUE
, NULL
, CUPSD_AUTH_NONE
))
1232 cupsdCloseClient(con
);
1239 * Send 417-expectation-failed header...
1242 if (!cupsdSendHeader(con
, HTTP_EXPECTATION_FAILED
, NULL
, CUPSD_AUTH_NONE
))
1244 cupsdCloseClient(con
);
1248 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1249 httpPrintf(HTTP(con
), "\r\n");
1251 if (cupsdFlushHeader(con
) < 0)
1253 cupsdCloseClient(con
);
1259 switch (con
->http
.state
)
1261 case HTTP_GET_SEND
:
1262 if (!strncmp(con
->uri
, "/printers/", 10) &&
1263 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1266 * Send PPD file - get the real printer name since printer
1267 * names are not case sensitive but filenames can be...
1270 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1272 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1273 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1276 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1278 cupsdCloseClient(con
);
1286 if ((!strncmp(con
->uri
, "/admin", 6) &&
1287 strncmp(con
->uri
, "/admin/conf/", 12) &&
1288 strncmp(con
->uri
, "/admin/log/", 11)) ||
1289 !strncmp(con
->uri
, "/printers", 9) ||
1290 !strncmp(con
->uri
, "/classes", 8) ||
1291 !strncmp(con
->uri
, "/help", 5) ||
1292 !strncmp(con
->uri
, "/jobs", 5))
1295 * Send CGI output...
1298 if (!strncmp(con
->uri
, "/admin", 6))
1300 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1303 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1305 else if (!strncmp(con
->uri
, "/printers", 9))
1307 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1310 if (con
->uri
[9] && con
->uri
[10])
1311 cupsdSetString(&con
->options
, con
->uri
+ 9);
1313 cupsdSetString(&con
->options
, NULL
);
1315 else if (!strncmp(con
->uri
, "/classes", 8))
1317 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1320 if (con
->uri
[8] && con
->uri
[9])
1321 cupsdSetString(&con
->options
, con
->uri
+ 8);
1323 cupsdSetString(&con
->options
, NULL
);
1325 else if (!strncmp(con
->uri
, "/jobs", 5))
1327 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1330 if (con
->uri
[5] && con
->uri
[6])
1331 cupsdSetString(&con
->options
, con
->uri
+ 5);
1333 cupsdSetString(&con
->options
, NULL
);
1337 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1340 if (con
->uri
[5] && con
->uri
[6])
1341 cupsdSetString(&con
->options
, con
->uri
+ 5);
1343 cupsdSetString(&con
->options
, NULL
);
1346 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1348 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1350 cupsdCloseClient(con
);
1355 cupsdLogRequest(con
, HTTP_OK
);
1357 if (con
->http
.version
<= HTTP_1_0
)
1358 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1360 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1361 (strchr(con
->uri
+ 12, '/') ||
1362 strlen(con
->uri
) == 12)) ||
1363 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1364 (strchr(con
->uri
+ 11, '/') ||
1365 strlen(con
->uri
) == 11)))
1368 * GET can only be done to configuration files under
1372 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1374 cupsdCloseClient(con
);
1386 if ((filename
= get_file(con
, &filestats
, buf
,
1387 sizeof(buf
))) == NULL
)
1389 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1391 cupsdCloseClient(con
);
1398 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1400 if (is_cgi(con
, filename
, &filestats
, type
))
1403 * Note: con->command and con->options were set by
1407 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1409 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1411 cupsdCloseClient(con
);
1416 cupsdLogRequest(con
, HTTP_OK
);
1418 if (con
->http
.version
<= HTTP_1_0
)
1419 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1423 if (!check_if_modified(con
, &filestats
))
1425 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1427 cupsdCloseClient(con
);
1434 strcpy(line
, "text/plain");
1436 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1438 if (!write_file(con
, HTTP_OK
, filename
, line
, &filestats
))
1440 cupsdCloseClient(con
);
1447 case HTTP_POST_RECV
:
1449 * See if the POST request includes a Content-Length field, and if
1450 * so check the length against any limits that are set...
1453 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "POST %s", con
->uri
);
1454 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "CONTENT_TYPE = %s",
1455 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
1457 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1458 MaxRequestSize
> 0 &&
1459 con
->http
.data_remaining
> MaxRequestSize
)
1462 * Request too large...
1465 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1467 cupsdCloseClient(con
);
1473 else if (con
->http
.data_remaining
< 0 ||
1474 (!con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1475 con
->http
.data_encoding
== HTTP_ENCODE_LENGTH
))
1478 * Negative content lengths are invalid!
1481 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1483 cupsdCloseClient(con
);
1491 * See what kind of POST request this is; for IPP requests the
1492 * content-type field will be "application/ipp"...
1495 if (!strcmp(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
],
1497 con
->request
= ippNew();
1498 else if ((!strncmp(con
->uri
, "/admin", 6) &&
1499 strncmp(con
->uri
, "/admin/conf/", 12) &&
1500 strncmp(con
->uri
, "/admin/log/", 11)) ||
1501 !strncmp(con
->uri
, "/printers", 9) ||
1502 !strncmp(con
->uri
, "/classes", 8) ||
1503 !strncmp(con
->uri
, "/help", 5) ||
1504 !strncmp(con
->uri
, "/jobs", 5))
1510 if (!strncmp(con
->uri
, "/admin", 6))
1512 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1515 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1517 else if (!strncmp(con
->uri
, "/printers", 9))
1519 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1522 if (con
->uri
[9] && con
->uri
[10])
1523 cupsdSetString(&con
->options
, con
->uri
+ 9);
1525 cupsdSetString(&con
->options
, NULL
);
1527 else if (!strncmp(con
->uri
, "/classes", 8))
1529 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1532 if (con
->uri
[8] && con
->uri
[9])
1533 cupsdSetString(&con
->options
, con
->uri
+ 8);
1535 cupsdSetString(&con
->options
, NULL
);
1537 else if (!strncmp(con
->uri
, "/jobs", 5))
1539 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1542 if (con
->uri
[5] && con
->uri
[6])
1543 cupsdSetString(&con
->options
, con
->uri
+ 5);
1545 cupsdSetString(&con
->options
, NULL
);
1549 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1552 if (con
->uri
[5] && con
->uri
[6])
1553 cupsdSetString(&con
->options
, con
->uri
+ 5);
1555 cupsdSetString(&con
->options
, NULL
);
1558 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1559 "cupsdReadClient: %d command=\"%s\", "
1561 con
->http
.fd
, con
->command
,
1562 con
->options
? con
->options
: "(null)");
1564 if (con
->http
.version
<= HTTP_1_0
)
1565 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1573 if ((filename
= get_file(con
, &filestats
, buf
,
1574 sizeof(buf
))) == NULL
)
1576 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1578 cupsdCloseClient(con
);
1585 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1587 if (!is_cgi(con
, filename
, &filestats
, type
))
1590 * Only POST to CGI's...
1593 if (!cupsdSendError(con
, HTTP_UNAUTHORIZED
, CUPSD_AUTH_NONE
))
1595 cupsdCloseClient(con
);
1602 case HTTP_PUT_RECV
:
1604 * Validate the resource name...
1607 if (strncmp(con
->uri
, "/admin/conf/", 12) ||
1608 strchr(con
->uri
+ 12, '/') ||
1609 strlen(con
->uri
) == 12)
1612 * PUT can only be done to configuration files under
1616 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1618 cupsdCloseClient(con
);
1626 * See if the PUT request includes a Content-Length field, and if
1627 * so check the length against any limits that are set...
1630 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "PUT %s", con
->uri
);
1631 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "CONTENT_TYPE = %s",
1632 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
1634 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1635 MaxRequestSize
> 0 &&
1636 con
->http
.data_remaining
> MaxRequestSize
)
1639 * Request too large...
1642 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1644 cupsdCloseClient(con
);
1650 else if (con
->http
.data_remaining
< 0)
1653 * Negative content lengths are invalid!
1656 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1658 cupsdCloseClient(con
);
1666 * Open a temporary file to hold the request...
1669 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
1671 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1675 cupsdLogMessage(CUPSD_LOG_ERROR
,
1676 "Unable to create request file %s: %s",
1677 con
->filename
, strerror(errno
));
1679 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1681 cupsdCloseClient(con
);
1686 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1687 "cupsdReadClient: %d REQUEST %s=%d", con
->http
.fd
,
1688 con
->filename
, con
->file
);
1690 fchmod(con
->file
, 0640);
1691 fchown(con
->file
, RunUser
, Group
);
1692 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1697 cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
);
1698 cupsdCloseClient(con
);
1702 if (!strncmp(con
->uri
, "/printers/", 10) &&
1703 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1706 * Send PPD file - get the real printer name since printer
1707 * names are not case sensitive but filenames can be...
1710 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1712 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1713 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1716 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1718 cupsdCloseClient(con
);
1726 if ((!strncmp(con
->uri
, "/admin", 6) &&
1727 strncmp(con
->uri
, "/admin/conf/", 12) &&
1728 strncmp(con
->uri
, "/admin/log/", 11)) ||
1729 !strncmp(con
->uri
, "/printers", 9) ||
1730 !strncmp(con
->uri
, "/classes", 8) ||
1731 !strncmp(con
->uri
, "/help", 5) ||
1732 !strncmp(con
->uri
, "/jobs", 5))
1738 if (!cupsdSendHeader(con
, HTTP_OK
, "text/html", CUPSD_AUTH_NONE
))
1740 cupsdCloseClient(con
);
1744 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1746 cupsdCloseClient(con
);
1750 if (cupsdFlushHeader(con
) < 0)
1752 cupsdCloseClient(con
);
1756 cupsdLogRequest(con
, HTTP_OK
);
1758 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1759 (strchr(con
->uri
+ 12, '/') ||
1760 strlen(con
->uri
) == 12)) ||
1761 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1762 (strchr(con
->uri
+ 11, '/') ||
1763 strlen(con
->uri
) == 11)))
1766 * HEAD can only be done to configuration files under
1770 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1772 cupsdCloseClient(con
);
1778 else if ((filename
= get_file(con
, &filestats
, buf
,
1779 sizeof(buf
))) == NULL
)
1781 if (!cupsdSendHeader(con
, HTTP_NOT_FOUND
, "text/html", CUPSD_AUTH_NONE
))
1783 cupsdCloseClient(con
);
1787 cupsdLogRequest(con
, HTTP_NOT_FOUND
);
1789 else if (!check_if_modified(con
, &filestats
))
1791 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1793 cupsdCloseClient(con
);
1797 cupsdLogRequest(con
, HTTP_NOT_MODIFIED
);
1805 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1807 strcpy(line
, "text/plain");
1809 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1811 if (!cupsdSendHeader(con
, HTTP_OK
, line
, CUPSD_AUTH_NONE
))
1813 cupsdCloseClient(con
);
1817 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
1818 httpGetDateString(filestats
.st_mtime
)) < 0)
1820 cupsdCloseClient(con
);
1824 if (httpPrintf(HTTP(con
), "Content-Length: %lu\r\n",
1825 (unsigned long)filestats
.st_size
) < 0)
1827 cupsdCloseClient(con
);
1831 cupsdLogRequest(con
, HTTP_OK
);
1834 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1836 cupsdCloseClient(con
);
1840 if (cupsdFlushHeader(con
) < 0)
1842 cupsdCloseClient(con
);
1846 con
->http
.state
= HTTP_WAITING
;
1850 break; /* Anti-compiler-warning-code */
1856 * Handle any incoming data...
1859 switch (con
->http
.state
)
1861 case HTTP_PUT_RECV
:
1862 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1863 "cupsdReadClient: %d con->data_encoding=HTTP_ENCODE_%s, "
1864 "con->data_remaining=" CUPS_LLFMT
", con->file=%d",
1866 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
?
1867 "CHUNKED" : "LENGTH",
1868 CUPS_LLCAST con
->http
.data_remaining
, con
->file
);
1872 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
1874 cupsdCloseClient(con
);
1879 con
->bytes
+= bytes
;
1881 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1882 "cupsdReadClient: %d writing %d bytes to %d",
1883 con
->http
.fd
, bytes
, con
->file
);
1885 if (write(con
->file
, line
, bytes
) < bytes
)
1887 cupsdLogMessage(CUPSD_LOG_ERROR
,
1888 "cupsdReadClient: Unable to write %d bytes to %s: %s",
1889 bytes
, con
->filename
, strerror(errno
));
1891 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1892 "cupsdReadClient: Closing data file %d...",
1897 unlink(con
->filename
);
1898 cupsdClearString(&con
->filename
);
1900 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1902 cupsdCloseClient(con
);
1908 while (con
->http
.state
== HTTP_PUT_RECV
&& con
->http
.used
> 0);
1910 if (con
->http
.state
== HTTP_WAITING
)
1913 * End of file, see how big it is...
1916 fstat(con
->file
, &filestats
);
1918 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1919 "cupsdReadClient: %d Closing data file %d, size="
1921 con
->http
.fd
, con
->file
,
1922 CUPS_LLCAST filestats
.st_size
);
1927 if (filestats
.st_size
> MaxRequestSize
&&
1931 * Request is too big; remove it and send an error...
1934 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1935 "cupsdReadClient: %d Removing temp file %s",
1936 con
->http
.fd
, con
->filename
);
1937 unlink(con
->filename
);
1938 cupsdClearString(&con
->filename
);
1940 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1942 cupsdCloseClient(con
);
1948 * Install the configuration file...
1951 status
= install_conf_file(con
);
1954 * Return the status to the client...
1957 if (!cupsdSendError(con
, status
, CUPSD_AUTH_NONE
))
1959 cupsdCloseClient(con
);
1965 case HTTP_POST_RECV
:
1966 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1967 "cupsdReadClient: %d con->data_encoding=HTTP_ENCODE_"
1968 "%s, con->data_remaining=" CUPS_LLFMT
", con->file=%d",
1970 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
?
1971 "CHUNKED" : "LENGTH",
1972 CUPS_LLCAST con
->http
.data_remaining
, con
->file
);
1979 * Grab any request data from the connection...
1982 if ((ipp_state
= ippRead(&(con
->http
), con
->request
)) == IPP_ERROR
)
1984 cupsdLogMessage(CUPSD_LOG_ERROR
,
1985 "cupsdReadClient: %d IPP Read Error!",
1988 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
1989 cupsdCloseClient(con
);
1992 else if (ipp_state
!= IPP_DATA
)
1994 if (con
->http
.state
== HTTP_POST_SEND
)
1996 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
1997 cupsdCloseClient(con
);
2004 con
->bytes
+= ippLength(con
->request
);
2007 if (con
->file
< 0 && con
->http
.state
!= HTTP_POST_SEND
)
2010 * Create a file as needed for the request data...
2013 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
, request_id
++);
2014 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
2018 cupsdLogMessage(CUPSD_LOG_ERROR
,
2019 "Unable to create request file %s: %s",
2020 con
->filename
, strerror(errno
));
2022 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2024 cupsdCloseClient(con
);
2029 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdReadClient: %d REQUEST %s=%d", con
->http
.fd
,
2030 con
->filename
, con
->file
);
2032 fchmod(con
->file
, 0640);
2033 fchown(con
->file
, RunUser
, Group
);
2034 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2037 if (con
->http
.state
!= HTTP_POST_SEND
)
2039 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
2041 cupsdCloseClient(con
);
2046 con
->bytes
+= bytes
;
2048 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2049 "cupsdReadClient: %d writing %d bytes to %d",
2050 con
->http
.fd
, bytes
, con
->file
);
2052 if (write(con
->file
, line
, bytes
) < bytes
)
2054 cupsdLogMessage(CUPSD_LOG_ERROR
,
2055 "cupsdReadClient: Unable to write %d bytes to %s: %s",
2056 bytes
, con
->filename
, strerror(errno
));
2058 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2059 "cupsdReadClient: Closing file %d...",
2064 unlink(con
->filename
);
2065 cupsdClearString(&con
->filename
);
2067 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2069 cupsdCloseClient(con
);
2074 else if (con
->http
.state
== HTTP_POST_RECV
)
2076 else if (con
->http
.state
!= HTTP_POST_SEND
)
2078 cupsdCloseClient(con
);
2083 while (con
->http
.state
== HTTP_POST_RECV
&& con
->http
.used
> 0);
2085 if (con
->http
.state
== HTTP_POST_SEND
)
2089 fstat(con
->file
, &filestats
);
2091 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2092 "cupsdReadClient: %d Closing data file %d, "
2093 "size=" CUPS_LLFMT
".",
2094 con
->http
.fd
, con
->file
,
2095 CUPS_LLCAST filestats
.st_size
);
2100 if (filestats
.st_size
> MaxRequestSize
&&
2104 * Request is too big; remove it and send an error...
2107 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2108 "cupsdReadClient: %d Removing temp file %s",
2109 con
->http
.fd
, con
->filename
);
2110 unlink(con
->filename
);
2111 cupsdClearString(&con
->filename
);
2116 * Delete any IPP request data...
2119 ippDelete(con
->request
);
2120 con
->request
= NULL
;
2123 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2125 cupsdCloseClient(con
);
2132 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
2134 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
2136 cupsdCloseClient(con
);
2141 cupsdLogRequest(con
, HTTP_OK
);
2147 cupsdProcessIPPRequest(con
);
2151 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2152 "cupsdReadClient: %d Removing temp file %s",
2153 con
->http
.fd
, con
->filename
);
2154 unlink(con
->filename
);
2155 cupsdClearString(&con
->filename
);
2164 break; /* Anti-compiler-warning-code */
2167 if (con
->http
.state
== HTTP_WAITING
)
2169 if (!con
->http
.keep_alive
)
2170 cupsdCloseClient(con
);
2173 cupsArrayRemove(ActiveClients
, con
);
2174 cupsdSetBusyState();
2181 * 'cupsdSendCommand()' - Send output from a command via HTTP.
2184 int /* O - 1 on success, 0 on failure */
2186 cupsd_client_t
*con
, /* I - Client connection */
2187 char *command
, /* I - Command to run */
2188 char *options
, /* I - Command-line options */
2189 int root
) /* I - Run as root? */
2191 int fd
; /* Standard input file descriptor */
2196 fd
= open(con
->filename
, O_RDONLY
);
2200 cupsdLogMessage(CUPSD_LOG_ERROR
,
2201 "cupsdSendCommand: %d Unable to open \"%s\" for reading: %s",
2202 con
->http
.fd
, con
->filename
? con
->filename
: "/dev/null",
2207 fcntl(fd
, F_SETFD
, fcntl(fd
, F_GETFD
) | FD_CLOEXEC
);
2212 con
->pipe_pid
= pipe_command(con
, fd
, &(con
->file
), command
, options
, root
);
2217 cupsdLogMessage(CUPSD_LOG_INFO
, "Started \"%s\" (pid=%d)", command
,
2220 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendCommand: %d file=%d",
2221 con
->http
.fd
, con
->file
);
2223 if (con
->pipe_pid
== 0)
2226 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2228 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2230 con
->sent_header
= 0;
2231 con
->file_ready
= 0;
2232 con
->got_fields
= 0;
2240 * 'cupsdSendError()' - Send an error message via HTTP.
2243 int /* O - 1 if successful, 0 otherwise */
2244 cupsdSendError(cupsd_client_t
*con
, /* I - Connection */
2245 http_status_t code
, /* I - Error code */
2246 int auth_type
)/* I - Authentication type */
2250 * Force client to upgrade for authentication if that is how the
2251 * server is configured...
2254 if (code
== HTTP_UNAUTHORIZED
&&
2255 DefaultEncryption
== HTTP_ENCRYPT_REQUIRED
&&
2256 strcasecmp(con
->http
.hostname
, "localhost") &&
2259 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2260 "cupsdSendError: Encryption before authentication!");
2261 code
= HTTP_UPGRADE_REQUIRED
;
2263 #endif /* HAVE_SSL */
2266 * Put the request in the access_log file...
2269 cupsdLogRequest(con
, code
);
2271 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendError: %d code=%d (%s)",
2272 con
->http
.fd
, code
, httpStatus(code
));
2275 * To work around bugs in some proxies, don't use Keep-Alive for some
2278 * Kerberos authentication doesn't work without Keep-Alive, so
2279 * never disable it in that case.
2282 if (code
>= HTTP_BAD_REQUEST
&& con
->http
.auth_type
!= CUPSD_AUTH_NEGOTIATE
)
2283 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
2286 * Send an error message back to the client. If the error code is a
2287 * 400 or 500 series, make sure the message contains some text, too!
2290 if (!cupsdSendHeader(con
, code
, NULL
, auth_type
))
2294 if (code
== HTTP_UPGRADE_REQUIRED
)
2295 if (httpPrintf(HTTP(con
), "Connection: Upgrade\r\n") < 0)
2298 if (httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n") < 0)
2300 #endif /* HAVE_SSL */
2302 if (con
->http
.version
>= HTTP_1_1
&&
2303 con
->http
.keep_alive
== HTTP_KEEPALIVE_OFF
)
2305 if (httpPrintf(HTTP(con
), "Connection: close\r\n") < 0)
2309 if (code
>= HTTP_BAD_REQUEST
)
2312 * Send a human-readable error message.
2315 char message
[4096], /* Message for user */
2316 urltext
[1024], /* URL redirection text */
2317 redirect
[1024]; /* Redirection link */
2318 const char *text
; /* Status-specific text */
2323 if (code
== HTTP_UNAUTHORIZED
)
2324 text
= _cupsLangString(con
->language
,
2325 _("Enter your username and password or the "
2326 "root username and password to access this "
2327 "page. If you are using Kerberos authentication, "
2328 "make sure you have a valid Kerberos ticket."));
2329 else if (code
== HTTP_UPGRADE_REQUIRED
)
2333 snprintf(urltext
, sizeof(urltext
),
2334 _cupsLangString(con
->language
,
2335 _("You must access this page using the URL "
2336 "<A HREF=\"https://%s:%d%s\">"
2337 "https://%s:%d%s</A>.")),
2338 con
->servername
, con
->serverport
, con
->uri
,
2339 con
->servername
, con
->serverport
, con
->uri
);
2341 snprintf(redirect
, sizeof(redirect
),
2342 "<META HTTP-EQUIV=\"Refresh\" "
2343 "CONTENT=\"3;URL=https://%s:%d%s\">\n",
2344 con
->servername
, con
->serverport
, con
->uri
);
2349 snprintf(message
, sizeof(message
),
2350 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" "
2351 "\"http://www.w3.org/TR/REC-html40/loose.dtd\">\n"
2354 "\t<META HTTP-EQUIV=\"Content-Type\" "
2355 "CONTENT=\"text/html; charset=utf-8\">\n"
2356 "\t<TITLE>%d %s</TITLE>\n"
2357 "\t<LINK REL=\"STYLESHEET\" TYPE=\"text/css\" "
2358 "HREF=\"/cups.css\">\n"
2366 code
, httpStatus(code
), redirect
, code
, httpStatus(code
), text
);
2368 if (httpPrintf(HTTP(con
), "Content-Type: text/html; charset=utf-8\r\n") < 0)
2370 if (httpPrintf(HTTP(con
), "Content-Length: %d\r\n",
2371 (int)strlen(message
)) < 0)
2373 if (httpPrintf(HTTP(con
), "\r\n") < 0)
2375 if (httpPrintf(HTTP(con
), "%s", message
) < 0)
2378 else if (httpPrintf(HTTP(con
), "\r\n") < 0)
2381 if (cupsdFlushHeader(con
) < 0)
2384 con
->http
.state
= HTTP_WAITING
;
2391 * 'cupsdSendHeader()' - Send an HTTP request.
2394 int /* O - 1 on success, 0 on failure */
2396 cupsd_client_t
*con
, /* I - Client to send to */
2397 http_status_t code
, /* I - HTTP status code */
2398 char *type
, /* I - MIME type of document */
2399 int auth_type
) /* I - Type of authentication */
2401 char auth_str
[1024]; /* Authorization string */
2403 static char *gss_buf
= NULL
; /* Kerberos auth data buffer */
2404 static int gss_bufsize
= 0; /* Size of Kerberos auth data buffer */
2405 #endif /* HAVE_GSSAPI */
2409 * Send the HTTP status header...
2412 if (code
== HTTP_CONTINUE
)
2415 * 100-continue doesn't send any headers...
2418 return (httpPrintf(HTTP(con
), "HTTP/%d.%d 100 Continue\r\n\r\n",
2419 con
->http
.version
/ 100, con
->http
.version
% 100) > 0);
2422 httpFlushWrite(HTTP(con
));
2424 con
->http
.data_encoding
= HTTP_ENCODE_FIELDS
;
2426 if (httpPrintf(HTTP(con
), "HTTP/%d.%d %d %s\r\n", con
->http
.version
/ 100,
2427 con
->http
.version
% 100, code
, httpStatus(code
)) < 0)
2429 if (httpPrintf(HTTP(con
), "Date: %s\r\n", httpGetDateString(time(NULL
))) < 0)
2432 if (httpPrintf(HTTP(con
), "Server: %s\r\n", ServerHeader
) < 0)
2434 if (con
->http
.keep_alive
&& con
->http
.version
>= HTTP_1_0
)
2436 if (httpPrintf(HTTP(con
), "Connection: Keep-Alive\r\n") < 0)
2438 if (httpPrintf(HTTP(con
), "Keep-Alive: timeout=%d\r\n",
2439 KeepAliveTimeout
) < 0)
2442 if (code
== HTTP_METHOD_NOT_ALLOWED
)
2443 if (httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST\r\n") < 0)
2446 if (code
== HTTP_UNAUTHORIZED
)
2448 if (auth_type
== CUPSD_AUTH_NONE
)
2450 if (!con
->best
|| con
->best
->type
<= CUPSD_AUTH_NONE
)
2451 auth_type
= DefaultAuthType
;
2453 auth_type
= con
->best
->type
;
2458 if (auth_type
== CUPSD_AUTH_BASIC
|| auth_type
== CUPSD_AUTH_BASICDIGEST
)
2459 strlcpy(auth_str
, "Basic realm=\"CUPS\"", sizeof(auth_str
));
2460 else if (auth_type
== CUPSD_AUTH_DIGEST
)
2461 snprintf(auth_str
, sizeof(auth_str
), "Digest realm=\"CUPS\", nonce=\"%s\"",
2462 con
->http
.hostname
);
2464 else if (auth_type
== CUPSD_AUTH_NEGOTIATE
&& con
->gss_output_token
.length
== 0)
2465 strlcpy(auth_str
, "Negotiate", sizeof(auth_str
));
2466 #endif /* HAVE_GSSAPI */
2468 #ifdef HAVE_AUTHORIZATION_H
2469 if (con
->best
&& auth_type
!= CUPSD_AUTH_NEGOTIATE
)
2471 int i
; /* Looping var */
2472 char *auth_key
; /* Auth key buffer */
2473 size_t auth_size
; /* Size of remaining buffer */
2476 auth_key
= auth_str
+ strlen(auth_str
);
2477 auth_size
= sizeof(auth_str
) - (auth_key
- auth_str
);
2479 for (i
= 0; i
< con
->best
->num_names
; i
++)
2481 if (!strncasecmp(con
->best
->names
[i
], "@AUTHKEY(", 9))
2483 snprintf(auth_key
, auth_size
, ", authkey=\"%s\"",
2484 con
->best
->names
[i
] + 9);
2485 /* end parenthesis is stripped in conf.c */
2488 else if (!strcasecmp(con
->best
->names
[i
], "@SYSTEM") &&
2491 snprintf(auth_key
, auth_size
, ", authkey=\"%s\"", SystemGroupAuthKey
);
2496 #endif /* HAVE_AUTHORIZATION_H */
2500 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendHeader: WWW-Authenticate: %s",
2503 if (httpPrintf(HTTP(con
), "WWW-Authenticate: %s\r\n", auth_str
) < 0)
2510 * WWW-Authenticate: Negotiate can be included even for
2511 * non-401 replies...
2514 if (con
->gss_output_token
.length
> 0 && con
->gss_output_token
.length
<= 65536)
2516 OM_uint32 minor_status
; /* Minor status code */
2517 int bufsize
; /* Size of output token buffer */
2520 bufsize
= con
->gss_output_token
.length
* 4 / 3 + 2;
2522 if (bufsize
> gss_bufsize
)
2524 char *buf
; /* New buffer */
2527 bufsize
= (bufsize
+ 1023) & 1023;/* Round up */
2530 buf
= realloc(gss_buf
, bufsize
);
2532 buf
= malloc(bufsize
);
2536 cupsdLogMessage(CUPSD_LOG_ERROR
,
2537 "Unable to allocate %d bytes for Kerberos credentials!",
2543 gss_bufsize
= bufsize
;
2546 httpEncode64_2(gss_buf
, gss_bufsize
,
2547 con
->gss_output_token
.value
,
2548 con
->gss_output_token
.length
);
2549 gss_release_buffer(&minor_status
, &con
->gss_output_token
);
2551 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2552 "cupsdSendHeader: WWW-Authenticate: Negotiate %s", gss_buf
);
2554 if (httpPrintf(HTTP(con
), "WWW-Authenticate: Negotiate %s\r\n",
2558 else if (con
->gss_output_token
.length
> 65536)
2560 cupsdLogMessage(CUPSD_LOG_ERROR
,
2561 "Kerberos credentials larger than 64k (%d)!",
2562 (int)con
->gss_output_token
.length
);
2565 #endif /* HAVE_GSSAPI */
2567 if (con
->language
&& strcmp(con
->language
->language
, "C"))
2569 if (httpPrintf(HTTP(con
), "Content-Language: %s\r\n",
2570 con
->language
->language
) < 0)
2576 if (!strcmp(type
, "text/html"))
2578 if (httpPrintf(HTTP(con
),
2579 "Content-Type: text/html; charset=utf-8\r\n") < 0)
2582 else if (httpPrintf(HTTP(con
), "Content-Type: %s\r\n", type
) < 0)
2591 * 'cupsdUpdateCGI()' - Read status messages from CGI scripts and programs.
2595 cupsdUpdateCGI(void)
2597 char *ptr
, /* Pointer to end of line in buffer */
2598 message
[1024]; /* Pointer to message text */
2599 int loglevel
; /* Log level for message */
2602 while ((ptr
= cupsdStatBufUpdate(CGIStatusBuffer
, &loglevel
,
2603 message
, sizeof(message
))) != NULL
)
2604 if (!strchr(CGIStatusBuffer
->buffer
, '\n'))
2607 if (ptr
== NULL
&& !CGIStatusBuffer
->bufused
)
2610 * Fatal error on pipe - should never happen!
2613 cupsdLogMessage(CUPSD_LOG_CRIT
,
2614 "cupsdUpdateCGI: error reading from CGI error pipe - %s",
2621 * 'cupsdWriteClient()' - Write data to a client as needed.
2625 cupsdWriteClient(cupsd_client_t
*con
) /* I - Client connection */
2627 int bytes
; /* Number of bytes written */
2628 char buf
[16385]; /* Data buffer */
2629 char *bufptr
; /* Pointer into buffer */
2630 ipp_state_t ipp_state
; /* IPP state value */
2634 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2635 "cupsdWriteClient(con=%p) %d response=%p(%d), file=%d "
2636 "pipe_pid=%d state=%d",
2637 con
, con
->http
.fd
, con
->response
,
2638 con
->response
? con
->response
->state
: -1,
2639 con
->file
, con
->pipe_pid
, con
->http
.state
);
2642 if (con
->http
.state
!= HTTP_GET_SEND
&&
2643 con
->http
.state
!= HTTP_POST_SEND
)
2649 * Make sure we select on the CGI output...
2652 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2654 if (!con
->file_ready
)
2657 * Try again later when there is CGI output available...
2660 cupsdRemoveSelect(con
->http
.fd
);
2664 con
->file_ready
= 0;
2667 if (con
->response
&& con
->response
->state
!= IPP_DATA
)
2669 ipp_state
= ippWrite(HTTP(con
), con
->response
);
2670 bytes
= ipp_state
!= IPP_ERROR
&&
2671 (con
->file
>= 0 || ipp_state
!= IPP_DATA
);
2673 else if ((bytes
= read(con
->file
, buf
, sizeof(buf
) - 1)) > 0)
2675 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2676 "cupsdWriteClient: Read %d bytes from file %d...",
2679 if (con
->pipe_pid
&& !con
->got_fields
)
2682 * Inspect the data for Content-Type and other fields.
2687 for (bufptr
= buf
; !con
->got_fields
&& *bufptr
; bufptr
++)
2688 if (*bufptr
== '\n')
2691 * Send line to client...
2694 if (bufptr
> buf
&& bufptr
[-1] == '\r')
2698 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "Script header: %s", buf
);
2700 if (!con
->sent_header
)
2703 * Handle redirection and CGI status codes...
2706 if (!strncasecmp(buf
, "Location:", 9))
2708 cupsdSendHeader(con
, HTTP_SEE_OTHER
, NULL
, CUPSD_AUTH_NONE
);
2709 con
->sent_header
= 2;
2711 if (httpPrintf(HTTP(con
), "Content-Length: 0\r\n") < 0)
2714 else if (!strncasecmp(buf
, "Status:", 7))
2716 cupsdSendError(con
, (http_status_t
)atoi(buf
+ 7), CUPSD_AUTH_NONE
);
2717 con
->sent_header
= 2;
2721 cupsdSendHeader(con
, HTTP_OK
, NULL
, CUPSD_AUTH_NONE
);
2722 con
->sent_header
= 1;
2724 if (con
->http
.version
== HTTP_1_1
)
2726 if (httpPrintf(HTTP(con
), "Transfer-Encoding: chunked\r\n") < 0)
2732 if (strncasecmp(buf
, "Status:", 7))
2733 httpPrintf(HTTP(con
), "%s\r\n", buf
);
2735 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdWriteClient: %d %s",
2742 bytes
-= (bufptr
- buf
);
2743 memmove(buf
, bufptr
, bytes
+ 1);
2747 * See if the line was empty...
2750 if (con
->field_col
== 0)
2752 con
->got_fields
= 1;
2754 if (cupsdFlushHeader(con
) < 0)
2756 cupsdCloseClient(con
);
2760 if (con
->http
.version
== HTTP_1_1
)
2761 con
->http
.data_encoding
= HTTP_ENCODE_CHUNKED
;
2766 else if (*bufptr
!= '\r')
2769 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2770 "cupsdWriteClient: %d bytes=%d, got_fields=%d",
2771 con
->http
.fd
, bytes
, con
->got_fields
);
2773 if (bytes
> 0 && !con
->got_fields
)
2776 * Remaining text needs to go out...
2779 httpPrintf(HTTP(con
), "%s", buf
);
2781 con
->http
.activity
= time(NULL
);
2784 else if (bytes
== 0)
2785 con
->http
.activity
= time(NULL
);
2790 if (httpWrite2(HTTP(con
), buf
, bytes
) < 0)
2792 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2793 "cupsdWriteClient: %d Write of %d bytes failed!",
2794 con
->http
.fd
, bytes
);
2796 cupsdCloseClient(con
);
2800 httpFlushWrite(HTTP(con
));
2802 con
->bytes
+= bytes
;
2804 if (con
->http
.state
== HTTP_WAITING
)
2811 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdWriteClient: %d bytes < 0",
2814 cupsdLogRequest(con
, HTTP_OK
);
2816 httpFlushWrite(HTTP(con
));
2818 if (con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
&& con
->sent_header
== 1)
2820 if (httpWrite2(HTTP(con
), "", 0) < 0)
2822 cupsdCloseClient(con
);
2827 con
->http
.state
= HTTP_WAITING
;
2829 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
2833 cupsdRemoveSelect(con
->file
);
2836 cupsdEndProcess(con
->pipe_pid
, 0);
2838 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2839 "cupsdWriteClient: %d Closing data file %d.",
2840 con
->http
.fd
, con
->file
);
2849 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2850 "cupsdWriteClient: %d Removing temp file %s",
2851 con
->http
.fd
, con
->filename
);
2852 unlink(con
->filename
);
2853 cupsdClearString(&con
->filename
);
2858 ippDelete(con
->request
);
2859 con
->request
= NULL
;
2864 ippDelete(con
->response
);
2865 con
->response
= NULL
;
2868 cupsdClearString(&con
->command
);
2869 cupsdClearString(&con
->options
);
2870 cupsdClearString(&con
->query_string
);
2872 if (!con
->http
.keep_alive
)
2874 cupsdCloseClient(con
);
2879 con
->http
.activity
= time(NULL
);
2884 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
2887 static int /* O - 1 if modified since */
2889 cupsd_client_t
*con
, /* I - Client connection */
2890 struct stat
*filestats
) /* I - File information */
2892 char *ptr
; /* Pointer into field */
2893 time_t date
; /* Time/date value */
2894 off_t size
; /* Size/length value */
2899 ptr
= con
->http
.fields
[HTTP_FIELD_IF_MODIFIED_SINCE
];
2904 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2905 "check_if_modified: %d If-Modified-Since=\"%s\"",
2908 while (*ptr
!= '\0')
2910 while (isspace(*ptr
) || *ptr
== ';')
2913 if (strncasecmp(ptr
, "length=", 7) == 0)
2916 size
= strtoll(ptr
, NULL
, 10);
2918 while (isdigit(*ptr
))
2921 else if (isalpha(*ptr
))
2923 date
= httpGetDateTime(ptr
);
2924 while (*ptr
!= '\0' && *ptr
!= ';')
2931 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2932 "check_if_modified: %d sizes=" CUPS_LLFMT
","
2933 CUPS_LLFMT
" dates=%d,%d",
2934 con
->http
.fd
, CUPS_LLCAST size
,
2935 CUPS_LLCAST filestats
->st_size
, (int)date
,
2936 (int)filestats
->st_mtime
);
2938 return ((size
!= filestats
->st_size
&& size
!= 0) ||
2939 (date
< filestats
->st_mtime
&& date
!= 0) ||
2940 (size
== 0 && date
== 0));
2945 * 'compare_clients()' - Compare two client connections.
2948 static int /* O - Result of comparison */
2949 compare_clients(cupsd_client_t
*a
, /* I - First client */
2950 cupsd_client_t
*b
, /* I - Second client */
2951 void *data
) /* I - User data (not used) */
2966 * 'encrypt_client()' - Enable encryption for the client...
2969 static int /* O - 1 on success, 0 on error */
2970 encrypt_client(cupsd_client_t
*con
) /* I - Client to encrypt */
2973 SSL_CTX
*context
; /* Context for encryption */
2974 SSL
*conn
; /* Connection for encryption */
2975 BIO
*bio
; /* BIO data */
2976 unsigned long error
; /* Error code */
2980 * Verify that we have a certificate...
2983 if (access(ServerKey
, 0) || access(ServerCertificate
, 0))
2986 * Nope, make a self-signed certificate...
2989 if (!make_certificate(con
))
2994 * Create the SSL context and accept the connection...
2997 context
= SSL_CTX_new(SSLv23_server_method());
2999 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
3000 SSL_CTX_use_PrivateKey_file(context
, ServerKey
, SSL_FILETYPE_PEM
);
3001 SSL_CTX_use_certificate_file(context
, ServerCertificate
, SSL_FILETYPE_PEM
);
3003 bio
= BIO_new(_httpBIOMethods());
3004 BIO_ctrl(bio
, BIO_C_SET_FILE_PTR
, 0, (char *)HTTP(con
));
3006 conn
= SSL_new(context
);
3007 SSL_set_bio(conn
, bio
, bio
);
3009 if (SSL_accept(conn
) != 1)
3011 cupsdLogMessage(CUPSD_LOG_ERROR
,
3012 "encrypt_client: Unable to encrypt connection from %s!",
3013 con
->http
.hostname
);
3015 while ((error
= ERR_get_error()) != 0)
3016 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s",
3017 ERR_error_string(error
, NULL
));
3019 SSL_CTX_free(context
);
3024 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3025 "encrypt_client: %d Connection from %s now encrypted.",
3026 con
->http
.fd
, con
->http
.hostname
);
3028 con
->http
.tls
= conn
;
3031 # elif defined(HAVE_GNUTLS)
3032 http_tls_t
*conn
; /* TLS session object */
3033 int error
; /* Error code */
3034 gnutls_certificate_server_credentials
*credentials
;
3035 /* TLS credentials */
3039 * Verify that we have a certificate...
3042 if (access(ServerKey
, 0) || access(ServerCertificate
, 0))
3045 * Nope, make a self-signed certificate...
3048 if (!make_certificate(con
))
3053 * Create the SSL object and perform the SSL handshake...
3056 conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
));
3061 credentials
= (gnutls_certificate_server_credentials
*)
3062 malloc(sizeof(gnutls_certificate_server_credentials
));
3063 if (credentials
== NULL
)
3065 cupsdLogMessage(CUPSD_LOG_ERROR
,
3066 "encrypt_client: Unable to encrypt connection from %s!",
3067 con
->http
.hostname
);
3068 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s", strerror(errno
));
3074 gnutls_certificate_allocate_credentials(credentials
);
3075 gnutls_certificate_set_x509_key_file(*credentials
, ServerCertificate
,
3076 ServerKey
, GNUTLS_X509_FMT_PEM
);
3078 gnutls_init(&(conn
->session
), GNUTLS_SERVER
);
3079 gnutls_set_default_priority(conn
->session
);
3080 gnutls_credentials_set(conn
->session
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
3081 gnutls_transport_set_ptr(conn
->session
, (gnutls_transport_ptr
)HTTP(con
));
3082 gnutls_transport_set_pull_function(conn
->session
, _httpReadGNUTLS
);
3083 gnutls_transport_set_push_function(conn
->session
, _httpWriteGNUTLS
);
3085 error
= gnutls_handshake(conn
->session
);
3087 if (error
!= GNUTLS_E_SUCCESS
)
3089 cupsdLogMessage(CUPSD_LOG_ERROR
,
3090 "encrypt_client: Unable to encrypt connection from %s!",
3091 con
->http
.hostname
);
3092 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s",
3093 gnutls_strerror(error
));
3095 gnutls_deinit(conn
->session
);
3096 gnutls_certificate_free_credentials(*credentials
);
3102 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3103 "encrypt_client: %d Connection from %s now encrypted.",
3104 con
->http
.fd
, con
->http
.hostname
);
3106 conn
->credentials
= credentials
;
3107 con
->http
.tls
= conn
;
3110 # elif defined(HAVE_CDSASSL)
3111 OSStatus error
; /* Error code */
3112 http_tls_t
*conn
; /* CDSA connection information */
3115 if ((conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
))) == NULL
)
3119 conn
->session
= NULL
;
3120 conn
->certsArray
= get_cdsa_certificate(con
);
3122 if (!conn
->certsArray
)
3125 * No keychain (yet), make a self-signed certificate...
3128 if (make_certificate(con
))
3129 conn
->certsArray
= get_cdsa_certificate(con
);
3132 if (!conn
->certsArray
)
3134 cupsdLogMessage(CUPSD_LOG_ERROR
,
3135 "encrypt_client: Could not find signing key in keychain "
3136 "\"%s\"", ServerCertificate
);
3137 error
= errSSLBadCert
; /* errSSLBadConfiguration is a better choice, but not available on 10.2.x */
3141 error
= SSLNewContext(true, &conn
->session
);
3144 error
= SSLSetIOFuncs(conn
->session
, _httpReadCDSA
, _httpWriteCDSA
);
3147 error
= SSLSetProtocolVersionEnabled(conn
->session
, kSSLProtocol2
, false);
3150 error
= SSLSetConnection(conn
->session
, HTTP(con
));
3153 error
= SSLSetAllowsExpiredCerts(conn
->session
, true);
3156 error
= SSLSetAllowsAnyRoot(conn
->session
, true);
3159 error
= SSLSetCertificate(conn
->session
, conn
->certsArray
);
3164 * Perform SSL/TLS handshake
3167 while ((error
= SSLHandshake(conn
->session
)) == errSSLWouldBlock
)
3173 cupsdLogMessage(CUPSD_LOG_ERROR
,
3174 "encrypt_client: Unable to encrypt connection from %s!",
3175 con
->http
.hostname
);
3177 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s (%d)",
3178 cssmErrorString(error
), (int)error
);
3180 con
->http
.error
= error
;
3181 con
->http
.status
= HTTP_ERROR
;
3184 SSLDisposeContext(conn
->session
);
3186 if (conn
->certsArray
)
3187 CFRelease(conn
->certsArray
);
3194 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3195 "encrypt_client: %d Connection from %s now encrypted.",
3196 con
->http
.fd
, con
->http
.hostname
);
3198 con
->http
.tls
= conn
;
3201 # endif /* HAVE_LIBSSL */
3203 #endif /* HAVE_SSL */
3208 * 'get_cdsa_certificate()' - Get a SSL/TLS certificate from the System keychain.
3211 static CFArrayRef
/* O - Array of certificates */
3212 get_cdsa_certificate(cupsd_client_t
*con
) /* I - Client connection */
3214 OSStatus err
; /* Error info */
3215 SecKeychainRef keychain
; /* Keychain reference */
3216 SecIdentitySearchRef search
; /* Search reference */
3217 SecIdentityRef identity
; /* Identity */
3218 CFArrayRef certificates
= NULL
;
3219 /* Certificate array */
3222 if ((err
= SecKeychainOpen(ServerCertificate
, &keychain
)))
3224 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot open keychain \"%s\", %s",
3225 ServerCertificate
, cssmErrorString(err
));
3229 # if HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY
3231 * Use a policy to search for valid certificates who's common name matches the
3235 SecPolicySearchRef policy_search
; /* Policy search ref */
3236 SecPolicyRef policy
; /* Policy ref */
3237 CSSM_DATA options
; /* Policy options */
3238 CSSM_APPLE_TP_SSL_OPTIONS
3239 ssl_options
; /* SSL Option for hostname */
3242 if ((err
= SecPolicySearchCreate(CSSM_CERT_X_509v3
, &CSSMOID_APPLE_TP_SSL
,
3243 NULL
, &policy_search
)))
3245 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot create a policy search reference");
3246 CFRelease(keychain
);
3250 if ((err
= SecPolicySearchCopyNext(policy_search
, &policy
)))
3252 cupsdLogMessage(CUPSD_LOG_ERROR
,
3253 "Cannot find a policy to use for searching");
3254 CFRelease(keychain
);
3255 CFRelease(policy_search
);
3259 memset(&ssl_options
, 0, sizeof(ssl_options
));
3260 ssl_options
.Version
= CSSM_APPLE_TP_SSL_OPTS_VERSION
;
3261 ssl_options
.ServerName
= con
->servername
;
3262 ssl_options
.ServerNameLen
= strlen(con
->servername
);
3264 options
.Data
= (uint8
*)&ssl_options
;
3265 options
.Length
= sizeof(ssl_options
);
3267 if ((err
= SecPolicySetValue(policy
, &options
)))
3269 cupsdLogMessage(CUPSD_LOG_ERROR
,
3270 "Cannot set policy value to use for searching");
3271 CFRelease(keychain
);
3272 CFRelease(policy_search
);
3276 err
= SecIdentitySearchCreateWithPolicy(policy
, NULL
, CSSM_KEYUSE_SIGN
,
3277 keychain
, FALSE
, &search
);
3280 * Assume there is exactly one SecIdentity in the keychain...
3283 err
= SecIdentitySearchCreate(keychain
, CSSM_KEYUSE_SIGN
, &search
);
3284 # endif /* HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY */
3287 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3288 "Cannot create keychain search reference: %s",
3289 cssmErrorString(err
));
3292 if ((err
= SecIdentitySearchCopyNext(search
, &identity
)))
3294 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3295 "Cannot find signing key in keychain \"%s\", error %d",
3296 ServerCertificate
, (int)err
);
3300 if (CFGetTypeID(identity
) != SecIdentityGetTypeID())
3301 cupsdLogMessage(CUPSD_LOG_ERROR
,
3302 "SecIdentitySearchCopyNext CFTypeID failure!");
3305 if ((certificates
= CFArrayCreate(NULL
, (const void **)&identity
,
3306 1, &kCFTypeArrayCallBacks
)) == NULL
)
3307 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot create certificate array");
3310 CFRelease(identity
);
3316 # if HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY
3318 CFRelease(policy_search
);
3319 # endif /* HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY */
3321 return (certificates
);
3323 #endif /* HAVE_CDSASSL */
3327 * 'get_file()' - Get a filename and state info.
3330 static char * /* O - Real filename */
3331 get_file(cupsd_client_t
*con
, /* I - Client connection */
3332 struct stat
*filestats
, /* O - File information */
3333 char *filename
, /* IO - Filename buffer */
3334 int len
) /* I - Buffer length */
3336 int status
; /* Status of filesystem calls */
3337 char *ptr
; /* Pointer info filename */
3338 int plen
; /* Remaining length after pointer */
3339 char language
[7]; /* Language subdirectory, if any */
3343 * Figure out the real filename...
3348 if (!strncmp(con
->uri
, "/ppd/", 5))
3349 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
);
3350 else if (!strncmp(con
->uri
, "/rss/", 5) && !strchr(con
->uri
+ 5, '/'))
3351 snprintf(filename
, len
, "%s/rss/%s", CacheDir
, con
->uri
+ 5);
3352 else if (!strncmp(con
->uri
, "/admin/conf/", 12))
3353 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
+ 11);
3354 else if (!strncmp(con
->uri
, "/admin/log/", 11))
3356 if (!strncmp(con
->uri
+ 11, "access_log", 10) && AccessLog
[0] == '/')
3357 strlcpy(filename
, AccessLog
, len
);
3358 else if (!strncmp(con
->uri
+ 11, "error_log", 9) && ErrorLog
[0] == '/')
3359 strlcpy(filename
, ErrorLog
, len
);
3360 else if (!strncmp(con
->uri
+ 11, "page_log", 8) && PageLog
[0] == '/')
3361 strlcpy(filename
, PageLog
, len
);
3365 else if (con
->language
)
3367 snprintf(language
, sizeof(language
), "/%s", con
->language
->language
);
3368 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3371 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3373 if ((ptr
= strchr(filename
, '?')) != NULL
)
3377 * Grab the status for this language; if there isn't a language-specific file
3378 * then fallback to the default one...
3381 if ((status
= stat(filename
, filestats
)) != 0 && language
[0] &&
3382 strncmp(con
->uri
, "/ppd/", 5) &&
3383 strncmp(con
->uri
, "/admin/conf/", 12) &&
3384 strncmp(con
->uri
, "/admin/log/", 11))
3387 * Drop the country code...
3391 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3393 if ((ptr
= strchr(filename
, '?')) != NULL
)
3396 if ((status
= stat(filename
, filestats
)) != 0)
3399 * Drop the language prefix and try the root directory...
3403 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3405 if ((ptr
= strchr(filename
, '?')) != NULL
)
3408 status
= stat(filename
, filestats
);
3413 * If we're found a directory, get the index.html file instead...
3416 if (!status
&& S_ISDIR(filestats
->st_mode
))
3419 * Make sure the URI ends with a slash...
3422 if (con
->uri
[strlen(con
->uri
) - 1] != '/')
3423 strlcat(con
->uri
, "/", sizeof(con
->uri
));
3426 * Find the directory index file, trying every language...
3431 if (status
&& language
[0])
3434 * Try a different language subset...
3438 language
[0] = '\0'; /* Strip country code */
3440 language
[0] = '\0'; /* Strip language */
3444 * Look for the index file...
3447 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3449 if ((ptr
= strchr(filename
, '?')) != NULL
)
3452 ptr
= filename
+ strlen(filename
);
3453 plen
= len
- (ptr
- filename
);
3455 strlcpy(ptr
, "index.html", plen
);
3456 status
= stat(filename
, filestats
);
3461 strlcpy(ptr
, "index.class", plen
);
3462 status
= stat(filename
, filestats
);
3464 #endif /* HAVE_JAVA */
3469 strlcpy(ptr
, "index.pl", plen
);
3470 status
= stat(filename
, filestats
);
3472 #endif /* HAVE_PERL */
3477 strlcpy(ptr
, "index.php", plen
);
3478 status
= stat(filename
, filestats
);
3480 #endif /* HAVE_PHP */
3485 strlcpy(ptr
, "index.pyc", plen
);
3486 status
= stat(filename
, filestats
);
3491 strlcpy(ptr
, "index.py", plen
);
3492 status
= stat(filename
, filestats
);
3494 #endif /* HAVE_PYTHON */
3497 while (status
&& language
[0]);
3500 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "get_file: %d filename=%s size=%d",
3501 con
->http
.fd
, filename
,
3502 status
? -1 : (int)filestats
->st_size
);
3505 con
->http
.data_remaining
= (int)filestats
->st_size
;
3515 * 'install_conf_file()' - Install a configuration file.
3518 static http_status_t
/* O - Status */
3519 install_conf_file(cupsd_client_t
*con
) /* I - Connection */
3521 cups_file_t
*in
, /* Input file */
3522 *out
; /* Output file */
3523 char buffer
[1024]; /* Copy buffer */
3524 int bytes
; /* Number of bytes */
3525 char conffile
[1024], /* Configuration filename */
3526 newfile
[1024], /* New config filename */
3527 oldfile
[1024]; /* Old config filename */
3528 struct stat confinfo
; /* Config file info */
3532 * First construct the filenames...
3535 snprintf(conffile
, sizeof(conffile
), "%s%s", ServerRoot
, con
->uri
+ 11);
3536 snprintf(newfile
, sizeof(newfile
), "%s%s.N", ServerRoot
, con
->uri
+ 11);
3537 snprintf(oldfile
, sizeof(oldfile
), "%s%s.O", ServerRoot
, con
->uri
+ 11);
3539 cupsdLogMessage(CUPSD_LOG_INFO
, "Installing config file \"%s\"...", conffile
);
3542 * Get the owner, group, and permissions of the configuration file.
3543 * If it doesn't exist, assign it to the User and Group in the
3544 * cupsd.conf file with mode 0640 permissions.
3547 if (stat(conffile
, &confinfo
))
3549 confinfo
.st_uid
= User
;
3550 confinfo
.st_gid
= Group
;
3551 confinfo
.st_mode
= ConfigFilePerm
;
3555 * Open the request file and new config file...
3558 if ((in
= cupsFileOpen(con
->filename
, "rb")) == NULL
)
3560 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open request file \"%s\" - %s",
3561 con
->filename
, strerror(errno
));
3562 return (HTTP_SERVER_ERROR
);
3565 if ((out
= cupsFileOpen(newfile
, "wb")) == NULL
)
3568 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open config file \"%s\" - %s",
3569 newfile
, strerror(errno
));
3570 return (HTTP_SERVER_ERROR
);
3573 fchmod(cupsFileNumber(out
), confinfo
.st_mode
);
3574 fchown(cupsFileNumber(out
), confinfo
.st_uid
, confinfo
.st_gid
);
3577 * Copy from the request to the new config file...
3580 while ((bytes
= cupsFileRead(in
, buffer
, sizeof(buffer
))) > 0)
3581 if (cupsFileWrite(out
, buffer
, bytes
) < bytes
)
3583 cupsdLogMessage(CUPSD_LOG_ERROR
,
3584 "Unable to copy to config file \"%s\" - %s",
3585 newfile
, strerror(errno
));
3591 return (HTTP_SERVER_ERROR
);
3595 * Close the files...
3599 if (cupsFileClose(out
))
3601 cupsdLogMessage(CUPSD_LOG_ERROR
,
3602 "Error file closing config file \"%s\" - %s",
3603 newfile
, strerror(errno
));
3607 return (HTTP_SERVER_ERROR
);
3611 * Remove the request file...
3614 unlink(con
->filename
);
3615 cupsdClearString(&con
->filename
);
3618 * Unlink the old backup, rename the current config file to the backup
3619 * filename, and rename the new config file to the config file name...
3622 if (unlink(oldfile
))
3623 if (errno
!= ENOENT
)
3625 cupsdLogMessage(CUPSD_LOG_ERROR
,
3626 "Unable to remove backup config file \"%s\" - %s",
3627 oldfile
, strerror(errno
));
3631 return (HTTP_SERVER_ERROR
);
3634 if (rename(conffile
, oldfile
))
3635 if (errno
!= ENOENT
)
3637 cupsdLogMessage(CUPSD_LOG_ERROR
,
3638 "Unable to rename old config file \"%s\" - %s",
3639 conffile
, strerror(errno
));
3643 return (HTTP_SERVER_ERROR
);
3646 if (rename(newfile
, conffile
))
3648 cupsdLogMessage(CUPSD_LOG_ERROR
,
3649 "Unable to rename new config file \"%s\" - %s",
3650 newfile
, strerror(errno
));
3652 rename(oldfile
, conffile
);
3655 return (HTTP_SERVER_ERROR
);
3659 * If the cupsd.conf file was updated, set the NeedReload flag...
3662 if (!strcmp(con
->uri
, "/admin/conf/cupsd.conf"))
3663 NeedReload
= RELOAD_CUPSD
;
3665 NeedReload
= RELOAD_ALL
;
3667 ReloadTime
= time(NULL
);
3670 * Return that the file was created successfully...
3673 return (HTTP_CREATED
);
3678 * 'is_cgi()' - Is the resource a CGI script/program?
3681 static int /* O - 1 = CGI, 0 = file */
3682 is_cgi(cupsd_client_t
*con
, /* I - Client connection */
3683 const char *filename
, /* I - Real filename */
3684 struct stat
*filestats
, /* I - File information */
3685 mime_type_t
*type
) /* I - MIME type */
3687 const char *options
; /* Options on URL */
3690 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3691 "is_cgi(con=%p, filename=\"%s\", filestats=%p, type=%s/%s)\n",
3692 con
, filename
, filestats
, type
? type
->super
: "unknown",
3693 type
? type
->type
: "unknown");
3696 * Get the options, if any...
3699 if ((options
= strchr(con
->uri
, '?')) != NULL
)
3700 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", options
+ 1);
3703 * Check for known types...
3706 if (!type
|| strcasecmp(type
->super
, "application"))
3708 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "is_cgi: Returning 0...");
3712 if (!strcasecmp(type
->type
, "x-httpd-cgi") &&
3713 (filestats
->st_mode
& 0111))
3716 * "application/x-httpd-cgi" is a CGI script.
3719 cupsdSetString(&con
->command
, filename
);
3721 filename
= strrchr(filename
, '/') + 1; /* Filename always absolute */
3723 cupsdSetStringf(&con
->options
, " %s", options
);
3725 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3726 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3727 con
->command
, con
->options
);
3732 else if (!strcasecmp(type
->type
, "x-httpd-java"))
3735 * "application/x-httpd-java" is a Java servlet.
3738 cupsdSetString(&con
->command
, CUPS_JAVA
);
3741 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3743 cupsdSetStringf(&con
->options
, " %s", filename
);
3745 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3746 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3747 con
->command
, con
->options
);
3751 #endif /* HAVE_JAVA */
3753 else if (!strcasecmp(type
->type
, "x-httpd-perl"))
3756 * "application/x-httpd-perl" is a Perl page.
3759 cupsdSetString(&con
->command
, CUPS_PERL
);
3762 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3764 cupsdSetStringf(&con
->options
, " %s", filename
);
3766 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3767 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3768 con
->command
, con
->options
);
3772 #endif /* HAVE_PERL */
3774 else if (!strcasecmp(type
->type
, "x-httpd-php"))
3777 * "application/x-httpd-php" is a PHP page.
3780 cupsdSetString(&con
->command
, CUPS_PHP
);
3783 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3785 cupsdSetStringf(&con
->options
, " %s", filename
);
3787 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3788 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3789 con
->command
, con
->options
);
3793 #endif /* HAVE_PHP */
3795 else if (!strcasecmp(type
->type
, "x-httpd-python"))
3798 * "application/x-httpd-python" is a Python page.
3801 cupsdSetString(&con
->command
, CUPS_PYTHON
);
3804 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3806 cupsdSetStringf(&con
->options
, " %s", filename
);
3808 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3809 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3810 con
->command
, con
->options
);
3814 #endif /* HAVE_PYTHON */
3816 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "is_cgi: Returning 0...");
3823 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
3826 static int /* O - 0 if relative, 1 if absolute */
3827 is_path_absolute(const char *path
) /* I - Input path */
3830 * Check for a leading slash...
3837 * Check for "/.." in the path...
3840 while ((path
= strstr(path
, "/..")) != NULL
)
3842 if (!path
[3] || path
[3] == '/')
3849 * If we haven't found any relative paths, return 1 indicating an
3859 * 'make_certificate()' - Make a self-signed SSL/TLS certificate.
3862 static int /* O - 1 on success, 0 on failure */
3863 make_certificate(cupsd_client_t
*con
) /* I - Client connection */
3865 #if defined(HAVE_LIBSSL) && defined(HAVE_WAITPID)
3866 int pid
, /* Process ID of command */
3867 status
; /* Status of command */
3868 char command
[1024], /* Command */
3869 *argv
[12], /* Command-line arguments */
3870 *envp
[MAX_ENV
+ 1], /* Environment variables */
3871 home
[1024], /* HOME environment variable */
3872 infofile
[1024], /* Type-in information for cert */
3873 seedfile
[1024]; /* Random number seed file */
3874 int envc
, /* Number of environment variables */
3875 bytes
; /* Bytes written */
3876 cups_file_t
*fp
; /* Seed/info file */
3877 int infofd
; /* Info file descriptor */
3881 * Run the "openssl" command to seed the random number generator and
3882 * generate a self-signed certificate that is good for 10 years:
3884 * openssl rand -rand seedfile 1
3886 * openssl req -new -x509 -keyout ServerKey \
3887 * -out ServerCertificate -days 3650 -nodes
3889 * The seeding step is crucial in ensuring that the openssl command
3890 * does not block on systems without sufficient entropy...
3893 if (!cupsFileFind("openssl", getenv("PATH"), 1, command
, sizeof(command
)))
3895 cupsdLogMessage(CUPSD_LOG_ERROR
,
3896 "No SSL certificate and openssl command not found!");
3900 if (access("/dev/urandom", 0))
3903 * If the system doesn't provide /dev/urandom, then any random source
3904 * will probably be blocking-style, so generate some random data to
3905 * use as a seed for the certificate. Note that we have already
3906 * seeded the random number generator in cupsdInitCerts()...
3909 cupsdLogMessage(CUPSD_LOG_INFO
,
3910 "Seeding the random number generator...");
3912 snprintf(home
, sizeof(home
), "HOME=%s", TempDir
);
3915 * Write the seed file...
3918 if ((fp
= cupsTempFile2(seedfile
, sizeof(seedfile
))) == NULL
)
3920 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to create seed file %s - %s",
3921 seedfile
, strerror(errno
));
3925 for (bytes
= 0; bytes
< 262144; bytes
++)
3926 cupsFilePutChar(fp
, random());
3931 * Run the openssl command to seed its random number generator...
3934 argv
[0] = "openssl";
3941 envc
= cupsdLoadEnv(envp
, MAX_ENV
);
3942 envp
[envc
++] = home
;
3945 if (!cupsdStartProcess(command
, argv
, envp
, -1, -1, -1, -1, -1, 1, NULL
,
3952 while (waitpid(pid
, &status
, 0) < 0)
3959 cupsdFinishProcess(pid
, command
, sizeof(command
));
3962 * Remove the seed file, as it is no longer needed...
3969 if (WIFEXITED(status
))
3970 cupsdLogMessage(CUPSD_LOG_ERROR
,
3971 "Unable to seed random number generator - "
3972 "the openssl command stopped with status %d!",
3973 WEXITSTATUS(status
));
3975 cupsdLogMessage(CUPSD_LOG_ERROR
,
3976 "Unable to seed random number generator - "
3977 "the openssl command crashed on signal %d!",
3985 * Create a file with the certificate information fields...
3987 * Note: This assumes that the default questions are asked by the openssl
3991 if ((fp
= cupsTempFile2(infofile
, sizeof(infofile
))) == NULL
)
3993 cupsdLogMessage(CUPSD_LOG_ERROR
,
3994 "Unable to create certificate information file %s - %s",
3995 infofile
, strerror(errno
));
3999 cupsFilePrintf(fp
, ".\n.\n.\n%s\n.\n%s\n%s\n",
4000 ServerName
, ServerName
, ServerAdmin
);
4003 cupsdLogMessage(CUPSD_LOG_INFO
,
4004 "Generating SSL server key and certificate...");
4006 argv
[0] = "openssl";
4010 argv
[4] = "-keyout";
4011 argv
[5] = ServerKey
;
4013 argv
[7] = ServerCertificate
;
4016 argv
[10] = "-nodes";
4019 cupsdLoadEnv(envp
, MAX_ENV
);
4021 infofd
= open(infofile
, O_RDONLY
);
4023 if (!cupsdStartProcess(command
, argv
, envp
, infofd
, -1, -1, -1, -1, 1, NULL
,
4034 while (waitpid(pid
, &status
, 0) < 0)
4041 cupsdFinishProcess(pid
, command
, sizeof(command
));
4045 if (WIFEXITED(status
))
4046 cupsdLogMessage(CUPSD_LOG_ERROR
,
4047 "Unable to create SSL server key and certificate - "
4048 "the openssl command stopped with status %d!",
4049 WEXITSTATUS(status
));
4051 cupsdLogMessage(CUPSD_LOG_ERROR
,
4052 "Unable to create SSL server key and certificate - "
4053 "the openssl command crashed on signal %d!",
4058 cupsdLogMessage(CUPSD_LOG_INFO
, "Created SSL server key file \"%s\"...",
4060 cupsdLogMessage(CUPSD_LOG_INFO
,
4061 "Created SSL server certificate file \"%s\"...",
4067 #elif defined(HAVE_GNUTLS)
4068 gnutls_x509_crt crt
; /* Self-signed certificate */
4069 gnutls_x509_privkey key
; /* Encryption key */
4070 cups_lang_t
*language
; /* Default language info */
4071 cups_file_t
*fp
; /* Key/cert file */
4072 unsigned char buffer
[8192]; /* Buffer for x509 data */
4073 size_t bytes
; /* Number of bytes of data */
4074 unsigned char serial
[4]; /* Serial number buffer */
4075 time_t curtime
; /* Current time */
4076 int result
; /* Result of GNU TLS calls */
4080 * Create the encryption key...
4083 cupsdLogMessage(CUPSD_LOG_INFO
, "Generating SSL server key...");
4085 gnutls_x509_privkey_init(&key
);
4086 gnutls_x509_privkey_generate(key
, GNUTLS_PK_RSA
, 2048, 0);
4092 bytes
= sizeof(buffer
);
4094 if ((result
= gnutls_x509_privkey_export(key
, GNUTLS_X509_FMT_PEM
,
4095 buffer
, &bytes
)) < 0)
4097 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to export SSL server key - %s",
4098 gnutls_strerror(result
));
4099 gnutls_x509_privkey_deinit(key
);
4102 else if ((fp
= cupsFileOpen(ServerKey
, "w")) != NULL
)
4104 cupsFileWrite(fp
, (char *)buffer
, bytes
);
4107 cupsdLogMessage(CUPSD_LOG_INFO
, "Created SSL server key file \"%s\"...",
4112 cupsdLogMessage(CUPSD_LOG_ERROR
,
4113 "Unable to create SSL server key file \"%s\" - %s",
4114 ServerKey
, strerror(errno
));
4115 gnutls_x509_privkey_deinit(key
);
4120 * Create the self-signed certificate...
4123 cupsdLogMessage(CUPSD_LOG_INFO
, "Generating self-signed SSL certificate...");
4125 language
= cupsLangDefault();
4126 curtime
= time(NULL
);
4127 serial
[0] = curtime
>> 24;
4128 serial
[1] = curtime
>> 16;
4129 serial
[2] = curtime
>> 8;
4130 serial
[3] = curtime
;
4132 gnutls_x509_crt_init(&crt
);
4133 if (strlen(language
->language
) == 5)
4134 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
4135 language
->language
+ 3, 2);
4137 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
4139 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COMMON_NAME
, 0,
4140 ServerName
, strlen(ServerName
));
4141 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATION_NAME
, 0,
4142 ServerName
, strlen(ServerName
));
4143 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATIONAL_UNIT_NAME
,
4145 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_STATE_OR_PROVINCE_NAME
, 0,
4147 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_LOCALITY_NAME
, 0,
4149 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_PKCS9_EMAIL
, 0,
4150 ServerAdmin
, strlen(ServerAdmin
));
4151 gnutls_x509_crt_set_key(crt
, key
);
4152 gnutls_x509_crt_set_serial(crt
, serial
, sizeof(serial
));
4153 gnutls_x509_crt_set_activation_time(crt
, curtime
);
4154 gnutls_x509_crt_set_expiration_time(crt
, curtime
+ 10 * 365 * 86400);
4155 gnutls_x509_crt_set_ca_status(crt
, 0);
4156 gnutls_x509_crt_set_subject_alternative_name(crt
, GNUTLS_SAN_DNSNAME
,
4158 gnutls_x509_crt_set_key_purpose_oid(crt
, GNUTLS_KP_TLS_WWW_SERVER
, 0);
4159 gnutls_x509_crt_set_key_usage(crt
, GNUTLS_KEY_KEY_ENCIPHERMENT
);
4160 gnutls_x509_crt_set_version(crt
, 3);
4162 bytes
= sizeof(buffer
);
4163 if (gnutls_x509_crt_get_key_id(crt
, 0, buffer
, &bytes
) >= 0)
4164 gnutls_x509_crt_set_subject_key_id(crt
, buffer
, bytes
);
4166 gnutls_x509_crt_sign(crt
, crt
, key
);
4172 bytes
= sizeof(buffer
);
4173 if ((result
= gnutls_x509_crt_export(crt
, GNUTLS_X509_FMT_PEM
,
4174 buffer
, &bytes
)) < 0)
4175 cupsdLogMessage(CUPSD_LOG_ERROR
,
4176 "Unable to export SSL server certificate - %s",
4177 gnutls_strerror(result
));
4178 else if ((fp
= cupsFileOpen(ServerCertificate
, "w")) != NULL
)
4180 cupsFileWrite(fp
, (char *)buffer
, bytes
);
4183 cupsdLogMessage(CUPSD_LOG_INFO
,
4184 "Created SSL server certificate file \"%s\"...",
4188 cupsdLogMessage(CUPSD_LOG_ERROR
,
4189 "Unable to create SSL server certificate file \"%s\" - %s",
4190 ServerCertificate
, strerror(errno
));
4196 gnutls_x509_crt_deinit(crt
);
4197 gnutls_x509_privkey_deinit(key
);
4201 #elif defined(HAVE_CDSASSL) && defined(HAVE_WAITPID)
4202 int pid
, /* Process ID of command */
4203 status
; /* Status of command */
4204 char command
[1024], /* Command */
4205 *argv
[4], /* Command-line arguments */
4206 *envp
[MAX_ENV
+ 1], /* Environment variables */
4207 keychain
[1024], /* Keychain argument */
4208 infofile
[1024]; /* Type-in information for cert */
4209 cups_file_t
*fp
; /* Seed/info file */
4210 int infofd
; /* Info file descriptor */
4214 * Run the "certtool" command to generate a self-signed certificate...
4217 if (!cupsFileFind("certtool", getenv("PATH"), 1, command
, sizeof(command
)))
4219 cupsdLogMessage(CUPSD_LOG_ERROR
,
4220 "No SSL certificate and certtool command not found!");
4225 * Create a file with the certificate information fields...
4227 * Note: This assumes that the default questions are asked by the certtool
4231 if ((fp
= cupsTempFile2(infofile
, sizeof(infofile
))) == NULL
)
4233 cupsdLogMessage(CUPSD_LOG_ERROR
,
4234 "Unable to create certificate information file %s - %s",
4235 infofile
, strerror(errno
));
4239 cupsFilePrintf(fp
, "%s\nr\n\ny\nb\ns\ny\n%s\n\n\n\n\n%s\ny\n",
4240 con
->servername
, con
->servername
, ServerAdmin
);
4243 cupsdLogMessage(CUPSD_LOG_INFO
,
4244 "Generating SSL server key and certificate...");
4246 snprintf(keychain
, sizeof(keychain
), "k=%s", ServerCertificate
);
4248 argv
[0] = "certtool";
4253 cupsdLoadEnv(envp
, MAX_ENV
);
4255 infofd
= open(infofile
, O_RDONLY
);
4257 if (!cupsdStartProcess(command
, argv
, envp
, infofd
, -1, -1, -1, -1, 1, NULL
,
4268 while (waitpid(pid
, &status
, 0) < 0)
4275 cupsdFinishProcess(pid
, command
, sizeof(command
));
4279 if (WIFEXITED(status
))
4280 cupsdLogMessage(CUPSD_LOG_ERROR
,
4281 "Unable to create SSL server key and certificate - "
4282 "the certtool command stopped with status %d!",
4283 WEXITSTATUS(status
));
4285 cupsdLogMessage(CUPSD_LOG_ERROR
,
4286 "Unable to create SSL server key and certificate - "
4287 "the certtool command crashed on signal %d!",
4292 cupsdLogMessage(CUPSD_LOG_INFO
,
4293 "Created SSL server certificate file \"%s\"...",
4301 #endif /* HAVE_LIBSSL && HAVE_WAITPID */
4303 #endif /* HAVE_SSL */
4307 * 'pipe_command()' - Pipe the output of a command to the remote client.
4310 static int /* O - Process ID */
4311 pipe_command(cupsd_client_t
*con
, /* I - Client connection */
4312 int infile
, /* I - Standard input for command */
4313 int *outfile
, /* O - Standard output for command */
4314 char *command
, /* I - Command to run */
4315 char *options
, /* I - Options for command */
4316 int root
) /* I - Run as root? */
4318 int i
; /* Looping var */
4319 int pid
; /* Process ID */
4320 char *commptr
, /* Command string pointer */
4321 commch
; /* Command string character */
4322 char *uriptr
; /* URI string pointer */
4323 int fds
[2]; /* Pipe FDs */
4324 int argc
; /* Number of arguments */
4325 int envc
; /* Number of environment variables */
4326 char argbuf
[10240], /* Argument buffer */
4327 *argv
[100], /* Argument strings */
4328 *envp
[MAX_ENV
+ 20]; /* Environment variables */
4329 char auth_type
[256], /* CUPSD_AUTH_TYPE environment variable */
4330 content_length
[1024], /* CONTENT_LENGTH environment variable */
4331 content_type
[1024], /* CONTENT_TYPE environment variable */
4332 http_cookie
[32768], /* HTTP_COOKIE environment variable */
4333 http_referer
[1024], /* HTTP_REFERER environment variable */
4334 http_user_agent
[1024], /* HTTP_USER_AGENT environment variable */
4335 lang
[1024], /* LANG environment variable */
4336 path_info
[1024], /* PATH_INFO environment variable */
4337 remote_addr
[1024], /* REMOTE_ADDR environment variable */
4338 remote_host
[1024], /* REMOTE_HOST environment variable */
4339 remote_user
[1024], /* REMOTE_USER environment variable */
4340 script_filename
[1024], /* SCRIPT_FILENAME environment variable */
4341 script_name
[1024], /* SCRIPT_NAME environment variable */
4342 server_name
[1024], /* SERVER_NAME environment variable */
4343 server_port
[1024]; /* SERVER_PORT environment variable */
4344 ipp_attribute_t
*attr
; /* attributes-natural-language attribute */
4346 krb5_ccache ccache
= NULL
; /* Kerberos credentials */
4347 char krb5ccname
[1024]; /* KRB5CCNAME environment variable */
4348 #endif /* HAVE_GSSAPI */
4352 * Parse a copy of the options string, which is of the form:
4354 * argument+argument+argument
4355 * ?argument+argument+argument
4356 * param=value¶m=value
4357 * ?param=value¶m=value
4358 * /name?argument+argument+argument
4359 * /name?param=value¶m=value
4361 * If the string contains an "=" character after the initial name,
4362 * then we treat it as a HTTP GET form request and make a copy of
4363 * the remaining string for the environment variable.
4365 * The string is always parsed out as command-line arguments, to
4366 * be consistent with Apache...
4369 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4370 "pipe_command: command=\"%s\", options=\"%s\"",
4371 command
, options
? options
: "(null)");
4376 strlcpy(argbuf
, options
, sizeof(argbuf
));
4380 if (argbuf
[0] == '/')
4383 * Found some trailing path information, set PATH_INFO...
4386 if ((commptr
= strchr(argbuf
, '?')) == NULL
)
4387 commptr
= argbuf
+ strlen(argbuf
);
4391 snprintf(path_info
, sizeof(path_info
), "PATH_INFO=%s", argbuf
);
4397 path_info
[0] = '\0';
4399 if (*commptr
== ' ')
4403 if (*commptr
== '?' && con
->operation
== HTTP_GET
&& !con
->query_string
)
4406 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", commptr
);
4413 argv
[argc
++] = commptr
;
4415 for (; *commptr
&& argc
< 99; commptr
++)
4418 * Break arguments whenever we see a + or space...
4421 if (*commptr
== ' ' || *commptr
== '+')
4423 while (*commptr
== ' ' || *commptr
== '+')
4427 * If we don't have a blank string, save it as another argument...
4432 argv
[argc
] = commptr
;
4438 else if (*commptr
== '%' && isxdigit(commptr
[1] & 255) &&
4439 isxdigit(commptr
[2] & 255))
4442 * Convert the %xx notation to the individual character.
4445 if (commptr
[1] >= '0' && commptr
[1] <= '9')
4446 *commptr
= (commptr
[1] - '0') << 4;
4448 *commptr
= (tolower(commptr
[1]) - 'a' + 10) << 4;
4450 if (commptr
[2] >= '0' && commptr
[2] <= '9')
4451 *commptr
|= commptr
[2] - '0';
4453 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
4455 _cups_strcpy(commptr
+ 1, commptr
+ 3);
4458 * Check for a %00 and break if that is the case...
4470 * Setup the environment variables as needed...
4473 if (con
->username
[0])
4475 snprintf(auth_type
, sizeof(auth_type
), "CUPSD_AUTH_TYPE=%s",
4476 httpGetField(HTTP(con
), HTTP_FIELD_AUTHORIZATION
));
4478 if ((uriptr
= strchr(auth_type
+ 10, ' ')) != NULL
)
4482 auth_type
[0] = '\0';
4485 (attr
= ippFindAttribute(con
->request
, "attributes-natural-language",
4486 IPP_TAG_LANGUAGE
)) != NULL
)
4488 switch (strlen(attr
->values
[0].string
.text
))
4492 * This is an unknown or badly formatted language code; use
4493 * the POSIX locale...
4496 strcpy(lang
, "LANG=C");
4501 * Just the language code (ll)...
4504 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8",
4505 attr
->values
[0].string
.text
);
4510 * Language and country code (ll-cc)...
4513 snprintf(lang
, sizeof(lang
), "LANG=%c%c_%c%c.UTF8",
4514 attr
->values
[0].string
.text
[0],
4515 attr
->values
[0].string
.text
[1],
4516 toupper(attr
->values
[0].string
.text
[3] & 255),
4517 toupper(attr
->values
[0].string
.text
[4] & 255));
4521 else if (con
->language
)
4522 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8", con
->language
->language
);
4524 strcpy(lang
, "LANG=C");
4526 strcpy(remote_addr
, "REMOTE_ADDR=");
4527 httpAddrString(con
->http
.hostaddr
, remote_addr
+ 12,
4528 sizeof(remote_addr
) - 12);
4530 snprintf(remote_host
, sizeof(remote_host
), "REMOTE_HOST=%s",
4531 con
->http
.hostname
);
4533 snprintf(script_name
, sizeof(script_name
), "SCRIPT_NAME=%s", con
->uri
);
4534 if ((uriptr
= strchr(script_name
, '?')) != NULL
)
4537 snprintf(script_filename
, sizeof(script_filename
), "SCRIPT_FILENAME=%s%s",
4538 DocumentRoot
, script_name
+ 12);
4540 sprintf(server_port
, "SERVER_PORT=%d", con
->serverport
);
4542 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
4545 envc
= cupsdLoadEnv(envp
, (int)(sizeof(envp
) / sizeof(envp
[0])));
4548 envp
[envc
++] = auth_type
;
4550 envp
[envc
++] = lang
;
4551 envp
[envc
++] = "REDIRECT_STATUS=1";
4552 envp
[envc
++] = "GATEWAY_INTERFACE=CGI/1.1";
4553 envp
[envc
++] = server_name
;
4554 envp
[envc
++] = server_port
;
4555 envp
[envc
++] = remote_addr
;
4556 envp
[envc
++] = remote_host
;
4557 envp
[envc
++] = script_name
;
4558 envp
[envc
++] = script_filename
;
4561 envp
[envc
++] = path_info
;
4563 if (con
->username
[0])
4565 snprintf(remote_user
, sizeof(remote_user
), "REMOTE_USER=%s", con
->username
);
4567 envp
[envc
++] = remote_user
;
4570 * Save Kerberos credentials, if any...
4574 if (con
->gss_have_creds
)
4576 # if !defined(HAVE_KRB5_CC_NEW_UNIQUE) && !defined(HAVE_HEIMDAL)
4577 cupsdLogMessage(CUPSD_LOG_INFO
,
4578 "Sorry, your version of Kerberos does not support "
4579 "delegated credentials!");
4582 krb5_error_code error
; /* Kerberos error code */
4583 OM_uint32 major_status
, /* Major status code */
4584 minor_status
; /* Minor status code */
4585 krb5_principal principal
; /* Kerberos principal */
4590 * If the weak-linked GSSAPI/Kerberos library is not present, don't try
4594 if (krb5_init_context
!= NULL
)
4596 # endif /* __APPLE__ */
4599 * We MUST create a file-based cache because memory-based caches are
4600 * only valid for the current process/address space.
4602 * Due to various bugs/features in different versions of Kerberos, we
4603 * need either the krb5_cc_new_unique() function or Heimdal's version
4604 * of krb5_cc_gen_new() to create a new FILE: credential cache that
4605 * can be passed to the backend. These functions create a temporary
4606 * file (typically in /tmp) containing the cached credentials, which
4607 * are removed when we have successfully printed a job.
4610 # ifdef HAVE_KRB5_CC_NEW_UNIQUE
4611 if ((error
= krb5_cc_new_unique(KerberosContext
, "FILE", NULL
,
4613 # else /* HAVE_HEIMDAL */
4614 if ((error
= krb5_cc_gen_new(KerberosContext
, &krb5_fcc_ops
,
4616 # endif /* HAVE_KRB5_CC_NEW_UNIQUE */
4618 cupsdLogMessage(CUPSD_LOG_ERROR
,
4619 "Unable to create new credentials cache (%d/%s)",
4620 error
, strerror(errno
));
4623 else if ((error
= krb5_parse_name(KerberosContext
, con
->username
,
4626 cupsdLogMessage(CUPSD_LOG_ERROR
,
4627 "Unable to parse kerberos username (%d/%s)", error
,
4629 krb5_cc_destroy(KerberosContext
, ccache
);
4632 else if ((error
= krb5_cc_initialize(KerberosContext
, ccache
,
4635 cupsdLogMessage(CUPSD_LOG_ERROR
,
4636 "Unable to initialize credentials cache (%d/%s)", error
,
4638 krb5_cc_destroy(KerberosContext
, ccache
);
4639 krb5_free_principal(KerberosContext
, principal
);
4644 krb5_free_principal(KerberosContext
, principal
);
4647 * Copy the user's credentials to the new cache file...
4650 major_status
= gss_krb5_copy_ccache(&minor_status
,
4651 con
->gss_delegated_cred
, ccache
);
4653 if (GSS_ERROR(major_status
))
4655 cupsdLogGSSMessage(CUPSD_LOG_ERROR
, major_status
, minor_status
,
4656 "Unable to import client credentials cache");
4657 krb5_cc_destroy(KerberosContext
, ccache
);
4663 * Add the KRB5CCNAME environment variable to the job so that the
4664 * backend can use the credentials when printing.
4667 snprintf(krb5ccname
, sizeof(krb5ccname
), "KRB5CCNAME=FILE:%s",
4668 krb5_cc_get_name(KerberosContext
, ccache
));
4669 envp
[envc
++] = krb5ccname
;
4672 chown(krb5_cc_get_name(KerberosContext
, ccache
), User
, Group
);
4677 # endif /* __APPLE__ */
4678 # endif /* HAVE_KRB5_CC_NEW_UNIQUE || HAVE_HEIMDAL */
4680 #endif /* HAVE_GSSAPI */
4684 if (con
->http
.version
== HTTP_1_1
)
4685 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.1";
4686 else if (con
->http
.version
== HTTP_1_0
)
4687 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.0";
4689 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/0.9";
4691 if (con
->http
.cookie
)
4693 snprintf(http_cookie
, sizeof(http_cookie
), "HTTP_COOKIE=%s",
4695 envp
[envc
++] = http_cookie
;
4698 if (con
->http
.fields
[HTTP_FIELD_USER_AGENT
][0])
4700 snprintf(http_user_agent
, sizeof(http_user_agent
), "HTTP_USER_AGENT=%s",
4701 con
->http
.fields
[HTTP_FIELD_USER_AGENT
]);
4702 envp
[envc
++] = http_user_agent
;
4705 if (con
->http
.fields
[HTTP_FIELD_REFERER
][0])
4707 snprintf(http_referer
, sizeof(http_referer
), "HTTP_REFERER=%s",
4708 con
->http
.fields
[HTTP_FIELD_REFERER
]);
4709 envp
[envc
++] = http_referer
;
4712 if (con
->operation
== HTTP_GET
)
4714 envp
[envc
++] = "REQUEST_METHOD=GET";
4716 if (con
->query_string
)
4719 * Add GET form variables after ?...
4722 envp
[envc
++] = con
->query_string
;
4725 envp
[envc
++] = "QUERY_STRING=";
4729 sprintf(content_length
, "CONTENT_LENGTH=" CUPS_LLFMT
,
4730 CUPS_LLCAST con
->bytes
);
4731 snprintf(content_type
, sizeof(content_type
), "CONTENT_TYPE=%s",
4732 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
4734 envp
[envc
++] = "REQUEST_METHOD=POST";
4735 envp
[envc
++] = content_length
;
4736 envp
[envc
++] = content_type
;
4740 * Tell the CGI if we are using encryption...
4744 envp
[envc
++] = "HTTPS=ON";
4747 * Terminate the environment array...
4752 if (LogLevel
== CUPSD_LOG_DEBUG2
)
4754 for (i
= 0; i
< argc
; i
++)
4755 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4756 "pipe_command: argv[%d] = \"%s\"", i
, argv
[i
]);
4757 for (i
= 0; i
< envc
; i
++)
4758 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4759 "pipe_command: envp[%d] = \"%s\"", i
, envp
[i
]);
4763 * Create a pipe for the output...
4766 if (cupsdOpenPipe(fds
))
4768 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to create pipes for CGI %s - %s",
4769 argv
[0], strerror(errno
));
4774 * Then execute the command...
4777 if (cupsdStartProcess(command
, argv
, envp
, infile
, fds
[1], CGIPipes
[1],
4778 -1, -1, root
, DefaultProfile
, &pid
) < 0)
4781 * Error - can't fork!
4784 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to fork for CGI %s - %s", argv
[0],
4787 cupsdClosePipe(fds
);
4793 * Fork successful - return the PID...
4796 if (con
->username
[0])
4798 cupsdAddCert(pid
, con
->username
, ccache
);
4800 cupsdAddCert(pid
, con
->username
, NULL
);
4801 #endif /* HAVE_GSSAPI */
4803 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[CGI] %s started - PID = %d",
4815 * 'write_file()' - Send a file via HTTP.
4818 static int /* O - 0 on failure, 1 on success */
4819 write_file(cupsd_client_t
*con
, /* I - Client connection */
4820 http_status_t code
, /* I - HTTP status */
4821 char *filename
, /* I - Filename */
4822 char *type
, /* I - File type */
4823 struct stat
*filestats
) /* O - File information */
4825 con
->file
= open(filename
, O_RDONLY
);
4827 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "write_file: %d file=%d", con
->http
.fd
,
4833 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
4837 if (!cupsdSendHeader(con
, code
, type
, CUPSD_AUTH_NONE
))
4840 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
4841 httpGetDateString(filestats
->st_mtime
)) < 0)
4843 if (httpPrintf(HTTP(con
), "Content-Length: " CUPS_LLFMT
"\r\n",
4844 CUPS_LLCAST filestats
->st_size
) < 0)
4846 if (httpPrintf(HTTP(con
), "\r\n") < 0)
4849 if (cupsdFlushHeader(con
) < 0)
4852 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
4853 con
->http
.data_remaining
= filestats
->st_size
;
4855 if (con
->http
.data_remaining
<= INT_MAX
)
4856 con
->http
._data_remaining
= con
->http
.data_remaining
;
4858 con
->http
._data_remaining
= INT_MAX
;
4860 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
,
4861 (cupsd_selfunc_t
)cupsdWriteClient
, con
);
4868 * 'write_pipe()' - Flag that data is available on the CGI pipe.
4872 write_pipe(cupsd_client_t
*con
) /* I - Client connection */
4874 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "write_pipe: CGI output on fd %d...",
4877 con
->file_ready
= 1;
4879 cupsdRemoveSelect(con
->file
);
4880 cupsdAddSelect(con
->http
.fd
, NULL
, (cupsd_selfunc_t
)cupsdWriteClient
, con
);
4885 * End of "$Id: client.c 6999 2007-09-28 19:46:53Z mike $".