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_DEBUG
,
540 "SSL shutdown successful!");
543 cupsdLogMessage(CUPSD_LOG_ERROR
,
544 "Fatal error during SSL shutdown!");
546 while ((error
= ERR_get_error()) != 0)
547 cupsdLogMessage(CUPSD_LOG_ERROR
, "SSL shutdown failed: %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_DEBUG
,
564 "SSL shutdown successful!");
567 cupsdLogMessage(CUPSD_LOG_ERROR
,
568 "SSL shutdown failed: %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
))
871 cupsdLogMessage(CUPSD_LOG_ERROR
,
872 "Bad request line \"%s\" from %s!", line
,
874 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
875 cupsdCloseClient(con
);
879 con
->http
.version
= HTTP_0_9
;
882 if (sscanf(version
, "HTTP/%d.%d", &major
, &minor
) != 2)
884 cupsdLogMessage(CUPSD_LOG_ERROR
,
885 "Bad request line \"%s\" from %s!", line
,
887 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
888 cupsdCloseClient(con
);
894 con
->http
.version
= (http_version_t
)(major
* 100 + minor
);
895 if (con
->http
.version
== HTTP_1_1
&& KeepAlive
)
896 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
898 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
902 cupsdSendError(con
, HTTP_NOT_SUPPORTED
, CUPSD_AUTH_NONE
);
903 cupsdCloseClient(con
);
910 * Handle full URLs in the request line...
913 if (strcmp(con
->uri
, "*"))
915 char method
[HTTP_MAX_URI
], /* Method/scheme */
916 userpass
[HTTP_MAX_URI
], /* Username:password */
917 hostname
[HTTP_MAX_URI
], /* Hostname */
918 resource
[HTTP_MAX_URI
]; /* Resource path */
919 int port
; /* Port number */
923 * Separate the URI into its components...
926 httpSeparateURI(HTTP_URI_CODING_MOST
, con
->uri
,
927 method
, sizeof(method
),
928 userpass
, sizeof(userpass
),
929 hostname
, sizeof(hostname
), &port
,
930 resource
, sizeof(resource
));
933 * Only allow URIs with the servername, localhost, or an IP
937 if (strcmp(method
, "file") &&
938 strcasecmp(hostname
, ServerName
) &&
939 strcasecmp(hostname
, "localhost") &&
940 !isdigit(hostname
[0]))
943 * Nope, we don't do proxies...
946 cupsdLogMessage(CUPSD_LOG_ERROR
, "Bad URI \"%s\" in request!",
948 cupsdSendError(con
, HTTP_METHOD_NOT_ALLOWED
, CUPSD_AUTH_NONE
);
949 cupsdCloseClient(con
);
954 * Copy the resource portion back into the URI; both resource and
955 * con->uri are HTTP_MAX_URI bytes in size...
958 strcpy(con
->uri
, resource
);
962 * Process the request...
965 if (!strcmp(operation
, "GET"))
966 con
->http
.state
= HTTP_GET
;
967 else if (!strcmp(operation
, "PUT"))
968 con
->http
.state
= HTTP_PUT
;
969 else if (!strcmp(operation
, "POST"))
970 con
->http
.state
= HTTP_POST
;
971 else if (!strcmp(operation
, "DELETE"))
972 con
->http
.state
= HTTP_DELETE
;
973 else if (!strcmp(operation
, "TRACE"))
974 con
->http
.state
= HTTP_TRACE
;
975 else if (!strcmp(operation
, "OPTIONS"))
976 con
->http
.state
= HTTP_OPTIONS
;
977 else if (!strcmp(operation
, "HEAD"))
978 con
->http
.state
= HTTP_HEAD
;
981 cupsdLogMessage(CUPSD_LOG_ERROR
, "Bad operation \"%s\"!", operation
);
982 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
983 cupsdCloseClient(con
);
987 con
->start
= time(NULL
);
988 con
->operation
= con
->http
.state
;
990 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdReadClient: %d %s %s HTTP/%d.%d",
991 con
->http
.fd
, operation
, con
->uri
,
992 con
->http
.version
/ 100, con
->http
.version
% 100);
994 con
->http
.status
= HTTP_OK
;
996 cupsArrayAdd(ActiveClients
, con
);
1007 * Parse incoming parameters until the status changes...
1010 while ((status
= httpUpdate(HTTP(con
))) == HTTP_CONTINUE
)
1011 if (con
->http
.used
== 0 ||
1012 !memchr(con
->http
.buffer
, '\n', con
->http
.used
))
1015 if (status
!= HTTP_OK
&& status
!= HTTP_CONTINUE
)
1017 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
1018 cupsdCloseClient(con
);
1024 break; /* Anti-compiler-warning-code */
1028 * Handle new transfers...
1031 if (status
== HTTP_OK
)
1033 if (con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
][0])
1036 * Figure out the locale from the Accept-Language and Content-Type
1040 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ',')) != NULL
)
1043 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ';')) != NULL
)
1046 if ((ptr
= strstr(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
], "charset=")) != NULL
)
1049 * Combine language and charset, and trim any extra params in the
1053 snprintf(locale
, sizeof(locale
), "%s.%s",
1054 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ptr
+ 8);
1056 if ((ptr
= strchr(locale
, ',')) != NULL
)
1060 snprintf(locale
, sizeof(locale
), "%s.%s",
1061 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], DefaultCharset
);
1063 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1064 "cupsdReadClient: %d Browser asked for language \"%s\"...",
1065 con
->http
.fd
, locale
);
1067 con
->language
= cupsLangGet(locale
);
1070 con
->language
= cupsLangGet(DefaultLocale
);
1072 cupsdAuthorize(con
);
1074 if (!strncmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Keep-Alive", 10) &&
1076 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
1078 if (!con
->http
.fields
[HTTP_FIELD_HOST
][0] &&
1079 con
->http
.version
>= HTTP_1_1
)
1082 * HTTP/1.1 and higher require the "Host:" field...
1085 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1087 cupsdCloseClient(con
);
1091 else if (con
->operation
== HTTP_OPTIONS
)
1094 * Do OPTIONS command...
1097 if (con
->best
&& con
->best
->type
!= CUPSD_AUTH_NONE
)
1099 if (!cupsdSendHeader(con
, HTTP_UNAUTHORIZED
, NULL
, CUPSD_AUTH_NONE
))
1101 cupsdCloseClient(con
);
1106 if (!strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") &&
1107 con
->http
.tls
== NULL
)
1111 * Do encryption stuff...
1114 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
, CUPSD_AUTH_NONE
))
1116 cupsdCloseClient(con
);
1120 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1121 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1122 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1123 httpPrintf(HTTP(con
), "\r\n");
1125 if (cupsdFlushHeader(con
) < 0)
1127 cupsdCloseClient(con
);
1131 if (!encrypt_client(con
))
1133 cupsdCloseClient(con
);
1137 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
1139 cupsdCloseClient(con
);
1142 #endif /* HAVE_SSL */
1145 if (!cupsdSendHeader(con
, HTTP_OK
, NULL
, CUPSD_AUTH_NONE
))
1147 cupsdCloseClient(con
);
1151 httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n");
1152 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1153 httpPrintf(HTTP(con
), "\r\n");
1155 if (cupsdFlushHeader(con
) < 0)
1157 cupsdCloseClient(con
);
1161 else if (!is_path_absolute(con
->uri
))
1164 * Protect against malicious users!
1167 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1169 cupsdCloseClient(con
);
1175 if (!strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") &&
1176 con
->http
.tls
== NULL
)
1180 * Do encryption stuff...
1183 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
, CUPSD_AUTH_NONE
))
1185 cupsdCloseClient(con
);
1189 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1190 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1191 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1192 httpPrintf(HTTP(con
), "\r\n");
1194 if (cupsdFlushHeader(con
) < 0)
1196 cupsdCloseClient(con
);
1200 if (!encrypt_client(con
))
1202 cupsdCloseClient(con
);
1206 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
1208 cupsdCloseClient(con
);
1211 #endif /* HAVE_SSL */
1214 if ((status
= cupsdIsAuthorized(con
, NULL
)) != HTTP_OK
)
1216 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1217 "cupsdReadClient: Unauthorized request for %s...\n",
1219 cupsdSendError(con
, status
, CUPSD_AUTH_NONE
);
1220 cupsdCloseClient(con
);
1224 if (con
->http
.expect
&&
1225 (con
->operation
== HTTP_POST
|| con
->operation
== HTTP_PUT
))
1227 if (con
->http
.expect
== HTTP_CONTINUE
)
1230 * Send 100-continue header...
1233 if (!cupsdSendHeader(con
, HTTP_CONTINUE
, NULL
, CUPSD_AUTH_NONE
))
1235 cupsdCloseClient(con
);
1242 * Send 417-expectation-failed header...
1245 if (!cupsdSendHeader(con
, HTTP_EXPECTATION_FAILED
, NULL
, CUPSD_AUTH_NONE
))
1247 cupsdCloseClient(con
);
1251 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1252 httpPrintf(HTTP(con
), "\r\n");
1254 if (cupsdFlushHeader(con
) < 0)
1256 cupsdCloseClient(con
);
1262 switch (con
->http
.state
)
1264 case HTTP_GET_SEND
:
1265 if (!strncmp(con
->uri
, "/printers/", 10) &&
1266 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1269 * Send PPD file - get the real printer name since printer
1270 * names are not case sensitive but filenames can be...
1273 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1275 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1276 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1279 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1281 cupsdCloseClient(con
);
1289 if ((!strncmp(con
->uri
, "/admin", 6) &&
1290 strncmp(con
->uri
, "/admin/conf/", 12) &&
1291 strncmp(con
->uri
, "/admin/log/", 11)) ||
1292 !strncmp(con
->uri
, "/printers", 9) ||
1293 !strncmp(con
->uri
, "/classes", 8) ||
1294 !strncmp(con
->uri
, "/help", 5) ||
1295 !strncmp(con
->uri
, "/jobs", 5))
1298 * Send CGI output...
1301 if (!strncmp(con
->uri
, "/admin", 6))
1303 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1306 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1308 else if (!strncmp(con
->uri
, "/printers", 9))
1310 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1313 if (con
->uri
[9] && con
->uri
[10])
1314 cupsdSetString(&con
->options
, con
->uri
+ 9);
1316 cupsdSetString(&con
->options
, NULL
);
1318 else if (!strncmp(con
->uri
, "/classes", 8))
1320 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1323 if (con
->uri
[8] && con
->uri
[9])
1324 cupsdSetString(&con
->options
, con
->uri
+ 8);
1326 cupsdSetString(&con
->options
, NULL
);
1328 else if (!strncmp(con
->uri
, "/jobs", 5))
1330 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1333 if (con
->uri
[5] && con
->uri
[6])
1334 cupsdSetString(&con
->options
, con
->uri
+ 5);
1336 cupsdSetString(&con
->options
, NULL
);
1340 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1343 if (con
->uri
[5] && con
->uri
[6])
1344 cupsdSetString(&con
->options
, con
->uri
+ 5);
1346 cupsdSetString(&con
->options
, NULL
);
1349 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1351 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1353 cupsdCloseClient(con
);
1358 cupsdLogRequest(con
, HTTP_OK
);
1360 if (con
->http
.version
<= HTTP_1_0
)
1361 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1363 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1364 (strchr(con
->uri
+ 12, '/') ||
1365 strlen(con
->uri
) == 12)) ||
1366 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1367 (strchr(con
->uri
+ 11, '/') ||
1368 strlen(con
->uri
) == 11)))
1371 * GET can only be done to configuration files under
1375 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1377 cupsdCloseClient(con
);
1389 if ((filename
= get_file(con
, &filestats
, buf
,
1390 sizeof(buf
))) == NULL
)
1392 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1394 cupsdCloseClient(con
);
1401 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1403 if (is_cgi(con
, filename
, &filestats
, type
))
1406 * Note: con->command and con->options were set by
1410 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1412 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1414 cupsdCloseClient(con
);
1419 cupsdLogRequest(con
, HTTP_OK
);
1421 if (con
->http
.version
<= HTTP_1_0
)
1422 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1426 if (!check_if_modified(con
, &filestats
))
1428 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1430 cupsdCloseClient(con
);
1437 strcpy(line
, "text/plain");
1439 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1441 if (!write_file(con
, HTTP_OK
, filename
, line
, &filestats
))
1443 cupsdCloseClient(con
);
1450 case HTTP_POST_RECV
:
1452 * See if the POST request includes a Content-Length field, and if
1453 * so check the length against any limits that are set...
1456 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "POST %s", con
->uri
);
1457 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "CONTENT_TYPE = %s",
1458 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
1460 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1461 MaxRequestSize
> 0 &&
1462 con
->http
.data_remaining
> MaxRequestSize
)
1465 * Request too large...
1468 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1470 cupsdCloseClient(con
);
1476 else if (con
->http
.data_remaining
< 0 ||
1477 (!con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1478 con
->http
.data_encoding
== HTTP_ENCODE_LENGTH
))
1481 * Negative content lengths are invalid!
1484 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1486 cupsdCloseClient(con
);
1494 * See what kind of POST request this is; for IPP requests the
1495 * content-type field will be "application/ipp"...
1498 if (!strcmp(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
],
1500 con
->request
= ippNew();
1501 else if ((!strncmp(con
->uri
, "/admin", 6) &&
1502 strncmp(con
->uri
, "/admin/conf/", 12) &&
1503 strncmp(con
->uri
, "/admin/log/", 11)) ||
1504 !strncmp(con
->uri
, "/printers", 9) ||
1505 !strncmp(con
->uri
, "/classes", 8) ||
1506 !strncmp(con
->uri
, "/help", 5) ||
1507 !strncmp(con
->uri
, "/jobs", 5))
1513 if (!strncmp(con
->uri
, "/admin", 6))
1515 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1518 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1520 else if (!strncmp(con
->uri
, "/printers", 9))
1522 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1525 if (con
->uri
[9] && con
->uri
[10])
1526 cupsdSetString(&con
->options
, con
->uri
+ 9);
1528 cupsdSetString(&con
->options
, NULL
);
1530 else if (!strncmp(con
->uri
, "/classes", 8))
1532 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1535 if (con
->uri
[8] && con
->uri
[9])
1536 cupsdSetString(&con
->options
, con
->uri
+ 8);
1538 cupsdSetString(&con
->options
, NULL
);
1540 else if (!strncmp(con
->uri
, "/jobs", 5))
1542 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1545 if (con
->uri
[5] && con
->uri
[6])
1546 cupsdSetString(&con
->options
, con
->uri
+ 5);
1548 cupsdSetString(&con
->options
, NULL
);
1552 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1555 if (con
->uri
[5] && con
->uri
[6])
1556 cupsdSetString(&con
->options
, con
->uri
+ 5);
1558 cupsdSetString(&con
->options
, NULL
);
1561 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1562 "cupsdReadClient: %d command=\"%s\", "
1564 con
->http
.fd
, con
->command
,
1565 con
->options
? con
->options
: "(null)");
1567 if (con
->http
.version
<= HTTP_1_0
)
1568 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1576 if ((filename
= get_file(con
, &filestats
, buf
,
1577 sizeof(buf
))) == NULL
)
1579 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1581 cupsdCloseClient(con
);
1588 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1590 if (!is_cgi(con
, filename
, &filestats
, type
))
1593 * Only POST to CGI's...
1596 if (!cupsdSendError(con
, HTTP_UNAUTHORIZED
, CUPSD_AUTH_NONE
))
1598 cupsdCloseClient(con
);
1605 case HTTP_PUT_RECV
:
1607 * Validate the resource name...
1610 if (strncmp(con
->uri
, "/admin/conf/", 12) ||
1611 strchr(con
->uri
+ 12, '/') ||
1612 strlen(con
->uri
) == 12)
1615 * PUT can only be done to configuration files under
1619 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1621 cupsdCloseClient(con
);
1629 * See if the PUT request includes a Content-Length field, and if
1630 * so check the length against any limits that are set...
1633 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "PUT %s", con
->uri
);
1634 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "CONTENT_TYPE = %s",
1635 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
1637 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1638 MaxRequestSize
> 0 &&
1639 con
->http
.data_remaining
> MaxRequestSize
)
1642 * Request too large...
1645 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1647 cupsdCloseClient(con
);
1653 else if (con
->http
.data_remaining
< 0)
1656 * Negative content lengths are invalid!
1659 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1661 cupsdCloseClient(con
);
1669 * Open a temporary file to hold the request...
1672 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
1674 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1678 cupsdLogMessage(CUPSD_LOG_ERROR
,
1679 "Unable to create request file %s: %s",
1680 con
->filename
, strerror(errno
));
1682 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1684 cupsdCloseClient(con
);
1689 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1690 "cupsdReadClient: %d REQUEST %s=%d", con
->http
.fd
,
1691 con
->filename
, con
->file
);
1693 fchmod(con
->file
, 0640);
1694 fchown(con
->file
, RunUser
, Group
);
1695 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1700 cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
);
1701 cupsdCloseClient(con
);
1705 if (!strncmp(con
->uri
, "/printers/", 10) &&
1706 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1709 * Send PPD file - get the real printer name since printer
1710 * names are not case sensitive but filenames can be...
1713 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1715 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1716 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1719 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1721 cupsdCloseClient(con
);
1729 if ((!strncmp(con
->uri
, "/admin", 6) &&
1730 strncmp(con
->uri
, "/admin/conf/", 12) &&
1731 strncmp(con
->uri
, "/admin/log/", 11)) ||
1732 !strncmp(con
->uri
, "/printers", 9) ||
1733 !strncmp(con
->uri
, "/classes", 8) ||
1734 !strncmp(con
->uri
, "/help", 5) ||
1735 !strncmp(con
->uri
, "/jobs", 5))
1741 if (!cupsdSendHeader(con
, HTTP_OK
, "text/html", CUPSD_AUTH_NONE
))
1743 cupsdCloseClient(con
);
1747 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1749 cupsdCloseClient(con
);
1753 if (cupsdFlushHeader(con
) < 0)
1755 cupsdCloseClient(con
);
1759 cupsdLogRequest(con
, HTTP_OK
);
1761 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1762 (strchr(con
->uri
+ 12, '/') ||
1763 strlen(con
->uri
) == 12)) ||
1764 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1765 (strchr(con
->uri
+ 11, '/') ||
1766 strlen(con
->uri
) == 11)))
1769 * HEAD can only be done to configuration files under
1773 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1775 cupsdCloseClient(con
);
1781 else if ((filename
= get_file(con
, &filestats
, buf
,
1782 sizeof(buf
))) == NULL
)
1784 if (!cupsdSendHeader(con
, HTTP_NOT_FOUND
, "text/html", CUPSD_AUTH_NONE
))
1786 cupsdCloseClient(con
);
1790 cupsdLogRequest(con
, HTTP_NOT_FOUND
);
1792 else if (!check_if_modified(con
, &filestats
))
1794 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1796 cupsdCloseClient(con
);
1800 cupsdLogRequest(con
, HTTP_NOT_MODIFIED
);
1808 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1810 strcpy(line
, "text/plain");
1812 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1814 if (!cupsdSendHeader(con
, HTTP_OK
, line
, CUPSD_AUTH_NONE
))
1816 cupsdCloseClient(con
);
1820 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
1821 httpGetDateString(filestats
.st_mtime
)) < 0)
1823 cupsdCloseClient(con
);
1827 if (httpPrintf(HTTP(con
), "Content-Length: %lu\r\n",
1828 (unsigned long)filestats
.st_size
) < 0)
1830 cupsdCloseClient(con
);
1834 cupsdLogRequest(con
, HTTP_OK
);
1837 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1839 cupsdCloseClient(con
);
1843 if (cupsdFlushHeader(con
) < 0)
1845 cupsdCloseClient(con
);
1849 con
->http
.state
= HTTP_WAITING
;
1853 break; /* Anti-compiler-warning-code */
1859 * Handle any incoming data...
1862 switch (con
->http
.state
)
1864 case HTTP_PUT_RECV
:
1865 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1866 "cupsdReadClient: %d con->data_encoding=HTTP_ENCODE_%s, "
1867 "con->data_remaining=" CUPS_LLFMT
", con->file=%d",
1869 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
?
1870 "CHUNKED" : "LENGTH",
1871 CUPS_LLCAST con
->http
.data_remaining
, con
->file
);
1875 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
1877 cupsdCloseClient(con
);
1882 con
->bytes
+= bytes
;
1884 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1885 "cupsdReadClient: %d writing %d bytes to %d",
1886 con
->http
.fd
, bytes
, con
->file
);
1888 if (write(con
->file
, line
, bytes
) < bytes
)
1890 cupsdLogMessage(CUPSD_LOG_ERROR
,
1891 "cupsdReadClient: Unable to write %d bytes to %s: %s",
1892 bytes
, con
->filename
, strerror(errno
));
1894 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1895 "cupsdReadClient: Closing data file %d...",
1900 unlink(con
->filename
);
1901 cupsdClearString(&con
->filename
);
1903 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1905 cupsdCloseClient(con
);
1911 while (con
->http
.state
== HTTP_PUT_RECV
&& con
->http
.used
> 0);
1913 if (con
->http
.state
== HTTP_WAITING
)
1916 * End of file, see how big it is...
1919 fstat(con
->file
, &filestats
);
1921 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1922 "cupsdReadClient: %d Closing data file %d, size="
1924 con
->http
.fd
, con
->file
,
1925 CUPS_LLCAST filestats
.st_size
);
1930 if (filestats
.st_size
> MaxRequestSize
&&
1934 * Request is too big; remove it and send an error...
1937 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1938 "cupsdReadClient: %d Removing temp file %s",
1939 con
->http
.fd
, con
->filename
);
1940 unlink(con
->filename
);
1941 cupsdClearString(&con
->filename
);
1943 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1945 cupsdCloseClient(con
);
1951 * Install the configuration file...
1954 status
= install_conf_file(con
);
1957 * Return the status to the client...
1960 if (!cupsdSendError(con
, status
, CUPSD_AUTH_NONE
))
1962 cupsdCloseClient(con
);
1968 case HTTP_POST_RECV
:
1969 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1970 "cupsdReadClient: %d con->data_encoding=HTTP_ENCODE_"
1971 "%s, con->data_remaining=" CUPS_LLFMT
", con->file=%d",
1973 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
?
1974 "CHUNKED" : "LENGTH",
1975 CUPS_LLCAST con
->http
.data_remaining
, con
->file
);
1982 * Grab any request data from the connection...
1985 if ((ipp_state
= ippRead(&(con
->http
), con
->request
)) == IPP_ERROR
)
1987 cupsdLogMessage(CUPSD_LOG_ERROR
,
1988 "cupsdReadClient: %d IPP Read Error!",
1991 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
1992 cupsdCloseClient(con
);
1995 else if (ipp_state
!= IPP_DATA
)
1997 if (con
->http
.state
== HTTP_POST_SEND
)
1999 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
2000 cupsdCloseClient(con
);
2007 con
->bytes
+= ippLength(con
->request
);
2010 if (con
->file
< 0 && con
->http
.state
!= HTTP_POST_SEND
)
2013 * Create a file as needed for the request data...
2016 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
, request_id
++);
2017 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
2021 cupsdLogMessage(CUPSD_LOG_ERROR
,
2022 "Unable to create request file %s: %s",
2023 con
->filename
, strerror(errno
));
2025 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2027 cupsdCloseClient(con
);
2032 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdReadClient: %d REQUEST %s=%d", con
->http
.fd
,
2033 con
->filename
, con
->file
);
2035 fchmod(con
->file
, 0640);
2036 fchown(con
->file
, RunUser
, Group
);
2037 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2040 if (con
->http
.state
!= HTTP_POST_SEND
)
2042 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
2044 cupsdCloseClient(con
);
2049 con
->bytes
+= bytes
;
2051 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2052 "cupsdReadClient: %d writing %d bytes to %d",
2053 con
->http
.fd
, bytes
, con
->file
);
2055 if (write(con
->file
, line
, bytes
) < bytes
)
2057 cupsdLogMessage(CUPSD_LOG_ERROR
,
2058 "cupsdReadClient: Unable to write %d bytes to %s: %s",
2059 bytes
, con
->filename
, strerror(errno
));
2061 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2062 "cupsdReadClient: Closing file %d...",
2067 unlink(con
->filename
);
2068 cupsdClearString(&con
->filename
);
2070 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2072 cupsdCloseClient(con
);
2077 else if (con
->http
.state
== HTTP_POST_RECV
)
2079 else if (con
->http
.state
!= HTTP_POST_SEND
)
2081 cupsdCloseClient(con
);
2086 while (con
->http
.state
== HTTP_POST_RECV
&& con
->http
.used
> 0);
2088 if (con
->http
.state
== HTTP_POST_SEND
)
2092 fstat(con
->file
, &filestats
);
2094 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2095 "cupsdReadClient: %d Closing data file %d, "
2096 "size=" CUPS_LLFMT
".",
2097 con
->http
.fd
, con
->file
,
2098 CUPS_LLCAST filestats
.st_size
);
2103 if (filestats
.st_size
> MaxRequestSize
&&
2107 * Request is too big; remove it and send an error...
2110 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2111 "cupsdReadClient: %d Removing temp file %s",
2112 con
->http
.fd
, con
->filename
);
2113 unlink(con
->filename
);
2114 cupsdClearString(&con
->filename
);
2119 * Delete any IPP request data...
2122 ippDelete(con
->request
);
2123 con
->request
= NULL
;
2126 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2128 cupsdCloseClient(con
);
2135 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
2137 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
2139 cupsdCloseClient(con
);
2144 cupsdLogRequest(con
, HTTP_OK
);
2150 cupsdProcessIPPRequest(con
);
2154 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2155 "cupsdReadClient: %d Removing temp file %s",
2156 con
->http
.fd
, con
->filename
);
2157 unlink(con
->filename
);
2158 cupsdClearString(&con
->filename
);
2167 break; /* Anti-compiler-warning-code */
2170 if (con
->http
.state
== HTTP_WAITING
)
2172 if (!con
->http
.keep_alive
)
2173 cupsdCloseClient(con
);
2176 cupsArrayRemove(ActiveClients
, con
);
2177 cupsdSetBusyState();
2184 * 'cupsdSendCommand()' - Send output from a command via HTTP.
2187 int /* O - 1 on success, 0 on failure */
2189 cupsd_client_t
*con
, /* I - Client connection */
2190 char *command
, /* I - Command to run */
2191 char *options
, /* I - Command-line options */
2192 int root
) /* I - Run as root? */
2194 int fd
; /* Standard input file descriptor */
2199 fd
= open(con
->filename
, O_RDONLY
);
2203 cupsdLogMessage(CUPSD_LOG_ERROR
,
2204 "cupsdSendCommand: %d Unable to open \"%s\" for reading: %s",
2205 con
->http
.fd
, con
->filename
? con
->filename
: "/dev/null",
2210 fcntl(fd
, F_SETFD
, fcntl(fd
, F_GETFD
) | FD_CLOEXEC
);
2215 con
->pipe_pid
= pipe_command(con
, fd
, &(con
->file
), command
, options
, root
);
2220 cupsdLogMessage(CUPSD_LOG_INFO
, "Started \"%s\" (pid=%d)", command
,
2223 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendCommand: %d file=%d",
2224 con
->http
.fd
, con
->file
);
2226 if (con
->pipe_pid
== 0)
2229 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2231 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2233 con
->sent_header
= 0;
2234 con
->file_ready
= 0;
2235 con
->got_fields
= 0;
2243 * 'cupsdSendError()' - Send an error message via HTTP.
2246 int /* O - 1 if successful, 0 otherwise */
2247 cupsdSendError(cupsd_client_t
*con
, /* I - Connection */
2248 http_status_t code
, /* I - Error code */
2249 int auth_type
)/* I - Authentication type */
2253 * Force client to upgrade for authentication if that is how the
2254 * server is configured...
2257 if (code
== HTTP_UNAUTHORIZED
&&
2258 DefaultEncryption
== HTTP_ENCRYPT_REQUIRED
&&
2259 strcasecmp(con
->http
.hostname
, "localhost") &&
2262 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2263 "cupsdSendError: Encryption before authentication!");
2264 code
= HTTP_UPGRADE_REQUIRED
;
2266 #endif /* HAVE_SSL */
2269 * Put the request in the access_log file...
2272 cupsdLogRequest(con
, code
);
2274 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendError: %d code=%d (%s)",
2275 con
->http
.fd
, code
, httpStatus(code
));
2278 * To work around bugs in some proxies, don't use Keep-Alive for some
2281 * Kerberos authentication doesn't work without Keep-Alive, so
2282 * never disable it in that case.
2285 if (code
>= HTTP_BAD_REQUEST
&& con
->http
.auth_type
!= CUPSD_AUTH_NEGOTIATE
)
2286 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
2289 * Send an error message back to the client. If the error code is a
2290 * 400 or 500 series, make sure the message contains some text, too!
2293 if (!cupsdSendHeader(con
, code
, NULL
, auth_type
))
2297 if (code
== HTTP_UPGRADE_REQUIRED
)
2298 if (httpPrintf(HTTP(con
), "Connection: Upgrade\r\n") < 0)
2301 if (httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n") < 0)
2303 #endif /* HAVE_SSL */
2305 if (con
->http
.version
>= HTTP_1_1
&&
2306 con
->http
.keep_alive
== HTTP_KEEPALIVE_OFF
)
2308 if (httpPrintf(HTTP(con
), "Connection: close\r\n") < 0)
2312 if (code
>= HTTP_BAD_REQUEST
)
2315 * Send a human-readable error message.
2318 char message
[4096], /* Message for user */
2319 urltext
[1024], /* URL redirection text */
2320 redirect
[1024]; /* Redirection link */
2321 const char *text
; /* Status-specific text */
2326 if (code
== HTTP_UNAUTHORIZED
)
2327 text
= _cupsLangString(con
->language
,
2328 _("Enter your username and password or the "
2329 "root username and password to access this "
2330 "page. If you are using Kerberos authentication, "
2331 "make sure you have a valid Kerberos ticket."));
2332 else if (code
== HTTP_UPGRADE_REQUIRED
)
2336 snprintf(urltext
, sizeof(urltext
),
2337 _cupsLangString(con
->language
,
2338 _("You must access this page using the URL "
2339 "<A HREF=\"https://%s:%d%s\">"
2340 "https://%s:%d%s</A>.")),
2341 con
->servername
, con
->serverport
, con
->uri
,
2342 con
->servername
, con
->serverport
, con
->uri
);
2344 snprintf(redirect
, sizeof(redirect
),
2345 "<META HTTP-EQUIV=\"Refresh\" "
2346 "CONTENT=\"3;URL=https://%s:%d%s\">\n",
2347 con
->servername
, con
->serverport
, con
->uri
);
2352 snprintf(message
, sizeof(message
),
2353 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" "
2354 "\"http://www.w3.org/TR/REC-html40/loose.dtd\">\n"
2357 "\t<META HTTP-EQUIV=\"Content-Type\" "
2358 "CONTENT=\"text/html; charset=utf-8\">\n"
2359 "\t<TITLE>%d %s</TITLE>\n"
2360 "\t<LINK REL=\"STYLESHEET\" TYPE=\"text/css\" "
2361 "HREF=\"/cups.css\">\n"
2369 code
, httpStatus(code
), redirect
, code
, httpStatus(code
), text
);
2371 if (httpPrintf(HTTP(con
), "Content-Type: text/html; charset=utf-8\r\n") < 0)
2373 if (httpPrintf(HTTP(con
), "Content-Length: %d\r\n",
2374 (int)strlen(message
)) < 0)
2376 if (httpPrintf(HTTP(con
), "\r\n") < 0)
2378 if (httpPrintf(HTTP(con
), "%s", message
) < 0)
2381 else if (httpPrintf(HTTP(con
), "\r\n") < 0)
2384 if (cupsdFlushHeader(con
) < 0)
2387 con
->http
.state
= HTTP_WAITING
;
2394 * 'cupsdSendHeader()' - Send an HTTP request.
2397 int /* O - 1 on success, 0 on failure */
2399 cupsd_client_t
*con
, /* I - Client to send to */
2400 http_status_t code
, /* I - HTTP status code */
2401 char *type
, /* I - MIME type of document */
2402 int auth_type
) /* I - Type of authentication */
2404 char auth_str
[1024]; /* Authorization string */
2406 static char *gss_buf
= NULL
; /* Kerberos auth data buffer */
2407 static int gss_bufsize
= 0; /* Size of Kerberos auth data buffer */
2408 #endif /* HAVE_GSSAPI */
2412 * Send the HTTP status header...
2415 if (code
== HTTP_CONTINUE
)
2418 * 100-continue doesn't send any headers...
2421 return (httpPrintf(HTTP(con
), "HTTP/%d.%d 100 Continue\r\n\r\n",
2422 con
->http
.version
/ 100, con
->http
.version
% 100) > 0);
2425 httpFlushWrite(HTTP(con
));
2427 con
->http
.data_encoding
= HTTP_ENCODE_FIELDS
;
2429 if (httpPrintf(HTTP(con
), "HTTP/%d.%d %d %s\r\n", con
->http
.version
/ 100,
2430 con
->http
.version
% 100, code
, httpStatus(code
)) < 0)
2432 if (httpPrintf(HTTP(con
), "Date: %s\r\n", httpGetDateString(time(NULL
))) < 0)
2435 if (httpPrintf(HTTP(con
), "Server: %s\r\n", ServerHeader
) < 0)
2437 if (con
->http
.keep_alive
&& con
->http
.version
>= HTTP_1_0
)
2439 if (httpPrintf(HTTP(con
), "Connection: Keep-Alive\r\n") < 0)
2441 if (httpPrintf(HTTP(con
), "Keep-Alive: timeout=%d\r\n",
2442 KeepAliveTimeout
) < 0)
2445 if (code
== HTTP_METHOD_NOT_ALLOWED
)
2446 if (httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST\r\n") < 0)
2449 if (code
== HTTP_UNAUTHORIZED
)
2451 if (auth_type
== CUPSD_AUTH_NONE
)
2453 if (!con
->best
|| con
->best
->type
<= CUPSD_AUTH_NONE
)
2454 auth_type
= DefaultAuthType
;
2456 auth_type
= con
->best
->type
;
2461 if (auth_type
== CUPSD_AUTH_BASIC
|| auth_type
== CUPSD_AUTH_BASICDIGEST
)
2462 strlcpy(auth_str
, "Basic realm=\"CUPS\"", sizeof(auth_str
));
2463 else if (auth_type
== CUPSD_AUTH_DIGEST
)
2464 snprintf(auth_str
, sizeof(auth_str
), "Digest realm=\"CUPS\", nonce=\"%s\"",
2465 con
->http
.hostname
);
2467 else if (auth_type
== CUPSD_AUTH_NEGOTIATE
&& con
->gss_output_token
.length
== 0)
2468 strlcpy(auth_str
, "Negotiate", sizeof(auth_str
));
2469 #endif /* HAVE_GSSAPI */
2471 #ifdef HAVE_AUTHORIZATION_H
2472 if (con
->best
&& auth_type
!= CUPSD_AUTH_NEGOTIATE
)
2474 int i
; /* Looping var */
2475 char *auth_key
; /* Auth key buffer */
2476 size_t auth_size
; /* Size of remaining buffer */
2479 auth_key
= auth_str
+ strlen(auth_str
);
2480 auth_size
= sizeof(auth_str
) - (auth_key
- auth_str
);
2482 for (i
= 0; i
< con
->best
->num_names
; i
++)
2484 if (!strncasecmp(con
->best
->names
[i
], "@AUTHKEY(", 9))
2486 snprintf(auth_key
, auth_size
, ", authkey=\"%s\"",
2487 con
->best
->names
[i
] + 9);
2488 /* end parenthesis is stripped in conf.c */
2491 else if (!strcasecmp(con
->best
->names
[i
], "@SYSTEM") &&
2494 snprintf(auth_key
, auth_size
, ", authkey=\"%s\"", SystemGroupAuthKey
);
2499 #endif /* HAVE_AUTHORIZATION_H */
2503 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendHeader: WWW-Authenticate: %s",
2506 if (httpPrintf(HTTP(con
), "WWW-Authenticate: %s\r\n", auth_str
) < 0)
2513 * WWW-Authenticate: Negotiate can be included even for
2514 * non-401 replies...
2517 if (con
->gss_output_token
.length
> 0 && con
->gss_output_token
.length
<= 65536)
2519 OM_uint32 minor_status
; /* Minor status code */
2520 int bufsize
; /* Size of output token buffer */
2523 bufsize
= con
->gss_output_token
.length
* 4 / 3 + 2;
2525 if (bufsize
> gss_bufsize
)
2527 char *buf
; /* New buffer */
2530 bufsize
= (bufsize
+ 1023) & 1023;/* Round up */
2533 buf
= realloc(gss_buf
, bufsize
);
2535 buf
= malloc(bufsize
);
2539 cupsdLogMessage(CUPSD_LOG_ERROR
,
2540 "Unable to allocate %d bytes for Kerberos credentials!",
2546 gss_bufsize
= bufsize
;
2549 httpEncode64_2(gss_buf
, gss_bufsize
,
2550 con
->gss_output_token
.value
,
2551 con
->gss_output_token
.length
);
2552 gss_release_buffer(&minor_status
, &con
->gss_output_token
);
2554 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2555 "cupsdSendHeader: WWW-Authenticate: Negotiate %s", gss_buf
);
2557 if (httpPrintf(HTTP(con
), "WWW-Authenticate: Negotiate %s\r\n",
2561 else if (con
->gss_output_token
.length
> 65536)
2563 cupsdLogMessage(CUPSD_LOG_ERROR
,
2564 "Kerberos credentials larger than 64k (%d)!",
2565 (int)con
->gss_output_token
.length
);
2568 #endif /* HAVE_GSSAPI */
2570 if (con
->language
&& strcmp(con
->language
->language
, "C"))
2572 if (httpPrintf(HTTP(con
), "Content-Language: %s\r\n",
2573 con
->language
->language
) < 0)
2579 if (!strcmp(type
, "text/html"))
2581 if (httpPrintf(HTTP(con
),
2582 "Content-Type: text/html; charset=utf-8\r\n") < 0)
2585 else if (httpPrintf(HTTP(con
), "Content-Type: %s\r\n", type
) < 0)
2594 * 'cupsdUpdateCGI()' - Read status messages from CGI scripts and programs.
2598 cupsdUpdateCGI(void)
2600 char *ptr
, /* Pointer to end of line in buffer */
2601 message
[1024]; /* Pointer to message text */
2602 int loglevel
; /* Log level for message */
2605 while ((ptr
= cupsdStatBufUpdate(CGIStatusBuffer
, &loglevel
,
2606 message
, sizeof(message
))) != NULL
)
2607 if (!strchr(CGIStatusBuffer
->buffer
, '\n'))
2610 if (ptr
== NULL
&& !CGIStatusBuffer
->bufused
)
2613 * Fatal error on pipe - should never happen!
2616 cupsdLogMessage(CUPSD_LOG_CRIT
,
2617 "cupsdUpdateCGI: error reading from CGI error pipe - %s",
2624 * 'cupsdWriteClient()' - Write data to a client as needed.
2628 cupsdWriteClient(cupsd_client_t
*con
) /* I - Client connection */
2630 int bytes
; /* Number of bytes written */
2631 char buf
[16385]; /* Data buffer */
2632 char *bufptr
; /* Pointer into buffer */
2633 ipp_state_t ipp_state
; /* IPP state value */
2637 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2638 "cupsdWriteClient(con=%p) %d response=%p(%d), file=%d "
2639 "pipe_pid=%d state=%d",
2640 con
, con
->http
.fd
, con
->response
,
2641 con
->response
? con
->response
->state
: -1,
2642 con
->file
, con
->pipe_pid
, con
->http
.state
);
2645 if (con
->http
.state
!= HTTP_GET_SEND
&&
2646 con
->http
.state
!= HTTP_POST_SEND
)
2652 * Make sure we select on the CGI output...
2655 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2657 if (!con
->file_ready
)
2660 * Try again later when there is CGI output available...
2663 cupsdRemoveSelect(con
->http
.fd
);
2667 con
->file_ready
= 0;
2670 if (con
->response
&& con
->response
->state
!= IPP_DATA
)
2672 ipp_state
= ippWrite(HTTP(con
), con
->response
);
2673 bytes
= ipp_state
!= IPP_ERROR
&&
2674 (con
->file
>= 0 || ipp_state
!= IPP_DATA
);
2676 else if ((bytes
= read(con
->file
, buf
, sizeof(buf
) - 1)) > 0)
2678 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2679 "cupsdWriteClient: Read %d bytes from file %d...",
2682 if (con
->pipe_pid
&& !con
->got_fields
)
2685 * Inspect the data for Content-Type and other fields.
2690 for (bufptr
= buf
; !con
->got_fields
&& *bufptr
; bufptr
++)
2691 if (*bufptr
== '\n')
2694 * Send line to client...
2697 if (bufptr
> buf
&& bufptr
[-1] == '\r')
2701 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "Script header: %s", buf
);
2703 if (!con
->sent_header
)
2706 * Handle redirection and CGI status codes...
2709 if (!strncasecmp(buf
, "Location:", 9))
2711 cupsdSendHeader(con
, HTTP_SEE_OTHER
, NULL
, CUPSD_AUTH_NONE
);
2712 con
->sent_header
= 2;
2714 if (httpPrintf(HTTP(con
), "Content-Length: 0\r\n") < 0)
2717 else if (!strncasecmp(buf
, "Status:", 7))
2719 cupsdSendError(con
, (http_status_t
)atoi(buf
+ 7), CUPSD_AUTH_NONE
);
2720 con
->sent_header
= 2;
2724 cupsdSendHeader(con
, HTTP_OK
, NULL
, CUPSD_AUTH_NONE
);
2725 con
->sent_header
= 1;
2727 if (con
->http
.version
== HTTP_1_1
)
2729 if (httpPrintf(HTTP(con
), "Transfer-Encoding: chunked\r\n") < 0)
2735 if (strncasecmp(buf
, "Status:", 7))
2736 httpPrintf(HTTP(con
), "%s\r\n", buf
);
2738 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdWriteClient: %d %s",
2745 bytes
-= (bufptr
- buf
);
2746 memmove(buf
, bufptr
, bytes
+ 1);
2750 * See if the line was empty...
2753 if (con
->field_col
== 0)
2755 con
->got_fields
= 1;
2757 if (cupsdFlushHeader(con
) < 0)
2759 cupsdCloseClient(con
);
2763 if (con
->http
.version
== HTTP_1_1
)
2764 con
->http
.data_encoding
= HTTP_ENCODE_CHUNKED
;
2769 else if (*bufptr
!= '\r')
2772 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2773 "cupsdWriteClient: %d bytes=%d, got_fields=%d",
2774 con
->http
.fd
, bytes
, con
->got_fields
);
2776 if (bytes
> 0 && !con
->got_fields
)
2779 * Remaining text needs to go out...
2782 httpPrintf(HTTP(con
), "%s", buf
);
2784 con
->http
.activity
= time(NULL
);
2787 else if (bytes
== 0)
2789 con
->http
.activity
= time(NULL
);
2796 if (httpWrite2(HTTP(con
), buf
, bytes
) < 0)
2798 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2799 "cupsdWriteClient: %d Write of %d bytes failed!",
2800 con
->http
.fd
, bytes
);
2802 cupsdCloseClient(con
);
2806 if (con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
)
2807 httpFlushWrite(HTTP(con
));
2809 con
->bytes
+= bytes
;
2811 if (con
->http
.state
== HTTP_WAITING
)
2818 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdWriteClient: %d bytes < 0",
2821 cupsdLogRequest(con
, HTTP_OK
);
2823 httpFlushWrite(HTTP(con
));
2825 if (con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
&& con
->sent_header
== 1)
2827 if (httpWrite2(HTTP(con
), "", 0) < 0)
2829 cupsdCloseClient(con
);
2834 con
->http
.state
= HTTP_WAITING
;
2836 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
2840 cupsdRemoveSelect(con
->file
);
2843 cupsdEndProcess(con
->pipe_pid
, 0);
2845 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2846 "cupsdWriteClient: %d Closing data file %d.",
2847 con
->http
.fd
, con
->file
);
2856 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2857 "cupsdWriteClient: %d Removing temp file %s",
2858 con
->http
.fd
, con
->filename
);
2859 unlink(con
->filename
);
2860 cupsdClearString(&con
->filename
);
2865 ippDelete(con
->request
);
2866 con
->request
= NULL
;
2871 ippDelete(con
->response
);
2872 con
->response
= NULL
;
2875 cupsdClearString(&con
->command
);
2876 cupsdClearString(&con
->options
);
2877 cupsdClearString(&con
->query_string
);
2879 if (!con
->http
.keep_alive
)
2881 cupsdCloseClient(con
);
2886 con
->http
.activity
= time(NULL
);
2891 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
2894 static int /* O - 1 if modified since */
2896 cupsd_client_t
*con
, /* I - Client connection */
2897 struct stat
*filestats
) /* I - File information */
2899 char *ptr
; /* Pointer into field */
2900 time_t date
; /* Time/date value */
2901 off_t size
; /* Size/length value */
2906 ptr
= con
->http
.fields
[HTTP_FIELD_IF_MODIFIED_SINCE
];
2911 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2912 "check_if_modified: %d If-Modified-Since=\"%s\"",
2915 while (*ptr
!= '\0')
2917 while (isspace(*ptr
) || *ptr
== ';')
2920 if (strncasecmp(ptr
, "length=", 7) == 0)
2923 size
= strtoll(ptr
, NULL
, 10);
2925 while (isdigit(*ptr
))
2928 else if (isalpha(*ptr
))
2930 date
= httpGetDateTime(ptr
);
2931 while (*ptr
!= '\0' && *ptr
!= ';')
2938 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2939 "check_if_modified: %d sizes=" CUPS_LLFMT
","
2940 CUPS_LLFMT
" dates=%d,%d",
2941 con
->http
.fd
, CUPS_LLCAST size
,
2942 CUPS_LLCAST filestats
->st_size
, (int)date
,
2943 (int)filestats
->st_mtime
);
2945 return ((size
!= filestats
->st_size
&& size
!= 0) ||
2946 (date
< filestats
->st_mtime
&& date
!= 0) ||
2947 (size
== 0 && date
== 0));
2952 * 'compare_clients()' - Compare two client connections.
2955 static int /* O - Result of comparison */
2956 compare_clients(cupsd_client_t
*a
, /* I - First client */
2957 cupsd_client_t
*b
, /* I - Second client */
2958 void *data
) /* I - User data (not used) */
2973 * 'encrypt_client()' - Enable encryption for the client...
2976 static int /* O - 1 on success, 0 on error */
2977 encrypt_client(cupsd_client_t
*con
) /* I - Client to encrypt */
2980 SSL_CTX
*context
; /* Context for encryption */
2981 SSL
*conn
; /* Connection for encryption */
2982 BIO
*bio
; /* BIO data */
2983 unsigned long error
; /* Error code */
2987 * Verify that we have a certificate...
2990 if (access(ServerKey
, 0) || access(ServerCertificate
, 0))
2993 * Nope, make a self-signed certificate...
2996 if (!make_certificate(con
))
3001 * Create the SSL context and accept the connection...
3004 context
= SSL_CTX_new(SSLv23_server_method());
3006 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
3007 SSL_CTX_use_PrivateKey_file(context
, ServerKey
, SSL_FILETYPE_PEM
);
3008 SSL_CTX_use_certificate_file(context
, ServerCertificate
, SSL_FILETYPE_PEM
);
3010 bio
= BIO_new(_httpBIOMethods());
3011 BIO_ctrl(bio
, BIO_C_SET_FILE_PTR
, 0, (char *)HTTP(con
));
3013 conn
= SSL_new(context
);
3014 SSL_set_bio(conn
, bio
, bio
);
3016 if (SSL_accept(conn
) != 1)
3018 cupsdLogMessage(CUPSD_LOG_ERROR
,
3019 "encrypt_client: Unable to encrypt connection from %s!",
3020 con
->http
.hostname
);
3022 while ((error
= ERR_get_error()) != 0)
3023 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s",
3024 ERR_error_string(error
, NULL
));
3026 SSL_CTX_free(context
);
3031 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3032 "encrypt_client: %d Connection from %s now encrypted.",
3033 con
->http
.fd
, con
->http
.hostname
);
3035 con
->http
.tls
= conn
;
3038 # elif defined(HAVE_GNUTLS)
3039 http_tls_t
*conn
; /* TLS session object */
3040 int error
; /* Error code */
3041 gnutls_certificate_server_credentials
*credentials
;
3042 /* TLS credentials */
3046 * Verify that we have a certificate...
3049 if (access(ServerKey
, 0) || access(ServerCertificate
, 0))
3052 * Nope, make a self-signed certificate...
3055 if (!make_certificate(con
))
3060 * Create the SSL object and perform the SSL handshake...
3063 conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
));
3068 credentials
= (gnutls_certificate_server_credentials
*)
3069 malloc(sizeof(gnutls_certificate_server_credentials
));
3070 if (credentials
== NULL
)
3072 cupsdLogMessage(CUPSD_LOG_ERROR
,
3073 "encrypt_client: Unable to encrypt connection from %s!",
3074 con
->http
.hostname
);
3075 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s", strerror(errno
));
3081 gnutls_certificate_allocate_credentials(credentials
);
3082 gnutls_certificate_set_x509_key_file(*credentials
, ServerCertificate
,
3083 ServerKey
, GNUTLS_X509_FMT_PEM
);
3085 gnutls_init(&(conn
->session
), GNUTLS_SERVER
);
3086 gnutls_set_default_priority(conn
->session
);
3087 gnutls_credentials_set(conn
->session
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
3088 gnutls_transport_set_ptr(conn
->session
, (gnutls_transport_ptr
)HTTP(con
));
3089 gnutls_transport_set_pull_function(conn
->session
, _httpReadGNUTLS
);
3090 gnutls_transport_set_push_function(conn
->session
, _httpWriteGNUTLS
);
3092 error
= gnutls_handshake(conn
->session
);
3094 if (error
!= GNUTLS_E_SUCCESS
)
3096 cupsdLogMessage(CUPSD_LOG_ERROR
,
3097 "encrypt_client: Unable to encrypt connection from %s!",
3098 con
->http
.hostname
);
3099 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s",
3100 gnutls_strerror(error
));
3102 gnutls_deinit(conn
->session
);
3103 gnutls_certificate_free_credentials(*credentials
);
3109 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3110 "encrypt_client: %d Connection from %s now encrypted.",
3111 con
->http
.fd
, con
->http
.hostname
);
3113 conn
->credentials
= credentials
;
3114 con
->http
.tls
= conn
;
3117 # elif defined(HAVE_CDSASSL)
3118 OSStatus error
; /* Error code */
3119 http_tls_t
*conn
; /* CDSA connection information */
3122 if ((conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
))) == NULL
)
3126 conn
->session
= NULL
;
3127 conn
->certsArray
= get_cdsa_certificate(con
);
3129 if (!conn
->certsArray
)
3132 * No keychain (yet), make a self-signed certificate...
3135 if (make_certificate(con
))
3136 conn
->certsArray
= get_cdsa_certificate(con
);
3139 if (!conn
->certsArray
)
3141 cupsdLogMessage(CUPSD_LOG_ERROR
,
3142 "encrypt_client: Could not find signing key in keychain "
3143 "\"%s\"", ServerCertificate
);
3144 error
= errSSLBadCert
; /* errSSLBadConfiguration is a better choice, but not available on 10.2.x */
3148 error
= SSLNewContext(true, &conn
->session
);
3151 error
= SSLSetIOFuncs(conn
->session
, _httpReadCDSA
, _httpWriteCDSA
);
3154 error
= SSLSetProtocolVersionEnabled(conn
->session
, kSSLProtocol2
, false);
3157 error
= SSLSetConnection(conn
->session
, HTTP(con
));
3160 error
= SSLSetAllowsExpiredCerts(conn
->session
, true);
3163 error
= SSLSetAllowsAnyRoot(conn
->session
, true);
3166 error
= SSLSetCertificate(conn
->session
, conn
->certsArray
);
3171 * Perform SSL/TLS handshake
3174 while ((error
= SSLHandshake(conn
->session
)) == errSSLWouldBlock
)
3180 cupsdLogMessage(CUPSD_LOG_ERROR
,
3181 "encrypt_client: Unable to encrypt connection from %s!",
3182 con
->http
.hostname
);
3184 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s (%d)",
3185 cssmErrorString(error
), (int)error
);
3187 con
->http
.error
= error
;
3188 con
->http
.status
= HTTP_ERROR
;
3191 SSLDisposeContext(conn
->session
);
3193 if (conn
->certsArray
)
3194 CFRelease(conn
->certsArray
);
3201 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3202 "encrypt_client: %d Connection from %s now encrypted.",
3203 con
->http
.fd
, con
->http
.hostname
);
3205 con
->http
.tls
= conn
;
3208 # endif /* HAVE_LIBSSL */
3210 #endif /* HAVE_SSL */
3215 * 'get_cdsa_certificate()' - Get a SSL/TLS certificate from the System keychain.
3218 static CFArrayRef
/* O - Array of certificates */
3219 get_cdsa_certificate(cupsd_client_t
*con
) /* I - Client connection */
3221 OSStatus err
; /* Error info */
3222 SecKeychainRef keychain
; /* Keychain reference */
3223 SecIdentitySearchRef search
; /* Search reference */
3224 SecIdentityRef identity
; /* Identity */
3225 CFArrayRef certificates
= NULL
;
3226 /* Certificate array */
3229 if ((err
= SecKeychainOpen(ServerCertificate
, &keychain
)))
3231 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot open keychain \"%s\", %s",
3232 ServerCertificate
, cssmErrorString(err
));
3236 # if HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY
3238 * Use a policy to search for valid certificates who's common name matches the
3242 SecPolicySearchRef policy_search
; /* Policy search ref */
3243 SecPolicyRef policy
; /* Policy ref */
3244 CSSM_DATA options
; /* Policy options */
3245 CSSM_APPLE_TP_SSL_OPTIONS
3246 ssl_options
; /* SSL Option for hostname */
3249 if ((err
= SecPolicySearchCreate(CSSM_CERT_X_509v3
, &CSSMOID_APPLE_TP_SSL
,
3250 NULL
, &policy_search
)))
3252 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot create a policy search reference");
3253 CFRelease(keychain
);
3257 if ((err
= SecPolicySearchCopyNext(policy_search
, &policy
)))
3259 cupsdLogMessage(CUPSD_LOG_ERROR
,
3260 "Cannot find a policy to use for searching");
3261 CFRelease(keychain
);
3262 CFRelease(policy_search
);
3266 memset(&ssl_options
, 0, sizeof(ssl_options
));
3267 ssl_options
.Version
= CSSM_APPLE_TP_SSL_OPTS_VERSION
;
3268 ssl_options
.ServerName
= con
->servername
;
3269 ssl_options
.ServerNameLen
= strlen(con
->servername
);
3271 options
.Data
= (uint8
*)&ssl_options
;
3272 options
.Length
= sizeof(ssl_options
);
3274 if ((err
= SecPolicySetValue(policy
, &options
)))
3276 cupsdLogMessage(CUPSD_LOG_ERROR
,
3277 "Cannot set policy value to use for searching");
3278 CFRelease(keychain
);
3279 CFRelease(policy_search
);
3283 err
= SecIdentitySearchCreateWithPolicy(policy
, NULL
, CSSM_KEYUSE_SIGN
,
3284 keychain
, FALSE
, &search
);
3287 * Assume there is exactly one SecIdentity in the keychain...
3290 err
= SecIdentitySearchCreate(keychain
, CSSM_KEYUSE_SIGN
, &search
);
3291 # endif /* HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY */
3294 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3295 "Cannot create keychain search reference: %s",
3296 cssmErrorString(err
));
3299 if ((err
= SecIdentitySearchCopyNext(search
, &identity
)))
3301 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3302 "Cannot find signing key in keychain \"%s\", error %d",
3303 ServerCertificate
, (int)err
);
3307 if (CFGetTypeID(identity
) != SecIdentityGetTypeID())
3308 cupsdLogMessage(CUPSD_LOG_ERROR
,
3309 "SecIdentitySearchCopyNext CFTypeID failure!");
3312 if ((certificates
= CFArrayCreate(NULL
, (const void **)&identity
,
3313 1, &kCFTypeArrayCallBacks
)) == NULL
)
3314 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot create certificate array");
3317 CFRelease(identity
);
3323 # if HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY
3325 CFRelease(policy_search
);
3326 # endif /* HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY */
3328 return (certificates
);
3330 #endif /* HAVE_CDSASSL */
3334 * 'get_file()' - Get a filename and state info.
3337 static char * /* O - Real filename */
3338 get_file(cupsd_client_t
*con
, /* I - Client connection */
3339 struct stat
*filestats
, /* O - File information */
3340 char *filename
, /* IO - Filename buffer */
3341 int len
) /* I - Buffer length */
3343 int status
; /* Status of filesystem calls */
3344 char *ptr
; /* Pointer info filename */
3345 int plen
; /* Remaining length after pointer */
3346 char language
[7]; /* Language subdirectory, if any */
3350 * Figure out the real filename...
3355 if (!strncmp(con
->uri
, "/ppd/", 5))
3356 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
);
3357 else if (!strncmp(con
->uri
, "/rss/", 5) && !strchr(con
->uri
+ 5, '/'))
3358 snprintf(filename
, len
, "%s/rss/%s", CacheDir
, con
->uri
+ 5);
3359 else if (!strncmp(con
->uri
, "/admin/conf/", 12))
3360 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
+ 11);
3361 else if (!strncmp(con
->uri
, "/admin/log/", 11))
3363 if (!strncmp(con
->uri
+ 11, "access_log", 10) && AccessLog
[0] == '/')
3364 strlcpy(filename
, AccessLog
, len
);
3365 else if (!strncmp(con
->uri
+ 11, "error_log", 9) && ErrorLog
[0] == '/')
3366 strlcpy(filename
, ErrorLog
, len
);
3367 else if (!strncmp(con
->uri
+ 11, "page_log", 8) && PageLog
[0] == '/')
3368 strlcpy(filename
, PageLog
, len
);
3372 else if (con
->language
)
3374 snprintf(language
, sizeof(language
), "/%s", con
->language
->language
);
3375 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3378 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3380 if ((ptr
= strchr(filename
, '?')) != NULL
)
3384 * Grab the status for this language; if there isn't a language-specific file
3385 * then fallback to the default one...
3388 if ((status
= stat(filename
, filestats
)) != 0 && language
[0] &&
3389 strncmp(con
->uri
, "/ppd/", 5) &&
3390 strncmp(con
->uri
, "/admin/conf/", 12) &&
3391 strncmp(con
->uri
, "/admin/log/", 11))
3394 * Drop the country code...
3398 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3400 if ((ptr
= strchr(filename
, '?')) != NULL
)
3403 if ((status
= stat(filename
, filestats
)) != 0)
3406 * Drop the language prefix and try the root directory...
3410 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3412 if ((ptr
= strchr(filename
, '?')) != NULL
)
3415 status
= stat(filename
, filestats
);
3420 * If we're found a directory, get the index.html file instead...
3423 if (!status
&& S_ISDIR(filestats
->st_mode
))
3426 * Make sure the URI ends with a slash...
3429 if (con
->uri
[strlen(con
->uri
) - 1] != '/')
3430 strlcat(con
->uri
, "/", sizeof(con
->uri
));
3433 * Find the directory index file, trying every language...
3438 if (status
&& language
[0])
3441 * Try a different language subset...
3445 language
[0] = '\0'; /* Strip country code */
3447 language
[0] = '\0'; /* Strip language */
3451 * Look for the index file...
3454 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3456 if ((ptr
= strchr(filename
, '?')) != NULL
)
3459 ptr
= filename
+ strlen(filename
);
3460 plen
= len
- (ptr
- filename
);
3462 strlcpy(ptr
, "index.html", plen
);
3463 status
= stat(filename
, filestats
);
3468 strlcpy(ptr
, "index.class", plen
);
3469 status
= stat(filename
, filestats
);
3471 #endif /* HAVE_JAVA */
3476 strlcpy(ptr
, "index.pl", plen
);
3477 status
= stat(filename
, filestats
);
3479 #endif /* HAVE_PERL */
3484 strlcpy(ptr
, "index.php", plen
);
3485 status
= stat(filename
, filestats
);
3487 #endif /* HAVE_PHP */
3492 strlcpy(ptr
, "index.pyc", plen
);
3493 status
= stat(filename
, filestats
);
3498 strlcpy(ptr
, "index.py", plen
);
3499 status
= stat(filename
, filestats
);
3501 #endif /* HAVE_PYTHON */
3504 while (status
&& language
[0]);
3507 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "get_file: %d filename=%s size=%d",
3508 con
->http
.fd
, filename
,
3509 status
? -1 : (int)filestats
->st_size
);
3512 con
->http
.data_remaining
= (int)filestats
->st_size
;
3522 * 'install_conf_file()' - Install a configuration file.
3525 static http_status_t
/* O - Status */
3526 install_conf_file(cupsd_client_t
*con
) /* I - Connection */
3528 cups_file_t
*in
, /* Input file */
3529 *out
; /* Output file */
3530 char buffer
[1024]; /* Copy buffer */
3531 int bytes
; /* Number of bytes */
3532 char conffile
[1024], /* Configuration filename */
3533 newfile
[1024], /* New config filename */
3534 oldfile
[1024]; /* Old config filename */
3535 struct stat confinfo
; /* Config file info */
3539 * First construct the filenames...
3542 snprintf(conffile
, sizeof(conffile
), "%s%s", ServerRoot
, con
->uri
+ 11);
3543 snprintf(newfile
, sizeof(newfile
), "%s%s.N", ServerRoot
, con
->uri
+ 11);
3544 snprintf(oldfile
, sizeof(oldfile
), "%s%s.O", ServerRoot
, con
->uri
+ 11);
3546 cupsdLogMessage(CUPSD_LOG_INFO
, "Installing config file \"%s\"...", conffile
);
3549 * Get the owner, group, and permissions of the configuration file.
3550 * If it doesn't exist, assign it to the User and Group in the
3551 * cupsd.conf file with mode 0640 permissions.
3554 if (stat(conffile
, &confinfo
))
3556 confinfo
.st_uid
= User
;
3557 confinfo
.st_gid
= Group
;
3558 confinfo
.st_mode
= ConfigFilePerm
;
3562 * Open the request file and new config file...
3565 if ((in
= cupsFileOpen(con
->filename
, "rb")) == NULL
)
3567 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open request file \"%s\" - %s",
3568 con
->filename
, strerror(errno
));
3569 return (HTTP_SERVER_ERROR
);
3572 if ((out
= cupsFileOpen(newfile
, "wb")) == NULL
)
3575 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open config file \"%s\" - %s",
3576 newfile
, strerror(errno
));
3577 return (HTTP_SERVER_ERROR
);
3580 fchmod(cupsFileNumber(out
), confinfo
.st_mode
);
3581 fchown(cupsFileNumber(out
), confinfo
.st_uid
, confinfo
.st_gid
);
3584 * Copy from the request to the new config file...
3587 while ((bytes
= cupsFileRead(in
, buffer
, sizeof(buffer
))) > 0)
3588 if (cupsFileWrite(out
, buffer
, bytes
) < bytes
)
3590 cupsdLogMessage(CUPSD_LOG_ERROR
,
3591 "Unable to copy to config file \"%s\" - %s",
3592 newfile
, strerror(errno
));
3598 return (HTTP_SERVER_ERROR
);
3602 * Close the files...
3606 if (cupsFileClose(out
))
3608 cupsdLogMessage(CUPSD_LOG_ERROR
,
3609 "Error file closing config file \"%s\" - %s",
3610 newfile
, strerror(errno
));
3614 return (HTTP_SERVER_ERROR
);
3618 * Remove the request file...
3621 unlink(con
->filename
);
3622 cupsdClearString(&con
->filename
);
3625 * Unlink the old backup, rename the current config file to the backup
3626 * filename, and rename the new config file to the config file name...
3629 if (unlink(oldfile
))
3630 if (errno
!= ENOENT
)
3632 cupsdLogMessage(CUPSD_LOG_ERROR
,
3633 "Unable to remove backup config file \"%s\" - %s",
3634 oldfile
, strerror(errno
));
3638 return (HTTP_SERVER_ERROR
);
3641 if (rename(conffile
, oldfile
))
3642 if (errno
!= ENOENT
)
3644 cupsdLogMessage(CUPSD_LOG_ERROR
,
3645 "Unable to rename old config file \"%s\" - %s",
3646 conffile
, strerror(errno
));
3650 return (HTTP_SERVER_ERROR
);
3653 if (rename(newfile
, conffile
))
3655 cupsdLogMessage(CUPSD_LOG_ERROR
,
3656 "Unable to rename new config file \"%s\" - %s",
3657 newfile
, strerror(errno
));
3659 rename(oldfile
, conffile
);
3662 return (HTTP_SERVER_ERROR
);
3666 * If the cupsd.conf file was updated, set the NeedReload flag...
3669 if (!strcmp(con
->uri
, "/admin/conf/cupsd.conf"))
3670 NeedReload
= RELOAD_CUPSD
;
3672 NeedReload
= RELOAD_ALL
;
3674 ReloadTime
= time(NULL
);
3677 * Return that the file was created successfully...
3680 return (HTTP_CREATED
);
3685 * 'is_cgi()' - Is the resource a CGI script/program?
3688 static int /* O - 1 = CGI, 0 = file */
3689 is_cgi(cupsd_client_t
*con
, /* I - Client connection */
3690 const char *filename
, /* I - Real filename */
3691 struct stat
*filestats
, /* I - File information */
3692 mime_type_t
*type
) /* I - MIME type */
3694 const char *options
; /* Options on URL */
3697 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3698 "is_cgi(con=%p, filename=\"%s\", filestats=%p, type=%s/%s)\n",
3699 con
, filename
, filestats
, type
? type
->super
: "unknown",
3700 type
? type
->type
: "unknown");
3703 * Get the options, if any...
3706 if ((options
= strchr(con
->uri
, '?')) != NULL
)
3709 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", options
);
3713 * Check for known types...
3716 if (!type
|| strcasecmp(type
->super
, "application"))
3718 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "is_cgi: Returning 0...");
3722 if (!strcasecmp(type
->type
, "x-httpd-cgi") &&
3723 (filestats
->st_mode
& 0111))
3726 * "application/x-httpd-cgi" is a CGI script.
3729 cupsdSetString(&con
->command
, filename
);
3731 filename
= strrchr(filename
, '/') + 1; /* Filename always absolute */
3734 cupsdSetStringf(&con
->options
, " %s", options
);
3736 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3737 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3738 con
->command
, con
->options
);
3743 else if (!strcasecmp(type
->type
, "x-httpd-java"))
3746 * "application/x-httpd-java" is a Java servlet.
3749 cupsdSetString(&con
->command
, CUPS_JAVA
);
3752 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3754 cupsdSetStringf(&con
->options
, " %s", filename
);
3756 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3757 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3758 con
->command
, con
->options
);
3762 #endif /* HAVE_JAVA */
3764 else if (!strcasecmp(type
->type
, "x-httpd-perl"))
3767 * "application/x-httpd-perl" is a Perl page.
3770 cupsdSetString(&con
->command
, CUPS_PERL
);
3773 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3775 cupsdSetStringf(&con
->options
, " %s", filename
);
3777 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3778 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3779 con
->command
, con
->options
);
3783 #endif /* HAVE_PERL */
3785 else if (!strcasecmp(type
->type
, "x-httpd-php"))
3788 * "application/x-httpd-php" is a PHP page.
3791 cupsdSetString(&con
->command
, CUPS_PHP
);
3794 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3796 cupsdSetStringf(&con
->options
, " %s", filename
);
3798 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3799 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3800 con
->command
, con
->options
);
3804 #endif /* HAVE_PHP */
3806 else if (!strcasecmp(type
->type
, "x-httpd-python"))
3809 * "application/x-httpd-python" is a Python page.
3812 cupsdSetString(&con
->command
, CUPS_PYTHON
);
3815 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3817 cupsdSetStringf(&con
->options
, " %s", filename
);
3819 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3820 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3821 con
->command
, con
->options
);
3825 #endif /* HAVE_PYTHON */
3827 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "is_cgi: Returning 0...");
3834 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
3837 static int /* O - 0 if relative, 1 if absolute */
3838 is_path_absolute(const char *path
) /* I - Input path */
3841 * Check for a leading slash...
3848 * Check for "/.." in the path...
3851 while ((path
= strstr(path
, "/..")) != NULL
)
3853 if (!path
[3] || path
[3] == '/')
3860 * If we haven't found any relative paths, return 1 indicating an
3870 * 'make_certificate()' - Make a self-signed SSL/TLS certificate.
3873 static int /* O - 1 on success, 0 on failure */
3874 make_certificate(cupsd_client_t
*con
) /* I - Client connection */
3876 #if defined(HAVE_LIBSSL) && defined(HAVE_WAITPID)
3877 int pid
, /* Process ID of command */
3878 status
; /* Status of command */
3879 char command
[1024], /* Command */
3880 *argv
[12], /* Command-line arguments */
3881 *envp
[MAX_ENV
+ 1], /* Environment variables */
3882 home
[1024], /* HOME environment variable */
3883 infofile
[1024], /* Type-in information for cert */
3884 seedfile
[1024]; /* Random number seed file */
3885 int envc
, /* Number of environment variables */
3886 bytes
; /* Bytes written */
3887 cups_file_t
*fp
; /* Seed/info file */
3888 int infofd
; /* Info file descriptor */
3892 * Run the "openssl" command to seed the random number generator and
3893 * generate a self-signed certificate that is good for 10 years:
3895 * openssl rand -rand seedfile 1
3897 * openssl req -new -x509 -keyout ServerKey \
3898 * -out ServerCertificate -days 3650 -nodes
3900 * The seeding step is crucial in ensuring that the openssl command
3901 * does not block on systems without sufficient entropy...
3904 if (!cupsFileFind("openssl", getenv("PATH"), 1, command
, sizeof(command
)))
3906 cupsdLogMessage(CUPSD_LOG_ERROR
,
3907 "No SSL certificate and openssl command not found!");
3911 if (access("/dev/urandom", 0))
3914 * If the system doesn't provide /dev/urandom, then any random source
3915 * will probably be blocking-style, so generate some random data to
3916 * use as a seed for the certificate. Note that we have already
3917 * seeded the random number generator in cupsdInitCerts()...
3920 cupsdLogMessage(CUPSD_LOG_INFO
,
3921 "Seeding the random number generator...");
3923 snprintf(home
, sizeof(home
), "HOME=%s", TempDir
);
3926 * Write the seed file...
3929 if ((fp
= cupsTempFile2(seedfile
, sizeof(seedfile
))) == NULL
)
3931 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to create seed file %s - %s",
3932 seedfile
, strerror(errno
));
3936 for (bytes
= 0; bytes
< 262144; bytes
++)
3937 cupsFilePutChar(fp
, random());
3942 * Run the openssl command to seed its random number generator...
3945 argv
[0] = "openssl";
3952 envc
= cupsdLoadEnv(envp
, MAX_ENV
);
3953 envp
[envc
++] = home
;
3956 if (!cupsdStartProcess(command
, argv
, envp
, -1, -1, -1, -1, -1, 1, NULL
,
3963 while (waitpid(pid
, &status
, 0) < 0)
3970 cupsdFinishProcess(pid
, command
, sizeof(command
));
3973 * Remove the seed file, as it is no longer needed...
3980 if (WIFEXITED(status
))
3981 cupsdLogMessage(CUPSD_LOG_ERROR
,
3982 "Unable to seed random number generator - "
3983 "the openssl command stopped with status %d!",
3984 WEXITSTATUS(status
));
3986 cupsdLogMessage(CUPSD_LOG_ERROR
,
3987 "Unable to seed random number generator - "
3988 "the openssl command crashed on signal %d!",
3996 * Create a file with the certificate information fields...
3998 * Note: This assumes that the default questions are asked by the openssl
4002 if ((fp
= cupsTempFile2(infofile
, sizeof(infofile
))) == NULL
)
4004 cupsdLogMessage(CUPSD_LOG_ERROR
,
4005 "Unable to create certificate information file %s - %s",
4006 infofile
, strerror(errno
));
4010 cupsFilePrintf(fp
, ".\n.\n.\n%s\n.\n%s\n%s\n",
4011 ServerName
, ServerName
, ServerAdmin
);
4014 cupsdLogMessage(CUPSD_LOG_INFO
,
4015 "Generating SSL server key and certificate...");
4017 argv
[0] = "openssl";
4021 argv
[4] = "-keyout";
4022 argv
[5] = ServerKey
;
4024 argv
[7] = ServerCertificate
;
4027 argv
[10] = "-nodes";
4030 cupsdLoadEnv(envp
, MAX_ENV
);
4032 infofd
= open(infofile
, O_RDONLY
);
4034 if (!cupsdStartProcess(command
, argv
, envp
, infofd
, -1, -1, -1, -1, 1, NULL
,
4045 while (waitpid(pid
, &status
, 0) < 0)
4052 cupsdFinishProcess(pid
, command
, sizeof(command
));
4056 if (WIFEXITED(status
))
4057 cupsdLogMessage(CUPSD_LOG_ERROR
,
4058 "Unable to create SSL server key and certificate - "
4059 "the openssl command stopped with status %d!",
4060 WEXITSTATUS(status
));
4062 cupsdLogMessage(CUPSD_LOG_ERROR
,
4063 "Unable to create SSL server key and certificate - "
4064 "the openssl command crashed on signal %d!",
4069 cupsdLogMessage(CUPSD_LOG_INFO
, "Created SSL server key file \"%s\"...",
4071 cupsdLogMessage(CUPSD_LOG_INFO
,
4072 "Created SSL server certificate file \"%s\"...",
4078 #elif defined(HAVE_GNUTLS)
4079 gnutls_x509_crt crt
; /* Self-signed certificate */
4080 gnutls_x509_privkey key
; /* Encryption key */
4081 cups_lang_t
*language
; /* Default language info */
4082 cups_file_t
*fp
; /* Key/cert file */
4083 unsigned char buffer
[8192]; /* Buffer for x509 data */
4084 size_t bytes
; /* Number of bytes of data */
4085 unsigned char serial
[4]; /* Serial number buffer */
4086 time_t curtime
; /* Current time */
4087 int result
; /* Result of GNU TLS calls */
4091 * Create the encryption key...
4094 cupsdLogMessage(CUPSD_LOG_INFO
, "Generating SSL server key...");
4096 gnutls_x509_privkey_init(&key
);
4097 gnutls_x509_privkey_generate(key
, GNUTLS_PK_RSA
, 2048, 0);
4103 bytes
= sizeof(buffer
);
4105 if ((result
= gnutls_x509_privkey_export(key
, GNUTLS_X509_FMT_PEM
,
4106 buffer
, &bytes
)) < 0)
4108 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to export SSL server key - %s",
4109 gnutls_strerror(result
));
4110 gnutls_x509_privkey_deinit(key
);
4113 else if ((fp
= cupsFileOpen(ServerKey
, "w")) != NULL
)
4115 cupsFileWrite(fp
, (char *)buffer
, bytes
);
4118 cupsdLogMessage(CUPSD_LOG_INFO
, "Created SSL server key file \"%s\"...",
4123 cupsdLogMessage(CUPSD_LOG_ERROR
,
4124 "Unable to create SSL server key file \"%s\" - %s",
4125 ServerKey
, strerror(errno
));
4126 gnutls_x509_privkey_deinit(key
);
4131 * Create the self-signed certificate...
4134 cupsdLogMessage(CUPSD_LOG_INFO
, "Generating self-signed SSL certificate...");
4136 language
= cupsLangDefault();
4137 curtime
= time(NULL
);
4138 serial
[0] = curtime
>> 24;
4139 serial
[1] = curtime
>> 16;
4140 serial
[2] = curtime
>> 8;
4141 serial
[3] = curtime
;
4143 gnutls_x509_crt_init(&crt
);
4144 if (strlen(language
->language
) == 5)
4145 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
4146 language
->language
+ 3, 2);
4148 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
4150 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COMMON_NAME
, 0,
4151 ServerName
, strlen(ServerName
));
4152 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATION_NAME
, 0,
4153 ServerName
, strlen(ServerName
));
4154 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATIONAL_UNIT_NAME
,
4156 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_STATE_OR_PROVINCE_NAME
, 0,
4158 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_LOCALITY_NAME
, 0,
4160 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_PKCS9_EMAIL
, 0,
4161 ServerAdmin
, strlen(ServerAdmin
));
4162 gnutls_x509_crt_set_key(crt
, key
);
4163 gnutls_x509_crt_set_serial(crt
, serial
, sizeof(serial
));
4164 gnutls_x509_crt_set_activation_time(crt
, curtime
);
4165 gnutls_x509_crt_set_expiration_time(crt
, curtime
+ 10 * 365 * 86400);
4166 gnutls_x509_crt_set_ca_status(crt
, 0);
4167 gnutls_x509_crt_set_subject_alternative_name(crt
, GNUTLS_SAN_DNSNAME
,
4169 gnutls_x509_crt_set_key_purpose_oid(crt
, GNUTLS_KP_TLS_WWW_SERVER
, 0);
4170 gnutls_x509_crt_set_key_usage(crt
, GNUTLS_KEY_KEY_ENCIPHERMENT
);
4171 gnutls_x509_crt_set_version(crt
, 3);
4173 bytes
= sizeof(buffer
);
4174 if (gnutls_x509_crt_get_key_id(crt
, 0, buffer
, &bytes
) >= 0)
4175 gnutls_x509_crt_set_subject_key_id(crt
, buffer
, bytes
);
4177 gnutls_x509_crt_sign(crt
, crt
, key
);
4183 bytes
= sizeof(buffer
);
4184 if ((result
= gnutls_x509_crt_export(crt
, GNUTLS_X509_FMT_PEM
,
4185 buffer
, &bytes
)) < 0)
4186 cupsdLogMessage(CUPSD_LOG_ERROR
,
4187 "Unable to export SSL server certificate - %s",
4188 gnutls_strerror(result
));
4189 else if ((fp
= cupsFileOpen(ServerCertificate
, "w")) != NULL
)
4191 cupsFileWrite(fp
, (char *)buffer
, bytes
);
4194 cupsdLogMessage(CUPSD_LOG_INFO
,
4195 "Created SSL server certificate file \"%s\"...",
4199 cupsdLogMessage(CUPSD_LOG_ERROR
,
4200 "Unable to create SSL server certificate file \"%s\" - %s",
4201 ServerCertificate
, strerror(errno
));
4207 gnutls_x509_crt_deinit(crt
);
4208 gnutls_x509_privkey_deinit(key
);
4212 #elif defined(HAVE_CDSASSL) && defined(HAVE_WAITPID)
4213 int pid
, /* Process ID of command */
4214 status
; /* Status of command */
4215 char command
[1024], /* Command */
4216 *argv
[4], /* Command-line arguments */
4217 *envp
[MAX_ENV
+ 1], /* Environment variables */
4218 keychain
[1024], /* Keychain argument */
4219 infofile
[1024]; /* Type-in information for cert */
4220 cups_file_t
*fp
; /* Seed/info file */
4221 int infofd
; /* Info file descriptor */
4225 * Run the "certtool" command to generate a self-signed certificate...
4228 if (!cupsFileFind("certtool", getenv("PATH"), 1, command
, sizeof(command
)))
4230 cupsdLogMessage(CUPSD_LOG_ERROR
,
4231 "No SSL certificate and certtool command not found!");
4236 * Create a file with the certificate information fields...
4238 * Note: This assumes that the default questions are asked by the certtool
4242 if ((fp
= cupsTempFile2(infofile
, sizeof(infofile
))) == NULL
)
4244 cupsdLogMessage(CUPSD_LOG_ERROR
,
4245 "Unable to create certificate information file %s - %s",
4246 infofile
, strerror(errno
));
4250 cupsFilePrintf(fp
, "%s\nr\n\ny\nb\ns\ny\n%s\n\n\n\n\n%s\ny\n",
4251 con
->servername
, con
->servername
, ServerAdmin
);
4254 cupsdLogMessage(CUPSD_LOG_INFO
,
4255 "Generating SSL server key and certificate...");
4257 snprintf(keychain
, sizeof(keychain
), "k=%s", ServerCertificate
);
4259 argv
[0] = "certtool";
4264 cupsdLoadEnv(envp
, MAX_ENV
);
4266 infofd
= open(infofile
, O_RDONLY
);
4268 if (!cupsdStartProcess(command
, argv
, envp
, infofd
, -1, -1, -1, -1, 1, NULL
,
4279 while (waitpid(pid
, &status
, 0) < 0)
4286 cupsdFinishProcess(pid
, command
, sizeof(command
));
4290 if (WIFEXITED(status
))
4291 cupsdLogMessage(CUPSD_LOG_ERROR
,
4292 "Unable to create SSL server key and certificate - "
4293 "the certtool command stopped with status %d!",
4294 WEXITSTATUS(status
));
4296 cupsdLogMessage(CUPSD_LOG_ERROR
,
4297 "Unable to create SSL server key and certificate - "
4298 "the certtool command crashed on signal %d!",
4303 cupsdLogMessage(CUPSD_LOG_INFO
,
4304 "Created SSL server certificate file \"%s\"...",
4312 #endif /* HAVE_LIBSSL && HAVE_WAITPID */
4314 #endif /* HAVE_SSL */
4318 * 'pipe_command()' - Pipe the output of a command to the remote client.
4321 static int /* O - Process ID */
4322 pipe_command(cupsd_client_t
*con
, /* I - Client connection */
4323 int infile
, /* I - Standard input for command */
4324 int *outfile
, /* O - Standard output for command */
4325 char *command
, /* I - Command to run */
4326 char *options
, /* I - Options for command */
4327 int root
) /* I - Run as root? */
4329 int i
; /* Looping var */
4330 int pid
; /* Process ID */
4331 char *commptr
, /* Command string pointer */
4332 commch
; /* Command string character */
4333 char *uriptr
; /* URI string pointer */
4334 int fds
[2]; /* Pipe FDs */
4335 int argc
; /* Number of arguments */
4336 int envc
; /* Number of environment variables */
4337 char argbuf
[10240], /* Argument buffer */
4338 *argv
[100], /* Argument strings */
4339 *envp
[MAX_ENV
+ 20]; /* Environment variables */
4340 char auth_type
[256], /* CUPSD_AUTH_TYPE environment variable */
4341 content_length
[1024], /* CONTENT_LENGTH environment variable */
4342 content_type
[1024], /* CONTENT_TYPE environment variable */
4343 http_cookie
[32768], /* HTTP_COOKIE environment variable */
4344 http_referer
[1024], /* HTTP_REFERER environment variable */
4345 http_user_agent
[1024], /* HTTP_USER_AGENT environment variable */
4346 lang
[1024], /* LANG environment variable */
4347 path_info
[1024], /* PATH_INFO environment variable */
4348 remote_addr
[1024], /* REMOTE_ADDR environment variable */
4349 remote_host
[1024], /* REMOTE_HOST environment variable */
4350 remote_user
[1024], /* REMOTE_USER environment variable */
4351 script_filename
[1024], /* SCRIPT_FILENAME environment variable */
4352 script_name
[1024], /* SCRIPT_NAME environment variable */
4353 server_name
[1024], /* SERVER_NAME environment variable */
4354 server_port
[1024]; /* SERVER_PORT environment variable */
4355 ipp_attribute_t
*attr
; /* attributes-natural-language attribute */
4357 krb5_ccache ccache
= NULL
; /* Kerberos credentials */
4358 char krb5ccname
[1024]; /* KRB5CCNAME environment variable */
4359 #endif /* HAVE_GSSAPI */
4363 * Parse a copy of the options string, which is of the form:
4365 * argument+argument+argument
4366 * ?argument+argument+argument
4367 * param=value¶m=value
4368 * ?param=value¶m=value
4369 * /name?argument+argument+argument
4370 * /name?param=value¶m=value
4372 * If the string contains an "=" character after the initial name,
4373 * then we treat it as a HTTP GET form request and make a copy of
4374 * the remaining string for the environment variable.
4376 * The string is always parsed out as command-line arguments, to
4377 * be consistent with Apache...
4380 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4381 "pipe_command: command=\"%s\", options=\"%s\"",
4382 command
, options
? options
: "(null)");
4387 strlcpy(argbuf
, options
, sizeof(argbuf
));
4391 if (argbuf
[0] == '/')
4394 * Found some trailing path information, set PATH_INFO...
4397 if ((commptr
= strchr(argbuf
, '?')) == NULL
)
4398 commptr
= argbuf
+ strlen(argbuf
);
4402 snprintf(path_info
, sizeof(path_info
), "PATH_INFO=%s", argbuf
);
4408 path_info
[0] = '\0';
4410 if (*commptr
== ' ')
4414 if (*commptr
== '?' && con
->operation
== HTTP_GET
&& !con
->query_string
)
4417 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", commptr
);
4424 argv
[argc
++] = commptr
;
4426 for (; *commptr
&& argc
< 99; commptr
++)
4429 * Break arguments whenever we see a + or space...
4432 if (*commptr
== ' ' || *commptr
== '+')
4434 while (*commptr
== ' ' || *commptr
== '+')
4438 * If we don't have a blank string, save it as another argument...
4443 argv
[argc
] = commptr
;
4449 else if (*commptr
== '%' && isxdigit(commptr
[1] & 255) &&
4450 isxdigit(commptr
[2] & 255))
4453 * Convert the %xx notation to the individual character.
4456 if (commptr
[1] >= '0' && commptr
[1] <= '9')
4457 *commptr
= (commptr
[1] - '0') << 4;
4459 *commptr
= (tolower(commptr
[1]) - 'a' + 10) << 4;
4461 if (commptr
[2] >= '0' && commptr
[2] <= '9')
4462 *commptr
|= commptr
[2] - '0';
4464 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
4466 _cups_strcpy(commptr
+ 1, commptr
+ 3);
4469 * Check for a %00 and break if that is the case...
4481 * Setup the environment variables as needed...
4484 if (con
->username
[0])
4486 snprintf(auth_type
, sizeof(auth_type
), "CUPSD_AUTH_TYPE=%s",
4487 httpGetField(HTTP(con
), HTTP_FIELD_AUTHORIZATION
));
4489 if ((uriptr
= strchr(auth_type
+ 10, ' ')) != NULL
)
4493 auth_type
[0] = '\0';
4496 (attr
= ippFindAttribute(con
->request
, "attributes-natural-language",
4497 IPP_TAG_LANGUAGE
)) != NULL
)
4499 switch (strlen(attr
->values
[0].string
.text
))
4503 * This is an unknown or badly formatted language code; use
4504 * the POSIX locale...
4507 strcpy(lang
, "LANG=C");
4512 * Just the language code (ll)...
4515 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8",
4516 attr
->values
[0].string
.text
);
4521 * Language and country code (ll-cc)...
4524 snprintf(lang
, sizeof(lang
), "LANG=%c%c_%c%c.UTF8",
4525 attr
->values
[0].string
.text
[0],
4526 attr
->values
[0].string
.text
[1],
4527 toupper(attr
->values
[0].string
.text
[3] & 255),
4528 toupper(attr
->values
[0].string
.text
[4] & 255));
4532 else if (con
->language
)
4533 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8", con
->language
->language
);
4535 strcpy(lang
, "LANG=C");
4537 strcpy(remote_addr
, "REMOTE_ADDR=");
4538 httpAddrString(con
->http
.hostaddr
, remote_addr
+ 12,
4539 sizeof(remote_addr
) - 12);
4541 snprintf(remote_host
, sizeof(remote_host
), "REMOTE_HOST=%s",
4542 con
->http
.hostname
);
4544 snprintf(script_name
, sizeof(script_name
), "SCRIPT_NAME=%s", con
->uri
);
4545 if ((uriptr
= strchr(script_name
, '?')) != NULL
)
4548 snprintf(script_filename
, sizeof(script_filename
), "SCRIPT_FILENAME=%s%s",
4549 DocumentRoot
, script_name
+ 12);
4551 sprintf(server_port
, "SERVER_PORT=%d", con
->serverport
);
4553 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
4556 envc
= cupsdLoadEnv(envp
, (int)(sizeof(envp
) / sizeof(envp
[0])));
4559 envp
[envc
++] = auth_type
;
4561 envp
[envc
++] = lang
;
4562 envp
[envc
++] = "REDIRECT_STATUS=1";
4563 envp
[envc
++] = "GATEWAY_INTERFACE=CGI/1.1";
4564 envp
[envc
++] = server_name
;
4565 envp
[envc
++] = server_port
;
4566 envp
[envc
++] = remote_addr
;
4567 envp
[envc
++] = remote_host
;
4568 envp
[envc
++] = script_name
;
4569 envp
[envc
++] = script_filename
;
4572 envp
[envc
++] = path_info
;
4574 if (con
->username
[0])
4576 snprintf(remote_user
, sizeof(remote_user
), "REMOTE_USER=%s", con
->username
);
4578 envp
[envc
++] = remote_user
;
4581 * Save Kerberos credentials, if any...
4585 if (con
->gss_have_creds
)
4587 # if !defined(HAVE_KRB5_CC_NEW_UNIQUE) && !defined(HAVE_HEIMDAL)
4588 cupsdLogMessage(CUPSD_LOG_INFO
,
4589 "Sorry, your version of Kerberos does not support "
4590 "delegated credentials!");
4593 krb5_error_code error
; /* Kerberos error code */
4594 OM_uint32 major_status
, /* Major status code */
4595 minor_status
; /* Minor status code */
4596 krb5_principal principal
; /* Kerberos principal */
4601 * If the weak-linked GSSAPI/Kerberos library is not present, don't try
4605 if (krb5_init_context
!= NULL
)
4607 # endif /* __APPLE__ */
4610 * We MUST create a file-based cache because memory-based caches are
4611 * only valid for the current process/address space.
4613 * Due to various bugs/features in different versions of Kerberos, we
4614 * need either the krb5_cc_new_unique() function or Heimdal's version
4615 * of krb5_cc_gen_new() to create a new FILE: credential cache that
4616 * can be passed to the backend. These functions create a temporary
4617 * file (typically in /tmp) containing the cached credentials, which
4618 * are removed when we have successfully printed a job.
4621 # ifdef HAVE_KRB5_CC_NEW_UNIQUE
4622 if ((error
= krb5_cc_new_unique(KerberosContext
, "FILE", NULL
,
4624 # else /* HAVE_HEIMDAL */
4625 if ((error
= krb5_cc_gen_new(KerberosContext
, &krb5_fcc_ops
,
4627 # endif /* HAVE_KRB5_CC_NEW_UNIQUE */
4629 cupsdLogMessage(CUPSD_LOG_ERROR
,
4630 "Unable to create new credentials cache (%d/%s)",
4631 error
, strerror(errno
));
4634 else if ((error
= krb5_parse_name(KerberosContext
, con
->username
,
4637 cupsdLogMessage(CUPSD_LOG_ERROR
,
4638 "Unable to parse kerberos username (%d/%s)", error
,
4640 krb5_cc_destroy(KerberosContext
, ccache
);
4643 else if ((error
= krb5_cc_initialize(KerberosContext
, ccache
,
4646 cupsdLogMessage(CUPSD_LOG_ERROR
,
4647 "Unable to initialize credentials cache (%d/%s)", error
,
4649 krb5_cc_destroy(KerberosContext
, ccache
);
4650 krb5_free_principal(KerberosContext
, principal
);
4655 krb5_free_principal(KerberosContext
, principal
);
4658 * Copy the user's credentials to the new cache file...
4661 major_status
= gss_krb5_copy_ccache(&minor_status
,
4662 con
->gss_delegated_cred
, ccache
);
4664 if (GSS_ERROR(major_status
))
4666 cupsdLogGSSMessage(CUPSD_LOG_ERROR
, major_status
, minor_status
,
4667 "Unable to import client credentials cache");
4668 krb5_cc_destroy(KerberosContext
, ccache
);
4674 * Add the KRB5CCNAME environment variable to the job so that the
4675 * backend can use the credentials when printing.
4678 snprintf(krb5ccname
, sizeof(krb5ccname
), "KRB5CCNAME=FILE:%s",
4679 krb5_cc_get_name(KerberosContext
, ccache
));
4680 envp
[envc
++] = krb5ccname
;
4683 chown(krb5_cc_get_name(KerberosContext
, ccache
), User
, Group
);
4688 # endif /* __APPLE__ */
4689 # endif /* HAVE_KRB5_CC_NEW_UNIQUE || HAVE_HEIMDAL */
4691 #endif /* HAVE_GSSAPI */
4695 if (con
->http
.version
== HTTP_1_1
)
4696 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.1";
4697 else if (con
->http
.version
== HTTP_1_0
)
4698 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.0";
4700 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/0.9";
4702 if (con
->http
.cookie
)
4704 snprintf(http_cookie
, sizeof(http_cookie
), "HTTP_COOKIE=%s",
4706 envp
[envc
++] = http_cookie
;
4709 if (con
->http
.fields
[HTTP_FIELD_USER_AGENT
][0])
4711 snprintf(http_user_agent
, sizeof(http_user_agent
), "HTTP_USER_AGENT=%s",
4712 con
->http
.fields
[HTTP_FIELD_USER_AGENT
]);
4713 envp
[envc
++] = http_user_agent
;
4716 if (con
->http
.fields
[HTTP_FIELD_REFERER
][0])
4718 snprintf(http_referer
, sizeof(http_referer
), "HTTP_REFERER=%s",
4719 con
->http
.fields
[HTTP_FIELD_REFERER
]);
4720 envp
[envc
++] = http_referer
;
4723 if (con
->operation
== HTTP_GET
)
4725 envp
[envc
++] = "REQUEST_METHOD=GET";
4727 if (con
->query_string
)
4730 * Add GET form variables after ?...
4733 envp
[envc
++] = con
->query_string
;
4736 envp
[envc
++] = "QUERY_STRING=";
4740 sprintf(content_length
, "CONTENT_LENGTH=" CUPS_LLFMT
,
4741 CUPS_LLCAST con
->bytes
);
4742 snprintf(content_type
, sizeof(content_type
), "CONTENT_TYPE=%s",
4743 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
4745 envp
[envc
++] = "REQUEST_METHOD=POST";
4746 envp
[envc
++] = content_length
;
4747 envp
[envc
++] = content_type
;
4751 * Tell the CGI if we are using encryption...
4755 envp
[envc
++] = "HTTPS=ON";
4758 * Terminate the environment array...
4763 if (LogLevel
== CUPSD_LOG_DEBUG2
)
4765 for (i
= 0; i
< argc
; i
++)
4766 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4767 "pipe_command: argv[%d] = \"%s\"", i
, argv
[i
]);
4768 for (i
= 0; i
< envc
; i
++)
4769 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4770 "pipe_command: envp[%d] = \"%s\"", i
, envp
[i
]);
4774 * Create a pipe for the output...
4777 if (cupsdOpenPipe(fds
))
4779 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to create pipes for CGI %s - %s",
4780 argv
[0], strerror(errno
));
4785 * Then execute the command...
4788 if (cupsdStartProcess(command
, argv
, envp
, infile
, fds
[1], CGIPipes
[1],
4789 -1, -1, root
, DefaultProfile
, &pid
) < 0)
4792 * Error - can't fork!
4795 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to fork for CGI %s - %s", argv
[0],
4798 cupsdClosePipe(fds
);
4804 * Fork successful - return the PID...
4807 if (con
->username
[0])
4809 cupsdAddCert(pid
, con
->username
, ccache
);
4811 cupsdAddCert(pid
, con
->username
, NULL
);
4812 #endif /* HAVE_GSSAPI */
4814 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[CGI] %s started - PID = %d",
4826 * 'write_file()' - Send a file via HTTP.
4829 static int /* O - 0 on failure, 1 on success */
4830 write_file(cupsd_client_t
*con
, /* I - Client connection */
4831 http_status_t code
, /* I - HTTP status */
4832 char *filename
, /* I - Filename */
4833 char *type
, /* I - File type */
4834 struct stat
*filestats
) /* O - File information */
4836 con
->file
= open(filename
, O_RDONLY
);
4838 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "write_file: %d file=%d", con
->http
.fd
,
4844 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
4848 if (!cupsdSendHeader(con
, code
, type
, CUPSD_AUTH_NONE
))
4851 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
4852 httpGetDateString(filestats
->st_mtime
)) < 0)
4854 if (httpPrintf(HTTP(con
), "Content-Length: " CUPS_LLFMT
"\r\n",
4855 CUPS_LLCAST filestats
->st_size
) < 0)
4857 if (httpPrintf(HTTP(con
), "\r\n") < 0)
4860 if (cupsdFlushHeader(con
) < 0)
4863 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
4864 con
->http
.data_remaining
= filestats
->st_size
;
4866 if (con
->http
.data_remaining
<= INT_MAX
)
4867 con
->http
._data_remaining
= con
->http
.data_remaining
;
4869 con
->http
._data_remaining
= INT_MAX
;
4871 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
,
4872 (cupsd_selfunc_t
)cupsdWriteClient
, con
);
4879 * 'write_pipe()' - Flag that data is available on the CGI pipe.
4883 write_pipe(cupsd_client_t
*con
) /* I - Client connection */
4885 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "write_pipe: CGI output on fd %d...",
4888 con
->file_ready
= 1;
4890 cupsdRemoveSelect(con
->file
);
4891 cupsdAddSelect(con
->http
.fd
, NULL
, (cupsd_selfunc_t
)cupsdWriteClient
, con
);
4896 * End of "$Id: client.c 6999 2007-09-28 19:46:53Z mike $".