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 by Apple Inc.
7 * Copyright 1997-2007 by Easy Software Products, all rights reserved.
9 * This file contains Kerberos support code, copyright 2006 by
12 * These coded instructions, statements, and computer programs are the
13 * property of Apple Inc. and are protected by Federal copyright
14 * law. Distribution and use rights are outlined in the file "LICENSE.txt"
15 * which should have been included with this file. If this file is
16 * file is missing or damaged, see the license at "http://www.cups.org/".
20 * cupsdAcceptClient() - Accept a new client.
21 * cupsdCloseAllClients() - Close all remote clients immediately.
22 * cupsdCloseClient() - Close a remote client.
23 * cupsdFlushHeader() - Flush the header fields to the client.
24 * cupsdReadClient() - Read data from a client.
25 * cupsdSendCommand() - Send output from a command via HTTP.
26 * cupsdSendError() - Send an error message via HTTP.
27 * cupsdSendHeader() - Send an HTTP request.
28 * cupsdUpdateCGI() - Read status messages from CGI scripts and programs.
29 * cupsdWriteClient() - Write data to a client as needed.
30 * check_if_modified() - Decode an "If-Modified-Since" line.
31 * encrypt_client() - Enable encryption for the client...
32 * get_cdsa_certificate() - Convert a keychain name into the CFArrayRef
33 * required by SSLSetCertificate.
34 * get_file() - Get a filename and state info.
35 * install_conf_file() - Install a configuration file.
36 * is_cgi() - Is the resource a CGI script/program?
37 * is_path_absolute() - Is a path absolute and free of relative elements.
38 * make_certificate() - Make a self-signed SSL/TLS certificate.
39 * pipe_command() - Pipe the output of a command to the remote client.
40 * write_file() - Send a file via HTTP.
41 * write_pipe() - Flag that data is available on the CGI pipe.
45 * Include necessary headers...
48 #include <cups/http-private.h>
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
);
87 static int encrypt_client(cupsd_client_t
*con
);
90 static CFArrayRef
get_cdsa_certificate(cupsd_client_t
*con
);
91 #endif /* HAVE_CDSASSL */
92 static char *get_file(cupsd_client_t
*con
, struct stat
*filestats
,
93 char *filename
, int len
);
94 static http_status_t
install_conf_file(cupsd_client_t
*con
);
95 static int is_cgi(cupsd_client_t
*con
, const char *filename
,
96 struct stat
*filestats
, mime_type_t
*type
);
97 static int is_path_absolute(const char *path
);
99 static int make_certificate(cupsd_client_t
*con
);
100 #endif /* HAVE_SSL */
101 static int pipe_command(cupsd_client_t
*con
, int infile
, int *outfile
,
102 char *command
, char *options
, int root
);
103 static int write_file(cupsd_client_t
*con
, http_status_t code
,
104 char *filename
, char *type
,
105 struct stat
*filestats
);
106 static void write_pipe(cupsd_client_t
*con
);
110 * 'cupsdAcceptClient()' - Accept a new client.
114 cupsdAcceptClient(cupsd_listener_t
*lis
)/* I - Listener socket */
116 int count
; /* Count of connections on a host */
117 int val
; /* Parameter value */
118 cupsd_client_t
*con
, /* New client pointer */
119 *tempcon
; /* Temporary client pointer */
120 http_addrlist_t
*addrlist
, /* List of adddresses for host */
121 *addr
; /* Current address */
122 socklen_t addrlen
; /* Length of address */
123 char *hostname
; /* Hostname for address */
124 http_addr_t temp
; /* Temporary address variable */
125 static time_t last_dos
= 0; /* Time of last DoS attack */
128 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
129 "cupsdAcceptClient(lis=%p) %d Clients = %d",
130 lis
, lis
->fd
, cupsArrayCount(Clients
));
133 * Make sure we don't have a full set of clients already...
136 if (cupsArrayCount(Clients
) == MaxClients
)
140 * Get a pointer to the next available client...
144 Clients
= cupsArrayNew(NULL
, NULL
);
149 con
= calloc(1, sizeof(cupsd_client_t
));
151 con
->http
.activity
= time(NULL
);
153 con
->http
.hostaddr
= &(con
->clientaddr
);
156 * Accept the client and get the remote address...
159 addrlen
= sizeof(http_addr_t
);
161 if ((con
->http
.fd
= accept(lis
->fd
, (struct sockaddr
*)con
->http
.hostaddr
,
164 if (errno
== ENFILE
|| errno
== EMFILE
)
165 cupsdPauseListening();
167 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to accept client connection - %s.",
175 if (lis
->address
.addr
.sa_family
== AF_INET6
)
178 * Save the connected port number...
181 con
->http
.hostaddr
->ipv6
.sin6_port
= lis
->address
.ipv6
.sin6_port
;
184 * Convert IPv4 over IPv6 addresses (::ffff:n.n.n.n) to IPv4 forms we
185 * can more easily use...
188 if (con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[0] == 0 &&
189 con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[1] == 0 &&
190 ntohl(con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[2]) == 0xffff)
191 con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[2] = 0;
194 #endif /* AF_INET6 */
195 if (lis
->address
.addr
.sa_family
== AF_INET
)
196 con
->http
.hostaddr
->ipv4
.sin_port
= lis
->address
.ipv4
.sin_port
;
199 * Check the number of clients on the same address...
202 for (count
= 0, tempcon
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
204 tempcon
= (cupsd_client_t
*)cupsArrayNext(Clients
))
205 if (httpAddrEqual(tempcon
->http
.hostaddr
, con
->http
.hostaddr
))
208 if (count
>= MaxClientsPerHost
)
212 if (count
>= MaxClientsPerHost
)
214 if ((time(NULL
) - last_dos
) >= 60)
216 last_dos
= time(NULL
);
217 cupsdLogMessage(CUPSD_LOG_WARN
,
218 "Possible DoS attack - more than %d clients connecting "
220 MaxClientsPerHost
, tempcon
->http
.hostname
);
224 closesocket(con
->http
.fd
);
234 * Get the hostname or format the IP address as needed...
237 if (httpAddrLocalhost(con
->http
.hostaddr
))
240 * Map accesses from the loopback interface to "localhost"...
243 strlcpy(con
->http
.hostname
, "localhost", sizeof(con
->http
.hostname
));
244 hostname
= con
->http
.hostname
;
249 * Map accesses from the same host to the server name.
252 for (addr
= ServerAddrs
; addr
; addr
= addr
->next
)
253 if (httpAddrEqual(con
->http
.hostaddr
, &(addr
->addr
)))
258 strlcpy(con
->http
.hostname
, ServerName
, sizeof(con
->http
.hostname
));
259 hostname
= con
->http
.hostname
;
261 else if (HostNameLookups
)
262 hostname
= httpAddrLookup(con
->http
.hostaddr
, con
->http
.hostname
,
263 sizeof(con
->http
.hostname
));
267 httpAddrString(con
->http
.hostaddr
, con
->http
.hostname
,
268 sizeof(con
->http
.hostname
));
272 if (hostname
== NULL
&& HostNameLookups
== 2)
275 * Can't have an unresolved IP address with double-lookups enabled...
278 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
279 "cupsdAcceptClient: Closing connection %d...",
283 closesocket(con
->http
.fd
);
288 cupsdLogMessage(CUPSD_LOG_WARN
,
289 "Name lookup failed - connection from %s closed!",
296 if (HostNameLookups
== 2)
299 * Do double lookups as needed...
302 if ((addrlist
= httpAddrGetList(con
->http
.hostname
, AF_UNSPEC
, NULL
)) != NULL
)
305 * See if the hostname maps to the same IP address...
308 for (addr
= addrlist
; addr
; addr
= addr
->next
)
309 if (httpAddrEqual(con
->http
.hostaddr
, &(addr
->addr
)))
315 httpAddrFreeList(addrlist
);
320 * Can't have a hostname that doesn't resolve to the same IP address
321 * with double-lookups enabled...
324 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
325 "cupsdAcceptClient: Closing connection %d...",
329 closesocket(con
->http
.fd
);
334 cupsdLogMessage(CUPSD_LOG_WARN
,
335 "IP lookup failed - connection from %s closed!",
343 if (con
->http
.hostaddr
->addr
.sa_family
== AF_INET6
)
344 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdAcceptClient: %d from %s:%d (IPv6)",
345 con
->http
.fd
, con
->http
.hostname
,
346 ntohs(con
->http
.hostaddr
->ipv6
.sin6_port
));
348 #endif /* AF_INET6 */
350 if (con
->http
.hostaddr
->addr
.sa_family
== AF_LOCAL
)
351 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdAcceptClient: %d from %s (Domain)",
352 con
->http
.fd
, con
->http
.hostname
);
354 #endif /* AF_LOCAL */
355 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdAcceptClient: %d from %s:%d (IPv4)",
356 con
->http
.fd
, con
->http
.hostname
,
357 ntohs(con
->http
.hostaddr
->ipv4
.sin_port
));
360 * Get the local address the client connected to...
363 addrlen
= sizeof(temp
);
364 if (getsockname(con
->http
.fd
, (struct sockaddr
*)&temp
, &addrlen
))
366 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to get local address - %s",
369 strcpy(con
->servername
, "localhost");
370 con
->serverport
= LocalPort
;
375 if (temp
.addr
.sa_family
== AF_INET6
)
377 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
378 con
->serverport
= ntohs(lis
->address
.ipv6
.sin6_port
);
381 #endif /* AF_INET6 */
382 if (temp
.addr
.sa_family
== AF_INET
)
384 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
385 con
->serverport
= ntohs(lis
->address
.ipv4
.sin_port
);
389 strcpy(con
->servername
, "localhost");
390 con
->serverport
= LocalPort
;
394 cupsArrayAdd(Clients
, con
);
396 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
397 "cupsdAcceptClient: %d connected to server on %s:%d",
398 con
->http
.fd
, con
->servername
, con
->serverport
);
401 * Using TCP_NODELAY improves responsiveness, especially on systems
402 * with a slow loopback interface... Since we write large buffers
403 * when sending print files and requests, there shouldn't be any
404 * performance penalty for this...
408 setsockopt(con
->http
.fd
, IPPROTO_TCP
, TCP_NODELAY
, &val
, sizeof(val
));
411 * Close this file on all execs...
414 fcntl(con
->http
.fd
, F_SETFD
, fcntl(con
->http
.fd
, F_GETFD
) | FD_CLOEXEC
);
417 * Add the socket to the select() input mask.
420 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
423 * Temporarily suspend accept()'s until we lose a client...
426 if (cupsArrayCount(Clients
) == MaxClients
)
427 cupsdPauseListening();
431 * See if we are connecting on a secure port...
434 if (lis
->encryption
== HTTP_ENCRYPT_ALWAYS
)
437 * https connection; go secure...
440 con
->http
.encryption
= HTTP_ENCRYPT_ALWAYS
;
442 if (!encrypt_client(con
))
443 cupsdCloseClient(con
);
447 #endif /* HAVE_SSL */
452 * 'cupsdCloseAllClients()' - Close all remote clients immediately.
456 cupsdCloseAllClients(void)
458 cupsd_client_t
*con
; /* Current client */
461 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
463 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
464 cupsdCloseClient(con
);
469 * 'cupsdCloseClient()' - Close a remote client.
472 int /* O - 1 if partial close, 0 if fully closed */
473 cupsdCloseClient(cupsd_client_t
*con
) /* I - Client to close */
475 int partial
; /* Do partial close for SSL? */
477 SSL_CTX
*context
; /* Context for encryption */
478 SSL
*conn
; /* Connection for encryption */
479 unsigned long error
; /* Error code */
480 #elif defined(HAVE_GNUTLS)
481 http_tls_t
*conn
; /* TLS connection information */
482 int error
; /* Error code */
483 gnutls_certificate_server_credentials
*credentials
;
484 /* TLS credentials */
485 # elif defined(HAVE_CDSASSL)
486 http_tls_t
*conn
; /* CDSA connection information */
487 #endif /* HAVE_LIBSSL */
490 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdCloseClient: %d", con
->http
.fd
);
493 * Flush pending writes before closing...
496 httpFlushWrite(HTTP(con
));
502 * Shutdown encryption as needed...
510 conn
= (SSL
*)(con
->http
.tls
);
511 context
= SSL_get_SSL_CTX(conn
);
513 switch (SSL_shutdown(conn
))
516 cupsdLogMessage(CUPSD_LOG_INFO
,
517 "cupsdCloseClient: SSL shutdown successful!");
520 cupsdLogMessage(CUPSD_LOG_ERROR
,
521 "cupsdCloseClient: Fatal error during SSL shutdown!");
523 while ((error
= ERR_get_error()) != 0)
524 cupsdLogMessage(CUPSD_LOG_ERROR
, "cupsdCloseClient: %s",
525 ERR_error_string(error
, NULL
));
529 SSL_CTX_free(context
);
532 # elif defined(HAVE_GNUTLS)
533 conn
= (http_tls_t
*)(con
->http
.tls
);
534 credentials
= (gnutls_certificate_server_credentials
*)(conn
->credentials
);
536 error
= gnutls_bye(conn
->session
, GNUTLS_SHUT_WR
);
539 case GNUTLS_E_SUCCESS
:
540 cupsdLogMessage(CUPSD_LOG_INFO
,
541 "cupsdCloseClient: SSL shutdown successful!");
544 cupsdLogMessage(CUPSD_LOG_ERROR
,
545 "cupsdCloseClient: %s", gnutls_strerror(error
));
549 gnutls_deinit(conn
->session
);
550 gnutls_certificate_free_credentials(*credentials
);
554 # elif defined(HAVE_CDSASSL)
555 conn
= (http_tls_t
*)(con
->http
.tls
);
557 while (SSLClose(conn
->session
) == errSSLWouldBlock
)
560 SSLDisposeContext(conn
->session
);
562 if (conn
->certsArray
)
563 CFRelease(conn
->certsArray
);
566 # endif /* HAVE_LIBSSL */
568 con
->http
.tls
= NULL
;
570 #endif /* HAVE_SSL */
572 if (con
->pipe_pid
!= 0)
575 * Stop any CGI process...
578 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
579 "cupsdCloseClient: %d Killing process ID %d...",
580 con
->http
.fd
, con
->pipe_pid
);
581 cupsdEndProcess(con
->pipe_pid
, 1);
587 cupsdRemoveSelect(con
->file
);
589 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
590 "cupsdCloseClient: %d Closing data file %d.",
591 con
->http
.fd
, con
->file
);
598 * Close the socket and clear the file from the input set for select()...
601 if (con
->http
.fd
> 0)
606 * Only do a partial close so that the encrypted client gets everything.
609 shutdown(con
->http
.fd
, 0);
610 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
615 * Shut the socket down fully...
618 cupsdRemoveSelect(con
->http
.fd
);
630 if (con
->http
.input_set
)
631 free(con
->http
.input_set
);
633 httpClearCookie(HTTP(con
));
635 cupsdClearString(&con
->filename
);
636 cupsdClearString(&con
->command
);
637 cupsdClearString(&con
->options
);
638 cupsdClearString(&con
->query_string
);
642 ippDelete(con
->request
);
648 ippDelete(con
->response
);
649 con
->response
= NULL
;
654 cupsLangFree(con
->language
);
655 con
->language
= NULL
;
658 #ifdef HAVE_AUTHORIZATION_H
661 AuthorizationFree(con
->authref
, kAuthorizationFlagDefaults
);
664 #endif /* HAVE_AUTHORIZATION_H */
667 * Re-enable new client connections if we are going back under the
671 if (cupsArrayCount(Clients
) == MaxClients
)
672 cupsdResumeListening();
675 * Compact the list of clients as necessary...
678 cupsArrayRemove(Clients
, con
);
688 * 'cupsdFlushHeader()' - Flush the header fields to the client.
691 int /* I - Bytes written or -1 on error */
692 cupsdFlushHeader(cupsd_client_t
*con
) /* I - Client to flush to */
694 int bytes
= httpFlushWrite(HTTP(con
));
696 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
703 * 'cupsdReadClient()' - Read data from a client.
707 cupsdReadClient(cupsd_client_t
*con
) /* I - Client to read from */
709 char line
[32768], /* Line from client... */
710 operation
[64], /* Operation code from socket */
711 version
[64], /* HTTP version number string */
712 locale
[64], /* Locale */
713 *ptr
; /* Pointer into strings */
714 int major
, minor
; /* HTTP version numbers */
715 http_status_t status
; /* Transfer status */
716 ipp_state_t ipp_state
; /* State of IPP transfer */
717 int bytes
; /* Number of bytes to POST */
718 char *filename
; /* Name of file for GET/HEAD */
719 char buf
[1024]; /* Buffer for real filename */
720 struct stat filestats
; /* File information */
721 mime_type_t
*type
; /* MIME type of file */
722 cupsd_printer_t
*p
; /* Printer */
723 static unsigned request_id
= 0; /* Request ID for temp files */
726 status
= HTTP_CONTINUE
;
728 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
729 "cupsdReadClient: %d, used=%d, file=%d state=%d",
730 con
->http
.fd
, con
->http
.used
, con
->file
, con
->http
.state
);
734 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdReadClient: http error seen...");
735 cupsdCloseClient(con
);
743 * Automatically check for a SSL/TLS handshake...
748 if (recv(con
->http
.fd
, buf
, 1, MSG_PEEK
) == 1 &&
749 (!buf
[0] || !strchr("DGHOPT", buf
[0])))
752 * Encrypt this connection...
755 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
756 "cupsdReadClient: Saw first byte %02X, auto-negotiating SSL/TLS session...",
759 if (!encrypt_client(con
))
760 cupsdCloseClient(con
);
765 #endif /* HAVE_SSL */
767 switch (con
->http
.state
)
771 * See if we've received a request line...
774 if (httpGets(line
, sizeof(line
) - 1, HTTP(con
)) == NULL
)
776 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
777 "cupsdReadClient: httpGets returned EOF...");
778 cupsdCloseClient(con
);
783 * Ignore blank request lines...
790 * Clear other state variables...
793 httpClearFields(HTTP(con
));
795 con
->http
.activity
= time(NULL
);
796 con
->http
.version
= HTTP_1_0
;
797 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
798 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
799 con
->http
.data_remaining
= 0;
800 con
->http
._data_remaining
= 0;
801 con
->operation
= HTTP_WAITING
;
806 con
->username
[0] = '\0';
807 con
->password
[0] = '\0';
810 cupsdClearString(&con
->command
);
811 cupsdClearString(&con
->options
);
812 cupsdClearString(&con
->query_string
);
816 ippDelete(con
->request
);
822 ippDelete(con
->response
);
823 con
->response
= NULL
;
828 cupsLangFree(con
->language
);
829 con
->language
= NULL
;
833 con
->gss_have_creds
= 0;
834 #endif /* HAVE_GSSAPI */
837 * Grab the request line...
840 switch (sscanf(line
, "%63s%1023s%63s", operation
, con
->uri
, version
))
843 cupsdLogMessage(CUPSD_LOG_ERROR
,
844 "Bad request line \"%s\" from %s!", line
,
846 cupsdSendError(con
, HTTP_BAD_REQUEST
, AUTH_NONE
);
847 cupsdCloseClient(con
);
850 con
->http
.version
= HTTP_0_9
;
853 if (sscanf(version
, "HTTP/%d.%d", &major
, &minor
) != 2)
855 cupsdLogMessage(CUPSD_LOG_ERROR
,
856 "Bad request line \"%s\" from %s!", line
,
858 cupsdSendError(con
, HTTP_BAD_REQUEST
, AUTH_NONE
);
859 cupsdCloseClient(con
);
865 con
->http
.version
= (http_version_t
)(major
* 100 + minor
);
866 if (con
->http
.version
== HTTP_1_1
&& KeepAlive
)
867 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
869 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
873 cupsdSendError(con
, HTTP_NOT_SUPPORTED
, AUTH_NONE
);
874 cupsdCloseClient(con
);
881 * Handle full URLs in the request line...
884 if (strcmp(con
->uri
, "*"))
886 char method
[HTTP_MAX_URI
], /* Method/scheme */
887 userpass
[HTTP_MAX_URI
], /* Username:password */
888 hostname
[HTTP_MAX_URI
], /* Hostname */
889 resource
[HTTP_MAX_URI
]; /* Resource path */
890 int port
; /* Port number */
894 * Separate the URI into its components...
897 httpSeparateURI(HTTP_URI_CODING_MOST
, con
->uri
,
898 method
, sizeof(method
),
899 userpass
, sizeof(userpass
),
900 hostname
, sizeof(hostname
), &port
,
901 resource
, sizeof(resource
));
904 * Only allow URIs with the servername, localhost, or an IP
908 if (strcmp(method
, "file") &&
909 strcasecmp(hostname
, ServerName
) &&
910 strcasecmp(hostname
, "localhost") &&
911 !isdigit(hostname
[0]))
914 * Nope, we don't do proxies...
917 cupsdLogMessage(CUPSD_LOG_ERROR
, "Bad URI \"%s\" in request!",
919 cupsdSendError(con
, HTTP_METHOD_NOT_ALLOWED
, AUTH_NONE
);
920 cupsdCloseClient(con
);
925 * Copy the resource portion back into the URI; both resource and
926 * con->uri are HTTP_MAX_URI bytes in size...
929 strcpy(con
->uri
, resource
);
933 * Process the request...
936 if (!strcmp(operation
, "GET"))
937 con
->http
.state
= HTTP_GET
;
938 else if (!strcmp(operation
, "PUT"))
939 con
->http
.state
= HTTP_PUT
;
940 else if (!strcmp(operation
, "POST"))
941 con
->http
.state
= HTTP_POST
;
942 else if (!strcmp(operation
, "DELETE"))
943 con
->http
.state
= HTTP_DELETE
;
944 else if (!strcmp(operation
, "TRACE"))
945 con
->http
.state
= HTTP_TRACE
;
946 else if (!strcmp(operation
, "OPTIONS"))
947 con
->http
.state
= HTTP_OPTIONS
;
948 else if (!strcmp(operation
, "HEAD"))
949 con
->http
.state
= HTTP_HEAD
;
952 cupsdLogMessage(CUPSD_LOG_ERROR
, "Bad operation \"%s\"!", operation
);
953 cupsdSendError(con
, HTTP_BAD_REQUEST
, AUTH_NONE
);
954 cupsdCloseClient(con
);
958 con
->start
= time(NULL
);
959 con
->operation
= con
->http
.state
;
961 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdReadClient: %d %s %s HTTP/%d.%d",
962 con
->http
.fd
, operation
, con
->uri
,
963 con
->http
.version
/ 100, con
->http
.version
% 100);
965 con
->http
.status
= HTTP_OK
;
975 * Parse incoming parameters until the status changes...
978 while ((status
= httpUpdate(HTTP(con
))) == HTTP_CONTINUE
)
979 if (con
->http
.used
== 0 ||
980 !memchr(con
->http
.buffer
, '\n', con
->http
.used
))
983 if (status
!= HTTP_OK
&& status
!= HTTP_CONTINUE
)
985 cupsdSendError(con
, HTTP_BAD_REQUEST
, AUTH_NONE
);
986 cupsdCloseClient(con
);
992 break; /* Anti-compiler-warning-code */
996 * Handle new transfers...
999 if (status
== HTTP_OK
)
1001 if (con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
][0])
1004 * Figure out the locale from the Accept-Language and Content-Type
1008 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ',')) != NULL
)
1011 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ';')) != NULL
)
1014 if ((ptr
= strstr(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
], "charset=")) != NULL
)
1017 * Combine language and charset, and trim any extra params in the
1021 snprintf(locale
, sizeof(locale
), "%s.%s",
1022 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ptr
+ 8);
1024 if ((ptr
= strchr(locale
, ',')) != NULL
)
1028 snprintf(locale
, sizeof(locale
), "%s.%s",
1029 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], DefaultCharset
);
1031 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1032 "cupsdReadClient: %d Browser asked for language \"%s\"...",
1033 con
->http
.fd
, locale
);
1035 con
->language
= cupsLangGet(locale
);
1038 con
->language
= cupsLangGet(DefaultLocale
);
1040 cupsdAuthorize(con
);
1042 if (!strncmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Keep-Alive", 10) &&
1044 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
1046 if (!con
->http
.fields
[HTTP_FIELD_HOST
][0] &&
1047 con
->http
.version
>= HTTP_1_1
)
1050 * HTTP/1.1 and higher require the "Host:" field...
1053 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, AUTH_NONE
))
1055 cupsdCloseClient(con
);
1059 else if (con
->operation
== HTTP_OPTIONS
)
1062 * Do OPTIONS command...
1065 if (con
->best
&& con
->best
->type
!= AUTH_NONE
)
1067 if (!cupsdSendHeader(con
, HTTP_UNAUTHORIZED
, NULL
, AUTH_NONE
))
1069 cupsdCloseClient(con
);
1074 if (!strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") &&
1075 con
->http
.tls
== NULL
)
1079 * Do encryption stuff...
1082 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
, AUTH_NONE
))
1084 cupsdCloseClient(con
);
1088 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1089 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1090 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1091 httpPrintf(HTTP(con
), "\r\n");
1093 if (cupsdFlushHeader(con
) < 0)
1095 cupsdCloseClient(con
);
1099 if (!encrypt_client(con
))
1101 cupsdCloseClient(con
);
1105 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, AUTH_NONE
))
1107 cupsdCloseClient(con
);
1110 #endif /* HAVE_SSL */
1113 if (!cupsdSendHeader(con
, HTTP_OK
, NULL
, AUTH_NONE
))
1115 cupsdCloseClient(con
);
1119 httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n");
1120 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1121 httpPrintf(HTTP(con
), "\r\n");
1123 if (cupsdFlushHeader(con
) < 0)
1125 cupsdCloseClient(con
);
1129 else if (!is_path_absolute(con
->uri
))
1132 * Protect against malicious users!
1135 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, AUTH_NONE
))
1137 cupsdCloseClient(con
);
1143 if (!strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") &&
1144 con
->http
.tls
== NULL
)
1148 * Do encryption stuff...
1151 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
, AUTH_NONE
))
1153 cupsdCloseClient(con
);
1157 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1158 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1159 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1160 httpPrintf(HTTP(con
), "\r\n");
1162 if (cupsdFlushHeader(con
) < 0)
1164 cupsdCloseClient(con
);
1168 if (!encrypt_client(con
))
1170 cupsdCloseClient(con
);
1174 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, AUTH_NONE
))
1176 cupsdCloseClient(con
);
1179 #endif /* HAVE_SSL */
1182 if ((status
= cupsdIsAuthorized(con
, NULL
)) != HTTP_OK
)
1184 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1185 "cupsdReadClient: Unauthorized request for %s...\n",
1187 cupsdSendError(con
, status
, AUTH_NONE
);
1188 cupsdCloseClient(con
);
1192 if (con
->http
.expect
&&
1193 (con
->operation
== HTTP_POST
|| con
->operation
== HTTP_PUT
))
1195 if (con
->http
.expect
== HTTP_CONTINUE
)
1198 * Send 100-continue header...
1201 if (!cupsdSendHeader(con
, HTTP_CONTINUE
, NULL
, AUTH_NONE
))
1203 cupsdCloseClient(con
);
1210 * Send 417-expectation-failed header...
1213 if (!cupsdSendHeader(con
, HTTP_EXPECTATION_FAILED
, NULL
, AUTH_NONE
))
1215 cupsdCloseClient(con
);
1219 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1220 httpPrintf(HTTP(con
), "\r\n");
1222 if (cupsdFlushHeader(con
) < 0)
1224 cupsdCloseClient(con
);
1230 switch (con
->http
.state
)
1232 case HTTP_GET_SEND
:
1233 if (!strncmp(con
->uri
, "/printers/", 10) &&
1234 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1237 * Send PPD file - get the real printer name since printer
1238 * names are not case sensitive but filenames can be...
1241 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1243 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1244 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1247 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, AUTH_NONE
))
1249 cupsdCloseClient(con
);
1257 if ((!strncmp(con
->uri
, "/admin", 6) &&
1258 strncmp(con
->uri
, "/admin/conf/", 12) &&
1259 strncmp(con
->uri
, "/admin/log/", 11)) ||
1260 !strncmp(con
->uri
, "/printers", 9) ||
1261 !strncmp(con
->uri
, "/classes", 8) ||
1262 !strncmp(con
->uri
, "/help", 5) ||
1263 !strncmp(con
->uri
, "/jobs", 5))
1266 * Send CGI output...
1269 if (!strncmp(con
->uri
, "/admin", 6))
1271 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1274 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1276 else if (!strncmp(con
->uri
, "/printers", 9))
1278 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1281 if (con
->uri
[9] && con
->uri
[10])
1282 cupsdSetString(&con
->options
, con
->uri
+ 9);
1284 cupsdSetString(&con
->options
, NULL
);
1286 else if (!strncmp(con
->uri
, "/classes", 8))
1288 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1291 if (con
->uri
[8] && con
->uri
[9])
1292 cupsdSetString(&con
->options
, con
->uri
+ 8);
1294 cupsdSetString(&con
->options
, NULL
);
1296 else if (!strncmp(con
->uri
, "/jobs", 5))
1298 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1301 if (con
->uri
[5] && con
->uri
[6])
1302 cupsdSetString(&con
->options
, con
->uri
+ 5);
1304 cupsdSetString(&con
->options
, NULL
);
1308 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1311 if (con
->uri
[5] && con
->uri
[6])
1312 cupsdSetString(&con
->options
, con
->uri
+ 5);
1314 cupsdSetString(&con
->options
, NULL
);
1317 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1319 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, AUTH_NONE
))
1321 cupsdCloseClient(con
);
1326 cupsdLogRequest(con
, HTTP_OK
);
1328 if (con
->http
.version
<= HTTP_1_0
)
1329 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1331 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1332 (strchr(con
->uri
+ 12, '/') ||
1333 strlen(con
->uri
) == 12)) ||
1334 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1335 (strchr(con
->uri
+ 11, '/') ||
1336 strlen(con
->uri
) == 11)))
1339 * GET can only be done to configuration files under
1343 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, AUTH_NONE
))
1345 cupsdCloseClient(con
);
1357 if ((filename
= get_file(con
, &filestats
, buf
,
1358 sizeof(buf
))) == NULL
)
1360 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, AUTH_NONE
))
1362 cupsdCloseClient(con
);
1369 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1371 if (is_cgi(con
, filename
, &filestats
, type
))
1374 * Note: con->command and con->options were set by
1378 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1380 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, AUTH_NONE
))
1382 cupsdCloseClient(con
);
1387 cupsdLogRequest(con
, HTTP_OK
);
1389 if (con
->http
.version
<= HTTP_1_0
)
1390 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1394 if (!check_if_modified(con
, &filestats
))
1396 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
, AUTH_NONE
))
1398 cupsdCloseClient(con
);
1405 strcpy(line
, "text/plain");
1407 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1409 if (!write_file(con
, HTTP_OK
, filename
, line
, &filestats
))
1411 cupsdCloseClient(con
);
1418 case HTTP_POST_RECV
:
1420 * See if the POST request includes a Content-Length field, and if
1421 * so check the length against any limits that are set...
1424 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "POST %s", con
->uri
);
1425 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "CONTENT_TYPE = %s",
1426 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
1428 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1429 MaxRequestSize
> 0 &&
1430 con
->http
.data_remaining
> MaxRequestSize
)
1433 * Request too large...
1436 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, AUTH_NONE
))
1438 cupsdCloseClient(con
);
1444 else if (con
->http
.data_remaining
< 0)
1447 * Negative content lengths are invalid!
1450 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, AUTH_NONE
))
1452 cupsdCloseClient(con
);
1460 * See what kind of POST request this is; for IPP requests the
1461 * content-type field will be "application/ipp"...
1464 if (!strcmp(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
],
1466 con
->request
= ippNew();
1467 else if ((!strncmp(con
->uri
, "/admin", 6) &&
1468 strncmp(con
->uri
, "/admin/conf/", 12) &&
1469 strncmp(con
->uri
, "/admin/log/", 11)) ||
1470 !strncmp(con
->uri
, "/printers", 9) ||
1471 !strncmp(con
->uri
, "/classes", 8) ||
1472 !strncmp(con
->uri
, "/help", 5) ||
1473 !strncmp(con
->uri
, "/jobs", 5))
1479 if (!strncmp(con
->uri
, "/admin", 6))
1481 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1484 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1486 else if (!strncmp(con
->uri
, "/printers", 9))
1488 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1491 if (con
->uri
[9] && con
->uri
[10])
1492 cupsdSetString(&con
->options
, con
->uri
+ 9);
1494 cupsdSetString(&con
->options
, NULL
);
1496 else if (!strncmp(con
->uri
, "/classes", 8))
1498 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1501 if (con
->uri
[8] && con
->uri
[9])
1502 cupsdSetString(&con
->options
, con
->uri
+ 8);
1504 cupsdSetString(&con
->options
, NULL
);
1506 else if (!strncmp(con
->uri
, "/jobs", 5))
1508 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1511 if (con
->uri
[5] && con
->uri
[6])
1512 cupsdSetString(&con
->options
, con
->uri
+ 5);
1514 cupsdSetString(&con
->options
, NULL
);
1518 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1521 if (con
->uri
[5] && con
->uri
[6])
1522 cupsdSetString(&con
->options
, con
->uri
+ 5);
1524 cupsdSetString(&con
->options
, NULL
);
1527 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1528 "cupsdReadClient: %d command=\"%s\", "
1530 con
->http
.fd
, con
->command
,
1531 con
->options
? con
->options
: "(null)");
1533 if (con
->http
.version
<= HTTP_1_0
)
1534 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1542 if ((filename
= get_file(con
, &filestats
, buf
,
1543 sizeof(buf
))) == NULL
)
1545 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, AUTH_NONE
))
1547 cupsdCloseClient(con
);
1554 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1556 if (!is_cgi(con
, filename
, &filestats
, type
))
1559 * Only POST to CGI's...
1562 if (!cupsdSendError(con
, HTTP_UNAUTHORIZED
, AUTH_NONE
))
1564 cupsdCloseClient(con
);
1571 case HTTP_PUT_RECV
:
1573 * Validate the resource name...
1576 if (strncmp(con
->uri
, "/admin/conf/", 12) ||
1577 strchr(con
->uri
+ 12, '/') ||
1578 strlen(con
->uri
) == 12)
1581 * PUT can only be done to configuration files under
1585 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, AUTH_NONE
))
1587 cupsdCloseClient(con
);
1595 * See if the PUT request includes a Content-Length field, and if
1596 * so check the length against any limits that are set...
1599 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "PUT %s", con
->uri
);
1600 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "CONTENT_TYPE = %s",
1601 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
1603 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1604 MaxRequestSize
> 0 &&
1605 con
->http
.data_remaining
> MaxRequestSize
)
1608 * Request too large...
1611 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, AUTH_NONE
))
1613 cupsdCloseClient(con
);
1619 else if (con
->http
.data_remaining
< 0)
1622 * Negative content lengths are invalid!
1625 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, AUTH_NONE
))
1627 cupsdCloseClient(con
);
1635 * Open a temporary file to hold the request...
1638 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
1640 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1642 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1643 "cupsdReadClient: %d REQUEST %s=%d", con
->http
.fd
,
1644 con
->filename
, con
->file
);
1648 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, AUTH_NONE
))
1650 cupsdCloseClient(con
);
1655 fchmod(con
->file
, 0640);
1656 fchown(con
->file
, RunUser
, Group
);
1657 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1662 cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, AUTH_NONE
);
1663 cupsdCloseClient(con
);
1667 if (!strncmp(con
->uri
, "/printers/", 10) &&
1668 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1671 * Send PPD file - get the real printer name since printer
1672 * names are not case sensitive but filenames can be...
1675 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1677 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1678 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1681 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, AUTH_NONE
))
1683 cupsdCloseClient(con
);
1691 if ((!strncmp(con
->uri
, "/admin", 6) &&
1692 strncmp(con
->uri
, "/admin/conf/", 12) &&
1693 strncmp(con
->uri
, "/admin/log/", 11)) ||
1694 !strncmp(con
->uri
, "/printers", 9) ||
1695 !strncmp(con
->uri
, "/classes", 8) ||
1696 !strncmp(con
->uri
, "/help", 5) ||
1697 !strncmp(con
->uri
, "/jobs", 5))
1703 if (!cupsdSendHeader(con
, HTTP_OK
, "text/html", AUTH_NONE
))
1705 cupsdCloseClient(con
);
1709 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1711 cupsdCloseClient(con
);
1715 if (cupsdFlushHeader(con
) < 0)
1717 cupsdCloseClient(con
);
1721 cupsdLogRequest(con
, HTTP_OK
);
1723 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1724 (strchr(con
->uri
+ 12, '/') ||
1725 strlen(con
->uri
) == 12)) ||
1726 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1727 (strchr(con
->uri
+ 11, '/') ||
1728 strlen(con
->uri
) == 11)))
1731 * HEAD can only be done to configuration files under
1735 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, AUTH_NONE
))
1737 cupsdCloseClient(con
);
1743 else if ((filename
= get_file(con
, &filestats
, buf
,
1744 sizeof(buf
))) == NULL
)
1746 if (!cupsdSendHeader(con
, HTTP_NOT_FOUND
, "text/html", AUTH_NONE
))
1748 cupsdCloseClient(con
);
1752 cupsdLogRequest(con
, HTTP_NOT_FOUND
);
1754 else if (!check_if_modified(con
, &filestats
))
1756 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
, AUTH_NONE
))
1758 cupsdCloseClient(con
);
1762 cupsdLogRequest(con
, HTTP_NOT_MODIFIED
);
1770 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1772 strcpy(line
, "text/plain");
1774 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1776 if (!cupsdSendHeader(con
, HTTP_OK
, line
, AUTH_NONE
))
1778 cupsdCloseClient(con
);
1782 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
1783 httpGetDateString(filestats
.st_mtime
)) < 0)
1785 cupsdCloseClient(con
);
1789 if (httpPrintf(HTTP(con
), "Content-Length: %lu\r\n",
1790 (unsigned long)filestats
.st_size
) < 0)
1792 cupsdCloseClient(con
);
1796 cupsdLogRequest(con
, HTTP_OK
);
1799 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1801 cupsdCloseClient(con
);
1805 if (cupsdFlushHeader(con
) < 0)
1807 cupsdCloseClient(con
);
1811 con
->http
.state
= HTTP_WAITING
;
1815 break; /* Anti-compiler-warning-code */
1821 * Handle any incoming data...
1824 switch (con
->http
.state
)
1826 case HTTP_PUT_RECV
:
1827 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1828 "cupsdReadClient: %d con->data_encoding=HTTP_ENCODE_%s, "
1829 "con->data_remaining=" CUPS_LLFMT
", con->file=%d",
1831 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
?
1832 "CHUNKED" : "LENGTH",
1833 CUPS_LLCAST con
->http
.data_remaining
, con
->file
);
1837 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
1839 cupsdCloseClient(con
);
1844 con
->bytes
+= bytes
;
1846 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1847 "cupsdReadClient: %d writing %d bytes to %d",
1848 con
->http
.fd
, bytes
, con
->file
);
1850 if (write(con
->file
, line
, bytes
) < bytes
)
1852 cupsdLogMessage(CUPSD_LOG_ERROR
,
1853 "cupsdReadClient: Unable to write %d bytes to %s: %s",
1854 bytes
, con
->filename
, strerror(errno
));
1856 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1857 "cupsdReadClient: Closing data file %d...",
1862 unlink(con
->filename
);
1863 cupsdClearString(&con
->filename
);
1865 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, AUTH_NONE
))
1867 cupsdCloseClient(con
);
1873 while (con
->http
.state
== HTTP_PUT_RECV
&& con
->http
.used
> 0);
1875 if (con
->http
.state
== HTTP_WAITING
)
1878 * End of file, see how big it is...
1881 fstat(con
->file
, &filestats
);
1883 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1884 "cupsdReadClient: %d Closing data file %d, size="
1886 con
->http
.fd
, con
->file
,
1887 CUPS_LLCAST filestats
.st_size
);
1892 if (filestats
.st_size
> MaxRequestSize
&&
1896 * Request is too big; remove it and send an error...
1899 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1900 "cupsdReadClient: %d Removing temp file %s",
1901 con
->http
.fd
, con
->filename
);
1902 unlink(con
->filename
);
1903 cupsdClearString(&con
->filename
);
1905 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, AUTH_NONE
))
1907 cupsdCloseClient(con
);
1913 * Install the configuration file...
1916 status
= install_conf_file(con
);
1919 * Return the status to the client...
1922 if (!cupsdSendError(con
, status
, AUTH_NONE
))
1924 cupsdCloseClient(con
);
1930 case HTTP_POST_RECV
:
1931 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1932 "cupsdReadClient: %d con->data_encoding=HTTP_ENCODE_"
1933 "%s, con->data_remaining=" CUPS_LLFMT
", con->file=%d",
1935 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
?
1936 "CHUNKED" : "LENGTH",
1937 CUPS_LLCAST con
->http
.data_remaining
, con
->file
);
1944 * Grab any request data from the connection...
1947 if ((ipp_state
= ippRead(&(con
->http
), con
->request
)) == IPP_ERROR
)
1949 cupsdLogMessage(CUPSD_LOG_ERROR
,
1950 "cupsdReadClient: %d IPP Read Error!",
1953 cupsdSendError(con
, HTTP_BAD_REQUEST
, AUTH_NONE
);
1954 cupsdCloseClient(con
);
1957 else if (ipp_state
!= IPP_DATA
)
1959 if (con
->http
.state
== HTTP_POST_SEND
)
1961 cupsdSendError(con
, HTTP_BAD_REQUEST
, AUTH_NONE
);
1962 cupsdCloseClient(con
);
1969 con
->bytes
+= ippLength(con
->request
);
1972 if (con
->file
< 0 && con
->http
.state
!= HTTP_POST_SEND
)
1975 * Create a file as needed for the request data...
1978 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
, request_id
++);
1979 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1981 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdReadClient: %d REQUEST %s=%d", con
->http
.fd
,
1982 con
->filename
, con
->file
);
1986 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, AUTH_NONE
))
1988 cupsdCloseClient(con
);
1993 fchmod(con
->file
, 0640);
1994 fchown(con
->file
, RunUser
, Group
);
1995 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1998 if (con
->http
.state
!= HTTP_POST_SEND
)
2000 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
2002 cupsdCloseClient(con
);
2007 con
->bytes
+= bytes
;
2009 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2010 "cupsdReadClient: %d writing %d bytes to %d",
2011 con
->http
.fd
, bytes
, con
->file
);
2013 if (write(con
->file
, line
, bytes
) < bytes
)
2015 cupsdLogMessage(CUPSD_LOG_ERROR
,
2016 "cupsdReadClient: Unable to write %d bytes to %s: %s",
2017 bytes
, con
->filename
, strerror(errno
));
2019 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2020 "cupsdReadClient: Closing file %d...",
2025 unlink(con
->filename
);
2026 cupsdClearString(&con
->filename
);
2028 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, AUTH_NONE
))
2030 cupsdCloseClient(con
);
2035 else if (con
->http
.state
== HTTP_POST_RECV
)
2037 else if (con
->http
.state
!= HTTP_POST_SEND
)
2039 cupsdCloseClient(con
);
2044 while (con
->http
.state
== HTTP_POST_RECV
&& con
->http
.used
> 0);
2046 if (con
->http
.state
== HTTP_POST_SEND
)
2050 fstat(con
->file
, &filestats
);
2052 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2053 "cupsdReadClient: %d Closing data file %d, "
2054 "size=" CUPS_LLFMT
".",
2055 con
->http
.fd
, con
->file
,
2056 CUPS_LLCAST filestats
.st_size
);
2061 if (filestats
.st_size
> MaxRequestSize
&&
2065 * Request is too big; remove it and send an error...
2068 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2069 "cupsdReadClient: %d Removing temp file %s",
2070 con
->http
.fd
, con
->filename
);
2071 unlink(con
->filename
);
2072 cupsdClearString(&con
->filename
);
2077 * Delete any IPP request data...
2080 ippDelete(con
->request
);
2081 con
->request
= NULL
;
2084 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, AUTH_NONE
))
2086 cupsdCloseClient(con
);
2093 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
2095 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, AUTH_NONE
))
2097 cupsdCloseClient(con
);
2102 cupsdLogRequest(con
, HTTP_OK
);
2108 cupsdProcessIPPRequest(con
);
2112 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2113 "cupsdReadClient: %d Removing temp file %s",
2114 con
->http
.fd
, con
->filename
);
2115 unlink(con
->filename
);
2116 cupsdClearString(&con
->filename
);
2125 break; /* Anti-compiler-warning-code */
2128 if (!con
->http
.keep_alive
&& con
->http
.state
== HTTP_WAITING
)
2129 cupsdCloseClient(con
);
2134 * 'cupsdSendCommand()' - Send output from a command via HTTP.
2137 int /* O - 1 on success, 0 on failure */
2139 cupsd_client_t
*con
, /* I - Client connection */
2140 char *command
, /* I - Command to run */
2141 char *options
, /* I - Command-line options */
2142 int root
) /* I - Run as root? */
2144 int fd
; /* Standard input file descriptor */
2149 fd
= open(con
->filename
, O_RDONLY
);
2153 cupsdLogMessage(CUPSD_LOG_ERROR
,
2154 "cupsdSendCommand: %d Unable to open \"%s\" for reading: %s",
2155 con
->http
.fd
, con
->filename
? con
->filename
: "/dev/null",
2160 fcntl(fd
, F_SETFD
, fcntl(fd
, F_GETFD
) | FD_CLOEXEC
);
2165 con
->pipe_pid
= pipe_command(con
, fd
, &(con
->file
), command
, options
, root
);
2170 cupsdLogMessage(CUPSD_LOG_INFO
, "Started \"%s\" (pid=%d)", command
,
2173 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendCommand: %d file=%d",
2174 con
->http
.fd
, con
->file
);
2176 if (con
->pipe_pid
== 0)
2179 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2181 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2183 con
->sent_header
= 0;
2184 con
->file_ready
= 0;
2185 con
->got_fields
= 0;
2193 * 'cupsdSendError()' - Send an error message via HTTP.
2196 int /* O - 1 if successful, 0 otherwise */
2197 cupsdSendError(cupsd_client_t
*con
, /* I - Connection */
2198 http_status_t code
, /* I - Error code */
2199 int auth_type
)/* I - Authentication type */
2203 * Force client to upgrade for authentication if that is how the
2204 * server is configured...
2207 if (code
== HTTP_UNAUTHORIZED
&&
2208 DefaultEncryption
== HTTP_ENCRYPT_REQUIRED
&&
2209 strcasecmp(con
->http
.hostname
, "localhost") &&
2212 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2213 "cupsdSendError: Encryption before authentication!");
2214 code
= HTTP_UPGRADE_REQUIRED
;
2216 #endif /* HAVE_SSL */
2219 * Put the request in the access_log file...
2222 cupsdLogRequest(con
, code
);
2224 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendError: %d code=%d (%s)",
2225 con
->http
.fd
, code
, httpStatus(code
));
2228 * To work around bugs in some proxies, don't use Keep-Alive for some
2231 * Kerberos authentication doesn't work without Keep-Alive, so
2232 * never disable it in that case.
2235 if (code
>= HTTP_BAD_REQUEST
&& con
->http
.auth_type
!= AUTH_NEGOTIATE
)
2236 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
2239 * Send an error message back to the client. If the error code is a
2240 * 400 or 500 series, make sure the message contains some text, too!
2243 if (!cupsdSendHeader(con
, code
, NULL
, auth_type
))
2247 if (code
== HTTP_UPGRADE_REQUIRED
)
2248 if (httpPrintf(HTTP(con
), "Connection: Upgrade\r\n") < 0)
2251 if (httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n") < 0)
2253 #endif /* HAVE_SSL */
2255 if (con
->http
.version
>= HTTP_1_1
&&
2256 con
->http
.keep_alive
== HTTP_KEEPALIVE_OFF
)
2258 if (httpPrintf(HTTP(con
), "Connection: close\r\n") < 0)
2262 if (code
>= HTTP_BAD_REQUEST
)
2265 * Send a human-readable error message.
2268 char message
[4096], /* Message for user */
2269 urltext
[1024], /* URL redirection text */
2270 redirect
[1024]; /* Redirection link */
2271 const char *text
; /* Status-specific text */
2276 if (code
== HTTP_UNAUTHORIZED
)
2277 text
= _cupsLangString(con
->language
,
2278 _("Enter your username and password or the "
2279 "root username and password to access this "
2280 "page. If you are using Kerberos authentication, "
2281 "make sure you have a valid Kerberos ticket."));
2282 else if (code
== HTTP_UPGRADE_REQUIRED
)
2286 snprintf(urltext
, sizeof(urltext
),
2287 _cupsLangString(con
->language
,
2288 _("You must access this page using the URL "
2289 "<A HREF=\"https://%s:%d%s\">"
2290 "https://%s:%d%s</A>.")),
2291 con
->servername
, con
->serverport
, con
->uri
,
2292 con
->servername
, con
->serverport
, con
->uri
);
2294 snprintf(redirect
, sizeof(redirect
),
2295 "<META HTTP-EQUIV=\"Refresh\" "
2296 "CONTENT=\"3;URL=https://%s:%d%s\">\n",
2297 con
->servername
, con
->serverport
, con
->uri
);
2302 snprintf(message
, sizeof(message
),
2303 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" "
2304 "\"http://www.w3.org/TR/REC-html40/loose.dtd\">\n"
2307 "\t<META HTTP-EQUIV=\"Content-Type\" "
2308 "CONTENT=\"text/html; charset=utf-8\">\n"
2309 "\t<TITLE>%d %s</TITLE>\n"
2310 "\t<LINK REL=\"STYLESHEET\" TYPE=\"text/css\" "
2311 "HREF=\"/cups.css\">\n"
2319 code
, httpStatus(code
), redirect
, code
, httpStatus(code
), text
);
2321 if (httpPrintf(HTTP(con
), "Content-Type: text/html; charset=utf-8\r\n") < 0)
2323 if (httpPrintf(HTTP(con
), "Content-Length: %d\r\n",
2324 (int)strlen(message
)) < 0)
2326 if (httpPrintf(HTTP(con
), "\r\n") < 0)
2328 if (httpPrintf(HTTP(con
), "%s", message
) < 0)
2331 else if (httpPrintf(HTTP(con
), "\r\n") < 0)
2334 if (cupsdFlushHeader(con
) < 0)
2337 con
->http
.state
= HTTP_WAITING
;
2344 * 'cupsdSendHeader()' - Send an HTTP request.
2347 int /* O - 1 on success, 0 on failure */
2349 cupsd_client_t
*con
, /* I - Client to send to */
2350 http_status_t code
, /* I - HTTP status code */
2351 char *type
, /* I - MIME type of document */
2352 int auth_type
) /* I - Type of authentication */
2354 char auth_str
[1024]; /* Authorization string */
2358 * Send the HTTP status header...
2361 if (code
== HTTP_CONTINUE
)
2364 * 100-continue doesn't send any headers...
2367 return (httpPrintf(HTTP(con
), "HTTP/%d.%d 100 Continue\r\n\r\n",
2368 con
->http
.version
/ 100, con
->http
.version
% 100) > 0);
2371 httpFlushWrite(HTTP(con
));
2373 con
->http
.data_encoding
= HTTP_ENCODE_FIELDS
;
2375 if (httpPrintf(HTTP(con
), "HTTP/%d.%d %d %s\r\n", con
->http
.version
/ 100,
2376 con
->http
.version
% 100, code
, httpStatus(code
)) < 0)
2378 if (httpPrintf(HTTP(con
), "Date: %s\r\n", httpGetDateString(time(NULL
))) < 0)
2381 if (httpPrintf(HTTP(con
), "Server: %s\r\n", ServerHeader
) < 0)
2383 if (con
->http
.keep_alive
&& con
->http
.version
>= HTTP_1_0
)
2385 if (httpPrintf(HTTP(con
), "Connection: Keep-Alive\r\n") < 0)
2387 if (httpPrintf(HTTP(con
), "Keep-Alive: timeout=%d\r\n",
2388 KeepAliveTimeout
) < 0)
2391 if (code
== HTTP_METHOD_NOT_ALLOWED
)
2392 if (httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST\r\n") < 0)
2395 if (code
== HTTP_UNAUTHORIZED
)
2397 if (auth_type
== AUTH_NONE
)
2399 if (!con
->best
|| con
->best
->type
<= AUTH_NONE
)
2400 auth_type
= DefaultAuthType
;
2402 auth_type
= con
->best
->type
;
2407 if (auth_type
== AUTH_BASIC
|| auth_type
== AUTH_BASICDIGEST
)
2408 strlcpy(auth_str
, "Basic realm=\"CUPS\"", sizeof(auth_str
));
2409 else if (auth_type
== AUTH_DIGEST
)
2410 snprintf(auth_str
, sizeof(auth_str
), "Digest realm=\"CUPS\", nonce=\"%s\"",
2411 con
->http
.hostname
);
2413 else if (auth_type
== AUTH_NEGOTIATE
&& con
->gss_output_token
.length
== 0)
2414 strlcpy(auth_str
, "Negotiate", sizeof(auth_str
));
2415 #endif /* HAVE_GSSAPI */
2417 #ifdef HAVE_AUTHORIZATION_H
2418 if (con
->best
&& auth_type
!= AUTH_NEGOTIATE
)
2420 int i
; /* Looping var */
2421 char *auth_key
; /* Auth key buffer */
2422 size_t auth_size
; /* Size of remaining buffer */
2425 auth_key
= auth_str
+ strlen(auth_str
);
2426 auth_size
= sizeof(auth_str
) - (auth_key
- auth_str
);
2428 for (i
= 0; i
< con
->best
->num_names
; i
++)
2430 if (!strncasecmp(con
->best
->names
[i
], "@AUTHKEY(", 9))
2432 snprintf(auth_key
, auth_size
, ", authkey=\"%s\"",
2433 con
->best
->names
[i
] + 9);
2434 /* end parenthesis is stripped in conf.c */
2437 else if (!strcasecmp(con
->best
->names
[i
], "@SYSTEM") &&
2440 snprintf(auth_key
, auth_size
, ", authkey=\"%s\"", SystemGroupAuthKey
);
2445 #endif /* HAVE_AUTHORIZATION_H */
2449 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendHeader: WWW-Authenticate: %s",
2452 if (httpPrintf(HTTP(con
), "WWW-Authenticate: %s\r\n", auth_str
) < 0)
2459 * WWW-Authenticate: Negotiate can be included even for
2460 * non-401 replies...
2463 if (con
->gss_output_token
.length
> 0)
2465 char buf
[2048]; /* Output token buffer */
2466 OM_uint32 minor_status
; /* Minor status code */
2469 httpEncode64_2(buf
, sizeof(buf
),
2470 con
->gss_output_token
.value
,
2471 con
->gss_output_token
.length
);
2472 gss_release_buffer(&minor_status
, &con
->gss_output_token
);
2474 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2475 "cupsdSendHeader: WWW-Authenticate: Negotiate %s", buf
);
2477 if (httpPrintf(HTTP(con
), "WWW-Authenticate: Negotiate %s\r\n", buf
) < 0)
2480 #endif /* HAVE_GSSAPI */
2482 if (con
->language
&& strcmp(con
->language
->language
, "C"))
2484 if (httpPrintf(HTTP(con
), "Content-Language: %s\r\n",
2485 con
->language
->language
) < 0)
2491 if (!strcmp(type
, "text/html"))
2493 if (httpPrintf(HTTP(con
),
2494 "Content-Type: text/html; charset=utf-8\r\n") < 0)
2497 else if (httpPrintf(HTTP(con
), "Content-Type: %s\r\n", type
) < 0)
2506 * 'cupsdUpdateCGI()' - Read status messages from CGI scripts and programs.
2510 cupsdUpdateCGI(void)
2512 char *ptr
, /* Pointer to end of line in buffer */
2513 message
[1024]; /* Pointer to message text */
2514 int loglevel
; /* Log level for message */
2517 while ((ptr
= cupsdStatBufUpdate(CGIStatusBuffer
, &loglevel
,
2518 message
, sizeof(message
))) != NULL
)
2519 if (!strchr(CGIStatusBuffer
->buffer
, '\n'))
2522 if (ptr
== NULL
&& !CGIStatusBuffer
->bufused
)
2525 * Fatal error on pipe - should never happen!
2528 cupsdLogMessage(CUPSD_LOG_CRIT
,
2529 "cupsdUpdateCGI: error reading from CGI error pipe - %s",
2536 * 'cupsdWriteClient()' - Write data to a client as needed.
2540 cupsdWriteClient(cupsd_client_t
*con
) /* I - Client connection */
2542 int bytes
; /* Number of bytes written */
2543 char buf
[16385]; /* Data buffer */
2544 char *bufptr
; /* Pointer into buffer */
2545 ipp_state_t ipp_state
; /* IPP state value */
2549 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2550 "cupsdWriteClient(con=%p) %d response=%p(%d), file=%d "
2551 "pipe_pid=%d state=%d",
2552 con
, con
->http
.fd
, con
->response
, con
->response
->state
,
2553 con
->file
, con
->pipe_pid
, con
->http
.state
);
2556 if (con
->http
.state
!= HTTP_GET_SEND
&&
2557 con
->http
.state
!= HTTP_POST_SEND
)
2563 * Make sure we select on the CGI output...
2566 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2568 if (!con
->file_ready
)
2571 * Try again later when there is CGI output available...
2574 cupsdRemoveSelect(con
->http
.fd
);
2578 con
->file_ready
= 0;
2581 if (con
->response
&& con
->response
->state
!= IPP_DATA
)
2583 ipp_state
= ippWrite(HTTP(con
), con
->response
);
2584 bytes
= ipp_state
!= IPP_ERROR
&&
2585 (con
->file
>= 0 || ipp_state
!= IPP_DATA
);
2587 else if ((bytes
= read(con
->file
, buf
, sizeof(buf
) - 1)) > 0)
2589 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2590 "cupsdWriteClient: Read %d bytes from file %d...",
2593 if (con
->pipe_pid
&& !con
->got_fields
)
2596 * Inspect the data for Content-Type and other fields.
2601 for (bufptr
= buf
; !con
->got_fields
&& *bufptr
; bufptr
++)
2602 if (*bufptr
== '\n')
2605 * Send line to client...
2608 if (bufptr
> buf
&& bufptr
[-1] == '\r')
2612 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "Script header: %s", buf
);
2614 if (!con
->sent_header
)
2617 * Handle redirection and CGI status codes...
2620 if (!strncasecmp(buf
, "Location:", 9))
2622 cupsdSendHeader(con
, HTTP_SEE_OTHER
, NULL
, AUTH_NONE
);
2623 con
->sent_header
= 2;
2625 if (httpPrintf(HTTP(con
), "Content-Length: 0\r\n") < 0)
2628 else if (!strncasecmp(buf
, "Status:", 7))
2630 cupsdSendError(con
, (http_status_t
)atoi(buf
+ 7), AUTH_NONE
);
2631 con
->sent_header
= 2;
2635 cupsdSendHeader(con
, HTTP_OK
, NULL
, AUTH_NONE
);
2636 con
->sent_header
= 1;
2638 if (con
->http
.version
== HTTP_1_1
)
2640 if (httpPrintf(HTTP(con
), "Transfer-Encoding: chunked\r\n") < 0)
2646 if (strncasecmp(buf
, "Status:", 7))
2647 httpPrintf(HTTP(con
), "%s\r\n", buf
);
2649 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdWriteClient: %d %s",
2656 bytes
-= (bufptr
- buf
);
2657 memmove(buf
, bufptr
, bytes
+ 1);
2661 * See if the line was empty...
2664 if (con
->field_col
== 0)
2666 con
->got_fields
= 1;
2668 if (cupsdFlushHeader(con
) < 0)
2670 cupsdCloseClient(con
);
2674 if (con
->http
.version
== HTTP_1_1
)
2675 con
->http
.data_encoding
= HTTP_ENCODE_CHUNKED
;
2680 else if (*bufptr
!= '\r')
2683 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2684 "cupsdWriteClient: %d bytes=%d, got_fields=%d",
2685 con
->http
.fd
, bytes
, con
->got_fields
);
2687 if (bytes
> 0 && !con
->got_fields
)
2690 * Remaining text needs to go out...
2693 httpPrintf(HTTP(con
), "%s", buf
);
2695 con
->http
.activity
= time(NULL
);
2698 else if (bytes
== 0)
2699 con
->http
.activity
= time(NULL
);
2704 if (httpWrite2(HTTP(con
), buf
, bytes
) < 0)
2706 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2707 "cupsdWriteClient: %d Write of %d bytes failed!",
2708 con
->http
.fd
, bytes
);
2710 cupsdCloseClient(con
);
2714 con
->bytes
+= bytes
;
2716 if (con
->http
.state
== HTTP_WAITING
)
2723 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdWriteClient: %d bytes < 0",
2726 cupsdLogRequest(con
, HTTP_OK
);
2728 httpFlushWrite(HTTP(con
));
2730 if (con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
&& con
->sent_header
== 1)
2732 if (httpWrite2(HTTP(con
), "", 0) < 0)
2734 cupsdCloseClient(con
);
2739 con
->http
.state
= HTTP_WAITING
;
2741 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
2745 cupsdRemoveSelect(con
->file
);
2748 cupsdEndProcess(con
->pipe_pid
, 0);
2750 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2751 "cupsdWriteClient: %d Closing data file %d.",
2752 con
->http
.fd
, con
->file
);
2761 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2762 "cupsdWriteClient: %d Removing temp file %s",
2763 con
->http
.fd
, con
->filename
);
2764 unlink(con
->filename
);
2765 cupsdClearString(&con
->filename
);
2770 ippDelete(con
->request
);
2771 con
->request
= NULL
;
2776 ippDelete(con
->response
);
2777 con
->response
= NULL
;
2780 cupsdClearString(&con
->command
);
2781 cupsdClearString(&con
->options
);
2782 cupsdClearString(&con
->query_string
);
2784 if (!con
->http
.keep_alive
)
2786 cupsdCloseClient(con
);
2791 con
->http
.activity
= time(NULL
);
2796 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
2799 static int /* O - 1 if modified since */
2801 cupsd_client_t
*con
, /* I - Client connection */
2802 struct stat
*filestats
) /* I - File information */
2804 char *ptr
; /* Pointer into field */
2805 time_t date
; /* Time/date value */
2806 off_t size
; /* Size/length value */
2811 ptr
= con
->http
.fields
[HTTP_FIELD_IF_MODIFIED_SINCE
];
2816 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2817 "check_if_modified: %d If-Modified-Since=\"%s\"",
2820 while (*ptr
!= '\0')
2822 while (isspace(*ptr
) || *ptr
== ';')
2825 if (strncasecmp(ptr
, "length=", 7) == 0)
2828 size
= strtoll(ptr
, NULL
, 10);
2830 while (isdigit(*ptr
))
2833 else if (isalpha(*ptr
))
2835 date
= httpGetDateTime(ptr
);
2836 while (*ptr
!= '\0' && *ptr
!= ';')
2843 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2844 "check_if_modified: %d sizes=" CUPS_LLFMT
","
2845 CUPS_LLFMT
" dates=%d,%d",
2846 con
->http
.fd
, CUPS_LLCAST size
,
2847 CUPS_LLCAST filestats
->st_size
, (int)date
,
2848 (int)filestats
->st_mtime
);
2850 return ((size
!= filestats
->st_size
&& size
!= 0) ||
2851 (date
< filestats
->st_mtime
&& date
!= 0) ||
2852 (size
== 0 && date
== 0));
2858 * 'encrypt_client()' - Enable encryption for the client...
2861 static int /* O - 1 on success, 0 on error */
2862 encrypt_client(cupsd_client_t
*con
) /* I - Client to encrypt */
2865 SSL_CTX
*context
; /* Context for encryption */
2866 SSL
*conn
; /* Connection for encryption */
2867 BIO
*bio
; /* BIO data */
2868 unsigned long error
; /* Error code */
2872 * Verify that we have a certificate...
2875 if (access(ServerKey
, 0) || access(ServerCertificate
, 0))
2878 * Nope, make a self-signed certificate...
2881 if (!make_certificate(con
))
2886 * Create the SSL context and accept the connection...
2889 context
= SSL_CTX_new(SSLv23_server_method());
2891 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
2892 SSL_CTX_use_PrivateKey_file(context
, ServerKey
, SSL_FILETYPE_PEM
);
2893 SSL_CTX_use_certificate_file(context
, ServerCertificate
, SSL_FILETYPE_PEM
);
2895 bio
= BIO_new(_httpBIOMethods());
2896 BIO_ctrl(bio
, BIO_C_SET_FILE_PTR
, 0, (char *)HTTP(con
));
2898 conn
= SSL_new(context
);
2899 SSL_set_bio(conn
, bio
, bio
);
2901 if (SSL_accept(conn
) != 1)
2903 cupsdLogMessage(CUPSD_LOG_ERROR
,
2904 "encrypt_client: Unable to encrypt connection from %s!",
2905 con
->http
.hostname
);
2907 while ((error
= ERR_get_error()) != 0)
2908 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s",
2909 ERR_error_string(error
, NULL
));
2911 SSL_CTX_free(context
);
2916 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2917 "encrypt_client: %d Connection from %s now encrypted.",
2918 con
->http
.fd
, con
->http
.hostname
);
2920 con
->http
.tls
= conn
;
2923 # elif defined(HAVE_GNUTLS)
2924 http_tls_t
*conn
; /* TLS session object */
2925 int error
; /* Error code */
2926 gnutls_certificate_server_credentials
*credentials
;
2927 /* TLS credentials */
2931 * Verify that we have a certificate...
2934 if (access(ServerKey
, 0) || access(ServerCertificate
, 0))
2937 * Nope, make a self-signed certificate...
2940 if (!make_certificate(con
))
2945 * Create the SSL object and perform the SSL handshake...
2948 conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
));
2953 credentials
= (gnutls_certificate_server_credentials
*)
2954 malloc(sizeof(gnutls_certificate_server_credentials
));
2955 if (credentials
== NULL
)
2957 cupsdLogMessage(CUPSD_LOG_ERROR
,
2958 "encrypt_client: Unable to encrypt connection from %s!",
2959 con
->http
.hostname
);
2960 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s", strerror(errno
));
2966 gnutls_certificate_allocate_credentials(credentials
);
2967 gnutls_certificate_set_x509_key_file(*credentials
, ServerCertificate
,
2968 ServerKey
, GNUTLS_X509_FMT_PEM
);
2970 gnutls_init(&(conn
->session
), GNUTLS_SERVER
);
2971 gnutls_set_default_priority(conn
->session
);
2972 gnutls_credentials_set(conn
->session
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
2973 gnutls_transport_set_ptr(conn
->session
, (gnutls_transport_ptr
)HTTP(con
));
2974 gnutls_transport_set_pull_function(conn
->session
, _httpReadGNUTLS
);
2975 gnutls_transport_set_push_function(conn
->session
, _httpWriteGNUTLS
);
2977 error
= gnutls_handshake(conn
->session
);
2979 if (error
!= GNUTLS_E_SUCCESS
)
2981 cupsdLogMessage(CUPSD_LOG_ERROR
,
2982 "encrypt_client: Unable to encrypt connection from %s!",
2983 con
->http
.hostname
);
2984 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s",
2985 gnutls_strerror(error
));
2987 gnutls_deinit(conn
->session
);
2988 gnutls_certificate_free_credentials(*credentials
);
2994 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2995 "encrypt_client: %d Connection from %s now encrypted.",
2996 con
->http
.fd
, con
->http
.hostname
);
2998 conn
->credentials
= credentials
;
2999 con
->http
.tls
= conn
;
3002 # elif defined(HAVE_CDSASSL)
3003 OSStatus error
; /* Error code */
3004 http_tls_t
*conn
; /* CDSA connection information */
3007 if ((conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
))) == NULL
)
3011 conn
->session
= NULL
;
3012 conn
->certsArray
= get_cdsa_certificate(con
);
3014 if (!conn
->certsArray
)
3017 * No keychain (yet), make a self-signed certificate...
3020 if (make_certificate(con
))
3021 conn
->certsArray
= get_cdsa_certificate(con
);
3024 if (!conn
->certsArray
)
3026 cupsdLogMessage(CUPSD_LOG_ERROR
,
3027 "encrypt_client: Could not find signing key in keychain "
3028 "\"%s\"", ServerCertificate
);
3029 error
= errSSLBadCert
; /* errSSLBadConfiguration is a better choice, but not available on 10.2.x */
3033 error
= SSLNewContext(true, &conn
->session
);
3036 error
= SSLSetIOFuncs(conn
->session
, _httpReadCDSA
, _httpWriteCDSA
);
3039 error
= SSLSetProtocolVersionEnabled(conn
->session
, kSSLProtocol2
, false);
3042 error
= SSLSetConnection(conn
->session
, HTTP(con
));
3045 error
= SSLSetAllowsExpiredCerts(conn
->session
, true);
3048 error
= SSLSetAllowsAnyRoot(conn
->session
, true);
3051 error
= SSLSetCertificate(conn
->session
, conn
->certsArray
);
3056 * Perform SSL/TLS handshake
3059 while ((error
= SSLHandshake(conn
->session
)) == errSSLWouldBlock
)
3065 cupsdLogMessage(CUPSD_LOG_ERROR
,
3066 "encrypt_client: Unable to encrypt connection from %s!",
3067 con
->http
.hostname
);
3069 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s (%d)",
3070 cssmErrorString(error
), (int)error
);
3072 con
->http
.error
= error
;
3073 con
->http
.status
= HTTP_ERROR
;
3076 SSLDisposeContext(conn
->session
);
3078 if (conn
->certsArray
)
3079 CFRelease(conn
->certsArray
);
3086 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3087 "encrypt_client: %d Connection from %s now encrypted.",
3088 con
->http
.fd
, con
->http
.hostname
);
3090 con
->http
.tls
= conn
;
3093 # endif /* HAVE_LIBSSL */
3095 #endif /* HAVE_SSL */
3100 * 'get_cdsa_certificate()' - Get a SSL/TLS certificate from the System keychain.
3103 static CFArrayRef
/* O - Array of certificates */
3104 get_cdsa_certificate(cupsd_client_t
*con
) /* I - Client connection */
3106 OSStatus err
; /* Error info */
3107 SecKeychainRef keychain
; /* Keychain reference */
3108 SecIdentitySearchRef search
; /* Search reference */
3109 SecIdentityRef identity
; /* Identity */
3110 CFArrayRef certificates
= NULL
;
3111 /* Certificate array */
3114 if ((err
= SecKeychainOpen(ServerCertificate
, &keychain
)))
3116 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot open keychain \"%s\", %s",
3117 ServerCertificate
, cssmErrorString(err
));
3121 # if HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY
3123 * Use a policy to search for valid certificates who's common name matches the
3127 SecPolicySearchRef policy_search
; /* Policy search ref */
3128 SecPolicyRef policy
; /* Policy ref */
3129 CSSM_DATA options
; /* Policy options */
3130 CSSM_APPLE_TP_SSL_OPTIONS
3131 ssl_options
; /* SSL Option for hostname */
3134 if ((err
= SecPolicySearchCreate(CSSM_CERT_X_509v3
, &CSSMOID_APPLE_TP_SSL
,
3135 NULL
, &policy_search
)))
3137 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot create a policy search reference");
3138 CFRelease(keychain
);
3142 if ((err
= SecPolicySearchCopyNext(policy_search
, &policy
)))
3144 cupsdLogMessage(CUPSD_LOG_ERROR
,
3145 "Cannot find a policy to use for searching");
3146 CFRelease(keychain
);
3147 CFRelease(policy_search
);
3151 memset(&ssl_options
, 0, sizeof(ssl_options
));
3152 ssl_options
.Version
= CSSM_APPLE_TP_SSL_OPTS_VERSION
;
3153 ssl_options
.ServerName
= con
->servername
;
3154 ssl_options
.ServerNameLen
= strlen(con
->servername
);
3156 options
.Data
= (uint8
*)&ssl_options
;
3157 options
.Length
= sizeof(ssl_options
);
3159 if ((err
= SecPolicySetValue(policy
, &options
)))
3161 cupsdLogMessage(CUPSD_LOG_ERROR
,
3162 "Cannot set policy value to use for searching");
3163 CFRelease(keychain
);
3164 CFRelease(policy_search
);
3168 err
= SecIdentitySearchCreateWithPolicy(policy
, NULL
, CSSM_KEYUSE_SIGN
,
3169 keychain
, FALSE
, &search
);
3172 * Assume there is exactly one SecIdentity in the keychain...
3175 err
= SecIdentitySearchCreate(keychain
, CSSM_KEYUSE_SIGN
, &search
);
3176 # endif /* HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY */
3179 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3180 "Cannot create keychain search reference: %s",
3181 cssmErrorString(err
));
3184 if ((err
= SecIdentitySearchCopyNext(search
, &identity
)))
3186 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3187 "Cannot find signing key in keychain \"%s\", error %d",
3188 ServerCertificate
, (int)err
);
3192 if (CFGetTypeID(identity
) != SecIdentityGetTypeID())
3193 cupsdLogMessage(CUPSD_LOG_ERROR
,
3194 "SecIdentitySearchCopyNext CFTypeID failure!");
3197 if ((certificates
= CFArrayCreate(NULL
, (const void **)&identity
,
3198 1, &kCFTypeArrayCallBacks
)) == NULL
)
3199 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot create certificate array");
3202 CFRelease(identity
);
3208 # if HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY
3210 CFRelease(policy_search
);
3211 # endif /* HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY */
3213 return (certificates
);
3215 #endif /* HAVE_CDSASSL */
3219 * 'get_file()' - Get a filename and state info.
3222 static char * /* O - Real filename */
3223 get_file(cupsd_client_t
*con
, /* I - Client connection */
3224 struct stat
*filestats
, /* O - File information */
3225 char *filename
, /* IO - Filename buffer */
3226 int len
) /* I - Buffer length */
3228 int status
; /* Status of filesystem calls */
3229 char *ptr
; /* Pointer info filename */
3230 int plen
; /* Remaining length after pointer */
3231 char language
[7]; /* Language subdirectory, if any */
3235 * Figure out the real filename...
3240 if (!strncmp(con
->uri
, "/ppd/", 5))
3241 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
);
3242 else if (!strncmp(con
->uri
, "/rss/", 5) && !strchr(con
->uri
+ 5, '/'))
3243 snprintf(filename
, len
, "%s/rss/%s", CacheDir
, con
->uri
+ 5);
3244 else if (!strncmp(con
->uri
, "/admin/conf/", 12))
3245 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
+ 11);
3246 else if (!strncmp(con
->uri
, "/admin/log/", 11))
3248 if (!strncmp(con
->uri
+ 11, "access_log", 10) && AccessLog
[0] == '/')
3249 strlcpy(filename
, AccessLog
, len
);
3250 else if (!strncmp(con
->uri
+ 11, "error_log", 9) && ErrorLog
[0] == '/')
3251 strlcpy(filename
, ErrorLog
, len
);
3252 else if (!strncmp(con
->uri
+ 11, "page_log", 8) && PageLog
[0] == '/')
3253 strlcpy(filename
, PageLog
, len
);
3257 else if (con
->language
)
3259 snprintf(language
, sizeof(language
), "/%s", con
->language
->language
);
3260 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3263 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3265 if ((ptr
= strchr(filename
, '?')) != NULL
)
3269 * Grab the status for this language; if there isn't a language-specific file
3270 * then fallback to the default one...
3273 if ((status
= stat(filename
, filestats
)) != 0 && language
[0] &&
3274 strncmp(con
->uri
, "/ppd/", 5) &&
3275 strncmp(con
->uri
, "/admin/conf/", 12) &&
3276 strncmp(con
->uri
, "/admin/log/", 11))
3279 * Drop the country code...
3283 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3285 if ((ptr
= strchr(filename
, '?')) != NULL
)
3288 if ((status
= stat(filename
, filestats
)) != 0)
3291 * Drop the language prefix and try the root directory...
3295 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3297 if ((ptr
= strchr(filename
, '?')) != NULL
)
3300 status
= stat(filename
, filestats
);
3305 * If we're found a directory, get the index.html file instead...
3308 if (!status
&& S_ISDIR(filestats
->st_mode
))
3311 * Make sure the URI ends with a slash...
3314 if (con
->uri
[strlen(con
->uri
) - 1] != '/')
3315 strlcat(con
->uri
, "/", sizeof(con
->uri
));
3318 * Find the directory index file, trying every language...
3323 if (status
&& language
[0])
3326 * Try a different language subset...
3330 language
[0] = '\0'; /* Strip country code */
3332 language
[0] = '\0'; /* Strip language */
3336 * Look for the index file...
3339 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3341 if ((ptr
= strchr(filename
, '?')) != NULL
)
3344 ptr
= filename
+ strlen(filename
);
3345 plen
= len
- (ptr
- filename
);
3347 strlcpy(ptr
, "index.html", plen
);
3348 status
= stat(filename
, filestats
);
3353 strlcpy(ptr
, "index.class", plen
);
3354 status
= stat(filename
, filestats
);
3356 #endif /* HAVE_JAVA */
3361 strlcpy(ptr
, "index.pl", plen
);
3362 status
= stat(filename
, filestats
);
3364 #endif /* HAVE_PERL */
3369 strlcpy(ptr
, "index.php", plen
);
3370 status
= stat(filename
, filestats
);
3372 #endif /* HAVE_PHP */
3377 strlcpy(ptr
, "index.pyc", plen
);
3378 status
= stat(filename
, filestats
);
3383 strlcpy(ptr
, "index.py", plen
);
3384 status
= stat(filename
, filestats
);
3386 #endif /* HAVE_PYTHON */
3389 while (status
&& language
[0]);
3392 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "get_file: %d filename=%s size=%d",
3393 con
->http
.fd
, filename
,
3394 status
? -1 : (int)filestats
->st_size
);
3397 con
->http
.data_remaining
= (int)filestats
->st_size
;
3407 * 'install_conf_file()' - Install a configuration file.
3410 static http_status_t
/* O - Status */
3411 install_conf_file(cupsd_client_t
*con
) /* I - Connection */
3413 cups_file_t
*in
, /* Input file */
3414 *out
; /* Output file */
3415 char buffer
[1024]; /* Copy buffer */
3416 int bytes
; /* Number of bytes */
3417 char conffile
[1024], /* Configuration filename */
3418 newfile
[1024], /* New config filename */
3419 oldfile
[1024]; /* Old config filename */
3420 struct stat confinfo
; /* Config file info */
3424 * First construct the filenames...
3427 snprintf(conffile
, sizeof(conffile
), "%s%s", ServerRoot
, con
->uri
+ 11);
3428 snprintf(newfile
, sizeof(newfile
), "%s%s.N", ServerRoot
, con
->uri
+ 11);
3429 snprintf(oldfile
, sizeof(oldfile
), "%s%s.O", ServerRoot
, con
->uri
+ 11);
3431 cupsdLogMessage(CUPSD_LOG_INFO
, "Installing config file \"%s\"...", conffile
);
3434 * Get the owner, group, and permissions of the configuration file.
3435 * If it doesn't exist, assign it to the User and Group in the
3436 * cupsd.conf file with mode 0640 permissions.
3439 if (stat(conffile
, &confinfo
))
3441 confinfo
.st_uid
= User
;
3442 confinfo
.st_gid
= Group
;
3443 confinfo
.st_mode
= ConfigFilePerm
;
3447 * Open the request file and new config file...
3450 if ((in
= cupsFileOpen(con
->filename
, "rb")) == NULL
)
3452 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open request file \"%s\" - %s",
3453 con
->filename
, strerror(errno
));
3454 return (HTTP_SERVER_ERROR
);
3457 if ((out
= cupsFileOpen(newfile
, "wb")) == NULL
)
3460 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open config file \"%s\" - %s",
3461 newfile
, strerror(errno
));
3462 return (HTTP_SERVER_ERROR
);
3465 fchmod(cupsFileNumber(out
), confinfo
.st_mode
);
3466 fchown(cupsFileNumber(out
), confinfo
.st_uid
, confinfo
.st_gid
);
3469 * Copy from the request to the new config file...
3472 while ((bytes
= cupsFileRead(in
, buffer
, sizeof(buffer
))) > 0)
3473 if (cupsFileWrite(out
, buffer
, bytes
) < bytes
)
3475 cupsdLogMessage(CUPSD_LOG_ERROR
,
3476 "Unable to copy to config file \"%s\" - %s",
3477 newfile
, strerror(errno
));
3483 return (HTTP_SERVER_ERROR
);
3487 * Close the files...
3491 if (cupsFileClose(out
))
3493 cupsdLogMessage(CUPSD_LOG_ERROR
,
3494 "Error file closing config file \"%s\" - %s",
3495 newfile
, strerror(errno
));
3499 return (HTTP_SERVER_ERROR
);
3503 * Remove the request file...
3506 unlink(con
->filename
);
3507 cupsdClearString(&con
->filename
);
3510 * Unlink the old backup, rename the current config file to the backup
3511 * filename, and rename the new config file to the config file name...
3514 if (unlink(oldfile
))
3515 if (errno
!= ENOENT
)
3517 cupsdLogMessage(CUPSD_LOG_ERROR
,
3518 "Unable to remove backup config file \"%s\" - %s",
3519 oldfile
, strerror(errno
));
3523 return (HTTP_SERVER_ERROR
);
3526 if (rename(conffile
, oldfile
))
3527 if (errno
!= ENOENT
)
3529 cupsdLogMessage(CUPSD_LOG_ERROR
,
3530 "Unable to rename old config file \"%s\" - %s",
3531 conffile
, strerror(errno
));
3535 return (HTTP_SERVER_ERROR
);
3538 if (rename(newfile
, conffile
))
3540 cupsdLogMessage(CUPSD_LOG_ERROR
,
3541 "Unable to rename new config file \"%s\" - %s",
3542 newfile
, strerror(errno
));
3544 rename(oldfile
, conffile
);
3547 return (HTTP_SERVER_ERROR
);
3551 * If the cupsd.conf file was updated, set the NeedReload flag...
3554 if (!strcmp(con
->uri
, "/admin/conf/cupsd.conf"))
3555 NeedReload
= RELOAD_CUPSD
;
3557 NeedReload
= RELOAD_ALL
;
3559 ReloadTime
= time(NULL
);
3562 * Return that the file was created successfully...
3565 return (HTTP_CREATED
);
3570 * 'is_cgi()' - Is the resource a CGI script/program?
3573 static int /* O - 1 = CGI, 0 = file */
3574 is_cgi(cupsd_client_t
*con
, /* I - Client connection */
3575 const char *filename
, /* I - Real filename */
3576 struct stat
*filestats
, /* I - File information */
3577 mime_type_t
*type
) /* I - MIME type */
3579 const char *options
; /* Options on URL */
3582 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3583 "is_cgi(con=%p, filename=\"%s\", filestats=%p, type=%s/%s)\n",
3584 con
, filename
, filestats
, type
? type
->super
: "unknown",
3585 type
? type
->type
: "unknown");
3588 * Get the options, if any...
3591 if ((options
= strchr(con
->uri
, '?')) != NULL
)
3595 if (strchr(options
, '='))
3596 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", options
);
3600 * Check for known types...
3603 if (!type
|| strcasecmp(type
->super
, "application"))
3605 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "is_cgi: Returning 0...");
3609 if (!strcasecmp(type
->type
, "x-httpd-cgi") &&
3610 (filestats
->st_mode
& 0111))
3613 * "application/x-httpd-cgi" is a CGI script.
3616 cupsdSetString(&con
->command
, filename
);
3618 filename
= strrchr(filename
, '/') + 1; /* Filename always absolute */
3620 cupsdSetString(&con
->options
, options
);
3622 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3623 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3624 con
->command
, con
->options
);
3629 else if (!strcasecmp(type
->type
, "x-httpd-java"))
3632 * "application/x-httpd-java" is a Java servlet.
3635 cupsdSetString(&con
->command
, CUPS_JAVA
);
3638 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3640 cupsdSetStringf(&con
->options
, " %s", filename
);
3642 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3643 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3644 con
->command
, con
->options
);
3648 #endif /* HAVE_JAVA */
3650 else if (!strcasecmp(type
->type
, "x-httpd-perl"))
3653 * "application/x-httpd-perl" is a Perl page.
3656 cupsdSetString(&con
->command
, CUPS_PERL
);
3659 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3661 cupsdSetStringf(&con
->options
, " %s", filename
);
3663 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3664 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3665 con
->command
, con
->options
);
3669 #endif /* HAVE_PERL */
3671 else if (!strcasecmp(type
->type
, "x-httpd-php"))
3674 * "application/x-httpd-php" is a PHP page.
3677 cupsdSetString(&con
->command
, CUPS_PHP
);
3680 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3682 cupsdSetStringf(&con
->options
, " %s", filename
);
3684 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3685 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3686 con
->command
, con
->options
);
3690 #endif /* HAVE_PHP */
3692 else if (!strcasecmp(type
->type
, "x-httpd-python"))
3695 * "application/x-httpd-python" is a Python page.
3698 cupsdSetString(&con
->command
, CUPS_PYTHON
);
3701 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3703 cupsdSetStringf(&con
->options
, " %s", filename
);
3705 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3706 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3707 con
->command
, con
->options
);
3711 #endif /* HAVE_PYTHON */
3713 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "is_cgi: Returning 0...");
3720 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
3723 static int /* O - 0 if relative, 1 if absolute */
3724 is_path_absolute(const char *path
) /* I - Input path */
3727 * Check for a leading slash...
3734 * Check for "/.." in the path...
3737 while ((path
= strstr(path
, "/..")) != NULL
)
3739 if (!path
[3] || path
[3] == '/')
3746 * If we haven't found any relative paths, return 1 indicating an
3756 * 'make_certificate()' - Make a self-signed SSL/TLS certificate.
3759 static int /* O - 1 on success, 0 on failure */
3760 make_certificate(cupsd_client_t
*con
) /* I - Client connection */
3762 #if defined(HAVE_LIBSSL) && defined(HAVE_WAITPID)
3763 int pid
, /* Process ID of command */
3764 status
; /* Status of command */
3765 char command
[1024], /* Command */
3766 *argv
[12], /* Command-line arguments */
3767 *envp
[MAX_ENV
+ 1], /* Environment variables */
3768 home
[1024], /* HOME environment variable */
3769 infofile
[1024], /* Type-in information for cert */
3770 seedfile
[1024]; /* Random number seed file */
3771 int envc
, /* Number of environment variables */
3772 bytes
; /* Bytes written */
3773 cups_file_t
*fp
; /* Seed/info file */
3774 int infofd
; /* Info file descriptor */
3778 * Run the "openssl" command to seed the random number generator and
3779 * generate a self-signed certificate that is good for 10 years:
3781 * openssl rand -rand seedfile 1
3783 * openssl req -new -x509 -keyout ServerKey \
3784 * -out ServerCertificate -days 3650 -nodes
3786 * The seeding step is crucial in ensuring that the openssl command
3787 * does not block on systems without sufficient entropy...
3790 if (!cupsFileFind("openssl", getenv("PATH"), 1, command
, sizeof(command
)))
3792 cupsdLogMessage(CUPSD_LOG_ERROR
,
3793 "No SSL certificate and openssl command not found!");
3797 if (access("/dev/urandom", 0))
3800 * If the system doesn't provide /dev/urandom, then any random source
3801 * will probably be blocking-style, so generate some random data to
3802 * use as a seed for the certificate. Note that we have already
3803 * seeded the random number generator in cupsdInitCerts()...
3806 cupsdLogMessage(CUPSD_LOG_INFO
,
3807 "Seeding the random number generator...");
3809 snprintf(home
, sizeof(home
), "HOME=%s", TempDir
);
3812 * Write the seed file...
3815 if ((fp
= cupsTempFile2(seedfile
, sizeof(seedfile
))) == NULL
)
3817 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to create seed file %s - %s",
3818 seedfile
, strerror(errno
));
3822 for (bytes
= 0; bytes
< 262144; bytes
++)
3823 cupsFilePutChar(fp
, random());
3828 * Run the openssl command to seed its random number generator...
3831 argv
[0] = "openssl";
3838 envc
= cupsdLoadEnv(envp
, MAX_ENV
);
3839 envp
[envc
++] = home
;
3842 if (!cupsdStartProcess(command
, argv
, envp
, -1, -1, -1, -1, -1, 1, &pid
))
3848 while (waitpid(pid
, &status
, 0) < 0)
3855 cupsdFinishProcess(pid
, command
, sizeof(command
));
3858 * Remove the seed file, as it is no longer needed...
3865 if (WIFEXITED(status
))
3866 cupsdLogMessage(CUPSD_LOG_ERROR
,
3867 "Unable to seed random number generator - "
3868 "the openssl command stopped with status %d!",
3869 WEXITSTATUS(status
));
3871 cupsdLogMessage(CUPSD_LOG_ERROR
,
3872 "Unable to seed random number generator - "
3873 "the openssl command crashed on signal %d!",
3881 * Create a file with the certificate information fields...
3883 * Note: This assumes that the default questions are asked by the openssl
3887 if ((fp
= cupsTempFile2(infofile
, sizeof(infofile
))) == NULL
)
3889 cupsdLogMessage(CUPSD_LOG_ERROR
,
3890 "Unable to create certificate information file %s - %s",
3891 infofile
, strerror(errno
));
3895 cupsFilePrintf(fp
, ".\n.\n.\n%s\n.\n%s\n%s\n",
3896 ServerName
, ServerName
, ServerAdmin
);
3899 cupsdLogMessage(CUPSD_LOG_INFO
,
3900 "Generating SSL server key and certificate...");
3902 argv
[0] = "openssl";
3906 argv
[4] = "-keyout";
3907 argv
[5] = ServerKey
;
3909 argv
[7] = ServerCertificate
;
3912 argv
[10] = "-nodes";
3915 cupsdLoadEnv(envp
, MAX_ENV
);
3917 infofd
= open(infofile
, O_RDONLY
);
3919 if (!cupsdStartProcess(command
, argv
, envp
, infofd
, -1, -1, -1, -1, 1, &pid
))
3929 while (waitpid(pid
, &status
, 0) < 0)
3936 cupsdFinishProcess(pid
, command
, sizeof(command
));
3940 if (WIFEXITED(status
))
3941 cupsdLogMessage(CUPSD_LOG_ERROR
,
3942 "Unable to create SSL server key and certificate - "
3943 "the openssl command stopped with status %d!",
3944 WEXITSTATUS(status
));
3946 cupsdLogMessage(CUPSD_LOG_ERROR
,
3947 "Unable to create SSL server key and certificate - "
3948 "the openssl command crashed on signal %d!",
3953 cupsdLogMessage(CUPSD_LOG_INFO
, "Created SSL server key file \"%s\"...",
3955 cupsdLogMessage(CUPSD_LOG_INFO
,
3956 "Created SSL server certificate file \"%s\"...",
3962 #elif defined(HAVE_GNUTLS)
3963 gnutls_x509_crt crt
; /* Self-signed certificate */
3964 gnutls_x509_privkey key
; /* Encryption key */
3965 cups_lang_t
*language
; /* Default language info */
3966 cups_file_t
*fp
; /* Key/cert file */
3967 unsigned char buffer
[8192]; /* Buffer for x509 data */
3968 size_t bytes
; /* Number of bytes of data */
3969 unsigned char serial
[4]; /* Serial number buffer */
3970 time_t curtime
; /* Current time */
3971 int result
; /* Result of GNU TLS calls */
3975 * Create the encryption key...
3978 cupsdLogMessage(CUPSD_LOG_INFO
, "Generating SSL server key...");
3980 gnutls_x509_privkey_init(&key
);
3981 gnutls_x509_privkey_generate(key
, GNUTLS_PK_RSA
, 2048, 0);
3987 bytes
= sizeof(buffer
);
3989 if ((result
= gnutls_x509_privkey_export(key
, GNUTLS_X509_FMT_PEM
,
3990 buffer
, &bytes
)) < 0)
3992 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to export SSL server key - %s",
3993 gnutls_strerror(result
));
3994 gnutls_x509_privkey_deinit(key
);
3997 else if ((fp
= cupsFileOpen(ServerKey
, "w")) != NULL
)
3999 cupsFileWrite(fp
, (char *)buffer
, bytes
);
4002 cupsdLogMessage(CUPSD_LOG_INFO
, "Created SSL server key file \"%s\"...",
4007 cupsdLogMessage(CUPSD_LOG_ERROR
,
4008 "Unable to create SSL server key file \"%s\" - %s",
4009 ServerKey
, strerror(errno
));
4010 gnutls_x509_privkey_deinit(key
);
4015 * Create the self-signed certificate...
4018 cupsdLogMessage(CUPSD_LOG_INFO
, "Generating self-signed SSL certificate...");
4020 language
= cupsLangDefault();
4021 curtime
= time(NULL
);
4022 serial
[0] = curtime
>> 24;
4023 serial
[1] = curtime
>> 16;
4024 serial
[2] = curtime
>> 8;
4025 serial
[3] = curtime
;
4027 gnutls_x509_crt_init(&crt
);
4028 if (strlen(language
->language
) == 5)
4029 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
4030 language
->language
+ 3, 2);
4032 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
4034 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COMMON_NAME
, 0,
4035 ServerName
, strlen(ServerName
));
4036 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATION_NAME
, 0,
4037 ServerName
, strlen(ServerName
));
4038 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATIONAL_UNIT_NAME
,
4040 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_STATE_OR_PROVINCE_NAME
, 0,
4042 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_LOCALITY_NAME
, 0,
4044 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_PKCS9_EMAIL
, 0,
4045 ServerAdmin
, strlen(ServerAdmin
));
4046 gnutls_x509_crt_set_key(crt
, key
);
4047 gnutls_x509_crt_set_serial(crt
, serial
, sizeof(serial
));
4048 gnutls_x509_crt_set_activation_time(crt
, curtime
);
4049 gnutls_x509_crt_set_expiration_time(crt
, curtime
+ 10 * 365 * 86400);
4050 gnutls_x509_crt_set_ca_status(crt
, 0);
4051 gnutls_x509_crt_set_subject_alternative_name(crt
, GNUTLS_SAN_DNSNAME
,
4053 gnutls_x509_crt_set_key_purpose_oid(crt
, GNUTLS_KP_TLS_WWW_SERVER
, 0);
4054 gnutls_x509_crt_set_key_usage(crt
, GNUTLS_KEY_KEY_ENCIPHERMENT
);
4055 gnutls_x509_crt_set_version(crt
, 3);
4057 bytes
= sizeof(buffer
);
4058 if (gnutls_x509_crt_get_key_id(crt
, 0, buffer
, &bytes
) >= 0)
4059 gnutls_x509_crt_set_subject_key_id(crt
, buffer
, bytes
);
4061 gnutls_x509_crt_sign(crt
, crt
, key
);
4067 bytes
= sizeof(buffer
);
4068 if ((result
= gnutls_x509_crt_export(crt
, GNUTLS_X509_FMT_PEM
,
4069 buffer
, &bytes
)) < 0)
4070 cupsdLogMessage(CUPSD_LOG_ERROR
,
4071 "Unable to export SSL server certificate - %s",
4072 gnutls_strerror(result
));
4073 else if ((fp
= cupsFileOpen(ServerCertificate
, "w")) != NULL
)
4075 cupsFileWrite(fp
, (char *)buffer
, bytes
);
4078 cupsdLogMessage(CUPSD_LOG_INFO
,
4079 "Created SSL server certificate file \"%s\"...",
4083 cupsdLogMessage(CUPSD_LOG_ERROR
,
4084 "Unable to create SSL server certificate file \"%s\" - %s",
4085 ServerCertificate
, strerror(errno
));
4091 gnutls_x509_crt_deinit(crt
);
4092 gnutls_x509_privkey_deinit(key
);
4096 #elif defined(HAVE_CDSASSL) && defined(HAVE_WAITPID)
4097 int pid
, /* Process ID of command */
4098 status
; /* Status of command */
4099 char command
[1024], /* Command */
4100 *argv
[4], /* Command-line arguments */
4101 *envp
[MAX_ENV
+ 1], /* Environment variables */
4102 keychain
[1024], /* Keychain argument */
4103 infofile
[1024]; /* Type-in information for cert */
4104 cups_file_t
*fp
; /* Seed/info file */
4105 int infofd
; /* Info file descriptor */
4109 * Run the "certtool" command to generate a self-signed certificate...
4112 if (!cupsFileFind("certtool", getenv("PATH"), 1, command
, sizeof(command
)))
4114 cupsdLogMessage(CUPSD_LOG_ERROR
,
4115 "No SSL certificate and certtool command not found!");
4120 * Create a file with the certificate information fields...
4122 * Note: This assumes that the default questions are asked by the certtool
4126 if ((fp
= cupsTempFile2(infofile
, sizeof(infofile
))) == NULL
)
4128 cupsdLogMessage(CUPSD_LOG_ERROR
,
4129 "Unable to create certificate information file %s - %s",
4130 infofile
, strerror(errno
));
4134 cupsFilePrintf(fp
, "%s\nr\n\ny\nb\ns\ny\n%s\n\n\n\n\n%s\ny\n",
4135 con
->servername
, con
->servername
, ServerAdmin
);
4138 cupsdLogMessage(CUPSD_LOG_INFO
,
4139 "Generating SSL server key and certificate...");
4141 snprintf(keychain
, sizeof(keychain
), "k=%s", ServerCertificate
);
4143 argv
[0] = "certtool";
4148 cupsdLoadEnv(envp
, MAX_ENV
);
4150 infofd
= open(infofile
, O_RDONLY
);
4152 if (!cupsdStartProcess(command
, argv
, envp
, infofd
, -1, -1, -1, -1, 1, &pid
))
4162 while (waitpid(pid
, &status
, 0) < 0)
4169 cupsdFinishProcess(pid
, command
, sizeof(command
));
4173 if (WIFEXITED(status
))
4174 cupsdLogMessage(CUPSD_LOG_ERROR
,
4175 "Unable to create SSL server key and certificate - "
4176 "the certtool command stopped with status %d!",
4177 WEXITSTATUS(status
));
4179 cupsdLogMessage(CUPSD_LOG_ERROR
,
4180 "Unable to create SSL server key and certificate - "
4181 "the certtool command crashed on signal %d!",
4186 cupsdLogMessage(CUPSD_LOG_INFO
,
4187 "Created SSL server certificate file \"%s\"...",
4195 #endif /* HAVE_LIBSSL && HAVE_WAITPID */
4197 #endif /* HAVE_SSL */
4201 * 'pipe_command()' - Pipe the output of a command to the remote client.
4204 static int /* O - Process ID */
4205 pipe_command(cupsd_client_t
*con
, /* I - Client connection */
4206 int infile
, /* I - Standard input for command */
4207 int *outfile
, /* O - Standard output for command */
4208 char *command
, /* I - Command to run */
4209 char *options
, /* I - Options for command */
4210 int root
) /* I - Run as root? */
4212 int i
; /* Looping var */
4213 int pid
; /* Process ID */
4214 char *commptr
, /* Command string pointer */
4215 commch
; /* Command string character */
4216 char *uriptr
; /* URI string pointer */
4217 int fds
[2]; /* Pipe FDs */
4218 int argc
; /* Number of arguments */
4219 int envc
; /* Number of environment variables */
4220 char argbuf
[10240], /* Argument buffer */
4221 *argv
[100], /* Argument strings */
4222 *envp
[MAX_ENV
+ 20]; /* Environment variables */
4223 char auth_type
[256], /* AUTH_TYPE environment variable */
4224 content_length
[1024], /* CONTENT_LENGTH environment variable */
4225 content_type
[1024], /* CONTENT_TYPE environment variable */
4226 http_cookie
[32768], /* HTTP_COOKIE environment variable */
4227 http_referer
[1024], /* HTTP_REFERER environment variable */
4228 http_user_agent
[1024], /* HTTP_USER_AGENT environment variable */
4229 lang
[1024], /* LANG environment variable */
4230 path_info
[1024], /* PATH_INFO environment variable */
4231 remote_addr
[1024], /* REMOTE_ADDR environment variable */
4232 remote_host
[1024], /* REMOTE_HOST environment variable */
4233 remote_user
[1024], /* REMOTE_USER environment variable */
4234 script_filename
[1024], /* SCRIPT_FILENAME environment variable */
4235 script_name
[1024], /* SCRIPT_NAME environment variable */
4236 server_name
[1024], /* SERVER_NAME environment variable */
4237 server_port
[1024]; /* SERVER_PORT environment variable */
4238 ipp_attribute_t
*attr
; /* attributes-natural-language attribute */
4242 * Parse a copy of the options string, which is of the form:
4244 * argument+argument+argument
4245 * ?argument+argument+argument
4246 * param=value¶m=value
4247 * ?param=value¶m=value
4248 * /name?argument+argument+argument
4249 * /name?param=value¶m=value
4251 * If the string contains an "=" character after the initial name,
4252 * then we treat it as a HTTP GET form request and make a copy of
4253 * the remaining string for the environment variable.
4255 * The string is always parsed out as command-line arguments, to
4256 * be consistent with Apache...
4259 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4260 "pipe_command: command=\"%s\", options=\"%s\"",
4261 command
, options
? options
: "(null)");
4266 strlcpy(argbuf
, options
, sizeof(argbuf
));
4270 if (argbuf
[0] == '/')
4273 * Found some trailing path information, set PATH_INFO...
4276 if ((commptr
= strchr(argbuf
, '?')) == NULL
)
4277 commptr
= argbuf
+ strlen(argbuf
);
4281 snprintf(path_info
, sizeof(path_info
), "PATH_INFO=%s", argbuf
);
4287 path_info
[0] = '\0';
4289 if (*commptr
== ' ')
4293 if (*commptr
== '?' && con
->operation
== HTTP_GET
&& !con
->query_string
)
4296 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", commptr
);
4303 argv
[argc
++] = commptr
;
4305 for (; *commptr
&& argc
< 99; commptr
++)
4308 * Break arguments whenever we see a + or space...
4311 if (*commptr
== ' ' || *commptr
== '+')
4313 while (*commptr
== ' ' || *commptr
== '+')
4317 * If we don't have a blank string, save it as another argument...
4322 argv
[argc
] = commptr
;
4328 else if (*commptr
== '%' && isxdigit(commptr
[1] & 255) &&
4329 isxdigit(commptr
[2] & 255))
4332 * Convert the %xx notation to the individual character.
4335 if (commptr
[1] >= '0' && commptr
[1] <= '9')
4336 *commptr
= (commptr
[1] - '0') << 4;
4338 *commptr
= (tolower(commptr
[1]) - 'a' + 10) << 4;
4340 if (commptr
[2] >= '0' && commptr
[2] <= '9')
4341 *commptr
|= commptr
[2] - '0';
4343 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
4345 _cups_strcpy(commptr
+ 1, commptr
+ 3);
4348 * Check for a %00 and break if that is the case...
4360 * Setup the environment variables as needed...
4363 if (con
->username
[0])
4365 snprintf(auth_type
, sizeof(auth_type
), "AUTH_TYPE=%s",
4366 httpGetField(HTTP(con
), HTTP_FIELD_AUTHORIZATION
));
4368 if ((uriptr
= strchr(auth_type
+ 10, ' ')) != NULL
)
4372 auth_type
[0] = '\0';
4375 (attr
= ippFindAttribute(con
->request
, "attributes-natural-language",
4376 IPP_TAG_LANGUAGE
)) != NULL
)
4378 switch (strlen(attr
->values
[0].string
.text
))
4382 * This is an unknown or badly formatted language code; use
4383 * the POSIX locale...
4386 strcpy(lang
, "LANG=C");
4391 * Just the language code (ll)...
4394 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8",
4395 attr
->values
[0].string
.text
);
4400 * Language and country code (ll-cc)...
4403 snprintf(lang
, sizeof(lang
), "LANG=%c%c_%c%c.UTF8",
4404 attr
->values
[0].string
.text
[0],
4405 attr
->values
[0].string
.text
[1],
4406 toupper(attr
->values
[0].string
.text
[3] & 255),
4407 toupper(attr
->values
[0].string
.text
[4] & 255));
4411 else if (con
->language
)
4412 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8", con
->language
->language
);
4414 strcpy(lang
, "LANG=C");
4416 strcpy(remote_addr
, "REMOTE_ADDR=");
4417 httpAddrString(con
->http
.hostaddr
, remote_addr
+ 12,
4418 sizeof(remote_addr
) - 12);
4420 snprintf(remote_host
, sizeof(remote_host
), "REMOTE_HOST=%s",
4421 con
->http
.hostname
);
4423 snprintf(script_name
, sizeof(script_name
), "SCRIPT_NAME=%s", con
->uri
);
4424 if ((uriptr
= strchr(script_name
, '?')) != NULL
)
4427 snprintf(script_filename
, sizeof(script_filename
), "SCRIPT_FILENAME=%s%s",
4428 DocumentRoot
, script_name
+ 12);
4430 sprintf(server_port
, "SERVER_PORT=%d", con
->serverport
);
4432 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
4435 envc
= cupsdLoadEnv(envp
, (int)(sizeof(envp
) / sizeof(envp
[0])));
4438 envp
[envc
++] = auth_type
;
4440 envp
[envc
++] = lang
;
4441 envp
[envc
++] = "REDIRECT_STATUS=1";
4442 envp
[envc
++] = "GATEWAY_INTERFACE=CGI/1.1";
4443 envp
[envc
++] = server_name
;
4444 envp
[envc
++] = server_port
;
4445 envp
[envc
++] = remote_addr
;
4446 envp
[envc
++] = remote_host
;
4447 envp
[envc
++] = script_name
;
4448 envp
[envc
++] = script_filename
;
4451 envp
[envc
++] = path_info
;
4453 if (con
->username
[0])
4455 snprintf(remote_user
, sizeof(remote_user
), "REMOTE_USER=%s", con
->username
);
4457 envp
[envc
++] = remote_user
;
4460 if (con
->http
.version
== HTTP_1_1
)
4461 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.1";
4462 else if (con
->http
.version
== HTTP_1_0
)
4463 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.0";
4465 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/0.9";
4467 if (con
->http
.cookie
)
4469 snprintf(http_cookie
, sizeof(http_cookie
), "HTTP_COOKIE=%s",
4471 envp
[envc
++] = http_cookie
;
4474 if (con
->http
.fields
[HTTP_FIELD_USER_AGENT
][0])
4476 snprintf(http_user_agent
, sizeof(http_user_agent
), "HTTP_USER_AGENT=%s",
4477 con
->http
.fields
[HTTP_FIELD_USER_AGENT
]);
4478 envp
[envc
++] = http_user_agent
;
4481 if (con
->http
.fields
[HTTP_FIELD_REFERER
][0])
4483 snprintf(http_referer
, sizeof(http_referer
), "HTTP_REFERER=%s",
4484 con
->http
.fields
[HTTP_FIELD_REFERER
]);
4485 envp
[envc
++] = http_referer
;
4488 if (con
->operation
== HTTP_GET
)
4490 envp
[envc
++] = "REQUEST_METHOD=GET";
4492 if (con
->query_string
)
4495 * Add GET form variables after ?...
4498 envp
[envc
++] = con
->query_string
;
4503 sprintf(content_length
, "CONTENT_LENGTH=" CUPS_LLFMT
,
4504 CUPS_LLCAST con
->bytes
);
4505 snprintf(content_type
, sizeof(content_type
), "CONTENT_TYPE=%s",
4506 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
4508 envp
[envc
++] = "REQUEST_METHOD=POST";
4509 envp
[envc
++] = content_length
;
4510 envp
[envc
++] = content_type
;
4514 * Tell the CGI if we are using encryption...
4518 envp
[envc
++] = "HTTPS=ON";
4521 * Terminate the environment array...
4526 if (LogLevel
== CUPSD_LOG_DEBUG2
)
4528 for (i
= 0; i
< argc
; i
++)
4529 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4530 "pipe_command: argv[%d] = \"%s\"", i
, argv
[i
]);
4531 for (i
= 0; i
< envc
; i
++)
4532 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4533 "pipe_command: envp[%d] = \"%s\"", i
, envp
[i
]);
4537 * Create a pipe for the output...
4540 if (cupsdOpenPipe(fds
))
4542 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to create pipes for CGI %s - %s",
4543 argv
[0], strerror(errno
));
4548 * Then execute the command...
4551 if (cupsdStartProcess(command
, argv
, envp
, infile
, fds
[1], CGIPipes
[1],
4552 -1, -1, root
, &pid
) < 0)
4555 * Error - can't fork!
4558 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to fork for CGI %s - %s", argv
[0],
4561 cupsdClosePipe(fds
);
4567 * Fork successful - return the PID...
4570 if (con
->username
[0])
4571 cupsdAddCert(pid
, con
->username
);
4573 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[CGI] %s started - PID = %d",
4585 * 'write_file()' - Send a file via HTTP.
4588 static int /* O - 0 on failure, 1 on success */
4589 write_file(cupsd_client_t
*con
, /* I - Client connection */
4590 http_status_t code
, /* I - HTTP status */
4591 char *filename
, /* I - Filename */
4592 char *type
, /* I - File type */
4593 struct stat
*filestats
) /* O - File information */
4595 con
->file
= open(filename
, O_RDONLY
);
4597 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "write_file: %d file=%d", con
->http
.fd
,
4603 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
4607 if (!cupsdSendHeader(con
, code
, type
, AUTH_NONE
))
4610 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
4611 httpGetDateString(filestats
->st_mtime
)) < 0)
4613 if (httpPrintf(HTTP(con
), "Content-Length: " CUPS_LLFMT
"\r\n",
4614 CUPS_LLCAST filestats
->st_size
) < 0)
4616 if (httpPrintf(HTTP(con
), "\r\n") < 0)
4619 if (cupsdFlushHeader(con
) < 0)
4622 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
4623 con
->http
.data_remaining
= filestats
->st_size
;
4625 if (con
->http
.data_remaining
<= INT_MAX
)
4626 con
->http
._data_remaining
= con
->http
.data_remaining
;
4628 con
->http
._data_remaining
= INT_MAX
;
4630 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
,
4631 (cupsd_selfunc_t
)cupsdWriteClient
, con
);
4638 * 'write_pipe()' - Flag that data is available on the CGI pipe.
4642 write_pipe(cupsd_client_t
*con
) /* I - Client connection */
4644 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "write_pipe: CGI output on fd %d...",
4647 con
->file_ready
= 1;
4649 cupsdRemoveSelect(con
->file
);
4650 cupsdAddSelect(con
->http
.fd
, NULL
, (cupsd_selfunc_t
)cupsdWriteClient
, con
);
4655 * End of "$Id: client.c 6999 2007-09-28 19:46:53Z mike $".