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 */
2376 * Send the HTTP status header...
2379 if (code
== HTTP_CONTINUE
)
2382 * 100-continue doesn't send any headers...
2385 return (httpPrintf(HTTP(con
), "HTTP/%d.%d 100 Continue\r\n\r\n",
2386 con
->http
.version
/ 100, con
->http
.version
% 100) > 0);
2389 httpFlushWrite(HTTP(con
));
2391 con
->http
.data_encoding
= HTTP_ENCODE_FIELDS
;
2393 if (httpPrintf(HTTP(con
), "HTTP/%d.%d %d %s\r\n", con
->http
.version
/ 100,
2394 con
->http
.version
% 100, code
, httpStatus(code
)) < 0)
2396 if (httpPrintf(HTTP(con
), "Date: %s\r\n", httpGetDateString(time(NULL
))) < 0)
2399 if (httpPrintf(HTTP(con
), "Server: %s\r\n", ServerHeader
) < 0)
2401 if (con
->http
.keep_alive
&& con
->http
.version
>= HTTP_1_0
)
2403 if (httpPrintf(HTTP(con
), "Connection: Keep-Alive\r\n") < 0)
2405 if (httpPrintf(HTTP(con
), "Keep-Alive: timeout=%d\r\n",
2406 KeepAliveTimeout
) < 0)
2409 if (code
== HTTP_METHOD_NOT_ALLOWED
)
2410 if (httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST\r\n") < 0)
2413 if (code
== HTTP_UNAUTHORIZED
)
2415 if (auth_type
== CUPSD_AUTH_NONE
)
2417 if (!con
->best
|| con
->best
->type
<= CUPSD_AUTH_NONE
)
2418 auth_type
= DefaultAuthType
;
2420 auth_type
= con
->best
->type
;
2425 if (auth_type
== CUPSD_AUTH_BASIC
|| auth_type
== CUPSD_AUTH_BASICDIGEST
)
2426 strlcpy(auth_str
, "Basic realm=\"CUPS\"", sizeof(auth_str
));
2427 else if (auth_type
== CUPSD_AUTH_DIGEST
)
2428 snprintf(auth_str
, sizeof(auth_str
), "Digest realm=\"CUPS\", nonce=\"%s\"",
2429 con
->http
.hostname
);
2431 else if (auth_type
== CUPSD_AUTH_NEGOTIATE
&& con
->gss_output_token
.length
== 0)
2432 strlcpy(auth_str
, "Negotiate", sizeof(auth_str
));
2433 #endif /* HAVE_GSSAPI */
2435 #ifdef HAVE_AUTHORIZATION_H
2436 if (con
->best
&& auth_type
!= CUPSD_AUTH_NEGOTIATE
)
2438 int i
; /* Looping var */
2439 char *auth_key
; /* Auth key buffer */
2440 size_t auth_size
; /* Size of remaining buffer */
2443 auth_key
= auth_str
+ strlen(auth_str
);
2444 auth_size
= sizeof(auth_str
) - (auth_key
- auth_str
);
2446 for (i
= 0; i
< con
->best
->num_names
; i
++)
2448 if (!strncasecmp(con
->best
->names
[i
], "@AUTHKEY(", 9))
2450 snprintf(auth_key
, auth_size
, ", authkey=\"%s\"",
2451 con
->best
->names
[i
] + 9);
2452 /* end parenthesis is stripped in conf.c */
2455 else if (!strcasecmp(con
->best
->names
[i
], "@SYSTEM") &&
2458 snprintf(auth_key
, auth_size
, ", authkey=\"%s\"", SystemGroupAuthKey
);
2463 #endif /* HAVE_AUTHORIZATION_H */
2467 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendHeader: WWW-Authenticate: %s",
2470 if (httpPrintf(HTTP(con
), "WWW-Authenticate: %s\r\n", auth_str
) < 0)
2477 * WWW-Authenticate: Negotiate can be included even for
2478 * non-401 replies...
2481 if (con
->gss_output_token
.length
> 0)
2483 char buf
[2048]; /* Output token buffer */
2484 OM_uint32 minor_status
; /* Minor status code */
2487 httpEncode64_2(buf
, sizeof(buf
),
2488 con
->gss_output_token
.value
,
2489 con
->gss_output_token
.length
);
2490 gss_release_buffer(&minor_status
, &con
->gss_output_token
);
2492 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2493 "cupsdSendHeader: WWW-Authenticate: Negotiate %s", buf
);
2495 if (httpPrintf(HTTP(con
), "WWW-Authenticate: Negotiate %s\r\n", buf
) < 0)
2498 #endif /* HAVE_GSSAPI */
2500 if (con
->language
&& strcmp(con
->language
->language
, "C"))
2502 if (httpPrintf(HTTP(con
), "Content-Language: %s\r\n",
2503 con
->language
->language
) < 0)
2509 if (!strcmp(type
, "text/html"))
2511 if (httpPrintf(HTTP(con
),
2512 "Content-Type: text/html; charset=utf-8\r\n") < 0)
2515 else if (httpPrintf(HTTP(con
), "Content-Type: %s\r\n", type
) < 0)
2524 * 'cupsdUpdateCGI()' - Read status messages from CGI scripts and programs.
2528 cupsdUpdateCGI(void)
2530 char *ptr
, /* Pointer to end of line in buffer */
2531 message
[1024]; /* Pointer to message text */
2532 int loglevel
; /* Log level for message */
2535 while ((ptr
= cupsdStatBufUpdate(CGIStatusBuffer
, &loglevel
,
2536 message
, sizeof(message
))) != NULL
)
2537 if (!strchr(CGIStatusBuffer
->buffer
, '\n'))
2540 if (ptr
== NULL
&& !CGIStatusBuffer
->bufused
)
2543 * Fatal error on pipe - should never happen!
2546 cupsdLogMessage(CUPSD_LOG_CRIT
,
2547 "cupsdUpdateCGI: error reading from CGI error pipe - %s",
2554 * 'cupsdWriteClient()' - Write data to a client as needed.
2558 cupsdWriteClient(cupsd_client_t
*con
) /* I - Client connection */
2560 int bytes
; /* Number of bytes written */
2561 char buf
[16385]; /* Data buffer */
2562 char *bufptr
; /* Pointer into buffer */
2563 ipp_state_t ipp_state
; /* IPP state value */
2567 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2568 "cupsdWriteClient(con=%p) %d response=%p(%d), file=%d "
2569 "pipe_pid=%d state=%d",
2570 con
, con
->http
.fd
, con
->response
, con
->response
->state
,
2571 con
->file
, con
->pipe_pid
, con
->http
.state
);
2574 if (con
->http
.state
!= HTTP_GET_SEND
&&
2575 con
->http
.state
!= HTTP_POST_SEND
)
2581 * Make sure we select on the CGI output...
2584 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2586 if (!con
->file_ready
)
2589 * Try again later when there is CGI output available...
2592 cupsdRemoveSelect(con
->http
.fd
);
2596 con
->file_ready
= 0;
2599 if (con
->response
&& con
->response
->state
!= IPP_DATA
)
2601 ipp_state
= ippWrite(HTTP(con
), con
->response
);
2602 bytes
= ipp_state
!= IPP_ERROR
&&
2603 (con
->file
>= 0 || ipp_state
!= IPP_DATA
);
2605 else if ((bytes
= read(con
->file
, buf
, sizeof(buf
) - 1)) > 0)
2607 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2608 "cupsdWriteClient: Read %d bytes from file %d...",
2611 if (con
->pipe_pid
&& !con
->got_fields
)
2614 * Inspect the data for Content-Type and other fields.
2619 for (bufptr
= buf
; !con
->got_fields
&& *bufptr
; bufptr
++)
2620 if (*bufptr
== '\n')
2623 * Send line to client...
2626 if (bufptr
> buf
&& bufptr
[-1] == '\r')
2630 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "Script header: %s", buf
);
2632 if (!con
->sent_header
)
2635 * Handle redirection and CGI status codes...
2638 if (!strncasecmp(buf
, "Location:", 9))
2640 cupsdSendHeader(con
, HTTP_SEE_OTHER
, NULL
, CUPSD_AUTH_NONE
);
2641 con
->sent_header
= 2;
2643 if (httpPrintf(HTTP(con
), "Content-Length: 0\r\n") < 0)
2646 else if (!strncasecmp(buf
, "Status:", 7))
2648 cupsdSendError(con
, (http_status_t
)atoi(buf
+ 7), CUPSD_AUTH_NONE
);
2649 con
->sent_header
= 2;
2653 cupsdSendHeader(con
, HTTP_OK
, NULL
, CUPSD_AUTH_NONE
);
2654 con
->sent_header
= 1;
2656 if (con
->http
.version
== HTTP_1_1
)
2658 if (httpPrintf(HTTP(con
), "Transfer-Encoding: chunked\r\n") < 0)
2664 if (strncasecmp(buf
, "Status:", 7))
2665 httpPrintf(HTTP(con
), "%s\r\n", buf
);
2667 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdWriteClient: %d %s",
2674 bytes
-= (bufptr
- buf
);
2675 memmove(buf
, bufptr
, bytes
+ 1);
2679 * See if the line was empty...
2682 if (con
->field_col
== 0)
2684 con
->got_fields
= 1;
2686 if (cupsdFlushHeader(con
) < 0)
2688 cupsdCloseClient(con
);
2692 if (con
->http
.version
== HTTP_1_1
)
2693 con
->http
.data_encoding
= HTTP_ENCODE_CHUNKED
;
2698 else if (*bufptr
!= '\r')
2701 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2702 "cupsdWriteClient: %d bytes=%d, got_fields=%d",
2703 con
->http
.fd
, bytes
, con
->got_fields
);
2705 if (bytes
> 0 && !con
->got_fields
)
2708 * Remaining text needs to go out...
2711 httpPrintf(HTTP(con
), "%s", buf
);
2713 con
->http
.activity
= time(NULL
);
2716 else if (bytes
== 0)
2717 con
->http
.activity
= time(NULL
);
2722 if (httpWrite2(HTTP(con
), buf
, bytes
) < 0)
2724 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2725 "cupsdWriteClient: %d Write of %d bytes failed!",
2726 con
->http
.fd
, bytes
);
2728 cupsdCloseClient(con
);
2732 con
->bytes
+= bytes
;
2734 if (con
->http
.state
== HTTP_WAITING
)
2741 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdWriteClient: %d bytes < 0",
2744 cupsdLogRequest(con
, HTTP_OK
);
2746 httpFlushWrite(HTTP(con
));
2748 if (con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
&& con
->sent_header
== 1)
2750 if (httpWrite2(HTTP(con
), "", 0) < 0)
2752 cupsdCloseClient(con
);
2757 con
->http
.state
= HTTP_WAITING
;
2759 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
2763 cupsdRemoveSelect(con
->file
);
2766 cupsdEndProcess(con
->pipe_pid
, 0);
2768 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2769 "cupsdWriteClient: %d Closing data file %d.",
2770 con
->http
.fd
, con
->file
);
2779 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2780 "cupsdWriteClient: %d Removing temp file %s",
2781 con
->http
.fd
, con
->filename
);
2782 unlink(con
->filename
);
2783 cupsdClearString(&con
->filename
);
2788 ippDelete(con
->request
);
2789 con
->request
= NULL
;
2794 ippDelete(con
->response
);
2795 con
->response
= NULL
;
2798 cupsdClearString(&con
->command
);
2799 cupsdClearString(&con
->options
);
2800 cupsdClearString(&con
->query_string
);
2802 if (!con
->http
.keep_alive
)
2804 cupsdCloseClient(con
);
2809 con
->http
.activity
= time(NULL
);
2814 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
2817 static int /* O - 1 if modified since */
2819 cupsd_client_t
*con
, /* I - Client connection */
2820 struct stat
*filestats
) /* I - File information */
2822 char *ptr
; /* Pointer into field */
2823 time_t date
; /* Time/date value */
2824 off_t size
; /* Size/length value */
2829 ptr
= con
->http
.fields
[HTTP_FIELD_IF_MODIFIED_SINCE
];
2834 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2835 "check_if_modified: %d If-Modified-Since=\"%s\"",
2838 while (*ptr
!= '\0')
2840 while (isspace(*ptr
) || *ptr
== ';')
2843 if (strncasecmp(ptr
, "length=", 7) == 0)
2846 size
= strtoll(ptr
, NULL
, 10);
2848 while (isdigit(*ptr
))
2851 else if (isalpha(*ptr
))
2853 date
= httpGetDateTime(ptr
);
2854 while (*ptr
!= '\0' && *ptr
!= ';')
2861 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2862 "check_if_modified: %d sizes=" CUPS_LLFMT
","
2863 CUPS_LLFMT
" dates=%d,%d",
2864 con
->http
.fd
, CUPS_LLCAST size
,
2865 CUPS_LLCAST filestats
->st_size
, (int)date
,
2866 (int)filestats
->st_mtime
);
2868 return ((size
!= filestats
->st_size
&& size
!= 0) ||
2869 (date
< filestats
->st_mtime
&& date
!= 0) ||
2870 (size
== 0 && date
== 0));
2876 * 'encrypt_client()' - Enable encryption for the client...
2879 static int /* O - 1 on success, 0 on error */
2880 encrypt_client(cupsd_client_t
*con
) /* I - Client to encrypt */
2883 SSL_CTX
*context
; /* Context for encryption */
2884 SSL
*conn
; /* Connection for encryption */
2885 BIO
*bio
; /* BIO data */
2886 unsigned long error
; /* Error code */
2890 * Verify that we have a certificate...
2893 if (access(ServerKey
, 0) || access(ServerCertificate
, 0))
2896 * Nope, make a self-signed certificate...
2899 if (!make_certificate(con
))
2904 * Create the SSL context and accept the connection...
2907 context
= SSL_CTX_new(SSLv23_server_method());
2909 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
2910 SSL_CTX_use_PrivateKey_file(context
, ServerKey
, SSL_FILETYPE_PEM
);
2911 SSL_CTX_use_certificate_file(context
, ServerCertificate
, SSL_FILETYPE_PEM
);
2913 bio
= BIO_new(_httpBIOMethods());
2914 BIO_ctrl(bio
, BIO_C_SET_FILE_PTR
, 0, (char *)HTTP(con
));
2916 conn
= SSL_new(context
);
2917 SSL_set_bio(conn
, bio
, bio
);
2919 if (SSL_accept(conn
) != 1)
2921 cupsdLogMessage(CUPSD_LOG_ERROR
,
2922 "encrypt_client: Unable to encrypt connection from %s!",
2923 con
->http
.hostname
);
2925 while ((error
= ERR_get_error()) != 0)
2926 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s",
2927 ERR_error_string(error
, NULL
));
2929 SSL_CTX_free(context
);
2934 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2935 "encrypt_client: %d Connection from %s now encrypted.",
2936 con
->http
.fd
, con
->http
.hostname
);
2938 con
->http
.tls
= conn
;
2941 # elif defined(HAVE_GNUTLS)
2942 http_tls_t
*conn
; /* TLS session object */
2943 int error
; /* Error code */
2944 gnutls_certificate_server_credentials
*credentials
;
2945 /* TLS credentials */
2949 * Verify that we have a certificate...
2952 if (access(ServerKey
, 0) || access(ServerCertificate
, 0))
2955 * Nope, make a self-signed certificate...
2958 if (!make_certificate(con
))
2963 * Create the SSL object and perform the SSL handshake...
2966 conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
));
2971 credentials
= (gnutls_certificate_server_credentials
*)
2972 malloc(sizeof(gnutls_certificate_server_credentials
));
2973 if (credentials
== NULL
)
2975 cupsdLogMessage(CUPSD_LOG_ERROR
,
2976 "encrypt_client: Unable to encrypt connection from %s!",
2977 con
->http
.hostname
);
2978 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s", strerror(errno
));
2984 gnutls_certificate_allocate_credentials(credentials
);
2985 gnutls_certificate_set_x509_key_file(*credentials
, ServerCertificate
,
2986 ServerKey
, GNUTLS_X509_FMT_PEM
);
2988 gnutls_init(&(conn
->session
), GNUTLS_SERVER
);
2989 gnutls_set_default_priority(conn
->session
);
2990 gnutls_credentials_set(conn
->session
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
2991 gnutls_transport_set_ptr(conn
->session
, (gnutls_transport_ptr
)HTTP(con
));
2992 gnutls_transport_set_pull_function(conn
->session
, _httpReadGNUTLS
);
2993 gnutls_transport_set_push_function(conn
->session
, _httpWriteGNUTLS
);
2995 error
= gnutls_handshake(conn
->session
);
2997 if (error
!= GNUTLS_E_SUCCESS
)
2999 cupsdLogMessage(CUPSD_LOG_ERROR
,
3000 "encrypt_client: Unable to encrypt connection from %s!",
3001 con
->http
.hostname
);
3002 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s",
3003 gnutls_strerror(error
));
3005 gnutls_deinit(conn
->session
);
3006 gnutls_certificate_free_credentials(*credentials
);
3012 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3013 "encrypt_client: %d Connection from %s now encrypted.",
3014 con
->http
.fd
, con
->http
.hostname
);
3016 conn
->credentials
= credentials
;
3017 con
->http
.tls
= conn
;
3020 # elif defined(HAVE_CDSASSL)
3021 OSStatus error
; /* Error code */
3022 http_tls_t
*conn
; /* CDSA connection information */
3025 if ((conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
))) == NULL
)
3029 conn
->session
= NULL
;
3030 conn
->certsArray
= get_cdsa_certificate(con
);
3032 if (!conn
->certsArray
)
3035 * No keychain (yet), make a self-signed certificate...
3038 if (make_certificate(con
))
3039 conn
->certsArray
= get_cdsa_certificate(con
);
3042 if (!conn
->certsArray
)
3044 cupsdLogMessage(CUPSD_LOG_ERROR
,
3045 "encrypt_client: Could not find signing key in keychain "
3046 "\"%s\"", ServerCertificate
);
3047 error
= errSSLBadCert
; /* errSSLBadConfiguration is a better choice, but not available on 10.2.x */
3051 error
= SSLNewContext(true, &conn
->session
);
3054 error
= SSLSetIOFuncs(conn
->session
, _httpReadCDSA
, _httpWriteCDSA
);
3057 error
= SSLSetProtocolVersionEnabled(conn
->session
, kSSLProtocol2
, false);
3060 error
= SSLSetConnection(conn
->session
, HTTP(con
));
3063 error
= SSLSetAllowsExpiredCerts(conn
->session
, true);
3066 error
= SSLSetAllowsAnyRoot(conn
->session
, true);
3069 error
= SSLSetCertificate(conn
->session
, conn
->certsArray
);
3074 * Perform SSL/TLS handshake
3077 while ((error
= SSLHandshake(conn
->session
)) == errSSLWouldBlock
)
3083 cupsdLogMessage(CUPSD_LOG_ERROR
,
3084 "encrypt_client: Unable to encrypt connection from %s!",
3085 con
->http
.hostname
);
3087 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s (%d)",
3088 cssmErrorString(error
), (int)error
);
3090 con
->http
.error
= error
;
3091 con
->http
.status
= HTTP_ERROR
;
3094 SSLDisposeContext(conn
->session
);
3096 if (conn
->certsArray
)
3097 CFRelease(conn
->certsArray
);
3104 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3105 "encrypt_client: %d Connection from %s now encrypted.",
3106 con
->http
.fd
, con
->http
.hostname
);
3108 con
->http
.tls
= conn
;
3111 # endif /* HAVE_LIBSSL */
3113 #endif /* HAVE_SSL */
3118 * 'get_cdsa_certificate()' - Get a SSL/TLS certificate from the System keychain.
3121 static CFArrayRef
/* O - Array of certificates */
3122 get_cdsa_certificate(cupsd_client_t
*con
) /* I - Client connection */
3124 OSStatus err
; /* Error info */
3125 SecKeychainRef keychain
; /* Keychain reference */
3126 SecIdentitySearchRef search
; /* Search reference */
3127 SecIdentityRef identity
; /* Identity */
3128 CFArrayRef certificates
= NULL
;
3129 /* Certificate array */
3132 if ((err
= SecKeychainOpen(ServerCertificate
, &keychain
)))
3134 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot open keychain \"%s\", %s",
3135 ServerCertificate
, cssmErrorString(err
));
3139 # if HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY
3141 * Use a policy to search for valid certificates who's common name matches the
3145 SecPolicySearchRef policy_search
; /* Policy search ref */
3146 SecPolicyRef policy
; /* Policy ref */
3147 CSSM_DATA options
; /* Policy options */
3148 CSSM_APPLE_TP_SSL_OPTIONS
3149 ssl_options
; /* SSL Option for hostname */
3152 if ((err
= SecPolicySearchCreate(CSSM_CERT_X_509v3
, &CSSMOID_APPLE_TP_SSL
,
3153 NULL
, &policy_search
)))
3155 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot create a policy search reference");
3156 CFRelease(keychain
);
3160 if ((err
= SecPolicySearchCopyNext(policy_search
, &policy
)))
3162 cupsdLogMessage(CUPSD_LOG_ERROR
,
3163 "Cannot find a policy to use for searching");
3164 CFRelease(keychain
);
3165 CFRelease(policy_search
);
3169 memset(&ssl_options
, 0, sizeof(ssl_options
));
3170 ssl_options
.Version
= CSSM_APPLE_TP_SSL_OPTS_VERSION
;
3171 ssl_options
.ServerName
= con
->servername
;
3172 ssl_options
.ServerNameLen
= strlen(con
->servername
);
3174 options
.Data
= (uint8
*)&ssl_options
;
3175 options
.Length
= sizeof(ssl_options
);
3177 if ((err
= SecPolicySetValue(policy
, &options
)))
3179 cupsdLogMessage(CUPSD_LOG_ERROR
,
3180 "Cannot set policy value to use for searching");
3181 CFRelease(keychain
);
3182 CFRelease(policy_search
);
3186 err
= SecIdentitySearchCreateWithPolicy(policy
, NULL
, CSSM_KEYUSE_SIGN
,
3187 keychain
, FALSE
, &search
);
3190 * Assume there is exactly one SecIdentity in the keychain...
3193 err
= SecIdentitySearchCreate(keychain
, CSSM_KEYUSE_SIGN
, &search
);
3194 # endif /* HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY */
3197 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3198 "Cannot create keychain search reference: %s",
3199 cssmErrorString(err
));
3202 if ((err
= SecIdentitySearchCopyNext(search
, &identity
)))
3204 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3205 "Cannot find signing key in keychain \"%s\", error %d",
3206 ServerCertificate
, (int)err
);
3210 if (CFGetTypeID(identity
) != SecIdentityGetTypeID())
3211 cupsdLogMessage(CUPSD_LOG_ERROR
,
3212 "SecIdentitySearchCopyNext CFTypeID failure!");
3215 if ((certificates
= CFArrayCreate(NULL
, (const void **)&identity
,
3216 1, &kCFTypeArrayCallBacks
)) == NULL
)
3217 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot create certificate array");
3220 CFRelease(identity
);
3226 # if HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY
3228 CFRelease(policy_search
);
3229 # endif /* HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY */
3231 return (certificates
);
3233 #endif /* HAVE_CDSASSL */
3237 * 'get_file()' - Get a filename and state info.
3240 static char * /* O - Real filename */
3241 get_file(cupsd_client_t
*con
, /* I - Client connection */
3242 struct stat
*filestats
, /* O - File information */
3243 char *filename
, /* IO - Filename buffer */
3244 int len
) /* I - Buffer length */
3246 int status
; /* Status of filesystem calls */
3247 char *ptr
; /* Pointer info filename */
3248 int plen
; /* Remaining length after pointer */
3249 char language
[7]; /* Language subdirectory, if any */
3253 * Figure out the real filename...
3258 if (!strncmp(con
->uri
, "/ppd/", 5))
3259 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
);
3260 else if (!strncmp(con
->uri
, "/rss/", 5) && !strchr(con
->uri
+ 5, '/'))
3261 snprintf(filename
, len
, "%s/rss/%s", CacheDir
, con
->uri
+ 5);
3262 else if (!strncmp(con
->uri
, "/admin/conf/", 12))
3263 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
+ 11);
3264 else if (!strncmp(con
->uri
, "/admin/log/", 11))
3266 if (!strncmp(con
->uri
+ 11, "access_log", 10) && AccessLog
[0] == '/')
3267 strlcpy(filename
, AccessLog
, len
);
3268 else if (!strncmp(con
->uri
+ 11, "error_log", 9) && ErrorLog
[0] == '/')
3269 strlcpy(filename
, ErrorLog
, len
);
3270 else if (!strncmp(con
->uri
+ 11, "page_log", 8) && PageLog
[0] == '/')
3271 strlcpy(filename
, PageLog
, len
);
3275 else if (con
->language
)
3277 snprintf(language
, sizeof(language
), "/%s", con
->language
->language
);
3278 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3281 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3283 if ((ptr
= strchr(filename
, '?')) != NULL
)
3287 * Grab the status for this language; if there isn't a language-specific file
3288 * then fallback to the default one...
3291 if ((status
= stat(filename
, filestats
)) != 0 && language
[0] &&
3292 strncmp(con
->uri
, "/ppd/", 5) &&
3293 strncmp(con
->uri
, "/admin/conf/", 12) &&
3294 strncmp(con
->uri
, "/admin/log/", 11))
3297 * Drop the country code...
3301 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3303 if ((ptr
= strchr(filename
, '?')) != NULL
)
3306 if ((status
= stat(filename
, filestats
)) != 0)
3309 * Drop the language prefix and try the root directory...
3313 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3315 if ((ptr
= strchr(filename
, '?')) != NULL
)
3318 status
= stat(filename
, filestats
);
3323 * If we're found a directory, get the index.html file instead...
3326 if (!status
&& S_ISDIR(filestats
->st_mode
))
3329 * Make sure the URI ends with a slash...
3332 if (con
->uri
[strlen(con
->uri
) - 1] != '/')
3333 strlcat(con
->uri
, "/", sizeof(con
->uri
));
3336 * Find the directory index file, trying every language...
3341 if (status
&& language
[0])
3344 * Try a different language subset...
3348 language
[0] = '\0'; /* Strip country code */
3350 language
[0] = '\0'; /* Strip language */
3354 * Look for the index file...
3357 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3359 if ((ptr
= strchr(filename
, '?')) != NULL
)
3362 ptr
= filename
+ strlen(filename
);
3363 plen
= len
- (ptr
- filename
);
3365 strlcpy(ptr
, "index.html", plen
);
3366 status
= stat(filename
, filestats
);
3371 strlcpy(ptr
, "index.class", plen
);
3372 status
= stat(filename
, filestats
);
3374 #endif /* HAVE_JAVA */
3379 strlcpy(ptr
, "index.pl", plen
);
3380 status
= stat(filename
, filestats
);
3382 #endif /* HAVE_PERL */
3387 strlcpy(ptr
, "index.php", plen
);
3388 status
= stat(filename
, filestats
);
3390 #endif /* HAVE_PHP */
3395 strlcpy(ptr
, "index.pyc", plen
);
3396 status
= stat(filename
, filestats
);
3401 strlcpy(ptr
, "index.py", plen
);
3402 status
= stat(filename
, filestats
);
3404 #endif /* HAVE_PYTHON */
3407 while (status
&& language
[0]);
3410 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "get_file: %d filename=%s size=%d",
3411 con
->http
.fd
, filename
,
3412 status
? -1 : (int)filestats
->st_size
);
3415 con
->http
.data_remaining
= (int)filestats
->st_size
;
3425 * 'install_conf_file()' - Install a configuration file.
3428 static http_status_t
/* O - Status */
3429 install_conf_file(cupsd_client_t
*con
) /* I - Connection */
3431 cups_file_t
*in
, /* Input file */
3432 *out
; /* Output file */
3433 char buffer
[1024]; /* Copy buffer */
3434 int bytes
; /* Number of bytes */
3435 char conffile
[1024], /* Configuration filename */
3436 newfile
[1024], /* New config filename */
3437 oldfile
[1024]; /* Old config filename */
3438 struct stat confinfo
; /* Config file info */
3442 * First construct the filenames...
3445 snprintf(conffile
, sizeof(conffile
), "%s%s", ServerRoot
, con
->uri
+ 11);
3446 snprintf(newfile
, sizeof(newfile
), "%s%s.N", ServerRoot
, con
->uri
+ 11);
3447 snprintf(oldfile
, sizeof(oldfile
), "%s%s.O", ServerRoot
, con
->uri
+ 11);
3449 cupsdLogMessage(CUPSD_LOG_INFO
, "Installing config file \"%s\"...", conffile
);
3452 * Get the owner, group, and permissions of the configuration file.
3453 * If it doesn't exist, assign it to the User and Group in the
3454 * cupsd.conf file with mode 0640 permissions.
3457 if (stat(conffile
, &confinfo
))
3459 confinfo
.st_uid
= User
;
3460 confinfo
.st_gid
= Group
;
3461 confinfo
.st_mode
= ConfigFilePerm
;
3465 * Open the request file and new config file...
3468 if ((in
= cupsFileOpen(con
->filename
, "rb")) == NULL
)
3470 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open request file \"%s\" - %s",
3471 con
->filename
, strerror(errno
));
3472 return (HTTP_SERVER_ERROR
);
3475 if ((out
= cupsFileOpen(newfile
, "wb")) == NULL
)
3478 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open config file \"%s\" - %s",
3479 newfile
, strerror(errno
));
3480 return (HTTP_SERVER_ERROR
);
3483 fchmod(cupsFileNumber(out
), confinfo
.st_mode
);
3484 fchown(cupsFileNumber(out
), confinfo
.st_uid
, confinfo
.st_gid
);
3487 * Copy from the request to the new config file...
3490 while ((bytes
= cupsFileRead(in
, buffer
, sizeof(buffer
))) > 0)
3491 if (cupsFileWrite(out
, buffer
, bytes
) < bytes
)
3493 cupsdLogMessage(CUPSD_LOG_ERROR
,
3494 "Unable to copy to config file \"%s\" - %s",
3495 newfile
, strerror(errno
));
3501 return (HTTP_SERVER_ERROR
);
3505 * Close the files...
3509 if (cupsFileClose(out
))
3511 cupsdLogMessage(CUPSD_LOG_ERROR
,
3512 "Error file closing config file \"%s\" - %s",
3513 newfile
, strerror(errno
));
3517 return (HTTP_SERVER_ERROR
);
3521 * Remove the request file...
3524 unlink(con
->filename
);
3525 cupsdClearString(&con
->filename
);
3528 * Unlink the old backup, rename the current config file to the backup
3529 * filename, and rename the new config file to the config file name...
3532 if (unlink(oldfile
))
3533 if (errno
!= ENOENT
)
3535 cupsdLogMessage(CUPSD_LOG_ERROR
,
3536 "Unable to remove backup config file \"%s\" - %s",
3537 oldfile
, strerror(errno
));
3541 return (HTTP_SERVER_ERROR
);
3544 if (rename(conffile
, oldfile
))
3545 if (errno
!= ENOENT
)
3547 cupsdLogMessage(CUPSD_LOG_ERROR
,
3548 "Unable to rename old config file \"%s\" - %s",
3549 conffile
, strerror(errno
));
3553 return (HTTP_SERVER_ERROR
);
3556 if (rename(newfile
, conffile
))
3558 cupsdLogMessage(CUPSD_LOG_ERROR
,
3559 "Unable to rename new config file \"%s\" - %s",
3560 newfile
, strerror(errno
));
3562 rename(oldfile
, conffile
);
3565 return (HTTP_SERVER_ERROR
);
3569 * If the cupsd.conf file was updated, set the NeedReload flag...
3572 if (!strcmp(con
->uri
, "/admin/conf/cupsd.conf"))
3573 NeedReload
= RELOAD_CUPSD
;
3575 NeedReload
= RELOAD_ALL
;
3577 ReloadTime
= time(NULL
);
3580 * Return that the file was created successfully...
3583 return (HTTP_CREATED
);
3588 * 'is_cgi()' - Is the resource a CGI script/program?
3591 static int /* O - 1 = CGI, 0 = file */
3592 is_cgi(cupsd_client_t
*con
, /* I - Client connection */
3593 const char *filename
, /* I - Real filename */
3594 struct stat
*filestats
, /* I - File information */
3595 mime_type_t
*type
) /* I - MIME type */
3597 const char *options
; /* Options on URL */
3600 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3601 "is_cgi(con=%p, filename=\"%s\", filestats=%p, type=%s/%s)\n",
3602 con
, filename
, filestats
, type
? type
->super
: "unknown",
3603 type
? type
->type
: "unknown");
3606 * Get the options, if any...
3609 if ((options
= strchr(con
->uri
, '?')) != NULL
)
3613 if (strchr(options
, '='))
3614 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", options
);
3618 * Check for known types...
3621 if (!type
|| strcasecmp(type
->super
, "application"))
3623 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "is_cgi: Returning 0...");
3627 if (!strcasecmp(type
->type
, "x-httpd-cgi") &&
3628 (filestats
->st_mode
& 0111))
3631 * "application/x-httpd-cgi" is a CGI script.
3634 cupsdSetString(&con
->command
, filename
);
3636 filename
= strrchr(filename
, '/') + 1; /* Filename always absolute */
3638 cupsdSetString(&con
->options
, options
);
3640 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3641 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3642 con
->command
, con
->options
);
3647 else if (!strcasecmp(type
->type
, "x-httpd-java"))
3650 * "application/x-httpd-java" is a Java servlet.
3653 cupsdSetString(&con
->command
, CUPS_JAVA
);
3656 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3658 cupsdSetStringf(&con
->options
, " %s", filename
);
3660 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3661 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3662 con
->command
, con
->options
);
3666 #endif /* HAVE_JAVA */
3668 else if (!strcasecmp(type
->type
, "x-httpd-perl"))
3671 * "application/x-httpd-perl" is a Perl page.
3674 cupsdSetString(&con
->command
, CUPS_PERL
);
3677 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3679 cupsdSetStringf(&con
->options
, " %s", filename
);
3681 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3682 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3683 con
->command
, con
->options
);
3687 #endif /* HAVE_PERL */
3689 else if (!strcasecmp(type
->type
, "x-httpd-php"))
3692 * "application/x-httpd-php" is a PHP page.
3695 cupsdSetString(&con
->command
, CUPS_PHP
);
3698 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3700 cupsdSetStringf(&con
->options
, " %s", filename
);
3702 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3703 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3704 con
->command
, con
->options
);
3708 #endif /* HAVE_PHP */
3710 else if (!strcasecmp(type
->type
, "x-httpd-python"))
3713 * "application/x-httpd-python" is a Python page.
3716 cupsdSetString(&con
->command
, CUPS_PYTHON
);
3719 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3721 cupsdSetStringf(&con
->options
, " %s", filename
);
3723 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3724 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3725 con
->command
, con
->options
);
3729 #endif /* HAVE_PYTHON */
3731 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "is_cgi: Returning 0...");
3738 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
3741 static int /* O - 0 if relative, 1 if absolute */
3742 is_path_absolute(const char *path
) /* I - Input path */
3745 * Check for a leading slash...
3752 * Check for "/.." in the path...
3755 while ((path
= strstr(path
, "/..")) != NULL
)
3757 if (!path
[3] || path
[3] == '/')
3764 * If we haven't found any relative paths, return 1 indicating an
3774 * 'make_certificate()' - Make a self-signed SSL/TLS certificate.
3777 static int /* O - 1 on success, 0 on failure */
3778 make_certificate(cupsd_client_t
*con
) /* I - Client connection */
3780 #if defined(HAVE_LIBSSL) && defined(HAVE_WAITPID)
3781 int pid
, /* Process ID of command */
3782 status
; /* Status of command */
3783 char command
[1024], /* Command */
3784 *argv
[12], /* Command-line arguments */
3785 *envp
[MAX_ENV
+ 1], /* Environment variables */
3786 home
[1024], /* HOME environment variable */
3787 infofile
[1024], /* Type-in information for cert */
3788 seedfile
[1024]; /* Random number seed file */
3789 int envc
, /* Number of environment variables */
3790 bytes
; /* Bytes written */
3791 cups_file_t
*fp
; /* Seed/info file */
3792 int infofd
; /* Info file descriptor */
3796 * Run the "openssl" command to seed the random number generator and
3797 * generate a self-signed certificate that is good for 10 years:
3799 * openssl rand -rand seedfile 1
3801 * openssl req -new -x509 -keyout ServerKey \
3802 * -out ServerCertificate -days 3650 -nodes
3804 * The seeding step is crucial in ensuring that the openssl command
3805 * does not block on systems without sufficient entropy...
3808 if (!cupsFileFind("openssl", getenv("PATH"), 1, command
, sizeof(command
)))
3810 cupsdLogMessage(CUPSD_LOG_ERROR
,
3811 "No SSL certificate and openssl command not found!");
3815 if (access("/dev/urandom", 0))
3818 * If the system doesn't provide /dev/urandom, then any random source
3819 * will probably be blocking-style, so generate some random data to
3820 * use as a seed for the certificate. Note that we have already
3821 * seeded the random number generator in cupsdInitCerts()...
3824 cupsdLogMessage(CUPSD_LOG_INFO
,
3825 "Seeding the random number generator...");
3827 snprintf(home
, sizeof(home
), "HOME=%s", TempDir
);
3830 * Write the seed file...
3833 if ((fp
= cupsTempFile2(seedfile
, sizeof(seedfile
))) == NULL
)
3835 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to create seed file %s - %s",
3836 seedfile
, strerror(errno
));
3840 for (bytes
= 0; bytes
< 262144; bytes
++)
3841 cupsFilePutChar(fp
, random());
3846 * Run the openssl command to seed its random number generator...
3849 argv
[0] = "openssl";
3856 envc
= cupsdLoadEnv(envp
, MAX_ENV
);
3857 envp
[envc
++] = home
;
3860 if (!cupsdStartProcess(command
, argv
, envp
, -1, -1, -1, -1, -1, 1, NULL
,
3867 while (waitpid(pid
, &status
, 0) < 0)
3874 cupsdFinishProcess(pid
, command
, sizeof(command
));
3877 * Remove the seed file, as it is no longer needed...
3884 if (WIFEXITED(status
))
3885 cupsdLogMessage(CUPSD_LOG_ERROR
,
3886 "Unable to seed random number generator - "
3887 "the openssl command stopped with status %d!",
3888 WEXITSTATUS(status
));
3890 cupsdLogMessage(CUPSD_LOG_ERROR
,
3891 "Unable to seed random number generator - "
3892 "the openssl command crashed on signal %d!",
3900 * Create a file with the certificate information fields...
3902 * Note: This assumes that the default questions are asked by the openssl
3906 if ((fp
= cupsTempFile2(infofile
, sizeof(infofile
))) == NULL
)
3908 cupsdLogMessage(CUPSD_LOG_ERROR
,
3909 "Unable to create certificate information file %s - %s",
3910 infofile
, strerror(errno
));
3914 cupsFilePrintf(fp
, ".\n.\n.\n%s\n.\n%s\n%s\n",
3915 ServerName
, ServerName
, ServerAdmin
);
3918 cupsdLogMessage(CUPSD_LOG_INFO
,
3919 "Generating SSL server key and certificate...");
3921 argv
[0] = "openssl";
3925 argv
[4] = "-keyout";
3926 argv
[5] = ServerKey
;
3928 argv
[7] = ServerCertificate
;
3931 argv
[10] = "-nodes";
3934 cupsdLoadEnv(envp
, MAX_ENV
);
3936 infofd
= open(infofile
, O_RDONLY
);
3938 if (!cupsdStartProcess(command
, argv
, envp
, infofd
, -1, -1, -1, -1, 1, NULL
,
3949 while (waitpid(pid
, &status
, 0) < 0)
3956 cupsdFinishProcess(pid
, command
, sizeof(command
));
3960 if (WIFEXITED(status
))
3961 cupsdLogMessage(CUPSD_LOG_ERROR
,
3962 "Unable to create SSL server key and certificate - "
3963 "the openssl command stopped with status %d!",
3964 WEXITSTATUS(status
));
3966 cupsdLogMessage(CUPSD_LOG_ERROR
,
3967 "Unable to create SSL server key and certificate - "
3968 "the openssl command crashed on signal %d!",
3973 cupsdLogMessage(CUPSD_LOG_INFO
, "Created SSL server key file \"%s\"...",
3975 cupsdLogMessage(CUPSD_LOG_INFO
,
3976 "Created SSL server certificate file \"%s\"...",
3982 #elif defined(HAVE_GNUTLS)
3983 gnutls_x509_crt crt
; /* Self-signed certificate */
3984 gnutls_x509_privkey key
; /* Encryption key */
3985 cups_lang_t
*language
; /* Default language info */
3986 cups_file_t
*fp
; /* Key/cert file */
3987 unsigned char buffer
[8192]; /* Buffer for x509 data */
3988 size_t bytes
; /* Number of bytes of data */
3989 unsigned char serial
[4]; /* Serial number buffer */
3990 time_t curtime
; /* Current time */
3991 int result
; /* Result of GNU TLS calls */
3995 * Create the encryption key...
3998 cupsdLogMessage(CUPSD_LOG_INFO
, "Generating SSL server key...");
4000 gnutls_x509_privkey_init(&key
);
4001 gnutls_x509_privkey_generate(key
, GNUTLS_PK_RSA
, 2048, 0);
4007 bytes
= sizeof(buffer
);
4009 if ((result
= gnutls_x509_privkey_export(key
, GNUTLS_X509_FMT_PEM
,
4010 buffer
, &bytes
)) < 0)
4012 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to export SSL server key - %s",
4013 gnutls_strerror(result
));
4014 gnutls_x509_privkey_deinit(key
);
4017 else if ((fp
= cupsFileOpen(ServerKey
, "w")) != NULL
)
4019 cupsFileWrite(fp
, (char *)buffer
, bytes
);
4022 cupsdLogMessage(CUPSD_LOG_INFO
, "Created SSL server key file \"%s\"...",
4027 cupsdLogMessage(CUPSD_LOG_ERROR
,
4028 "Unable to create SSL server key file \"%s\" - %s",
4029 ServerKey
, strerror(errno
));
4030 gnutls_x509_privkey_deinit(key
);
4035 * Create the self-signed certificate...
4038 cupsdLogMessage(CUPSD_LOG_INFO
, "Generating self-signed SSL certificate...");
4040 language
= cupsLangDefault();
4041 curtime
= time(NULL
);
4042 serial
[0] = curtime
>> 24;
4043 serial
[1] = curtime
>> 16;
4044 serial
[2] = curtime
>> 8;
4045 serial
[3] = curtime
;
4047 gnutls_x509_crt_init(&crt
);
4048 if (strlen(language
->language
) == 5)
4049 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
4050 language
->language
+ 3, 2);
4052 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
4054 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COMMON_NAME
, 0,
4055 ServerName
, strlen(ServerName
));
4056 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATION_NAME
, 0,
4057 ServerName
, strlen(ServerName
));
4058 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATIONAL_UNIT_NAME
,
4060 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_STATE_OR_PROVINCE_NAME
, 0,
4062 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_LOCALITY_NAME
, 0,
4064 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_PKCS9_EMAIL
, 0,
4065 ServerAdmin
, strlen(ServerAdmin
));
4066 gnutls_x509_crt_set_key(crt
, key
);
4067 gnutls_x509_crt_set_serial(crt
, serial
, sizeof(serial
));
4068 gnutls_x509_crt_set_activation_time(crt
, curtime
);
4069 gnutls_x509_crt_set_expiration_time(crt
, curtime
+ 10 * 365 * 86400);
4070 gnutls_x509_crt_set_ca_status(crt
, 0);
4071 gnutls_x509_crt_set_subject_alternative_name(crt
, GNUTLS_SAN_DNSNAME
,
4073 gnutls_x509_crt_set_key_purpose_oid(crt
, GNUTLS_KP_TLS_WWW_SERVER
, 0);
4074 gnutls_x509_crt_set_key_usage(crt
, GNUTLS_KEY_KEY_ENCIPHERMENT
);
4075 gnutls_x509_crt_set_version(crt
, 3);
4077 bytes
= sizeof(buffer
);
4078 if (gnutls_x509_crt_get_key_id(crt
, 0, buffer
, &bytes
) >= 0)
4079 gnutls_x509_crt_set_subject_key_id(crt
, buffer
, bytes
);
4081 gnutls_x509_crt_sign(crt
, crt
, key
);
4087 bytes
= sizeof(buffer
);
4088 if ((result
= gnutls_x509_crt_export(crt
, GNUTLS_X509_FMT_PEM
,
4089 buffer
, &bytes
)) < 0)
4090 cupsdLogMessage(CUPSD_LOG_ERROR
,
4091 "Unable to export SSL server certificate - %s",
4092 gnutls_strerror(result
));
4093 else if ((fp
= cupsFileOpen(ServerCertificate
, "w")) != NULL
)
4095 cupsFileWrite(fp
, (char *)buffer
, bytes
);
4098 cupsdLogMessage(CUPSD_LOG_INFO
,
4099 "Created SSL server certificate file \"%s\"...",
4103 cupsdLogMessage(CUPSD_LOG_ERROR
,
4104 "Unable to create SSL server certificate file \"%s\" - %s",
4105 ServerCertificate
, strerror(errno
));
4111 gnutls_x509_crt_deinit(crt
);
4112 gnutls_x509_privkey_deinit(key
);
4116 #elif defined(HAVE_CDSASSL) && defined(HAVE_WAITPID)
4117 int pid
, /* Process ID of command */
4118 status
; /* Status of command */
4119 char command
[1024], /* Command */
4120 *argv
[4], /* Command-line arguments */
4121 *envp
[MAX_ENV
+ 1], /* Environment variables */
4122 keychain
[1024], /* Keychain argument */
4123 infofile
[1024]; /* Type-in information for cert */
4124 cups_file_t
*fp
; /* Seed/info file */
4125 int infofd
; /* Info file descriptor */
4129 * Run the "certtool" command to generate a self-signed certificate...
4132 if (!cupsFileFind("certtool", getenv("PATH"), 1, command
, sizeof(command
)))
4134 cupsdLogMessage(CUPSD_LOG_ERROR
,
4135 "No SSL certificate and certtool command not found!");
4140 * Create a file with the certificate information fields...
4142 * Note: This assumes that the default questions are asked by the certtool
4146 if ((fp
= cupsTempFile2(infofile
, sizeof(infofile
))) == NULL
)
4148 cupsdLogMessage(CUPSD_LOG_ERROR
,
4149 "Unable to create certificate information file %s - %s",
4150 infofile
, strerror(errno
));
4154 cupsFilePrintf(fp
, "%s\nr\n\ny\nb\ns\ny\n%s\n\n\n\n\n%s\ny\n",
4155 con
->servername
, con
->servername
, ServerAdmin
);
4158 cupsdLogMessage(CUPSD_LOG_INFO
,
4159 "Generating SSL server key and certificate...");
4161 snprintf(keychain
, sizeof(keychain
), "k=%s", ServerCertificate
);
4163 argv
[0] = "certtool";
4168 cupsdLoadEnv(envp
, MAX_ENV
);
4170 infofd
= open(infofile
, O_RDONLY
);
4172 if (!cupsdStartProcess(command
, argv
, envp
, infofd
, -1, -1, -1, -1, 1, NULL
,
4183 while (waitpid(pid
, &status
, 0) < 0)
4190 cupsdFinishProcess(pid
, command
, sizeof(command
));
4194 if (WIFEXITED(status
))
4195 cupsdLogMessage(CUPSD_LOG_ERROR
,
4196 "Unable to create SSL server key and certificate - "
4197 "the certtool command stopped with status %d!",
4198 WEXITSTATUS(status
));
4200 cupsdLogMessage(CUPSD_LOG_ERROR
,
4201 "Unable to create SSL server key and certificate - "
4202 "the certtool command crashed on signal %d!",
4207 cupsdLogMessage(CUPSD_LOG_INFO
,
4208 "Created SSL server certificate file \"%s\"...",
4216 #endif /* HAVE_LIBSSL && HAVE_WAITPID */
4218 #endif /* HAVE_SSL */
4222 * 'pipe_command()' - Pipe the output of a command to the remote client.
4225 static int /* O - Process ID */
4226 pipe_command(cupsd_client_t
*con
, /* I - Client connection */
4227 int infile
, /* I - Standard input for command */
4228 int *outfile
, /* O - Standard output for command */
4229 char *command
, /* I - Command to run */
4230 char *options
, /* I - Options for command */
4231 int root
) /* I - Run as root? */
4233 int i
; /* Looping var */
4234 int pid
; /* Process ID */
4235 char *commptr
, /* Command string pointer */
4236 commch
; /* Command string character */
4237 char *uriptr
; /* URI string pointer */
4238 int fds
[2]; /* Pipe FDs */
4239 int argc
; /* Number of arguments */
4240 int envc
; /* Number of environment variables */
4241 char argbuf
[10240], /* Argument buffer */
4242 *argv
[100], /* Argument strings */
4243 *envp
[MAX_ENV
+ 20]; /* Environment variables */
4244 char auth_type
[256], /* CUPSD_AUTH_TYPE environment variable */
4245 content_length
[1024], /* CONTENT_LENGTH environment variable */
4246 content_type
[1024], /* CONTENT_TYPE environment variable */
4247 http_cookie
[32768], /* HTTP_COOKIE environment variable */
4248 http_referer
[1024], /* HTTP_REFERER environment variable */
4249 http_user_agent
[1024], /* HTTP_USER_AGENT environment variable */
4250 lang
[1024], /* LANG environment variable */
4251 path_info
[1024], /* PATH_INFO environment variable */
4252 remote_addr
[1024], /* REMOTE_ADDR environment variable */
4253 remote_host
[1024], /* REMOTE_HOST environment variable */
4254 remote_user
[1024], /* REMOTE_USER environment variable */
4255 script_filename
[1024], /* SCRIPT_FILENAME environment variable */
4256 script_name
[1024], /* SCRIPT_NAME environment variable */
4257 server_name
[1024], /* SERVER_NAME environment variable */
4258 server_port
[1024]; /* SERVER_PORT environment variable */
4259 ipp_attribute_t
*attr
; /* attributes-natural-language attribute */
4261 krb5_ccache ccache
= NULL
; /* Kerberos credentials */
4262 char krb5ccname
[1024]; /* KRB5CCNAME environment variable */
4263 #endif /* HAVE_GSSAPI */
4267 * Parse a copy of the options string, which is of the form:
4269 * argument+argument+argument
4270 * ?argument+argument+argument
4271 * param=value¶m=value
4272 * ?param=value¶m=value
4273 * /name?argument+argument+argument
4274 * /name?param=value¶m=value
4276 * If the string contains an "=" character after the initial name,
4277 * then we treat it as a HTTP GET form request and make a copy of
4278 * the remaining string for the environment variable.
4280 * The string is always parsed out as command-line arguments, to
4281 * be consistent with Apache...
4284 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4285 "pipe_command: command=\"%s\", options=\"%s\"",
4286 command
, options
? options
: "(null)");
4291 strlcpy(argbuf
, options
, sizeof(argbuf
));
4295 if (argbuf
[0] == '/')
4298 * Found some trailing path information, set PATH_INFO...
4301 if ((commptr
= strchr(argbuf
, '?')) == NULL
)
4302 commptr
= argbuf
+ strlen(argbuf
);
4306 snprintf(path_info
, sizeof(path_info
), "PATH_INFO=%s", argbuf
);
4312 path_info
[0] = '\0';
4314 if (*commptr
== ' ')
4318 if (*commptr
== '?' && con
->operation
== HTTP_GET
&& !con
->query_string
)
4321 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", commptr
);
4328 argv
[argc
++] = commptr
;
4330 for (; *commptr
&& argc
< 99; commptr
++)
4333 * Break arguments whenever we see a + or space...
4336 if (*commptr
== ' ' || *commptr
== '+')
4338 while (*commptr
== ' ' || *commptr
== '+')
4342 * If we don't have a blank string, save it as another argument...
4347 argv
[argc
] = commptr
;
4353 else if (*commptr
== '%' && isxdigit(commptr
[1] & 255) &&
4354 isxdigit(commptr
[2] & 255))
4357 * Convert the %xx notation to the individual character.
4360 if (commptr
[1] >= '0' && commptr
[1] <= '9')
4361 *commptr
= (commptr
[1] - '0') << 4;
4363 *commptr
= (tolower(commptr
[1]) - 'a' + 10) << 4;
4365 if (commptr
[2] >= '0' && commptr
[2] <= '9')
4366 *commptr
|= commptr
[2] - '0';
4368 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
4370 _cups_strcpy(commptr
+ 1, commptr
+ 3);
4373 * Check for a %00 and break if that is the case...
4385 * Setup the environment variables as needed...
4388 if (con
->username
[0])
4390 snprintf(auth_type
, sizeof(auth_type
), "CUPSD_AUTH_TYPE=%s",
4391 httpGetField(HTTP(con
), HTTP_FIELD_AUTHORIZATION
));
4393 if ((uriptr
= strchr(auth_type
+ 10, ' ')) != NULL
)
4397 auth_type
[0] = '\0';
4400 (attr
= ippFindAttribute(con
->request
, "attributes-natural-language",
4401 IPP_TAG_LANGUAGE
)) != NULL
)
4403 switch (strlen(attr
->values
[0].string
.text
))
4407 * This is an unknown or badly formatted language code; use
4408 * the POSIX locale...
4411 strcpy(lang
, "LANG=C");
4416 * Just the language code (ll)...
4419 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8",
4420 attr
->values
[0].string
.text
);
4425 * Language and country code (ll-cc)...
4428 snprintf(lang
, sizeof(lang
), "LANG=%c%c_%c%c.UTF8",
4429 attr
->values
[0].string
.text
[0],
4430 attr
->values
[0].string
.text
[1],
4431 toupper(attr
->values
[0].string
.text
[3] & 255),
4432 toupper(attr
->values
[0].string
.text
[4] & 255));
4436 else if (con
->language
)
4437 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8", con
->language
->language
);
4439 strcpy(lang
, "LANG=C");
4441 strcpy(remote_addr
, "REMOTE_ADDR=");
4442 httpAddrString(con
->http
.hostaddr
, remote_addr
+ 12,
4443 sizeof(remote_addr
) - 12);
4445 snprintf(remote_host
, sizeof(remote_host
), "REMOTE_HOST=%s",
4446 con
->http
.hostname
);
4448 snprintf(script_name
, sizeof(script_name
), "SCRIPT_NAME=%s", con
->uri
);
4449 if ((uriptr
= strchr(script_name
, '?')) != NULL
)
4452 snprintf(script_filename
, sizeof(script_filename
), "SCRIPT_FILENAME=%s%s",
4453 DocumentRoot
, script_name
+ 12);
4455 sprintf(server_port
, "SERVER_PORT=%d", con
->serverport
);
4457 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
4460 envc
= cupsdLoadEnv(envp
, (int)(sizeof(envp
) / sizeof(envp
[0])));
4463 envp
[envc
++] = auth_type
;
4465 envp
[envc
++] = lang
;
4466 envp
[envc
++] = "REDIRECT_STATUS=1";
4467 envp
[envc
++] = "GATEWAY_INTERFACE=CGI/1.1";
4468 envp
[envc
++] = server_name
;
4469 envp
[envc
++] = server_port
;
4470 envp
[envc
++] = remote_addr
;
4471 envp
[envc
++] = remote_host
;
4472 envp
[envc
++] = script_name
;
4473 envp
[envc
++] = script_filename
;
4476 envp
[envc
++] = path_info
;
4478 if (con
->username
[0])
4480 snprintf(remote_user
, sizeof(remote_user
), "REMOTE_USER=%s", con
->username
);
4482 envp
[envc
++] = remote_user
;
4485 * Save Kerberos credentials, if any...
4489 if (con
->gss_have_creds
)
4491 # if !defined(HAVE_KRB5_CC_NEW_UNIQUE) && !defined(HAVE_HEIMDAL)
4492 cupsdLogMessage(CUPSD_LOG_INFO
,
4493 "Sorry, your version of Kerberos does not support "
4494 "delegated credentials!");
4497 krb5_error_code error
; /* Kerberos error code */
4498 OM_uint32 major_status
, /* Major status code */
4499 minor_status
; /* Minor status code */
4500 krb5_principal principal
; /* Kerberos principal */
4505 * If the weak-linked GSSAPI/Kerberos library is not present, don't try
4509 if (krb5_init_context
!= NULL
)
4511 # endif /* __APPLE__ */
4514 * We MUST create a file-based cache because memory-based caches are
4515 * only valid for the current process/address space.
4517 * Due to various bugs/features in different versions of Kerberos, we
4518 * need either the krb5_cc_new_unique() function or Heimdal's version
4519 * of krb5_cc_gen_new() to create a new FILE: credential cache that
4520 * can be passed to the backend. These functions create a temporary
4521 * file (typically in /tmp) containing the cached credentials, which
4522 * are removed when we have successfully printed a job.
4525 # ifdef HAVE_KRB5_CC_NEW_UNIQUE
4526 if ((error
= krb5_cc_new_unique(KerberosContext
, "FILE", NULL
,
4528 # else /* HAVE_HEIMDAL */
4529 if ((error
= krb5_cc_gen_new(KerberosContext
, &krb5_fcc_ops
,
4531 # endif /* HAVE_KRB5_CC_NEW_UNIQUE */
4533 cupsdLogMessage(CUPSD_LOG_ERROR
,
4534 "Unable to create new credentials cache (%d/%s)",
4535 error
, strerror(errno
));
4538 else if ((error
= krb5_parse_name(KerberosContext
, con
->username
,
4541 cupsdLogMessage(CUPSD_LOG_ERROR
,
4542 "Unable to parse kerberos username (%d/%s)", error
,
4544 krb5_cc_destroy(KerberosContext
, ccache
);
4547 else if ((error
= krb5_cc_initialize(KerberosContext
, ccache
,
4550 cupsdLogMessage(CUPSD_LOG_ERROR
,
4551 "Unable to initialize credentials cache (%d/%s)", error
,
4553 krb5_cc_destroy(KerberosContext
, ccache
);
4554 krb5_free_principal(KerberosContext
, principal
);
4559 krb5_free_principal(KerberosContext
, principal
);
4562 * Copy the user's credentials to the new cache file...
4565 major_status
= gss_krb5_copy_ccache(&minor_status
,
4566 con
->gss_delegated_cred
, ccache
);
4568 if (GSS_ERROR(major_status
))
4570 cupsdLogGSSMessage(CUPSD_LOG_ERROR
, major_status
, minor_status
,
4571 "Unable to import client credentials cache");
4572 krb5_cc_destroy(KerberosContext
, ccache
);
4578 * Add the KRB5CCNAME environment variable to the job so that the
4579 * backend can use the credentials when printing.
4582 snprintf(krb5ccname
, sizeof(krb5ccname
), "KRB5CCNAME=FILE:%s",
4583 krb5_cc_get_name(KerberosContext
, ccache
));
4584 envp
[envc
++] = krb5ccname
;
4587 chown(krb5_cc_get_name(KerberosContext
, ccache
), User
, Group
);
4592 # endif /* __APPLE__ */
4593 # endif /* HAVE_KRB5_CC_NEW_UNIQUE || HAVE_HEIMDAL */
4595 #endif /* HAVE_GSSAPI */
4599 if (con
->http
.version
== HTTP_1_1
)
4600 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.1";
4601 else if (con
->http
.version
== HTTP_1_0
)
4602 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.0";
4604 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/0.9";
4606 if (con
->http
.cookie
)
4608 snprintf(http_cookie
, sizeof(http_cookie
), "HTTP_COOKIE=%s",
4610 envp
[envc
++] = http_cookie
;
4613 if (con
->http
.fields
[HTTP_FIELD_USER_AGENT
][0])
4615 snprintf(http_user_agent
, sizeof(http_user_agent
), "HTTP_USER_AGENT=%s",
4616 con
->http
.fields
[HTTP_FIELD_USER_AGENT
]);
4617 envp
[envc
++] = http_user_agent
;
4620 if (con
->http
.fields
[HTTP_FIELD_REFERER
][0])
4622 snprintf(http_referer
, sizeof(http_referer
), "HTTP_REFERER=%s",
4623 con
->http
.fields
[HTTP_FIELD_REFERER
]);
4624 envp
[envc
++] = http_referer
;
4627 if (con
->operation
== HTTP_GET
)
4629 envp
[envc
++] = "REQUEST_METHOD=GET";
4631 if (con
->query_string
)
4634 * Add GET form variables after ?...
4637 envp
[envc
++] = con
->query_string
;
4642 sprintf(content_length
, "CONTENT_LENGTH=" CUPS_LLFMT
,
4643 CUPS_LLCAST con
->bytes
);
4644 snprintf(content_type
, sizeof(content_type
), "CONTENT_TYPE=%s",
4645 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
4647 envp
[envc
++] = "REQUEST_METHOD=POST";
4648 envp
[envc
++] = content_length
;
4649 envp
[envc
++] = content_type
;
4653 * Tell the CGI if we are using encryption...
4657 envp
[envc
++] = "HTTPS=ON";
4660 * Terminate the environment array...
4665 if (LogLevel
== CUPSD_LOG_DEBUG2
)
4667 for (i
= 0; i
< argc
; i
++)
4668 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4669 "pipe_command: argv[%d] = \"%s\"", i
, argv
[i
]);
4670 for (i
= 0; i
< envc
; i
++)
4671 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4672 "pipe_command: envp[%d] = \"%s\"", i
, envp
[i
]);
4676 * Create a pipe for the output...
4679 if (cupsdOpenPipe(fds
))
4681 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to create pipes for CGI %s - %s",
4682 argv
[0], strerror(errno
));
4687 * Then execute the command...
4690 if (cupsdStartProcess(command
, argv
, envp
, infile
, fds
[1], CGIPipes
[1],
4691 -1, -1, root
, DefaultProfile
, &pid
) < 0)
4694 * Error - can't fork!
4697 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to fork for CGI %s - %s", argv
[0],
4700 cupsdClosePipe(fds
);
4706 * Fork successful - return the PID...
4709 if (con
->username
[0])
4711 cupsdAddCert(pid
, con
->username
, ccache
);
4713 cupsdAddCert(pid
, con
->username
, NULL
);
4714 #endif /* HAVE_GSSAPI */
4716 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[CGI] %s started - PID = %d",
4728 * 'write_file()' - Send a file via HTTP.
4731 static int /* O - 0 on failure, 1 on success */
4732 write_file(cupsd_client_t
*con
, /* I - Client connection */
4733 http_status_t code
, /* I - HTTP status */
4734 char *filename
, /* I - Filename */
4735 char *type
, /* I - File type */
4736 struct stat
*filestats
) /* O - File information */
4738 con
->file
= open(filename
, O_RDONLY
);
4740 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "write_file: %d file=%d", con
->http
.fd
,
4746 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
4750 if (!cupsdSendHeader(con
, code
, type
, CUPSD_AUTH_NONE
))
4753 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
4754 httpGetDateString(filestats
->st_mtime
)) < 0)
4756 if (httpPrintf(HTTP(con
), "Content-Length: " CUPS_LLFMT
"\r\n",
4757 CUPS_LLCAST filestats
->st_size
) < 0)
4759 if (httpPrintf(HTTP(con
), "\r\n") < 0)
4762 if (cupsdFlushHeader(con
) < 0)
4765 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
4766 con
->http
.data_remaining
= filestats
->st_size
;
4768 if (con
->http
.data_remaining
<= INT_MAX
)
4769 con
->http
._data_remaining
= con
->http
.data_remaining
;
4771 con
->http
._data_remaining
= INT_MAX
;
4773 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
,
4774 (cupsd_selfunc_t
)cupsdWriteClient
, con
);
4781 * 'write_pipe()' - Flag that data is available on the CGI pipe.
4785 write_pipe(cupsd_client_t
*con
) /* I - Client connection */
4787 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "write_pipe: CGI output on fd %d...",
4790 con
->file_ready
= 1;
4792 cupsdRemoveSelect(con
->file
);
4793 cupsdAddSelect(con
->http
.fd
, NULL
, (cupsd_selfunc_t
)cupsdWriteClient
, con
);
4798 * End of "$Id: client.c 6999 2007-09-28 19:46:53Z mike $".