2 * "$Id: client.c 6999 2007-09-28 19:46:53Z mike $"
4 * Client routines for the Common UNIX Printing System (CUPS) scheduler.
6 * Copyright 2007-2008 by Apple Inc.
7 * Copyright 1997-2007 by Easy Software Products, all rights reserved.
9 * This file contains Kerberos support code, copyright 2006 by
12 * These coded instructions, statements, and computer programs are the
13 * property of Apple Inc. and are protected by Federal copyright
14 * law. Distribution and use rights are outlined in the file "LICENSE.txt"
15 * which should have been included with this file. If this file is
16 * file is missing or damaged, see the license at "http://www.cups.org/".
20 * cupsdAcceptClient() - Accept a new client.
21 * cupsdCloseAllClients() - Close all remote clients immediately.
22 * cupsdCloseClient() - Close a remote client.
23 * cupsdFlushHeader() - Flush the header fields to the client.
24 * cupsdReadClient() - Read data from a client.
25 * cupsdSendCommand() - Send output from a command via HTTP.
26 * cupsdSendError() - Send an error message via HTTP.
27 * cupsdSendHeader() - Send an HTTP request.
28 * cupsdUpdateCGI() - Read status messages from CGI scripts and programs.
29 * cupsdWriteClient() - Write data to a client as needed.
30 * check_if_modified() - Decode an "If-Modified-Since" line.
31 * encrypt_client() - Enable encryption for the client...
32 * get_cdsa_certificate() - Convert a keychain name into the CFArrayRef
33 * required by SSLSetCertificate.
34 * get_file() - Get a filename and state info.
35 * install_conf_file() - Install a configuration file.
36 * is_cgi() - Is the resource a CGI script/program?
37 * is_path_absolute() - Is a path absolute and free of relative elements.
38 * make_certificate() - Make a self-signed SSL/TLS certificate.
39 * pipe_command() - Pipe the output of a command to the remote client.
40 * write_file() - Send a file via HTTP.
41 * write_pipe() - Flag that data is available on the CGI pipe.
45 * Include necessary headers...
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
);
148 cupsdLogMessage(CUPSD_LOG_ERROR
,
149 "Unable to allocate memory for client array!");
150 cupsdPauseListening();
154 if ((con
= calloc(1, sizeof(cupsd_client_t
))) == NULL
)
156 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to allocate memory for client!");
157 cupsdPauseListening();
161 con
->http
.activity
= time(NULL
);
163 con
->http
.hostaddr
= &(con
->clientaddr
);
166 * Accept the client and get the remote address...
169 addrlen
= sizeof(http_addr_t
);
171 if ((con
->http
.fd
= accept(lis
->fd
, (struct sockaddr
*)con
->http
.hostaddr
,
174 if (errno
== ENFILE
|| errno
== EMFILE
)
175 cupsdPauseListening();
177 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to accept client connection - %s.",
185 if (lis
->address
.addr
.sa_family
== AF_INET6
)
188 * Save the connected port number...
191 con
->http
.hostaddr
->ipv6
.sin6_port
= lis
->address
.ipv6
.sin6_port
;
194 * Convert IPv4 over IPv6 addresses (::ffff:n.n.n.n) to IPv4 forms we
195 * can more easily use...
198 if (con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[0] == 0 &&
199 con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[1] == 0 &&
200 ntohl(con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[2]) == 0xffff)
201 con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[2] = 0;
204 #endif /* AF_INET6 */
205 if (lis
->address
.addr
.sa_family
== AF_INET
)
206 con
->http
.hostaddr
->ipv4
.sin_port
= lis
->address
.ipv4
.sin_port
;
209 * Check the number of clients on the same address...
212 for (count
= 0, tempcon
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
214 tempcon
= (cupsd_client_t
*)cupsArrayNext(Clients
))
215 if (httpAddrEqual(tempcon
->http
.hostaddr
, con
->http
.hostaddr
))
218 if (count
>= MaxClientsPerHost
)
222 if (count
>= MaxClientsPerHost
)
224 if ((time(NULL
) - last_dos
) >= 60)
226 last_dos
= time(NULL
);
227 cupsdLogMessage(CUPSD_LOG_WARN
,
228 "Possible DoS attack - more than %d clients connecting "
230 MaxClientsPerHost
, tempcon
->http
.hostname
);
234 closesocket(con
->http
.fd
);
244 * Get the hostname or format the IP address as needed...
247 if (httpAddrLocalhost(con
->http
.hostaddr
))
250 * Map accesses from the loopback interface to "localhost"...
253 strlcpy(con
->http
.hostname
, "localhost", sizeof(con
->http
.hostname
));
254 hostname
= con
->http
.hostname
;
259 * Map accesses from the same host to the server name.
262 for (addr
= ServerAddrs
; addr
; addr
= addr
->next
)
263 if (httpAddrEqual(con
->http
.hostaddr
, &(addr
->addr
)))
268 strlcpy(con
->http
.hostname
, ServerName
, sizeof(con
->http
.hostname
));
269 hostname
= con
->http
.hostname
;
271 else if (HostNameLookups
)
272 hostname
= httpAddrLookup(con
->http
.hostaddr
, con
->http
.hostname
,
273 sizeof(con
->http
.hostname
));
277 httpAddrString(con
->http
.hostaddr
, con
->http
.hostname
,
278 sizeof(con
->http
.hostname
));
282 if (hostname
== NULL
&& HostNameLookups
== 2)
285 * Can't have an unresolved IP address with double-lookups enabled...
288 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
289 "cupsdAcceptClient: Closing connection %d...",
293 closesocket(con
->http
.fd
);
298 cupsdLogMessage(CUPSD_LOG_WARN
,
299 "Name lookup failed - connection from %s closed!",
306 if (HostNameLookups
== 2)
309 * Do double lookups as needed...
312 if ((addrlist
= httpAddrGetList(con
->http
.hostname
, AF_UNSPEC
, NULL
)) != NULL
)
315 * See if the hostname maps to the same IP address...
318 for (addr
= addrlist
; addr
; addr
= addr
->next
)
319 if (httpAddrEqual(con
->http
.hostaddr
, &(addr
->addr
)))
325 httpAddrFreeList(addrlist
);
330 * Can't have a hostname that doesn't resolve to the same IP address
331 * with double-lookups enabled...
334 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
335 "cupsdAcceptClient: Closing connection %d...",
339 closesocket(con
->http
.fd
);
344 cupsdLogMessage(CUPSD_LOG_WARN
,
345 "IP lookup failed - connection from %s closed!",
353 if (con
->http
.hostaddr
->addr
.sa_family
== AF_INET6
)
354 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdAcceptClient: %d from %s:%d (IPv6)",
355 con
->http
.fd
, con
->http
.hostname
,
356 ntohs(con
->http
.hostaddr
->ipv6
.sin6_port
));
358 #endif /* AF_INET6 */
360 if (con
->http
.hostaddr
->addr
.sa_family
== AF_LOCAL
)
361 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdAcceptClient: %d from %s (Domain)",
362 con
->http
.fd
, con
->http
.hostname
);
364 #endif /* AF_LOCAL */
365 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdAcceptClient: %d from %s:%d (IPv4)",
366 con
->http
.fd
, con
->http
.hostname
,
367 ntohs(con
->http
.hostaddr
->ipv4
.sin_port
));
370 * Get the local address the client connected to...
373 addrlen
= sizeof(temp
);
374 if (getsockname(con
->http
.fd
, (struct sockaddr
*)&temp
, &addrlen
))
376 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to get local address - %s",
379 strcpy(con
->servername
, "localhost");
380 con
->serverport
= LocalPort
;
385 if (temp
.addr
.sa_family
== AF_INET6
)
387 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
388 con
->serverport
= ntohs(lis
->address
.ipv6
.sin6_port
);
391 #endif /* AF_INET6 */
392 if (temp
.addr
.sa_family
== AF_INET
)
394 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
395 con
->serverport
= ntohs(lis
->address
.ipv4
.sin_port
);
399 strcpy(con
->servername
, "localhost");
400 con
->serverport
= LocalPort
;
404 cupsArrayAdd(Clients
, con
);
406 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
407 "cupsdAcceptClient: %d connected to server on %s:%d",
408 con
->http
.fd
, con
->servername
, con
->serverport
);
411 * Using TCP_NODELAY improves responsiveness, especially on systems
412 * with a slow loopback interface... Since we write large buffers
413 * when sending print files and requests, there shouldn't be any
414 * performance penalty for this...
418 setsockopt(con
->http
.fd
, IPPROTO_TCP
, TCP_NODELAY
, &val
, sizeof(val
));
421 * Close this file on all execs...
424 fcntl(con
->http
.fd
, F_SETFD
, fcntl(con
->http
.fd
, F_GETFD
) | FD_CLOEXEC
);
427 * Add the socket to the select() input mask.
430 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
433 * Temporarily suspend accept()'s until we lose a client...
436 if (cupsArrayCount(Clients
) == MaxClients
)
437 cupsdPauseListening();
441 * See if we are connecting on a secure port...
444 if (lis
->encryption
== HTTP_ENCRYPT_ALWAYS
)
447 * https connection; go secure...
450 con
->http
.encryption
= HTTP_ENCRYPT_ALWAYS
;
452 if (!encrypt_client(con
))
453 cupsdCloseClient(con
);
457 #endif /* HAVE_SSL */
462 * 'cupsdCloseAllClients()' - Close all remote clients immediately.
466 cupsdCloseAllClients(void)
468 cupsd_client_t
*con
; /* Current client */
471 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
473 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
474 cupsdCloseClient(con
);
479 * 'cupsdCloseClient()' - Close a remote client.
482 int /* O - 1 if partial close, 0 if fully closed */
483 cupsdCloseClient(cupsd_client_t
*con
) /* I - Client to close */
485 int partial
; /* Do partial close for SSL? */
487 SSL_CTX
*context
; /* Context for encryption */
488 SSL
*conn
; /* Connection for encryption */
489 unsigned long error
; /* Error code */
490 #elif defined(HAVE_GNUTLS)
491 http_tls_t
*conn
; /* TLS connection information */
492 int error
; /* Error code */
493 gnutls_certificate_server_credentials
*credentials
;
494 /* TLS credentials */
495 # elif defined(HAVE_CDSASSL)
496 http_tls_t
*conn
; /* CDSA connection information */
497 #endif /* HAVE_LIBSSL */
500 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdCloseClient: %d", con
->http
.fd
);
503 * Flush pending writes before closing...
506 httpFlushWrite(HTTP(con
));
512 * Shutdown encryption as needed...
520 conn
= (SSL
*)(con
->http
.tls
);
521 context
= SSL_get_SSL_CTX(conn
);
523 switch (SSL_shutdown(conn
))
526 cupsdLogMessage(CUPSD_LOG_INFO
,
527 "cupsdCloseClient: SSL shutdown successful!");
530 cupsdLogMessage(CUPSD_LOG_ERROR
,
531 "cupsdCloseClient: Fatal error during SSL shutdown!");
533 while ((error
= ERR_get_error()) != 0)
534 cupsdLogMessage(CUPSD_LOG_ERROR
, "cupsdCloseClient: %s",
535 ERR_error_string(error
, NULL
));
539 SSL_CTX_free(context
);
542 # elif defined(HAVE_GNUTLS)
543 conn
= (http_tls_t
*)(con
->http
.tls
);
544 credentials
= (gnutls_certificate_server_credentials
*)(conn
->credentials
);
546 error
= gnutls_bye(conn
->session
, GNUTLS_SHUT_WR
);
549 case GNUTLS_E_SUCCESS
:
550 cupsdLogMessage(CUPSD_LOG_INFO
,
551 "cupsdCloseClient: SSL shutdown successful!");
554 cupsdLogMessage(CUPSD_LOG_ERROR
,
555 "cupsdCloseClient: %s", gnutls_strerror(error
));
559 gnutls_deinit(conn
->session
);
560 gnutls_certificate_free_credentials(*credentials
);
564 # elif defined(HAVE_CDSASSL)
565 conn
= (http_tls_t
*)(con
->http
.tls
);
567 while (SSLClose(conn
->session
) == errSSLWouldBlock
)
570 SSLDisposeContext(conn
->session
);
572 if (conn
->certsArray
)
573 CFRelease(conn
->certsArray
);
576 # endif /* HAVE_LIBSSL */
578 con
->http
.tls
= NULL
;
580 #endif /* HAVE_SSL */
582 if (con
->pipe_pid
!= 0)
585 * Stop any CGI process...
588 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
589 "cupsdCloseClient: %d Killing process ID %d...",
590 con
->http
.fd
, con
->pipe_pid
);
591 cupsdEndProcess(con
->pipe_pid
, 1);
597 cupsdRemoveSelect(con
->file
);
599 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
600 "cupsdCloseClient: %d Closing data file %d.",
601 con
->http
.fd
, con
->file
);
608 * Close the socket and clear the file from the input set for select()...
611 if (con
->http
.fd
> 0)
616 * Only do a partial close so that the encrypted client gets everything.
619 shutdown(con
->http
.fd
, 0);
620 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
625 * Shut the socket down fully...
628 cupsdRemoveSelect(con
->http
.fd
);
640 if (con
->http
.input_set
)
641 free(con
->http
.input_set
);
643 httpClearCookie(HTTP(con
));
645 cupsdClearString(&con
->filename
);
646 cupsdClearString(&con
->command
);
647 cupsdClearString(&con
->options
);
648 cupsdClearString(&con
->query_string
);
652 ippDelete(con
->request
);
658 ippDelete(con
->response
);
659 con
->response
= NULL
;
664 cupsLangFree(con
->language
);
665 con
->language
= NULL
;
668 #ifdef HAVE_AUTHORIZATION_H
671 AuthorizationFree(con
->authref
, kAuthorizationFlagDefaults
);
674 #endif /* HAVE_AUTHORIZATION_H */
677 * Re-enable new client connections if we are going back under the
681 if (cupsArrayCount(Clients
) == MaxClients
)
682 cupsdResumeListening();
685 * Compact the list of clients as necessary...
688 cupsArrayRemove(Clients
, con
);
698 * 'cupsdFlushHeader()' - Flush the header fields to the client.
701 int /* I - Bytes written or -1 on error */
702 cupsdFlushHeader(cupsd_client_t
*con
) /* I - Client to flush to */
704 int bytes
= httpFlushWrite(HTTP(con
));
706 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
713 * 'cupsdReadClient()' - Read data from a client.
717 cupsdReadClient(cupsd_client_t
*con
) /* I - Client to read from */
719 char line
[32768], /* Line from client... */
720 operation
[64], /* Operation code from socket */
721 version
[64], /* HTTP version number string */
722 locale
[64], /* Locale */
723 *ptr
; /* Pointer into strings */
724 int major
, minor
; /* HTTP version numbers */
725 http_status_t status
; /* Transfer status */
726 ipp_state_t ipp_state
; /* State of IPP transfer */
727 int bytes
; /* Number of bytes to POST */
728 char *filename
; /* Name of file for GET/HEAD */
729 char buf
[1024]; /* Buffer for real filename */
730 struct stat filestats
; /* File information */
731 mime_type_t
*type
; /* MIME type of file */
732 cupsd_printer_t
*p
; /* Printer */
733 static unsigned request_id
= 0; /* Request ID for temp files */
736 status
= HTTP_CONTINUE
;
738 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
739 "cupsdReadClient: %d, used=%d, file=%d state=%d",
740 con
->http
.fd
, con
->http
.used
, con
->file
, con
->http
.state
);
744 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdReadClient: http error seen...");
745 cupsdCloseClient(con
);
753 * Automatically check for a SSL/TLS handshake...
758 if (recv(con
->http
.fd
, buf
, 1, MSG_PEEK
) == 1 &&
759 (!buf
[0] || !strchr("DGHOPT", buf
[0])))
762 * Encrypt this connection...
765 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
766 "cupsdReadClient: Saw first byte %02X, auto-negotiating SSL/TLS session...",
769 if (!encrypt_client(con
))
770 cupsdCloseClient(con
);
775 #endif /* HAVE_SSL */
777 switch (con
->http
.state
)
781 * See if we've received a request line...
784 if (httpGets(line
, sizeof(line
) - 1, HTTP(con
)) == NULL
)
786 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
787 "cupsdReadClient: httpGets returned EOF...");
788 cupsdCloseClient(con
);
793 * Ignore blank request lines...
800 * Clear other state variables...
803 httpClearFields(HTTP(con
));
805 con
->http
.activity
= time(NULL
);
806 con
->http
.version
= HTTP_1_0
;
807 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
808 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
809 con
->http
.data_remaining
= 0;
810 con
->http
._data_remaining
= 0;
811 con
->operation
= HTTP_WAITING
;
816 con
->username
[0] = '\0';
817 con
->password
[0] = '\0';
820 cupsdClearString(&con
->command
);
821 cupsdClearString(&con
->options
);
822 cupsdClearString(&con
->query_string
);
826 ippDelete(con
->request
);
832 ippDelete(con
->response
);
833 con
->response
= NULL
;
838 cupsLangFree(con
->language
);
839 con
->language
= NULL
;
843 con
->gss_have_creds
= 0;
844 #endif /* HAVE_GSSAPI */
847 * Grab the request line...
850 switch (sscanf(line
, "%63s%1023s%63s", operation
, con
->uri
, version
))
853 cupsdLogMessage(CUPSD_LOG_ERROR
,
854 "Bad request line \"%s\" from %s!", line
,
856 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
857 cupsdCloseClient(con
);
860 con
->http
.version
= HTTP_0_9
;
863 if (sscanf(version
, "HTTP/%d.%d", &major
, &minor
) != 2)
865 cupsdLogMessage(CUPSD_LOG_ERROR
,
866 "Bad request line \"%s\" from %s!", line
,
868 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
869 cupsdCloseClient(con
);
875 con
->http
.version
= (http_version_t
)(major
* 100 + minor
);
876 if (con
->http
.version
== HTTP_1_1
&& KeepAlive
)
877 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
879 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
883 cupsdSendError(con
, HTTP_NOT_SUPPORTED
, CUPSD_AUTH_NONE
);
884 cupsdCloseClient(con
);
891 * Handle full URLs in the request line...
894 if (strcmp(con
->uri
, "*"))
896 char method
[HTTP_MAX_URI
], /* Method/scheme */
897 userpass
[HTTP_MAX_URI
], /* Username:password */
898 hostname
[HTTP_MAX_URI
], /* Hostname */
899 resource
[HTTP_MAX_URI
]; /* Resource path */
900 int port
; /* Port number */
904 * Separate the URI into its components...
907 httpSeparateURI(HTTP_URI_CODING_MOST
, con
->uri
,
908 method
, sizeof(method
),
909 userpass
, sizeof(userpass
),
910 hostname
, sizeof(hostname
), &port
,
911 resource
, sizeof(resource
));
914 * Only allow URIs with the servername, localhost, or an IP
918 if (strcmp(method
, "file") &&
919 strcasecmp(hostname
, ServerName
) &&
920 strcasecmp(hostname
, "localhost") &&
921 !isdigit(hostname
[0]))
924 * Nope, we don't do proxies...
927 cupsdLogMessage(CUPSD_LOG_ERROR
, "Bad URI \"%s\" in request!",
929 cupsdSendError(con
, HTTP_METHOD_NOT_ALLOWED
, CUPSD_AUTH_NONE
);
930 cupsdCloseClient(con
);
935 * Copy the resource portion back into the URI; both resource and
936 * con->uri are HTTP_MAX_URI bytes in size...
939 strcpy(con
->uri
, resource
);
943 * Process the request...
946 if (!strcmp(operation
, "GET"))
947 con
->http
.state
= HTTP_GET
;
948 else if (!strcmp(operation
, "PUT"))
949 con
->http
.state
= HTTP_PUT
;
950 else if (!strcmp(operation
, "POST"))
951 con
->http
.state
= HTTP_POST
;
952 else if (!strcmp(operation
, "DELETE"))
953 con
->http
.state
= HTTP_DELETE
;
954 else if (!strcmp(operation
, "TRACE"))
955 con
->http
.state
= HTTP_TRACE
;
956 else if (!strcmp(operation
, "OPTIONS"))
957 con
->http
.state
= HTTP_OPTIONS
;
958 else if (!strcmp(operation
, "HEAD"))
959 con
->http
.state
= HTTP_HEAD
;
962 cupsdLogMessage(CUPSD_LOG_ERROR
, "Bad operation \"%s\"!", operation
);
963 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
964 cupsdCloseClient(con
);
968 con
->start
= time(NULL
);
969 con
->operation
= con
->http
.state
;
971 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdReadClient: %d %s %s HTTP/%d.%d",
972 con
->http
.fd
, operation
, con
->uri
,
973 con
->http
.version
/ 100, con
->http
.version
% 100);
975 con
->http
.status
= HTTP_OK
;
985 * Parse incoming parameters until the status changes...
988 while ((status
= httpUpdate(HTTP(con
))) == HTTP_CONTINUE
)
989 if (con
->http
.used
== 0 ||
990 !memchr(con
->http
.buffer
, '\n', con
->http
.used
))
993 if (status
!= HTTP_OK
&& status
!= HTTP_CONTINUE
)
995 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
996 cupsdCloseClient(con
);
1002 break; /* Anti-compiler-warning-code */
1006 * Handle new transfers...
1009 if (status
== HTTP_OK
)
1011 if (con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
][0])
1014 * Figure out the locale from the Accept-Language and Content-Type
1018 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ',')) != NULL
)
1021 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ';')) != NULL
)
1024 if ((ptr
= strstr(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
], "charset=")) != NULL
)
1027 * Combine language and charset, and trim any extra params in the
1031 snprintf(locale
, sizeof(locale
), "%s.%s",
1032 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ptr
+ 8);
1034 if ((ptr
= strchr(locale
, ',')) != NULL
)
1038 snprintf(locale
, sizeof(locale
), "%s.%s",
1039 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], DefaultCharset
);
1041 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1042 "cupsdReadClient: %d Browser asked for language \"%s\"...",
1043 con
->http
.fd
, locale
);
1045 con
->language
= cupsLangGet(locale
);
1048 con
->language
= cupsLangGet(DefaultLocale
);
1050 cupsdAuthorize(con
);
1052 if (!strncmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Keep-Alive", 10) &&
1054 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
1056 if (!con
->http
.fields
[HTTP_FIELD_HOST
][0] &&
1057 con
->http
.version
>= HTTP_1_1
)
1060 * HTTP/1.1 and higher require the "Host:" field...
1063 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1065 cupsdCloseClient(con
);
1069 else if (con
->operation
== HTTP_OPTIONS
)
1072 * Do OPTIONS command...
1075 if (con
->best
&& con
->best
->type
!= CUPSD_AUTH_NONE
)
1077 if (!cupsdSendHeader(con
, HTTP_UNAUTHORIZED
, NULL
, CUPSD_AUTH_NONE
))
1079 cupsdCloseClient(con
);
1084 if (!strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") &&
1085 con
->http
.tls
== NULL
)
1089 * Do encryption stuff...
1092 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
, CUPSD_AUTH_NONE
))
1094 cupsdCloseClient(con
);
1098 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1099 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1100 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1101 httpPrintf(HTTP(con
), "\r\n");
1103 if (cupsdFlushHeader(con
) < 0)
1105 cupsdCloseClient(con
);
1109 if (!encrypt_client(con
))
1111 cupsdCloseClient(con
);
1115 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
1117 cupsdCloseClient(con
);
1120 #endif /* HAVE_SSL */
1123 if (!cupsdSendHeader(con
, HTTP_OK
, NULL
, CUPSD_AUTH_NONE
))
1125 cupsdCloseClient(con
);
1129 httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n");
1130 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1131 httpPrintf(HTTP(con
), "\r\n");
1133 if (cupsdFlushHeader(con
) < 0)
1135 cupsdCloseClient(con
);
1139 else if (!is_path_absolute(con
->uri
))
1142 * Protect against malicious users!
1145 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1147 cupsdCloseClient(con
);
1153 if (!strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") &&
1154 con
->http
.tls
== NULL
)
1158 * Do encryption stuff...
1161 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
, CUPSD_AUTH_NONE
))
1163 cupsdCloseClient(con
);
1167 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1168 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1169 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1170 httpPrintf(HTTP(con
), "\r\n");
1172 if (cupsdFlushHeader(con
) < 0)
1174 cupsdCloseClient(con
);
1178 if (!encrypt_client(con
))
1180 cupsdCloseClient(con
);
1184 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
1186 cupsdCloseClient(con
);
1189 #endif /* HAVE_SSL */
1192 if ((status
= cupsdIsAuthorized(con
, NULL
)) != HTTP_OK
)
1194 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1195 "cupsdReadClient: Unauthorized request for %s...\n",
1197 cupsdSendError(con
, status
, CUPSD_AUTH_NONE
);
1198 cupsdCloseClient(con
);
1202 if (con
->http
.expect
&&
1203 (con
->operation
== HTTP_POST
|| con
->operation
== HTTP_PUT
))
1205 if (con
->http
.expect
== HTTP_CONTINUE
)
1208 * Send 100-continue header...
1211 if (!cupsdSendHeader(con
, HTTP_CONTINUE
, NULL
, CUPSD_AUTH_NONE
))
1213 cupsdCloseClient(con
);
1220 * Send 417-expectation-failed header...
1223 if (!cupsdSendHeader(con
, HTTP_EXPECTATION_FAILED
, NULL
, CUPSD_AUTH_NONE
))
1225 cupsdCloseClient(con
);
1229 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1230 httpPrintf(HTTP(con
), "\r\n");
1232 if (cupsdFlushHeader(con
) < 0)
1234 cupsdCloseClient(con
);
1240 switch (con
->http
.state
)
1242 case HTTP_GET_SEND
:
1243 if (!strncmp(con
->uri
, "/printers/", 10) &&
1244 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1247 * Send PPD file - get the real printer name since printer
1248 * names are not case sensitive but filenames can be...
1251 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1253 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1254 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1257 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1259 cupsdCloseClient(con
);
1267 if ((!strncmp(con
->uri
, "/admin", 6) &&
1268 strncmp(con
->uri
, "/admin/conf/", 12) &&
1269 strncmp(con
->uri
, "/admin/log/", 11)) ||
1270 !strncmp(con
->uri
, "/printers", 9) ||
1271 !strncmp(con
->uri
, "/classes", 8) ||
1272 !strncmp(con
->uri
, "/help", 5) ||
1273 !strncmp(con
->uri
, "/jobs", 5))
1276 * Send CGI output...
1279 if (!strncmp(con
->uri
, "/admin", 6))
1281 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1284 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1286 else if (!strncmp(con
->uri
, "/printers", 9))
1288 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1291 if (con
->uri
[9] && con
->uri
[10])
1292 cupsdSetString(&con
->options
, con
->uri
+ 9);
1294 cupsdSetString(&con
->options
, NULL
);
1296 else if (!strncmp(con
->uri
, "/classes", 8))
1298 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1301 if (con
->uri
[8] && con
->uri
[9])
1302 cupsdSetString(&con
->options
, con
->uri
+ 8);
1304 cupsdSetString(&con
->options
, NULL
);
1306 else if (!strncmp(con
->uri
, "/jobs", 5))
1308 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1311 if (con
->uri
[5] && con
->uri
[6])
1312 cupsdSetString(&con
->options
, con
->uri
+ 5);
1314 cupsdSetString(&con
->options
, NULL
);
1318 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1321 if (con
->uri
[5] && con
->uri
[6])
1322 cupsdSetString(&con
->options
, con
->uri
+ 5);
1324 cupsdSetString(&con
->options
, NULL
);
1327 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1329 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1331 cupsdCloseClient(con
);
1336 cupsdLogRequest(con
, HTTP_OK
);
1338 if (con
->http
.version
<= HTTP_1_0
)
1339 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1341 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1342 (strchr(con
->uri
+ 12, '/') ||
1343 strlen(con
->uri
) == 12)) ||
1344 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1345 (strchr(con
->uri
+ 11, '/') ||
1346 strlen(con
->uri
) == 11)))
1349 * GET can only be done to configuration files under
1353 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1355 cupsdCloseClient(con
);
1367 if ((filename
= get_file(con
, &filestats
, buf
,
1368 sizeof(buf
))) == NULL
)
1370 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1372 cupsdCloseClient(con
);
1379 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1381 if (is_cgi(con
, filename
, &filestats
, type
))
1384 * Note: con->command and con->options were set by
1388 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1390 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1392 cupsdCloseClient(con
);
1397 cupsdLogRequest(con
, HTTP_OK
);
1399 if (con
->http
.version
<= HTTP_1_0
)
1400 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1404 if (!check_if_modified(con
, &filestats
))
1406 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1408 cupsdCloseClient(con
);
1415 strcpy(line
, "text/plain");
1417 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1419 if (!write_file(con
, HTTP_OK
, filename
, line
, &filestats
))
1421 cupsdCloseClient(con
);
1428 case HTTP_POST_RECV
:
1430 * See if the POST request includes a Content-Length field, and if
1431 * so check the length against any limits that are set...
1434 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "POST %s", con
->uri
);
1435 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "CONTENT_TYPE = %s",
1436 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
1438 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1439 MaxRequestSize
> 0 &&
1440 con
->http
.data_remaining
> MaxRequestSize
)
1443 * Request too large...
1446 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1448 cupsdCloseClient(con
);
1454 else if (con
->http
.data_remaining
< 0)
1457 * Negative content lengths are invalid!
1460 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1462 cupsdCloseClient(con
);
1470 * See what kind of POST request this is; for IPP requests the
1471 * content-type field will be "application/ipp"...
1474 if (!strcmp(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
],
1476 con
->request
= ippNew();
1477 else if ((!strncmp(con
->uri
, "/admin", 6) &&
1478 strncmp(con
->uri
, "/admin/conf/", 12) &&
1479 strncmp(con
->uri
, "/admin/log/", 11)) ||
1480 !strncmp(con
->uri
, "/printers", 9) ||
1481 !strncmp(con
->uri
, "/classes", 8) ||
1482 !strncmp(con
->uri
, "/help", 5) ||
1483 !strncmp(con
->uri
, "/jobs", 5))
1489 if (!strncmp(con
->uri
, "/admin", 6))
1491 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1494 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1496 else if (!strncmp(con
->uri
, "/printers", 9))
1498 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1501 if (con
->uri
[9] && con
->uri
[10])
1502 cupsdSetString(&con
->options
, con
->uri
+ 9);
1504 cupsdSetString(&con
->options
, NULL
);
1506 else if (!strncmp(con
->uri
, "/classes", 8))
1508 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1511 if (con
->uri
[8] && con
->uri
[9])
1512 cupsdSetString(&con
->options
, con
->uri
+ 8);
1514 cupsdSetString(&con
->options
, NULL
);
1516 else if (!strncmp(con
->uri
, "/jobs", 5))
1518 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1521 if (con
->uri
[5] && con
->uri
[6])
1522 cupsdSetString(&con
->options
, con
->uri
+ 5);
1524 cupsdSetString(&con
->options
, NULL
);
1528 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1531 if (con
->uri
[5] && con
->uri
[6])
1532 cupsdSetString(&con
->options
, con
->uri
+ 5);
1534 cupsdSetString(&con
->options
, NULL
);
1537 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1538 "cupsdReadClient: %d command=\"%s\", "
1540 con
->http
.fd
, con
->command
,
1541 con
->options
? con
->options
: "(null)");
1543 if (con
->http
.version
<= HTTP_1_0
)
1544 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1552 if ((filename
= get_file(con
, &filestats
, buf
,
1553 sizeof(buf
))) == NULL
)
1555 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1557 cupsdCloseClient(con
);
1564 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1566 if (!is_cgi(con
, filename
, &filestats
, type
))
1569 * Only POST to CGI's...
1572 if (!cupsdSendError(con
, HTTP_UNAUTHORIZED
, CUPSD_AUTH_NONE
))
1574 cupsdCloseClient(con
);
1581 case HTTP_PUT_RECV
:
1583 * Validate the resource name...
1586 if (strncmp(con
->uri
, "/admin/conf/", 12) ||
1587 strchr(con
->uri
+ 12, '/') ||
1588 strlen(con
->uri
) == 12)
1591 * PUT can only be done to configuration files under
1595 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1597 cupsdCloseClient(con
);
1605 * See if the PUT request includes a Content-Length field, and if
1606 * so check the length against any limits that are set...
1609 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "PUT %s", con
->uri
);
1610 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "CONTENT_TYPE = %s",
1611 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
1613 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1614 MaxRequestSize
> 0 &&
1615 con
->http
.data_remaining
> MaxRequestSize
)
1618 * Request too large...
1621 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1623 cupsdCloseClient(con
);
1629 else if (con
->http
.data_remaining
< 0)
1632 * Negative content lengths are invalid!
1635 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1637 cupsdCloseClient(con
);
1645 * Open a temporary file to hold the request...
1648 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
1650 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1654 cupsdLogMessage(CUPSD_LOG_ERROR
,
1655 "Unable to create request file %s: %s",
1656 con
->filename
, strerror(errno
));
1658 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1660 cupsdCloseClient(con
);
1665 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1666 "cupsdReadClient: %d REQUEST %s=%d", con
->http
.fd
,
1667 con
->filename
, con
->file
);
1669 fchmod(con
->file
, 0640);
1670 fchown(con
->file
, RunUser
, Group
);
1671 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1676 cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
);
1677 cupsdCloseClient(con
);
1681 if (!strncmp(con
->uri
, "/printers/", 10) &&
1682 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1685 * Send PPD file - get the real printer name since printer
1686 * names are not case sensitive but filenames can be...
1689 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1691 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1692 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1695 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1697 cupsdCloseClient(con
);
1705 if ((!strncmp(con
->uri
, "/admin", 6) &&
1706 strncmp(con
->uri
, "/admin/conf/", 12) &&
1707 strncmp(con
->uri
, "/admin/log/", 11)) ||
1708 !strncmp(con
->uri
, "/printers", 9) ||
1709 !strncmp(con
->uri
, "/classes", 8) ||
1710 !strncmp(con
->uri
, "/help", 5) ||
1711 !strncmp(con
->uri
, "/jobs", 5))
1717 if (!cupsdSendHeader(con
, HTTP_OK
, "text/html", CUPSD_AUTH_NONE
))
1719 cupsdCloseClient(con
);
1723 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1725 cupsdCloseClient(con
);
1729 if (cupsdFlushHeader(con
) < 0)
1731 cupsdCloseClient(con
);
1735 cupsdLogRequest(con
, HTTP_OK
);
1737 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1738 (strchr(con
->uri
+ 12, '/') ||
1739 strlen(con
->uri
) == 12)) ||
1740 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1741 (strchr(con
->uri
+ 11, '/') ||
1742 strlen(con
->uri
) == 11)))
1745 * HEAD can only be done to configuration files under
1749 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1751 cupsdCloseClient(con
);
1757 else if ((filename
= get_file(con
, &filestats
, buf
,
1758 sizeof(buf
))) == NULL
)
1760 if (!cupsdSendHeader(con
, HTTP_NOT_FOUND
, "text/html", CUPSD_AUTH_NONE
))
1762 cupsdCloseClient(con
);
1766 cupsdLogRequest(con
, HTTP_NOT_FOUND
);
1768 else if (!check_if_modified(con
, &filestats
))
1770 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1772 cupsdCloseClient(con
);
1776 cupsdLogRequest(con
, HTTP_NOT_MODIFIED
);
1784 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1786 strcpy(line
, "text/plain");
1788 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1790 if (!cupsdSendHeader(con
, HTTP_OK
, line
, CUPSD_AUTH_NONE
))
1792 cupsdCloseClient(con
);
1796 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
1797 httpGetDateString(filestats
.st_mtime
)) < 0)
1799 cupsdCloseClient(con
);
1803 if (httpPrintf(HTTP(con
), "Content-Length: %lu\r\n",
1804 (unsigned long)filestats
.st_size
) < 0)
1806 cupsdCloseClient(con
);
1810 cupsdLogRequest(con
, HTTP_OK
);
1813 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1815 cupsdCloseClient(con
);
1819 if (cupsdFlushHeader(con
) < 0)
1821 cupsdCloseClient(con
);
1825 con
->http
.state
= HTTP_WAITING
;
1829 break; /* Anti-compiler-warning-code */
1835 * Handle any incoming data...
1838 switch (con
->http
.state
)
1840 case HTTP_PUT_RECV
:
1841 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1842 "cupsdReadClient: %d con->data_encoding=HTTP_ENCODE_%s, "
1843 "con->data_remaining=" CUPS_LLFMT
", con->file=%d",
1845 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
?
1846 "CHUNKED" : "LENGTH",
1847 CUPS_LLCAST con
->http
.data_remaining
, con
->file
);
1851 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
1853 cupsdCloseClient(con
);
1858 con
->bytes
+= bytes
;
1860 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1861 "cupsdReadClient: %d writing %d bytes to %d",
1862 con
->http
.fd
, bytes
, con
->file
);
1864 if (write(con
->file
, line
, bytes
) < bytes
)
1866 cupsdLogMessage(CUPSD_LOG_ERROR
,
1867 "cupsdReadClient: Unable to write %d bytes to %s: %s",
1868 bytes
, con
->filename
, strerror(errno
));
1870 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1871 "cupsdReadClient: Closing data file %d...",
1876 unlink(con
->filename
);
1877 cupsdClearString(&con
->filename
);
1879 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1881 cupsdCloseClient(con
);
1887 while (con
->http
.state
== HTTP_PUT_RECV
&& con
->http
.used
> 0);
1889 if (con
->http
.state
== HTTP_WAITING
)
1892 * End of file, see how big it is...
1895 fstat(con
->file
, &filestats
);
1897 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1898 "cupsdReadClient: %d Closing data file %d, size="
1900 con
->http
.fd
, con
->file
,
1901 CUPS_LLCAST filestats
.st_size
);
1906 if (filestats
.st_size
> MaxRequestSize
&&
1910 * Request is too big; remove it and send an error...
1913 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1914 "cupsdReadClient: %d Removing temp file %s",
1915 con
->http
.fd
, con
->filename
);
1916 unlink(con
->filename
);
1917 cupsdClearString(&con
->filename
);
1919 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1921 cupsdCloseClient(con
);
1927 * Install the configuration file...
1930 status
= install_conf_file(con
);
1933 * Return the status to the client...
1936 if (!cupsdSendError(con
, status
, CUPSD_AUTH_NONE
))
1938 cupsdCloseClient(con
);
1944 case HTTP_POST_RECV
:
1945 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1946 "cupsdReadClient: %d con->data_encoding=HTTP_ENCODE_"
1947 "%s, con->data_remaining=" CUPS_LLFMT
", con->file=%d",
1949 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
?
1950 "CHUNKED" : "LENGTH",
1951 CUPS_LLCAST con
->http
.data_remaining
, con
->file
);
1958 * Grab any request data from the connection...
1961 if ((ipp_state
= ippRead(&(con
->http
), con
->request
)) == IPP_ERROR
)
1963 cupsdLogMessage(CUPSD_LOG_ERROR
,
1964 "cupsdReadClient: %d IPP Read Error!",
1967 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
1968 cupsdCloseClient(con
);
1971 else if (ipp_state
!= IPP_DATA
)
1973 if (con
->http
.state
== HTTP_POST_SEND
)
1975 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
1976 cupsdCloseClient(con
);
1983 con
->bytes
+= ippLength(con
->request
);
1986 if (con
->file
< 0 && con
->http
.state
!= HTTP_POST_SEND
)
1989 * Create a file as needed for the request data...
1992 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
, request_id
++);
1993 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1997 cupsdLogMessage(CUPSD_LOG_ERROR
,
1998 "Unable to create request file %s: %s",
1999 con
->filename
, strerror(errno
));
2001 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2003 cupsdCloseClient(con
);
2008 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdReadClient: %d REQUEST %s=%d", con
->http
.fd
,
2009 con
->filename
, con
->file
);
2011 fchmod(con
->file
, 0640);
2012 fchown(con
->file
, RunUser
, Group
);
2013 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2016 if (con
->http
.state
!= HTTP_POST_SEND
)
2018 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
2020 cupsdCloseClient(con
);
2025 con
->bytes
+= bytes
;
2027 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2028 "cupsdReadClient: %d writing %d bytes to %d",
2029 con
->http
.fd
, bytes
, con
->file
);
2031 if (write(con
->file
, line
, bytes
) < bytes
)
2033 cupsdLogMessage(CUPSD_LOG_ERROR
,
2034 "cupsdReadClient: Unable to write %d bytes to %s: %s",
2035 bytes
, con
->filename
, strerror(errno
));
2037 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2038 "cupsdReadClient: Closing file %d...",
2043 unlink(con
->filename
);
2044 cupsdClearString(&con
->filename
);
2046 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2048 cupsdCloseClient(con
);
2053 else if (con
->http
.state
== HTTP_POST_RECV
)
2055 else if (con
->http
.state
!= HTTP_POST_SEND
)
2057 cupsdCloseClient(con
);
2062 while (con
->http
.state
== HTTP_POST_RECV
&& con
->http
.used
> 0);
2064 if (con
->http
.state
== HTTP_POST_SEND
)
2068 fstat(con
->file
, &filestats
);
2070 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2071 "cupsdReadClient: %d Closing data file %d, "
2072 "size=" CUPS_LLFMT
".",
2073 con
->http
.fd
, con
->file
,
2074 CUPS_LLCAST filestats
.st_size
);
2079 if (filestats
.st_size
> MaxRequestSize
&&
2083 * Request is too big; remove it and send an error...
2086 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2087 "cupsdReadClient: %d Removing temp file %s",
2088 con
->http
.fd
, con
->filename
);
2089 unlink(con
->filename
);
2090 cupsdClearString(&con
->filename
);
2095 * Delete any IPP request data...
2098 ippDelete(con
->request
);
2099 con
->request
= NULL
;
2102 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2104 cupsdCloseClient(con
);
2111 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
2113 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
2115 cupsdCloseClient(con
);
2120 cupsdLogRequest(con
, HTTP_OK
);
2126 cupsdProcessIPPRequest(con
);
2130 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2131 "cupsdReadClient: %d Removing temp file %s",
2132 con
->http
.fd
, con
->filename
);
2133 unlink(con
->filename
);
2134 cupsdClearString(&con
->filename
);
2143 break; /* Anti-compiler-warning-code */
2146 if (!con
->http
.keep_alive
&& con
->http
.state
== HTTP_WAITING
)
2147 cupsdCloseClient(con
);
2152 * 'cupsdSendCommand()' - Send output from a command via HTTP.
2155 int /* O - 1 on success, 0 on failure */
2157 cupsd_client_t
*con
, /* I - Client connection */
2158 char *command
, /* I - Command to run */
2159 char *options
, /* I - Command-line options */
2160 int root
) /* I - Run as root? */
2162 int fd
; /* Standard input file descriptor */
2167 fd
= open(con
->filename
, O_RDONLY
);
2171 cupsdLogMessage(CUPSD_LOG_ERROR
,
2172 "cupsdSendCommand: %d Unable to open \"%s\" for reading: %s",
2173 con
->http
.fd
, con
->filename
? con
->filename
: "/dev/null",
2178 fcntl(fd
, F_SETFD
, fcntl(fd
, F_GETFD
) | FD_CLOEXEC
);
2183 con
->pipe_pid
= pipe_command(con
, fd
, &(con
->file
), command
, options
, root
);
2188 cupsdLogMessage(CUPSD_LOG_INFO
, "Started \"%s\" (pid=%d)", command
,
2191 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendCommand: %d file=%d",
2192 con
->http
.fd
, con
->file
);
2194 if (con
->pipe_pid
== 0)
2197 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2199 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2201 con
->sent_header
= 0;
2202 con
->file_ready
= 0;
2203 con
->got_fields
= 0;
2211 * 'cupsdSendError()' - Send an error message via HTTP.
2214 int /* O - 1 if successful, 0 otherwise */
2215 cupsdSendError(cupsd_client_t
*con
, /* I - Connection */
2216 http_status_t code
, /* I - Error code */
2217 int auth_type
)/* I - Authentication type */
2221 * Force client to upgrade for authentication if that is how the
2222 * server is configured...
2225 if (code
== HTTP_UNAUTHORIZED
&&
2226 DefaultEncryption
== HTTP_ENCRYPT_REQUIRED
&&
2227 strcasecmp(con
->http
.hostname
, "localhost") &&
2230 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2231 "cupsdSendError: Encryption before authentication!");
2232 code
= HTTP_UPGRADE_REQUIRED
;
2234 #endif /* HAVE_SSL */
2237 * Put the request in the access_log file...
2240 cupsdLogRequest(con
, code
);
2242 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendError: %d code=%d (%s)",
2243 con
->http
.fd
, code
, httpStatus(code
));
2246 * To work around bugs in some proxies, don't use Keep-Alive for some
2249 * Kerberos authentication doesn't work without Keep-Alive, so
2250 * never disable it in that case.
2253 if (code
>= HTTP_BAD_REQUEST
&& con
->http
.auth_type
!= CUPSD_AUTH_NEGOTIATE
)
2254 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
2257 * Send an error message back to the client. If the error code is a
2258 * 400 or 500 series, make sure the message contains some text, too!
2261 if (!cupsdSendHeader(con
, code
, NULL
, auth_type
))
2265 if (code
== HTTP_UPGRADE_REQUIRED
)
2266 if (httpPrintf(HTTP(con
), "Connection: Upgrade\r\n") < 0)
2269 if (httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n") < 0)
2271 #endif /* HAVE_SSL */
2273 if (con
->http
.version
>= HTTP_1_1
&&
2274 con
->http
.keep_alive
== HTTP_KEEPALIVE_OFF
)
2276 if (httpPrintf(HTTP(con
), "Connection: close\r\n") < 0)
2280 if (code
>= HTTP_BAD_REQUEST
)
2283 * Send a human-readable error message.
2286 char message
[4096], /* Message for user */
2287 urltext
[1024], /* URL redirection text */
2288 redirect
[1024]; /* Redirection link */
2289 const char *text
; /* Status-specific text */
2294 if (code
== HTTP_UNAUTHORIZED
)
2295 text
= _cupsLangString(con
->language
,
2296 _("Enter your username and password or the "
2297 "root username and password to access this "
2298 "page. If you are using Kerberos authentication, "
2299 "make sure you have a valid Kerberos ticket."));
2300 else if (code
== HTTP_UPGRADE_REQUIRED
)
2304 snprintf(urltext
, sizeof(urltext
),
2305 _cupsLangString(con
->language
,
2306 _("You must access this page using the URL "
2307 "<A HREF=\"https://%s:%d%s\">"
2308 "https://%s:%d%s</A>.")),
2309 con
->servername
, con
->serverport
, con
->uri
,
2310 con
->servername
, con
->serverport
, con
->uri
);
2312 snprintf(redirect
, sizeof(redirect
),
2313 "<META HTTP-EQUIV=\"Refresh\" "
2314 "CONTENT=\"3;URL=https://%s:%d%s\">\n",
2315 con
->servername
, con
->serverport
, con
->uri
);
2320 snprintf(message
, sizeof(message
),
2321 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" "
2322 "\"http://www.w3.org/TR/REC-html40/loose.dtd\">\n"
2325 "\t<META HTTP-EQUIV=\"Content-Type\" "
2326 "CONTENT=\"text/html; charset=utf-8\">\n"
2327 "\t<TITLE>%d %s</TITLE>\n"
2328 "\t<LINK REL=\"STYLESHEET\" TYPE=\"text/css\" "
2329 "HREF=\"/cups.css\">\n"
2337 code
, httpStatus(code
), redirect
, code
, httpStatus(code
), text
);
2339 if (httpPrintf(HTTP(con
), "Content-Type: text/html; charset=utf-8\r\n") < 0)
2341 if (httpPrintf(HTTP(con
), "Content-Length: %d\r\n",
2342 (int)strlen(message
)) < 0)
2344 if (httpPrintf(HTTP(con
), "\r\n") < 0)
2346 if (httpPrintf(HTTP(con
), "%s", message
) < 0)
2349 else if (httpPrintf(HTTP(con
), "\r\n") < 0)
2352 if (cupsdFlushHeader(con
) < 0)
2355 con
->http
.state
= HTTP_WAITING
;
2362 * 'cupsdSendHeader()' - Send an HTTP request.
2365 int /* O - 1 on success, 0 on failure */
2367 cupsd_client_t
*con
, /* I - Client to send to */
2368 http_status_t code
, /* I - HTTP status code */
2369 char *type
, /* I - MIME type of document */
2370 int auth_type
) /* I - Type of authentication */
2372 char auth_str
[1024]; /* Authorization string */
2374 static char *gss_buf
= NULL
; /* Kerberos auth data buffer */
2375 static int gss_bufsize
= 0; /* Size of Kerberos auth data buffer */
2376 #endif /* HAVE_GSSAPI */
2380 * Send the HTTP status header...
2383 if (code
== HTTP_CONTINUE
)
2386 * 100-continue doesn't send any headers...
2389 return (httpPrintf(HTTP(con
), "HTTP/%d.%d 100 Continue\r\n\r\n",
2390 con
->http
.version
/ 100, con
->http
.version
% 100) > 0);
2393 httpFlushWrite(HTTP(con
));
2395 con
->http
.data_encoding
= HTTP_ENCODE_FIELDS
;
2397 if (httpPrintf(HTTP(con
), "HTTP/%d.%d %d %s\r\n", con
->http
.version
/ 100,
2398 con
->http
.version
% 100, code
, httpStatus(code
)) < 0)
2400 if (httpPrintf(HTTP(con
), "Date: %s\r\n", httpGetDateString(time(NULL
))) < 0)
2403 if (httpPrintf(HTTP(con
), "Server: %s\r\n", ServerHeader
) < 0)
2405 if (con
->http
.keep_alive
&& con
->http
.version
>= HTTP_1_0
)
2407 if (httpPrintf(HTTP(con
), "Connection: Keep-Alive\r\n") < 0)
2409 if (httpPrintf(HTTP(con
), "Keep-Alive: timeout=%d\r\n",
2410 KeepAliveTimeout
) < 0)
2413 if (code
== HTTP_METHOD_NOT_ALLOWED
)
2414 if (httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST\r\n") < 0)
2417 if (code
== HTTP_UNAUTHORIZED
)
2419 if (auth_type
== CUPSD_AUTH_NONE
)
2421 if (!con
->best
|| con
->best
->type
<= CUPSD_AUTH_NONE
)
2422 auth_type
= DefaultAuthType
;
2424 auth_type
= con
->best
->type
;
2429 if (auth_type
== CUPSD_AUTH_BASIC
|| auth_type
== CUPSD_AUTH_BASICDIGEST
)
2430 strlcpy(auth_str
, "Basic realm=\"CUPS\"", sizeof(auth_str
));
2431 else if (auth_type
== CUPSD_AUTH_DIGEST
)
2432 snprintf(auth_str
, sizeof(auth_str
), "Digest realm=\"CUPS\", nonce=\"%s\"",
2433 con
->http
.hostname
);
2435 else if (auth_type
== CUPSD_AUTH_NEGOTIATE
&& con
->gss_output_token
.length
== 0)
2436 strlcpy(auth_str
, "Negotiate", sizeof(auth_str
));
2437 #endif /* HAVE_GSSAPI */
2439 #ifdef HAVE_AUTHORIZATION_H
2440 if (con
->best
&& auth_type
!= CUPSD_AUTH_NEGOTIATE
)
2442 int i
; /* Looping var */
2443 char *auth_key
; /* Auth key buffer */
2444 size_t auth_size
; /* Size of remaining buffer */
2447 auth_key
= auth_str
+ strlen(auth_str
);
2448 auth_size
= sizeof(auth_str
) - (auth_key
- auth_str
);
2450 for (i
= 0; i
< con
->best
->num_names
; i
++)
2452 if (!strncasecmp(con
->best
->names
[i
], "@AUTHKEY(", 9))
2454 snprintf(auth_key
, auth_size
, ", authkey=\"%s\"",
2455 con
->best
->names
[i
] + 9);
2456 /* end parenthesis is stripped in conf.c */
2459 else if (!strcasecmp(con
->best
->names
[i
], "@SYSTEM") &&
2462 snprintf(auth_key
, auth_size
, ", authkey=\"%s\"", SystemGroupAuthKey
);
2467 #endif /* HAVE_AUTHORIZATION_H */
2471 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendHeader: WWW-Authenticate: %s",
2474 if (httpPrintf(HTTP(con
), "WWW-Authenticate: %s\r\n", auth_str
) < 0)
2481 * WWW-Authenticate: Negotiate can be included even for
2482 * non-401 replies...
2485 if (con
->gss_output_token
.length
> 0 && con
->gss_output_token
.length
<= 65536)
2487 OM_uint32 minor_status
; /* Minor status code */
2488 int bufsize
; /* Size of output token buffer */
2491 bufsize
= con
->gss_output_token
.length
* 4 / 3 + 2;
2493 if (bufsize
> gss_bufsize
)
2495 char *buf
; /* New buffer */
2498 bufsize
= (bufsize
+ 1023) & 1023;/* Round up */
2501 buf
= realloc(gss_buf
, bufsize
);
2503 buf
= malloc(bufsize
);
2507 cupsdLogMessage(CUPSD_LOG_ERROR
,
2508 "Unable to allocate %d bytes for Kerberos credentials!",
2514 gss_bufsize
= bufsize
;
2517 httpEncode64_2(gss_buf
, gss_bufsize
,
2518 con
->gss_output_token
.value
,
2519 con
->gss_output_token
.length
);
2520 gss_release_buffer(&minor_status
, &con
->gss_output_token
);
2522 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2523 "cupsdSendHeader: WWW-Authenticate: Negotiate %s", gss_buf
);
2525 if (httpPrintf(HTTP(con
), "WWW-Authenticate: Negotiate %s\r\n",
2529 else if (con
->gss_output_token
.length
> 65536)
2531 cupsdLogMessage(CUPSD_LOG_ERROR
,
2532 "Kerberos credentials larger than 64k (%d)!",
2533 (int)con
->gss_output_token
.length
);
2536 #endif /* HAVE_GSSAPI */
2538 if (con
->language
&& strcmp(con
->language
->language
, "C"))
2540 if (httpPrintf(HTTP(con
), "Content-Language: %s\r\n",
2541 con
->language
->language
) < 0)
2547 if (!strcmp(type
, "text/html"))
2549 if (httpPrintf(HTTP(con
),
2550 "Content-Type: text/html; charset=utf-8\r\n") < 0)
2553 else if (httpPrintf(HTTP(con
), "Content-Type: %s\r\n", type
) < 0)
2562 * 'cupsdUpdateCGI()' - Read status messages from CGI scripts and programs.
2566 cupsdUpdateCGI(void)
2568 char *ptr
, /* Pointer to end of line in buffer */
2569 message
[1024]; /* Pointer to message text */
2570 int loglevel
; /* Log level for message */
2573 while ((ptr
= cupsdStatBufUpdate(CGIStatusBuffer
, &loglevel
,
2574 message
, sizeof(message
))) != NULL
)
2575 if (!strchr(CGIStatusBuffer
->buffer
, '\n'))
2578 if (ptr
== NULL
&& !CGIStatusBuffer
->bufused
)
2581 * Fatal error on pipe - should never happen!
2584 cupsdLogMessage(CUPSD_LOG_CRIT
,
2585 "cupsdUpdateCGI: error reading from CGI error pipe - %s",
2592 * 'cupsdWriteClient()' - Write data to a client as needed.
2596 cupsdWriteClient(cupsd_client_t
*con
) /* I - Client connection */
2598 int bytes
; /* Number of bytes written */
2599 char buf
[16385]; /* Data buffer */
2600 char *bufptr
; /* Pointer into buffer */
2601 ipp_state_t ipp_state
; /* IPP state value */
2605 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2606 "cupsdWriteClient(con=%p) %d response=%p(%d), file=%d "
2607 "pipe_pid=%d state=%d",
2608 con
, con
->http
.fd
, con
->response
, con
->response
->state
,
2609 con
->file
, con
->pipe_pid
, con
->http
.state
);
2612 if (con
->http
.state
!= HTTP_GET_SEND
&&
2613 con
->http
.state
!= HTTP_POST_SEND
)
2619 * Make sure we select on the CGI output...
2622 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2624 if (!con
->file_ready
)
2627 * Try again later when there is CGI output available...
2630 cupsdRemoveSelect(con
->http
.fd
);
2634 con
->file_ready
= 0;
2637 if (con
->response
&& con
->response
->state
!= IPP_DATA
)
2639 ipp_state
= ippWrite(HTTP(con
), con
->response
);
2640 bytes
= ipp_state
!= IPP_ERROR
&&
2641 (con
->file
>= 0 || ipp_state
!= IPP_DATA
);
2643 else if ((bytes
= read(con
->file
, buf
, sizeof(buf
) - 1)) > 0)
2645 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2646 "cupsdWriteClient: Read %d bytes from file %d...",
2649 if (con
->pipe_pid
&& !con
->got_fields
)
2652 * Inspect the data for Content-Type and other fields.
2657 for (bufptr
= buf
; !con
->got_fields
&& *bufptr
; bufptr
++)
2658 if (*bufptr
== '\n')
2661 * Send line to client...
2664 if (bufptr
> buf
&& bufptr
[-1] == '\r')
2668 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "Script header: %s", buf
);
2670 if (!con
->sent_header
)
2673 * Handle redirection and CGI status codes...
2676 if (!strncasecmp(buf
, "Location:", 9))
2678 cupsdSendHeader(con
, HTTP_SEE_OTHER
, NULL
, CUPSD_AUTH_NONE
);
2679 con
->sent_header
= 2;
2681 if (httpPrintf(HTTP(con
), "Content-Length: 0\r\n") < 0)
2684 else if (!strncasecmp(buf
, "Status:", 7))
2686 cupsdSendError(con
, (http_status_t
)atoi(buf
+ 7), CUPSD_AUTH_NONE
);
2687 con
->sent_header
= 2;
2691 cupsdSendHeader(con
, HTTP_OK
, NULL
, CUPSD_AUTH_NONE
);
2692 con
->sent_header
= 1;
2694 if (con
->http
.version
== HTTP_1_1
)
2696 if (httpPrintf(HTTP(con
), "Transfer-Encoding: chunked\r\n") < 0)
2702 if (strncasecmp(buf
, "Status:", 7))
2703 httpPrintf(HTTP(con
), "%s\r\n", buf
);
2705 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdWriteClient: %d %s",
2712 bytes
-= (bufptr
- buf
);
2713 memmove(buf
, bufptr
, bytes
+ 1);
2717 * See if the line was empty...
2720 if (con
->field_col
== 0)
2722 con
->got_fields
= 1;
2724 if (cupsdFlushHeader(con
) < 0)
2726 cupsdCloseClient(con
);
2730 if (con
->http
.version
== HTTP_1_1
)
2731 con
->http
.data_encoding
= HTTP_ENCODE_CHUNKED
;
2736 else if (*bufptr
!= '\r')
2739 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2740 "cupsdWriteClient: %d bytes=%d, got_fields=%d",
2741 con
->http
.fd
, bytes
, con
->got_fields
);
2743 if (bytes
> 0 && !con
->got_fields
)
2746 * Remaining text needs to go out...
2749 httpPrintf(HTTP(con
), "%s", buf
);
2751 con
->http
.activity
= time(NULL
);
2754 else if (bytes
== 0)
2755 con
->http
.activity
= time(NULL
);
2760 if (httpWrite2(HTTP(con
), buf
, bytes
) < 0)
2762 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2763 "cupsdWriteClient: %d Write of %d bytes failed!",
2764 con
->http
.fd
, bytes
);
2766 cupsdCloseClient(con
);
2770 con
->bytes
+= bytes
;
2772 if (con
->http
.state
== HTTP_WAITING
)
2779 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdWriteClient: %d bytes < 0",
2782 cupsdLogRequest(con
, HTTP_OK
);
2784 httpFlushWrite(HTTP(con
));
2786 if (con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
&& con
->sent_header
== 1)
2788 if (httpWrite2(HTTP(con
), "", 0) < 0)
2790 cupsdCloseClient(con
);
2795 con
->http
.state
= HTTP_WAITING
;
2797 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
2801 cupsdRemoveSelect(con
->file
);
2804 cupsdEndProcess(con
->pipe_pid
, 0);
2806 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2807 "cupsdWriteClient: %d Closing data file %d.",
2808 con
->http
.fd
, con
->file
);
2817 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2818 "cupsdWriteClient: %d Removing temp file %s",
2819 con
->http
.fd
, con
->filename
);
2820 unlink(con
->filename
);
2821 cupsdClearString(&con
->filename
);
2826 ippDelete(con
->request
);
2827 con
->request
= NULL
;
2832 ippDelete(con
->response
);
2833 con
->response
= NULL
;
2836 cupsdClearString(&con
->command
);
2837 cupsdClearString(&con
->options
);
2838 cupsdClearString(&con
->query_string
);
2840 if (!con
->http
.keep_alive
)
2842 cupsdCloseClient(con
);
2847 con
->http
.activity
= time(NULL
);
2852 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
2855 static int /* O - 1 if modified since */
2857 cupsd_client_t
*con
, /* I - Client connection */
2858 struct stat
*filestats
) /* I - File information */
2860 char *ptr
; /* Pointer into field */
2861 time_t date
; /* Time/date value */
2862 off_t size
; /* Size/length value */
2867 ptr
= con
->http
.fields
[HTTP_FIELD_IF_MODIFIED_SINCE
];
2872 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2873 "check_if_modified: %d If-Modified-Since=\"%s\"",
2876 while (*ptr
!= '\0')
2878 while (isspace(*ptr
) || *ptr
== ';')
2881 if (strncasecmp(ptr
, "length=", 7) == 0)
2884 size
= strtoll(ptr
, NULL
, 10);
2886 while (isdigit(*ptr
))
2889 else if (isalpha(*ptr
))
2891 date
= httpGetDateTime(ptr
);
2892 while (*ptr
!= '\0' && *ptr
!= ';')
2899 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2900 "check_if_modified: %d sizes=" CUPS_LLFMT
","
2901 CUPS_LLFMT
" dates=%d,%d",
2902 con
->http
.fd
, CUPS_LLCAST size
,
2903 CUPS_LLCAST filestats
->st_size
, (int)date
,
2904 (int)filestats
->st_mtime
);
2906 return ((size
!= filestats
->st_size
&& size
!= 0) ||
2907 (date
< filestats
->st_mtime
&& date
!= 0) ||
2908 (size
== 0 && date
== 0));
2914 * 'encrypt_client()' - Enable encryption for the client...
2917 static int /* O - 1 on success, 0 on error */
2918 encrypt_client(cupsd_client_t
*con
) /* I - Client to encrypt */
2921 SSL_CTX
*context
; /* Context for encryption */
2922 SSL
*conn
; /* Connection for encryption */
2923 BIO
*bio
; /* BIO data */
2924 unsigned long error
; /* Error code */
2928 * Verify that we have a certificate...
2931 if (access(ServerKey
, 0) || access(ServerCertificate
, 0))
2934 * Nope, make a self-signed certificate...
2937 if (!make_certificate(con
))
2942 * Create the SSL context and accept the connection...
2945 context
= SSL_CTX_new(SSLv23_server_method());
2947 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
2948 SSL_CTX_use_PrivateKey_file(context
, ServerKey
, SSL_FILETYPE_PEM
);
2949 SSL_CTX_use_certificate_file(context
, ServerCertificate
, SSL_FILETYPE_PEM
);
2951 bio
= BIO_new(_httpBIOMethods());
2952 BIO_ctrl(bio
, BIO_C_SET_FILE_PTR
, 0, (char *)HTTP(con
));
2954 conn
= SSL_new(context
);
2955 SSL_set_bio(conn
, bio
, bio
);
2957 if (SSL_accept(conn
) != 1)
2959 cupsdLogMessage(CUPSD_LOG_ERROR
,
2960 "encrypt_client: Unable to encrypt connection from %s!",
2961 con
->http
.hostname
);
2963 while ((error
= ERR_get_error()) != 0)
2964 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s",
2965 ERR_error_string(error
, NULL
));
2967 SSL_CTX_free(context
);
2972 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2973 "encrypt_client: %d Connection from %s now encrypted.",
2974 con
->http
.fd
, con
->http
.hostname
);
2976 con
->http
.tls
= conn
;
2979 # elif defined(HAVE_GNUTLS)
2980 http_tls_t
*conn
; /* TLS session object */
2981 int error
; /* Error code */
2982 gnutls_certificate_server_credentials
*credentials
;
2983 /* TLS credentials */
2987 * Verify that we have a certificate...
2990 if (access(ServerKey
, 0) || access(ServerCertificate
, 0))
2993 * Nope, make a self-signed certificate...
2996 if (!make_certificate(con
))
3001 * Create the SSL object and perform the SSL handshake...
3004 conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
));
3009 credentials
= (gnutls_certificate_server_credentials
*)
3010 malloc(sizeof(gnutls_certificate_server_credentials
));
3011 if (credentials
== NULL
)
3013 cupsdLogMessage(CUPSD_LOG_ERROR
,
3014 "encrypt_client: Unable to encrypt connection from %s!",
3015 con
->http
.hostname
);
3016 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s", strerror(errno
));
3022 gnutls_certificate_allocate_credentials(credentials
);
3023 gnutls_certificate_set_x509_key_file(*credentials
, ServerCertificate
,
3024 ServerKey
, GNUTLS_X509_FMT_PEM
);
3026 gnutls_init(&(conn
->session
), GNUTLS_SERVER
);
3027 gnutls_set_default_priority(conn
->session
);
3028 gnutls_credentials_set(conn
->session
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
3029 gnutls_transport_set_ptr(conn
->session
, (gnutls_transport_ptr
)HTTP(con
));
3030 gnutls_transport_set_pull_function(conn
->session
, _httpReadGNUTLS
);
3031 gnutls_transport_set_push_function(conn
->session
, _httpWriteGNUTLS
);
3033 error
= gnutls_handshake(conn
->session
);
3035 if (error
!= GNUTLS_E_SUCCESS
)
3037 cupsdLogMessage(CUPSD_LOG_ERROR
,
3038 "encrypt_client: Unable to encrypt connection from %s!",
3039 con
->http
.hostname
);
3040 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s",
3041 gnutls_strerror(error
));
3043 gnutls_deinit(conn
->session
);
3044 gnutls_certificate_free_credentials(*credentials
);
3050 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3051 "encrypt_client: %d Connection from %s now encrypted.",
3052 con
->http
.fd
, con
->http
.hostname
);
3054 conn
->credentials
= credentials
;
3055 con
->http
.tls
= conn
;
3058 # elif defined(HAVE_CDSASSL)
3059 OSStatus error
; /* Error code */
3060 http_tls_t
*conn
; /* CDSA connection information */
3063 if ((conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
))) == NULL
)
3067 conn
->session
= NULL
;
3068 conn
->certsArray
= get_cdsa_certificate(con
);
3070 if (!conn
->certsArray
)
3073 * No keychain (yet), make a self-signed certificate...
3076 if (make_certificate(con
))
3077 conn
->certsArray
= get_cdsa_certificate(con
);
3080 if (!conn
->certsArray
)
3082 cupsdLogMessage(CUPSD_LOG_ERROR
,
3083 "encrypt_client: Could not find signing key in keychain "
3084 "\"%s\"", ServerCertificate
);
3085 error
= errSSLBadCert
; /* errSSLBadConfiguration is a better choice, but not available on 10.2.x */
3089 error
= SSLNewContext(true, &conn
->session
);
3092 error
= SSLSetIOFuncs(conn
->session
, _httpReadCDSA
, _httpWriteCDSA
);
3095 error
= SSLSetProtocolVersionEnabled(conn
->session
, kSSLProtocol2
, false);
3098 error
= SSLSetConnection(conn
->session
, HTTP(con
));
3101 error
= SSLSetAllowsExpiredCerts(conn
->session
, true);
3104 error
= SSLSetAllowsAnyRoot(conn
->session
, true);
3107 error
= SSLSetCertificate(conn
->session
, conn
->certsArray
);
3112 * Perform SSL/TLS handshake
3115 while ((error
= SSLHandshake(conn
->session
)) == errSSLWouldBlock
)
3121 cupsdLogMessage(CUPSD_LOG_ERROR
,
3122 "encrypt_client: Unable to encrypt connection from %s!",
3123 con
->http
.hostname
);
3125 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s (%d)",
3126 cssmErrorString(error
), (int)error
);
3128 con
->http
.error
= error
;
3129 con
->http
.status
= HTTP_ERROR
;
3132 SSLDisposeContext(conn
->session
);
3134 if (conn
->certsArray
)
3135 CFRelease(conn
->certsArray
);
3142 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3143 "encrypt_client: %d Connection from %s now encrypted.",
3144 con
->http
.fd
, con
->http
.hostname
);
3146 con
->http
.tls
= conn
;
3149 # endif /* HAVE_LIBSSL */
3151 #endif /* HAVE_SSL */
3156 * 'get_cdsa_certificate()' - Get a SSL/TLS certificate from the System keychain.
3159 static CFArrayRef
/* O - Array of certificates */
3160 get_cdsa_certificate(cupsd_client_t
*con
) /* I - Client connection */
3162 OSStatus err
; /* Error info */
3163 SecKeychainRef keychain
; /* Keychain reference */
3164 SecIdentitySearchRef search
; /* Search reference */
3165 SecIdentityRef identity
; /* Identity */
3166 CFArrayRef certificates
= NULL
;
3167 /* Certificate array */
3170 if ((err
= SecKeychainOpen(ServerCertificate
, &keychain
)))
3172 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot open keychain \"%s\", %s",
3173 ServerCertificate
, cssmErrorString(err
));
3177 # if HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY
3179 * Use a policy to search for valid certificates who's common name matches the
3183 SecPolicySearchRef policy_search
; /* Policy search ref */
3184 SecPolicyRef policy
; /* Policy ref */
3185 CSSM_DATA options
; /* Policy options */
3186 CSSM_APPLE_TP_SSL_OPTIONS
3187 ssl_options
; /* SSL Option for hostname */
3190 if ((err
= SecPolicySearchCreate(CSSM_CERT_X_509v3
, &CSSMOID_APPLE_TP_SSL
,
3191 NULL
, &policy_search
)))
3193 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot create a policy search reference");
3194 CFRelease(keychain
);
3198 if ((err
= SecPolicySearchCopyNext(policy_search
, &policy
)))
3200 cupsdLogMessage(CUPSD_LOG_ERROR
,
3201 "Cannot find a policy to use for searching");
3202 CFRelease(keychain
);
3203 CFRelease(policy_search
);
3207 memset(&ssl_options
, 0, sizeof(ssl_options
));
3208 ssl_options
.Version
= CSSM_APPLE_TP_SSL_OPTS_VERSION
;
3209 ssl_options
.ServerName
= con
->servername
;
3210 ssl_options
.ServerNameLen
= strlen(con
->servername
);
3212 options
.Data
= (uint8
*)&ssl_options
;
3213 options
.Length
= sizeof(ssl_options
);
3215 if ((err
= SecPolicySetValue(policy
, &options
)))
3217 cupsdLogMessage(CUPSD_LOG_ERROR
,
3218 "Cannot set policy value to use for searching");
3219 CFRelease(keychain
);
3220 CFRelease(policy_search
);
3224 err
= SecIdentitySearchCreateWithPolicy(policy
, NULL
, CSSM_KEYUSE_SIGN
,
3225 keychain
, FALSE
, &search
);
3228 * Assume there is exactly one SecIdentity in the keychain...
3231 err
= SecIdentitySearchCreate(keychain
, CSSM_KEYUSE_SIGN
, &search
);
3232 # endif /* HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY */
3235 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3236 "Cannot create keychain search reference: %s",
3237 cssmErrorString(err
));
3240 if ((err
= SecIdentitySearchCopyNext(search
, &identity
)))
3242 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3243 "Cannot find signing key in keychain \"%s\", error %d",
3244 ServerCertificate
, (int)err
);
3248 if (CFGetTypeID(identity
) != SecIdentityGetTypeID())
3249 cupsdLogMessage(CUPSD_LOG_ERROR
,
3250 "SecIdentitySearchCopyNext CFTypeID failure!");
3253 if ((certificates
= CFArrayCreate(NULL
, (const void **)&identity
,
3254 1, &kCFTypeArrayCallBacks
)) == NULL
)
3255 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot create certificate array");
3258 CFRelease(identity
);
3264 # if HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY
3266 CFRelease(policy_search
);
3267 # endif /* HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY */
3269 return (certificates
);
3271 #endif /* HAVE_CDSASSL */
3275 * 'get_file()' - Get a filename and state info.
3278 static char * /* O - Real filename */
3279 get_file(cupsd_client_t
*con
, /* I - Client connection */
3280 struct stat
*filestats
, /* O - File information */
3281 char *filename
, /* IO - Filename buffer */
3282 int len
) /* I - Buffer length */
3284 int status
; /* Status of filesystem calls */
3285 char *ptr
; /* Pointer info filename */
3286 int plen
; /* Remaining length after pointer */
3287 char language
[7]; /* Language subdirectory, if any */
3291 * Figure out the real filename...
3296 if (!strncmp(con
->uri
, "/ppd/", 5))
3297 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
);
3298 else if (!strncmp(con
->uri
, "/rss/", 5) && !strchr(con
->uri
+ 5, '/'))
3299 snprintf(filename
, len
, "%s/rss/%s", CacheDir
, con
->uri
+ 5);
3300 else if (!strncmp(con
->uri
, "/admin/conf/", 12))
3301 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
+ 11);
3302 else if (!strncmp(con
->uri
, "/admin/log/", 11))
3304 if (!strncmp(con
->uri
+ 11, "access_log", 10) && AccessLog
[0] == '/')
3305 strlcpy(filename
, AccessLog
, len
);
3306 else if (!strncmp(con
->uri
+ 11, "error_log", 9) && ErrorLog
[0] == '/')
3307 strlcpy(filename
, ErrorLog
, len
);
3308 else if (!strncmp(con
->uri
+ 11, "page_log", 8) && PageLog
[0] == '/')
3309 strlcpy(filename
, PageLog
, len
);
3313 else if (con
->language
)
3315 snprintf(language
, sizeof(language
), "/%s", con
->language
->language
);
3316 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3319 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3321 if ((ptr
= strchr(filename
, '?')) != NULL
)
3325 * Grab the status for this language; if there isn't a language-specific file
3326 * then fallback to the default one...
3329 if ((status
= stat(filename
, filestats
)) != 0 && language
[0] &&
3330 strncmp(con
->uri
, "/ppd/", 5) &&
3331 strncmp(con
->uri
, "/admin/conf/", 12) &&
3332 strncmp(con
->uri
, "/admin/log/", 11))
3335 * Drop the country code...
3339 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3341 if ((ptr
= strchr(filename
, '?')) != NULL
)
3344 if ((status
= stat(filename
, filestats
)) != 0)
3347 * Drop the language prefix and try the root directory...
3351 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3353 if ((ptr
= strchr(filename
, '?')) != NULL
)
3356 status
= stat(filename
, filestats
);
3361 * If we're found a directory, get the index.html file instead...
3364 if (!status
&& S_ISDIR(filestats
->st_mode
))
3367 * Make sure the URI ends with a slash...
3370 if (con
->uri
[strlen(con
->uri
) - 1] != '/')
3371 strlcat(con
->uri
, "/", sizeof(con
->uri
));
3374 * Find the directory index file, trying every language...
3379 if (status
&& language
[0])
3382 * Try a different language subset...
3386 language
[0] = '\0'; /* Strip country code */
3388 language
[0] = '\0'; /* Strip language */
3392 * Look for the index file...
3395 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3397 if ((ptr
= strchr(filename
, '?')) != NULL
)
3400 ptr
= filename
+ strlen(filename
);
3401 plen
= len
- (ptr
- filename
);
3403 strlcpy(ptr
, "index.html", plen
);
3404 status
= stat(filename
, filestats
);
3409 strlcpy(ptr
, "index.class", plen
);
3410 status
= stat(filename
, filestats
);
3412 #endif /* HAVE_JAVA */
3417 strlcpy(ptr
, "index.pl", plen
);
3418 status
= stat(filename
, filestats
);
3420 #endif /* HAVE_PERL */
3425 strlcpy(ptr
, "index.php", plen
);
3426 status
= stat(filename
, filestats
);
3428 #endif /* HAVE_PHP */
3433 strlcpy(ptr
, "index.pyc", plen
);
3434 status
= stat(filename
, filestats
);
3439 strlcpy(ptr
, "index.py", plen
);
3440 status
= stat(filename
, filestats
);
3442 #endif /* HAVE_PYTHON */
3445 while (status
&& language
[0]);
3448 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "get_file: %d filename=%s size=%d",
3449 con
->http
.fd
, filename
,
3450 status
? -1 : (int)filestats
->st_size
);
3453 con
->http
.data_remaining
= (int)filestats
->st_size
;
3463 * 'install_conf_file()' - Install a configuration file.
3466 static http_status_t
/* O - Status */
3467 install_conf_file(cupsd_client_t
*con
) /* I - Connection */
3469 cups_file_t
*in
, /* Input file */
3470 *out
; /* Output file */
3471 char buffer
[1024]; /* Copy buffer */
3472 int bytes
; /* Number of bytes */
3473 char conffile
[1024], /* Configuration filename */
3474 newfile
[1024], /* New config filename */
3475 oldfile
[1024]; /* Old config filename */
3476 struct stat confinfo
; /* Config file info */
3480 * First construct the filenames...
3483 snprintf(conffile
, sizeof(conffile
), "%s%s", ServerRoot
, con
->uri
+ 11);
3484 snprintf(newfile
, sizeof(newfile
), "%s%s.N", ServerRoot
, con
->uri
+ 11);
3485 snprintf(oldfile
, sizeof(oldfile
), "%s%s.O", ServerRoot
, con
->uri
+ 11);
3487 cupsdLogMessage(CUPSD_LOG_INFO
, "Installing config file \"%s\"...", conffile
);
3490 * Get the owner, group, and permissions of the configuration file.
3491 * If it doesn't exist, assign it to the User and Group in the
3492 * cupsd.conf file with mode 0640 permissions.
3495 if (stat(conffile
, &confinfo
))
3497 confinfo
.st_uid
= User
;
3498 confinfo
.st_gid
= Group
;
3499 confinfo
.st_mode
= ConfigFilePerm
;
3503 * Open the request file and new config file...
3506 if ((in
= cupsFileOpen(con
->filename
, "rb")) == NULL
)
3508 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open request file \"%s\" - %s",
3509 con
->filename
, strerror(errno
));
3510 return (HTTP_SERVER_ERROR
);
3513 if ((out
= cupsFileOpen(newfile
, "wb")) == NULL
)
3516 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open config file \"%s\" - %s",
3517 newfile
, strerror(errno
));
3518 return (HTTP_SERVER_ERROR
);
3521 fchmod(cupsFileNumber(out
), confinfo
.st_mode
);
3522 fchown(cupsFileNumber(out
), confinfo
.st_uid
, confinfo
.st_gid
);
3525 * Copy from the request to the new config file...
3528 while ((bytes
= cupsFileRead(in
, buffer
, sizeof(buffer
))) > 0)
3529 if (cupsFileWrite(out
, buffer
, bytes
) < bytes
)
3531 cupsdLogMessage(CUPSD_LOG_ERROR
,
3532 "Unable to copy to config file \"%s\" - %s",
3533 newfile
, strerror(errno
));
3539 return (HTTP_SERVER_ERROR
);
3543 * Close the files...
3547 if (cupsFileClose(out
))
3549 cupsdLogMessage(CUPSD_LOG_ERROR
,
3550 "Error file closing config file \"%s\" - %s",
3551 newfile
, strerror(errno
));
3555 return (HTTP_SERVER_ERROR
);
3559 * Remove the request file...
3562 unlink(con
->filename
);
3563 cupsdClearString(&con
->filename
);
3566 * Unlink the old backup, rename the current config file to the backup
3567 * filename, and rename the new config file to the config file name...
3570 if (unlink(oldfile
))
3571 if (errno
!= ENOENT
)
3573 cupsdLogMessage(CUPSD_LOG_ERROR
,
3574 "Unable to remove backup config file \"%s\" - %s",
3575 oldfile
, strerror(errno
));
3579 return (HTTP_SERVER_ERROR
);
3582 if (rename(conffile
, oldfile
))
3583 if (errno
!= ENOENT
)
3585 cupsdLogMessage(CUPSD_LOG_ERROR
,
3586 "Unable to rename old config file \"%s\" - %s",
3587 conffile
, strerror(errno
));
3591 return (HTTP_SERVER_ERROR
);
3594 if (rename(newfile
, conffile
))
3596 cupsdLogMessage(CUPSD_LOG_ERROR
,
3597 "Unable to rename new config file \"%s\" - %s",
3598 newfile
, strerror(errno
));
3600 rename(oldfile
, conffile
);
3603 return (HTTP_SERVER_ERROR
);
3607 * If the cupsd.conf file was updated, set the NeedReload flag...
3610 if (!strcmp(con
->uri
, "/admin/conf/cupsd.conf"))
3611 NeedReload
= RELOAD_CUPSD
;
3613 NeedReload
= RELOAD_ALL
;
3615 ReloadTime
= time(NULL
);
3618 * Return that the file was created successfully...
3621 return (HTTP_CREATED
);
3626 * 'is_cgi()' - Is the resource a CGI script/program?
3629 static int /* O - 1 = CGI, 0 = file */
3630 is_cgi(cupsd_client_t
*con
, /* I - Client connection */
3631 const char *filename
, /* I - Real filename */
3632 struct stat
*filestats
, /* I - File information */
3633 mime_type_t
*type
) /* I - MIME type */
3635 const char *options
; /* Options on URL */
3638 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3639 "is_cgi(con=%p, filename=\"%s\", filestats=%p, type=%s/%s)\n",
3640 con
, filename
, filestats
, type
? type
->super
: "unknown",
3641 type
? type
->type
: "unknown");
3644 * Get the options, if any...
3647 if ((options
= strchr(con
->uri
, '?')) != NULL
)
3651 if (strchr(options
, '='))
3652 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", options
);
3656 * Check for known types...
3659 if (!type
|| strcasecmp(type
->super
, "application"))
3661 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "is_cgi: Returning 0...");
3665 if (!strcasecmp(type
->type
, "x-httpd-cgi") &&
3666 (filestats
->st_mode
& 0111))
3669 * "application/x-httpd-cgi" is a CGI script.
3672 cupsdSetString(&con
->command
, filename
);
3674 filename
= strrchr(filename
, '/') + 1; /* Filename always absolute */
3676 cupsdSetString(&con
->options
, options
);
3678 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3679 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3680 con
->command
, con
->options
);
3685 else if (!strcasecmp(type
->type
, "x-httpd-java"))
3688 * "application/x-httpd-java" is a Java servlet.
3691 cupsdSetString(&con
->command
, CUPS_JAVA
);
3694 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3696 cupsdSetStringf(&con
->options
, " %s", filename
);
3698 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3699 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3700 con
->command
, con
->options
);
3704 #endif /* HAVE_JAVA */
3706 else if (!strcasecmp(type
->type
, "x-httpd-perl"))
3709 * "application/x-httpd-perl" is a Perl page.
3712 cupsdSetString(&con
->command
, CUPS_PERL
);
3715 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3717 cupsdSetStringf(&con
->options
, " %s", filename
);
3719 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3720 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3721 con
->command
, con
->options
);
3725 #endif /* HAVE_PERL */
3727 else if (!strcasecmp(type
->type
, "x-httpd-php"))
3730 * "application/x-httpd-php" is a PHP page.
3733 cupsdSetString(&con
->command
, CUPS_PHP
);
3736 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3738 cupsdSetStringf(&con
->options
, " %s", filename
);
3740 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3741 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3742 con
->command
, con
->options
);
3746 #endif /* HAVE_PHP */
3748 else if (!strcasecmp(type
->type
, "x-httpd-python"))
3751 * "application/x-httpd-python" is a Python page.
3754 cupsdSetString(&con
->command
, CUPS_PYTHON
);
3757 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3759 cupsdSetStringf(&con
->options
, " %s", filename
);
3761 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3762 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3763 con
->command
, con
->options
);
3767 #endif /* HAVE_PYTHON */
3769 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "is_cgi: Returning 0...");
3776 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
3779 static int /* O - 0 if relative, 1 if absolute */
3780 is_path_absolute(const char *path
) /* I - Input path */
3783 * Check for a leading slash...
3790 * Check for "/.." in the path...
3793 while ((path
= strstr(path
, "/..")) != NULL
)
3795 if (!path
[3] || path
[3] == '/')
3802 * If we haven't found any relative paths, return 1 indicating an
3812 * 'make_certificate()' - Make a self-signed SSL/TLS certificate.
3815 static int /* O - 1 on success, 0 on failure */
3816 make_certificate(cupsd_client_t
*con
) /* I - Client connection */
3818 #if defined(HAVE_LIBSSL) && defined(HAVE_WAITPID)
3819 int pid
, /* Process ID of command */
3820 status
; /* Status of command */
3821 char command
[1024], /* Command */
3822 *argv
[12], /* Command-line arguments */
3823 *envp
[MAX_ENV
+ 1], /* Environment variables */
3824 home
[1024], /* HOME environment variable */
3825 infofile
[1024], /* Type-in information for cert */
3826 seedfile
[1024]; /* Random number seed file */
3827 int envc
, /* Number of environment variables */
3828 bytes
; /* Bytes written */
3829 cups_file_t
*fp
; /* Seed/info file */
3830 int infofd
; /* Info file descriptor */
3834 * Run the "openssl" command to seed the random number generator and
3835 * generate a self-signed certificate that is good for 10 years:
3837 * openssl rand -rand seedfile 1
3839 * openssl req -new -x509 -keyout ServerKey \
3840 * -out ServerCertificate -days 3650 -nodes
3842 * The seeding step is crucial in ensuring that the openssl command
3843 * does not block on systems without sufficient entropy...
3846 if (!cupsFileFind("openssl", getenv("PATH"), 1, command
, sizeof(command
)))
3848 cupsdLogMessage(CUPSD_LOG_ERROR
,
3849 "No SSL certificate and openssl command not found!");
3853 if (access("/dev/urandom", 0))
3856 * If the system doesn't provide /dev/urandom, then any random source
3857 * will probably be blocking-style, so generate some random data to
3858 * use as a seed for the certificate. Note that we have already
3859 * seeded the random number generator in cupsdInitCerts()...
3862 cupsdLogMessage(CUPSD_LOG_INFO
,
3863 "Seeding the random number generator...");
3865 snprintf(home
, sizeof(home
), "HOME=%s", TempDir
);
3868 * Write the seed file...
3871 if ((fp
= cupsTempFile2(seedfile
, sizeof(seedfile
))) == NULL
)
3873 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to create seed file %s - %s",
3874 seedfile
, strerror(errno
));
3878 for (bytes
= 0; bytes
< 262144; bytes
++)
3879 cupsFilePutChar(fp
, random());
3884 * Run the openssl command to seed its random number generator...
3887 argv
[0] = "openssl";
3894 envc
= cupsdLoadEnv(envp
, MAX_ENV
);
3895 envp
[envc
++] = home
;
3898 if (!cupsdStartProcess(command
, argv
, envp
, -1, -1, -1, -1, -1, 1, NULL
,
3905 while (waitpid(pid
, &status
, 0) < 0)
3912 cupsdFinishProcess(pid
, command
, sizeof(command
));
3915 * Remove the seed file, as it is no longer needed...
3922 if (WIFEXITED(status
))
3923 cupsdLogMessage(CUPSD_LOG_ERROR
,
3924 "Unable to seed random number generator - "
3925 "the openssl command stopped with status %d!",
3926 WEXITSTATUS(status
));
3928 cupsdLogMessage(CUPSD_LOG_ERROR
,
3929 "Unable to seed random number generator - "
3930 "the openssl command crashed on signal %d!",
3938 * Create a file with the certificate information fields...
3940 * Note: This assumes that the default questions are asked by the openssl
3944 if ((fp
= cupsTempFile2(infofile
, sizeof(infofile
))) == NULL
)
3946 cupsdLogMessage(CUPSD_LOG_ERROR
,
3947 "Unable to create certificate information file %s - %s",
3948 infofile
, strerror(errno
));
3952 cupsFilePrintf(fp
, ".\n.\n.\n%s\n.\n%s\n%s\n",
3953 ServerName
, ServerName
, ServerAdmin
);
3956 cupsdLogMessage(CUPSD_LOG_INFO
,
3957 "Generating SSL server key and certificate...");
3959 argv
[0] = "openssl";
3963 argv
[4] = "-keyout";
3964 argv
[5] = ServerKey
;
3966 argv
[7] = ServerCertificate
;
3969 argv
[10] = "-nodes";
3972 cupsdLoadEnv(envp
, MAX_ENV
);
3974 infofd
= open(infofile
, O_RDONLY
);
3976 if (!cupsdStartProcess(command
, argv
, envp
, infofd
, -1, -1, -1, -1, 1, NULL
,
3987 while (waitpid(pid
, &status
, 0) < 0)
3994 cupsdFinishProcess(pid
, command
, sizeof(command
));
3998 if (WIFEXITED(status
))
3999 cupsdLogMessage(CUPSD_LOG_ERROR
,
4000 "Unable to create SSL server key and certificate - "
4001 "the openssl command stopped with status %d!",
4002 WEXITSTATUS(status
));
4004 cupsdLogMessage(CUPSD_LOG_ERROR
,
4005 "Unable to create SSL server key and certificate - "
4006 "the openssl command crashed on signal %d!",
4011 cupsdLogMessage(CUPSD_LOG_INFO
, "Created SSL server key file \"%s\"...",
4013 cupsdLogMessage(CUPSD_LOG_INFO
,
4014 "Created SSL server certificate file \"%s\"...",
4020 #elif defined(HAVE_GNUTLS)
4021 gnutls_x509_crt crt
; /* Self-signed certificate */
4022 gnutls_x509_privkey key
; /* Encryption key */
4023 cups_lang_t
*language
; /* Default language info */
4024 cups_file_t
*fp
; /* Key/cert file */
4025 unsigned char buffer
[8192]; /* Buffer for x509 data */
4026 size_t bytes
; /* Number of bytes of data */
4027 unsigned char serial
[4]; /* Serial number buffer */
4028 time_t curtime
; /* Current time */
4029 int result
; /* Result of GNU TLS calls */
4033 * Create the encryption key...
4036 cupsdLogMessage(CUPSD_LOG_INFO
, "Generating SSL server key...");
4038 gnutls_x509_privkey_init(&key
);
4039 gnutls_x509_privkey_generate(key
, GNUTLS_PK_RSA
, 2048, 0);
4045 bytes
= sizeof(buffer
);
4047 if ((result
= gnutls_x509_privkey_export(key
, GNUTLS_X509_FMT_PEM
,
4048 buffer
, &bytes
)) < 0)
4050 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to export SSL server key - %s",
4051 gnutls_strerror(result
));
4052 gnutls_x509_privkey_deinit(key
);
4055 else if ((fp
= cupsFileOpen(ServerKey
, "w")) != NULL
)
4057 cupsFileWrite(fp
, (char *)buffer
, bytes
);
4060 cupsdLogMessage(CUPSD_LOG_INFO
, "Created SSL server key file \"%s\"...",
4065 cupsdLogMessage(CUPSD_LOG_ERROR
,
4066 "Unable to create SSL server key file \"%s\" - %s",
4067 ServerKey
, strerror(errno
));
4068 gnutls_x509_privkey_deinit(key
);
4073 * Create the self-signed certificate...
4076 cupsdLogMessage(CUPSD_LOG_INFO
, "Generating self-signed SSL certificate...");
4078 language
= cupsLangDefault();
4079 curtime
= time(NULL
);
4080 serial
[0] = curtime
>> 24;
4081 serial
[1] = curtime
>> 16;
4082 serial
[2] = curtime
>> 8;
4083 serial
[3] = curtime
;
4085 gnutls_x509_crt_init(&crt
);
4086 if (strlen(language
->language
) == 5)
4087 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
4088 language
->language
+ 3, 2);
4090 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
4092 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COMMON_NAME
, 0,
4093 ServerName
, strlen(ServerName
));
4094 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATION_NAME
, 0,
4095 ServerName
, strlen(ServerName
));
4096 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATIONAL_UNIT_NAME
,
4098 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_STATE_OR_PROVINCE_NAME
, 0,
4100 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_LOCALITY_NAME
, 0,
4102 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_PKCS9_EMAIL
, 0,
4103 ServerAdmin
, strlen(ServerAdmin
));
4104 gnutls_x509_crt_set_key(crt
, key
);
4105 gnutls_x509_crt_set_serial(crt
, serial
, sizeof(serial
));
4106 gnutls_x509_crt_set_activation_time(crt
, curtime
);
4107 gnutls_x509_crt_set_expiration_time(crt
, curtime
+ 10 * 365 * 86400);
4108 gnutls_x509_crt_set_ca_status(crt
, 0);
4109 gnutls_x509_crt_set_subject_alternative_name(crt
, GNUTLS_SAN_DNSNAME
,
4111 gnutls_x509_crt_set_key_purpose_oid(crt
, GNUTLS_KP_TLS_WWW_SERVER
, 0);
4112 gnutls_x509_crt_set_key_usage(crt
, GNUTLS_KEY_KEY_ENCIPHERMENT
);
4113 gnutls_x509_crt_set_version(crt
, 3);
4115 bytes
= sizeof(buffer
);
4116 if (gnutls_x509_crt_get_key_id(crt
, 0, buffer
, &bytes
) >= 0)
4117 gnutls_x509_crt_set_subject_key_id(crt
, buffer
, bytes
);
4119 gnutls_x509_crt_sign(crt
, crt
, key
);
4125 bytes
= sizeof(buffer
);
4126 if ((result
= gnutls_x509_crt_export(crt
, GNUTLS_X509_FMT_PEM
,
4127 buffer
, &bytes
)) < 0)
4128 cupsdLogMessage(CUPSD_LOG_ERROR
,
4129 "Unable to export SSL server certificate - %s",
4130 gnutls_strerror(result
));
4131 else if ((fp
= cupsFileOpen(ServerCertificate
, "w")) != NULL
)
4133 cupsFileWrite(fp
, (char *)buffer
, bytes
);
4136 cupsdLogMessage(CUPSD_LOG_INFO
,
4137 "Created SSL server certificate file \"%s\"...",
4141 cupsdLogMessage(CUPSD_LOG_ERROR
,
4142 "Unable to create SSL server certificate file \"%s\" - %s",
4143 ServerCertificate
, strerror(errno
));
4149 gnutls_x509_crt_deinit(crt
);
4150 gnutls_x509_privkey_deinit(key
);
4154 #elif defined(HAVE_CDSASSL) && defined(HAVE_WAITPID)
4155 int pid
, /* Process ID of command */
4156 status
; /* Status of command */
4157 char command
[1024], /* Command */
4158 *argv
[4], /* Command-line arguments */
4159 *envp
[MAX_ENV
+ 1], /* Environment variables */
4160 keychain
[1024], /* Keychain argument */
4161 infofile
[1024]; /* Type-in information for cert */
4162 cups_file_t
*fp
; /* Seed/info file */
4163 int infofd
; /* Info file descriptor */
4167 * Run the "certtool" command to generate a self-signed certificate...
4170 if (!cupsFileFind("certtool", getenv("PATH"), 1, command
, sizeof(command
)))
4172 cupsdLogMessage(CUPSD_LOG_ERROR
,
4173 "No SSL certificate and certtool command not found!");
4178 * Create a file with the certificate information fields...
4180 * Note: This assumes that the default questions are asked by the certtool
4184 if ((fp
= cupsTempFile2(infofile
, sizeof(infofile
))) == NULL
)
4186 cupsdLogMessage(CUPSD_LOG_ERROR
,
4187 "Unable to create certificate information file %s - %s",
4188 infofile
, strerror(errno
));
4192 cupsFilePrintf(fp
, "%s\nr\n\ny\nb\ns\ny\n%s\n\n\n\n\n%s\ny\n",
4193 con
->servername
, con
->servername
, ServerAdmin
);
4196 cupsdLogMessage(CUPSD_LOG_INFO
,
4197 "Generating SSL server key and certificate...");
4199 snprintf(keychain
, sizeof(keychain
), "k=%s", ServerCertificate
);
4201 argv
[0] = "certtool";
4206 cupsdLoadEnv(envp
, MAX_ENV
);
4208 infofd
= open(infofile
, O_RDONLY
);
4210 if (!cupsdStartProcess(command
, argv
, envp
, infofd
, -1, -1, -1, -1, 1, NULL
,
4221 while (waitpid(pid
, &status
, 0) < 0)
4228 cupsdFinishProcess(pid
, command
, sizeof(command
));
4232 if (WIFEXITED(status
))
4233 cupsdLogMessage(CUPSD_LOG_ERROR
,
4234 "Unable to create SSL server key and certificate - "
4235 "the certtool command stopped with status %d!",
4236 WEXITSTATUS(status
));
4238 cupsdLogMessage(CUPSD_LOG_ERROR
,
4239 "Unable to create SSL server key and certificate - "
4240 "the certtool command crashed on signal %d!",
4245 cupsdLogMessage(CUPSD_LOG_INFO
,
4246 "Created SSL server certificate file \"%s\"...",
4254 #endif /* HAVE_LIBSSL && HAVE_WAITPID */
4256 #endif /* HAVE_SSL */
4260 * 'pipe_command()' - Pipe the output of a command to the remote client.
4263 static int /* O - Process ID */
4264 pipe_command(cupsd_client_t
*con
, /* I - Client connection */
4265 int infile
, /* I - Standard input for command */
4266 int *outfile
, /* O - Standard output for command */
4267 char *command
, /* I - Command to run */
4268 char *options
, /* I - Options for command */
4269 int root
) /* I - Run as root? */
4271 int i
; /* Looping var */
4272 int pid
; /* Process ID */
4273 char *commptr
, /* Command string pointer */
4274 commch
; /* Command string character */
4275 char *uriptr
; /* URI string pointer */
4276 int fds
[2]; /* Pipe FDs */
4277 int argc
; /* Number of arguments */
4278 int envc
; /* Number of environment variables */
4279 char argbuf
[10240], /* Argument buffer */
4280 *argv
[100], /* Argument strings */
4281 *envp
[MAX_ENV
+ 20]; /* Environment variables */
4282 char auth_type
[256], /* CUPSD_AUTH_TYPE environment variable */
4283 content_length
[1024], /* CONTENT_LENGTH environment variable */
4284 content_type
[1024], /* CONTENT_TYPE environment variable */
4285 http_cookie
[32768], /* HTTP_COOKIE environment variable */
4286 http_referer
[1024], /* HTTP_REFERER environment variable */
4287 http_user_agent
[1024], /* HTTP_USER_AGENT environment variable */
4288 lang
[1024], /* LANG environment variable */
4289 path_info
[1024], /* PATH_INFO environment variable */
4290 remote_addr
[1024], /* REMOTE_ADDR environment variable */
4291 remote_host
[1024], /* REMOTE_HOST environment variable */
4292 remote_user
[1024], /* REMOTE_USER environment variable */
4293 script_filename
[1024], /* SCRIPT_FILENAME environment variable */
4294 script_name
[1024], /* SCRIPT_NAME environment variable */
4295 server_name
[1024], /* SERVER_NAME environment variable */
4296 server_port
[1024]; /* SERVER_PORT environment variable */
4297 ipp_attribute_t
*attr
; /* attributes-natural-language attribute */
4299 krb5_ccache ccache
= NULL
; /* Kerberos credentials */
4300 char krb5ccname
[1024]; /* KRB5CCNAME environment variable */
4301 #endif /* HAVE_GSSAPI */
4305 * Parse a copy of the options string, which is of the form:
4307 * argument+argument+argument
4308 * ?argument+argument+argument
4309 * param=value¶m=value
4310 * ?param=value¶m=value
4311 * /name?argument+argument+argument
4312 * /name?param=value¶m=value
4314 * If the string contains an "=" character after the initial name,
4315 * then we treat it as a HTTP GET form request and make a copy of
4316 * the remaining string for the environment variable.
4318 * The string is always parsed out as command-line arguments, to
4319 * be consistent with Apache...
4322 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4323 "pipe_command: command=\"%s\", options=\"%s\"",
4324 command
, options
? options
: "(null)");
4329 strlcpy(argbuf
, options
, sizeof(argbuf
));
4333 if (argbuf
[0] == '/')
4336 * Found some trailing path information, set PATH_INFO...
4339 if ((commptr
= strchr(argbuf
, '?')) == NULL
)
4340 commptr
= argbuf
+ strlen(argbuf
);
4344 snprintf(path_info
, sizeof(path_info
), "PATH_INFO=%s", argbuf
);
4350 path_info
[0] = '\0';
4352 if (*commptr
== ' ')
4356 if (*commptr
== '?' && con
->operation
== HTTP_GET
&& !con
->query_string
)
4359 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", commptr
);
4366 argv
[argc
++] = commptr
;
4368 for (; *commptr
&& argc
< 99; commptr
++)
4371 * Break arguments whenever we see a + or space...
4374 if (*commptr
== ' ' || *commptr
== '+')
4376 while (*commptr
== ' ' || *commptr
== '+')
4380 * If we don't have a blank string, save it as another argument...
4385 argv
[argc
] = commptr
;
4391 else if (*commptr
== '%' && isxdigit(commptr
[1] & 255) &&
4392 isxdigit(commptr
[2] & 255))
4395 * Convert the %xx notation to the individual character.
4398 if (commptr
[1] >= '0' && commptr
[1] <= '9')
4399 *commptr
= (commptr
[1] - '0') << 4;
4401 *commptr
= (tolower(commptr
[1]) - 'a' + 10) << 4;
4403 if (commptr
[2] >= '0' && commptr
[2] <= '9')
4404 *commptr
|= commptr
[2] - '0';
4406 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
4408 _cups_strcpy(commptr
+ 1, commptr
+ 3);
4411 * Check for a %00 and break if that is the case...
4423 * Setup the environment variables as needed...
4426 if (con
->username
[0])
4428 snprintf(auth_type
, sizeof(auth_type
), "CUPSD_AUTH_TYPE=%s",
4429 httpGetField(HTTP(con
), HTTP_FIELD_AUTHORIZATION
));
4431 if ((uriptr
= strchr(auth_type
+ 10, ' ')) != NULL
)
4435 auth_type
[0] = '\0';
4438 (attr
= ippFindAttribute(con
->request
, "attributes-natural-language",
4439 IPP_TAG_LANGUAGE
)) != NULL
)
4441 switch (strlen(attr
->values
[0].string
.text
))
4445 * This is an unknown or badly formatted language code; use
4446 * the POSIX locale...
4449 strcpy(lang
, "LANG=C");
4454 * Just the language code (ll)...
4457 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8",
4458 attr
->values
[0].string
.text
);
4463 * Language and country code (ll-cc)...
4466 snprintf(lang
, sizeof(lang
), "LANG=%c%c_%c%c.UTF8",
4467 attr
->values
[0].string
.text
[0],
4468 attr
->values
[0].string
.text
[1],
4469 toupper(attr
->values
[0].string
.text
[3] & 255),
4470 toupper(attr
->values
[0].string
.text
[4] & 255));
4474 else if (con
->language
)
4475 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8", con
->language
->language
);
4477 strcpy(lang
, "LANG=C");
4479 strcpy(remote_addr
, "REMOTE_ADDR=");
4480 httpAddrString(con
->http
.hostaddr
, remote_addr
+ 12,
4481 sizeof(remote_addr
) - 12);
4483 snprintf(remote_host
, sizeof(remote_host
), "REMOTE_HOST=%s",
4484 con
->http
.hostname
);
4486 snprintf(script_name
, sizeof(script_name
), "SCRIPT_NAME=%s", con
->uri
);
4487 if ((uriptr
= strchr(script_name
, '?')) != NULL
)
4490 snprintf(script_filename
, sizeof(script_filename
), "SCRIPT_FILENAME=%s%s",
4491 DocumentRoot
, script_name
+ 12);
4493 sprintf(server_port
, "SERVER_PORT=%d", con
->serverport
);
4495 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
4498 envc
= cupsdLoadEnv(envp
, (int)(sizeof(envp
) / sizeof(envp
[0])));
4501 envp
[envc
++] = auth_type
;
4503 envp
[envc
++] = lang
;
4504 envp
[envc
++] = "REDIRECT_STATUS=1";
4505 envp
[envc
++] = "GATEWAY_INTERFACE=CGI/1.1";
4506 envp
[envc
++] = server_name
;
4507 envp
[envc
++] = server_port
;
4508 envp
[envc
++] = remote_addr
;
4509 envp
[envc
++] = remote_host
;
4510 envp
[envc
++] = script_name
;
4511 envp
[envc
++] = script_filename
;
4514 envp
[envc
++] = path_info
;
4516 if (con
->username
[0])
4518 snprintf(remote_user
, sizeof(remote_user
), "REMOTE_USER=%s", con
->username
);
4520 envp
[envc
++] = remote_user
;
4523 * Save Kerberos credentials, if any...
4527 if (con
->gss_have_creds
)
4529 # if !defined(HAVE_KRB5_CC_NEW_UNIQUE) && !defined(HAVE_HEIMDAL)
4530 cupsdLogMessage(CUPSD_LOG_INFO
,
4531 "Sorry, your version of Kerberos does not support "
4532 "delegated credentials!");
4535 krb5_error_code error
; /* Kerberos error code */
4536 OM_uint32 major_status
, /* Major status code */
4537 minor_status
; /* Minor status code */
4538 krb5_principal principal
; /* Kerberos principal */
4543 * If the weak-linked GSSAPI/Kerberos library is not present, don't try
4547 if (krb5_init_context
!= NULL
)
4549 # endif /* __APPLE__ */
4552 * We MUST create a file-based cache because memory-based caches are
4553 * only valid for the current process/address space.
4555 * Due to various bugs/features in different versions of Kerberos, we
4556 * need either the krb5_cc_new_unique() function or Heimdal's version
4557 * of krb5_cc_gen_new() to create a new FILE: credential cache that
4558 * can be passed to the backend. These functions create a temporary
4559 * file (typically in /tmp) containing the cached credentials, which
4560 * are removed when we have successfully printed a job.
4563 # ifdef HAVE_KRB5_CC_NEW_UNIQUE
4564 if ((error
= krb5_cc_new_unique(KerberosContext
, "FILE", NULL
,
4566 # else /* HAVE_HEIMDAL */
4567 if ((error
= krb5_cc_gen_new(KerberosContext
, &krb5_fcc_ops
,
4569 # endif /* HAVE_KRB5_CC_NEW_UNIQUE */
4571 cupsdLogMessage(CUPSD_LOG_ERROR
,
4572 "Unable to create new credentials cache (%d/%s)",
4573 error
, strerror(errno
));
4576 else if ((error
= krb5_parse_name(KerberosContext
, con
->username
,
4579 cupsdLogMessage(CUPSD_LOG_ERROR
,
4580 "Unable to parse kerberos username (%d/%s)", error
,
4582 krb5_cc_destroy(KerberosContext
, ccache
);
4585 else if ((error
= krb5_cc_initialize(KerberosContext
, ccache
,
4588 cupsdLogMessage(CUPSD_LOG_ERROR
,
4589 "Unable to initialize credentials cache (%d/%s)", error
,
4591 krb5_cc_destroy(KerberosContext
, ccache
);
4592 krb5_free_principal(KerberosContext
, principal
);
4597 krb5_free_principal(KerberosContext
, principal
);
4600 * Copy the user's credentials to the new cache file...
4603 major_status
= gss_krb5_copy_ccache(&minor_status
,
4604 con
->gss_delegated_cred
, ccache
);
4606 if (GSS_ERROR(major_status
))
4608 cupsdLogGSSMessage(CUPSD_LOG_ERROR
, major_status
, minor_status
,
4609 "Unable to import client credentials cache");
4610 krb5_cc_destroy(KerberosContext
, ccache
);
4616 * Add the KRB5CCNAME environment variable to the job so that the
4617 * backend can use the credentials when printing.
4620 snprintf(krb5ccname
, sizeof(krb5ccname
), "KRB5CCNAME=FILE:%s",
4621 krb5_cc_get_name(KerberosContext
, ccache
));
4622 envp
[envc
++] = krb5ccname
;
4625 chown(krb5_cc_get_name(KerberosContext
, ccache
), User
, Group
);
4630 # endif /* __APPLE__ */
4631 # endif /* HAVE_KRB5_CC_NEW_UNIQUE || HAVE_HEIMDAL */
4633 #endif /* HAVE_GSSAPI */
4637 if (con
->http
.version
== HTTP_1_1
)
4638 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.1";
4639 else if (con
->http
.version
== HTTP_1_0
)
4640 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.0";
4642 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/0.9";
4644 if (con
->http
.cookie
)
4646 snprintf(http_cookie
, sizeof(http_cookie
), "HTTP_COOKIE=%s",
4648 envp
[envc
++] = http_cookie
;
4651 if (con
->http
.fields
[HTTP_FIELD_USER_AGENT
][0])
4653 snprintf(http_user_agent
, sizeof(http_user_agent
), "HTTP_USER_AGENT=%s",
4654 con
->http
.fields
[HTTP_FIELD_USER_AGENT
]);
4655 envp
[envc
++] = http_user_agent
;
4658 if (con
->http
.fields
[HTTP_FIELD_REFERER
][0])
4660 snprintf(http_referer
, sizeof(http_referer
), "HTTP_REFERER=%s",
4661 con
->http
.fields
[HTTP_FIELD_REFERER
]);
4662 envp
[envc
++] = http_referer
;
4665 if (con
->operation
== HTTP_GET
)
4667 envp
[envc
++] = "REQUEST_METHOD=GET";
4669 if (con
->query_string
)
4672 * Add GET form variables after ?...
4675 envp
[envc
++] = con
->query_string
;
4680 sprintf(content_length
, "CONTENT_LENGTH=" CUPS_LLFMT
,
4681 CUPS_LLCAST con
->bytes
);
4682 snprintf(content_type
, sizeof(content_type
), "CONTENT_TYPE=%s",
4683 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
4685 envp
[envc
++] = "REQUEST_METHOD=POST";
4686 envp
[envc
++] = content_length
;
4687 envp
[envc
++] = content_type
;
4691 * Tell the CGI if we are using encryption...
4695 envp
[envc
++] = "HTTPS=ON";
4698 * Terminate the environment array...
4703 if (LogLevel
== CUPSD_LOG_DEBUG2
)
4705 for (i
= 0; i
< argc
; i
++)
4706 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4707 "pipe_command: argv[%d] = \"%s\"", i
, argv
[i
]);
4708 for (i
= 0; i
< envc
; i
++)
4709 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4710 "pipe_command: envp[%d] = \"%s\"", i
, envp
[i
]);
4714 * Create a pipe for the output...
4717 if (cupsdOpenPipe(fds
))
4719 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to create pipes for CGI %s - %s",
4720 argv
[0], strerror(errno
));
4725 * Then execute the command...
4728 if (cupsdStartProcess(command
, argv
, envp
, infile
, fds
[1], CGIPipes
[1],
4729 -1, -1, root
, DefaultProfile
, &pid
) < 0)
4732 * Error - can't fork!
4735 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to fork for CGI %s - %s", argv
[0],
4738 cupsdClosePipe(fds
);
4744 * Fork successful - return the PID...
4747 if (con
->username
[0])
4749 cupsdAddCert(pid
, con
->username
, ccache
);
4751 cupsdAddCert(pid
, con
->username
, NULL
);
4752 #endif /* HAVE_GSSAPI */
4754 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[CGI] %s started - PID = %d",
4766 * 'write_file()' - Send a file via HTTP.
4769 static int /* O - 0 on failure, 1 on success */
4770 write_file(cupsd_client_t
*con
, /* I - Client connection */
4771 http_status_t code
, /* I - HTTP status */
4772 char *filename
, /* I - Filename */
4773 char *type
, /* I - File type */
4774 struct stat
*filestats
) /* O - File information */
4776 con
->file
= open(filename
, O_RDONLY
);
4778 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "write_file: %d file=%d", con
->http
.fd
,
4784 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
4788 if (!cupsdSendHeader(con
, code
, type
, CUPSD_AUTH_NONE
))
4791 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
4792 httpGetDateString(filestats
->st_mtime
)) < 0)
4794 if (httpPrintf(HTTP(con
), "Content-Length: " CUPS_LLFMT
"\r\n",
4795 CUPS_LLCAST filestats
->st_size
) < 0)
4797 if (httpPrintf(HTTP(con
), "\r\n") < 0)
4800 if (cupsdFlushHeader(con
) < 0)
4803 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
4804 con
->http
.data_remaining
= filestats
->st_size
;
4806 if (con
->http
.data_remaining
<= INT_MAX
)
4807 con
->http
._data_remaining
= con
->http
.data_remaining
;
4809 con
->http
._data_remaining
= INT_MAX
;
4811 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
,
4812 (cupsd_selfunc_t
)cupsdWriteClient
, con
);
4819 * 'write_pipe()' - Flag that data is available on the CGI pipe.
4823 write_pipe(cupsd_client_t
*con
) /* I - Client connection */
4825 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "write_pipe: CGI output on fd %d...",
4828 con
->file_ready
= 1;
4830 cupsdRemoveSelect(con
->file
);
4831 cupsdAddSelect(con
->http
.fd
, NULL
, (cupsd_selfunc_t
)cupsdWriteClient
, con
);
4836 * End of "$Id: client.c 6999 2007-09-28 19:46:53Z mike $".