2 * "$Id: client.c 6504 2007-05-02 00:14:56Z mike $"
4 * Client routines for the Common UNIX Printing System (CUPS) scheduler.
6 * Copyright 1997-2007 by Easy Software Products, all rights reserved.
8 * This file contains Kerberos support code, copyright 2006 by
11 * These coded instructions, statements, and computer programs are the
12 * property of Easy Software Products and are protected by Federal
13 * copyright law. Distribution and use rights are outlined in the file
14 * "LICENSE.txt" which should have been included with this file. If this
15 * file is missing or damaged please contact Easy Software Products
18 * Attn: CUPS Licensing Information
19 * Easy Software Products
20 * 44141 Airport View Drive, Suite 204
21 * Hollywood, Maryland 20636 USA
23 * Voice: (301) 373-9600
24 * EMail: cups-info@cups.org
25 * WWW: http://www.cups.org
29 * cupsdAcceptClient() - Accept a new client.
30 * cupsdCloseAllClients() - Close all remote clients immediately.
31 * cupsdCloseClient() - Close a remote client.
32 * cupsdFlushHeader() - Flush the header fields to the client.
33 * cupsdReadClient() - Read data from a client.
34 * cupsdSendCommand() - Send output from a command via HTTP.
35 * cupsdSendError() - Send an error message via HTTP.
36 * cupsdSendHeader() - Send an HTTP request.
37 * cupsdUpdateCGI() - Read status messages from CGI scripts and programs.
38 * cupsdWriteClient() - Write data to a client as needed.
39 * check_if_modified() - Decode an "If-Modified-Since" line.
40 * encrypt_client() - Enable encryption for the client...
41 * get_cdsa_certificate() - Convert a keychain name into the CFArrayRef
42 * required by SSLSetCertificate.
43 * get_file() - Get a filename and state info.
44 * install_conf_file() - Install a configuration file.
45 * is_cgi() - Is the resource a CGI script/program?
46 * is_path_absolute() - Is a path absolute and free of relative elements.
47 * make_certificate() - Make a self-signed SSL/TLS certificate.
48 * pipe_command() - Pipe the output of a command to the remote client.
49 * write_file() - Send a file via HTTP.
50 * write_pipe() - Flag that data is available on the CGI pipe.
54 * Include necessary headers...
57 #include <cups/http-private.h>
61 # include <Security/Security.h>
62 # ifdef HAVE_SECIDENTITYSEARCHPRIV_H
63 # include <Security/SecIdentitySearchPriv.h>
64 # else /* Declare prototype for function in that header... */
65 extern OSStatus
SecIdentitySearchCreateWithPolicy(SecPolicyRef policy
,
66 CFStringRef idString
, CSSM_KEYUSE keyUsage
,
67 CFTypeRef keychainOrArray
,
68 Boolean returnOnlyValidIdentities
,
69 SecIdentitySearchRef
* searchRef
);
70 # endif /* HAVE_SECIDENTITYSEARCHPRIV_H */
71 # ifdef HAVE_SECPOLICYPRIV_H
72 # include <Security/SecPolicyPriv.h>
73 # else /* Declare prototype for function in that header... */
74 extern OSStatus
SecPolicySetValue(SecPolicyRef policyRef
,
75 const CSSM_DATA
*value
);
76 # endif /* HAVE_SECPOLICYPRIV_H */
77 # ifdef HAVE_SECBASEPRIV_H
78 # include <Security/SecBasePriv.h>
79 # else /* Declare prototype for function in that header... */
80 extern const char *cssmErrorString(int error
);
81 # endif /* HAVE_SECBASEPRIV_H */
82 #endif /* HAVE_CDSASSL */
85 # include <gnutls/x509.h>
86 #endif /* HAVE_GNUTLS */
93 static int check_if_modified(cupsd_client_t
*con
,
94 struct stat
*filestats
);
96 static int encrypt_client(cupsd_client_t
*con
);
99 static CFArrayRef
get_cdsa_certificate(cupsd_client_t
*con
);
100 #endif /* HAVE_CDSASSL */
101 static char *get_file(cupsd_client_t
*con
, struct stat
*filestats
,
102 char *filename
, int len
);
103 static http_status_t
install_conf_file(cupsd_client_t
*con
);
104 static int is_cgi(cupsd_client_t
*con
, const char *filename
,
105 struct stat
*filestats
, mime_type_t
*type
);
106 static int is_path_absolute(const char *path
);
108 static int make_certificate(cupsd_client_t
*con
);
109 #endif /* HAVE_SSL */
110 static int pipe_command(cupsd_client_t
*con
, int infile
, int *outfile
,
111 char *command
, char *options
, int root
);
112 static int write_file(cupsd_client_t
*con
, http_status_t code
,
113 char *filename
, char *type
,
114 struct stat
*filestats
);
115 static void write_pipe(cupsd_client_t
*con
);
119 * 'cupsdAcceptClient()' - Accept a new client.
123 cupsdAcceptClient(cupsd_listener_t
*lis
)/* I - Listener socket */
125 int count
; /* Count of connections on a host */
126 int val
; /* Parameter value */
127 cupsd_client_t
*con
, /* New client pointer */
128 *tempcon
; /* Temporary client pointer */
129 http_addrlist_t
*addrlist
, /* List of adddresses for host */
130 *addr
; /* Current address */
131 socklen_t addrlen
; /* Length of address */
132 char *hostname
; /* Hostname for address */
133 http_addr_t temp
; /* Temporary address variable */
134 static time_t last_dos
= 0; /* Time of last DoS attack */
137 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
138 "cupsdAcceptClient(lis=%p) %d Clients = %d",
139 lis
, lis
->fd
, cupsArrayCount(Clients
));
142 * Make sure we don't have a full set of clients already...
145 if (cupsArrayCount(Clients
) == MaxClients
)
149 * Get a pointer to the next available client...
153 Clients
= cupsArrayNew(NULL
, NULL
);
158 con
= calloc(1, sizeof(cupsd_client_t
));
160 con
->http
.activity
= time(NULL
);
162 con
->http
.hostaddr
= &(con
->clientaddr
);
165 * Accept the client and get the remote address...
168 addrlen
= sizeof(http_addr_t
);
170 if ((con
->http
.fd
= accept(lis
->fd
, (struct sockaddr
*)con
->http
.hostaddr
,
173 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to accept client connection - %s.",
180 if (lis
->address
.addr
.sa_family
== AF_INET6
)
183 * Save the connected port number...
186 con
->http
.hostaddr
->ipv6
.sin6_port
= lis
->address
.ipv6
.sin6_port
;
189 * Convert IPv4 over IPv6 addresses (::ffff:n.n.n.n) to IPv4 forms we
190 * can more easily use...
193 if (con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[0] == 0 &&
194 con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[1] == 0 &&
195 ntohl(con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[2]) == 0xffff)
196 con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[2] = 0;
199 #endif /* AF_INET6 */
200 if (lis
->address
.addr
.sa_family
== AF_INET
)
201 con
->http
.hostaddr
->ipv4
.sin_port
= lis
->address
.ipv4
.sin_port
;
204 * Check the number of clients on the same address...
207 for (count
= 0, tempcon
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
209 tempcon
= (cupsd_client_t
*)cupsArrayNext(Clients
))
210 if (httpAddrEqual(tempcon
->http
.hostaddr
, con
->http
.hostaddr
))
213 if (count
>= MaxClientsPerHost
)
217 if (count
>= MaxClientsPerHost
)
219 if ((time(NULL
) - last_dos
) >= 60)
221 last_dos
= time(NULL
);
222 cupsdLogMessage(CUPSD_LOG_WARN
,
223 "Possible DoS attack - more than %d clients connecting "
225 MaxClientsPerHost
, tempcon
->http
.hostname
);
229 closesocket(con
->http
.fd
);
239 * Get the hostname or format the IP address as needed...
242 if (httpAddrLocalhost(con
->http
.hostaddr
))
245 * Map accesses from the loopback interface to "localhost"...
248 strlcpy(con
->http
.hostname
, "localhost", sizeof(con
->http
.hostname
));
249 hostname
= con
->http
.hostname
;
254 * Map accesses from the same host to the server name.
257 for (addr
= ServerAddrs
; addr
; addr
= addr
->next
)
258 if (httpAddrEqual(con
->http
.hostaddr
, &(addr
->addr
)))
263 strlcpy(con
->http
.hostname
, ServerName
, sizeof(con
->http
.hostname
));
264 hostname
= con
->http
.hostname
;
266 else if (HostNameLookups
)
267 hostname
= httpAddrLookup(con
->http
.hostaddr
, con
->http
.hostname
,
268 sizeof(con
->http
.hostname
));
272 httpAddrString(con
->http
.hostaddr
, con
->http
.hostname
,
273 sizeof(con
->http
.hostname
));
277 if (hostname
== NULL
&& HostNameLookups
== 2)
280 * Can't have an unresolved IP address with double-lookups enabled...
283 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
284 "cupsdAcceptClient: Closing connection %d...",
288 closesocket(con
->http
.fd
);
293 cupsdLogMessage(CUPSD_LOG_WARN
,
294 "Name lookup failed - connection from %s closed!",
301 if (HostNameLookups
== 2)
304 * Do double lookups as needed...
307 if ((addrlist
= httpAddrGetList(con
->http
.hostname
, AF_UNSPEC
, NULL
)) != NULL
)
310 * See if the hostname maps to the same IP address...
313 for (addr
= addrlist
; addr
; addr
= addr
->next
)
314 if (httpAddrEqual(con
->http
.hostaddr
, &(addr
->addr
)))
320 httpAddrFreeList(addrlist
);
325 * Can't have a hostname that doesn't resolve to the same IP address
326 * with double-lookups enabled...
329 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
330 "cupsdAcceptClient: Closing connection %d...",
334 closesocket(con
->http
.fd
);
339 cupsdLogMessage(CUPSD_LOG_WARN
,
340 "IP lookup failed - connection from %s closed!",
348 if (con
->http
.hostaddr
->addr
.sa_family
== AF_INET6
)
349 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdAcceptClient: %d from %s:%d (IPv6)",
350 con
->http
.fd
, con
->http
.hostname
,
351 ntohs(con
->http
.hostaddr
->ipv6
.sin6_port
));
353 #endif /* AF_INET6 */
355 if (con
->http
.hostaddr
->addr
.sa_family
== AF_LOCAL
)
356 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdAcceptClient: %d from %s (Domain)",
357 con
->http
.fd
, con
->http
.hostname
);
359 #endif /* AF_LOCAL */
360 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdAcceptClient: %d from %s:%d (IPv4)",
361 con
->http
.fd
, con
->http
.hostname
,
362 ntohs(con
->http
.hostaddr
->ipv4
.sin_port
));
365 * Get the local address the client connected to...
368 addrlen
= sizeof(temp
);
369 if (getsockname(con
->http
.fd
, (struct sockaddr
*)&temp
, &addrlen
))
371 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to get local address - %s",
374 strcpy(con
->servername
, "localhost");
375 con
->serverport
= LocalPort
;
380 if (temp
.addr
.sa_family
== AF_INET6
)
382 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
383 con
->serverport
= ntohs(lis
->address
.ipv6
.sin6_port
);
386 #endif /* AF_INET6 */
387 if (temp
.addr
.sa_family
== AF_INET
)
389 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
390 con
->serverport
= ntohs(lis
->address
.ipv4
.sin_port
);
394 strcpy(con
->servername
, "localhost");
395 con
->serverport
= LocalPort
;
399 cupsArrayAdd(Clients
, con
);
401 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
402 "cupsdAcceptClient: %d connected to server on %s:%d",
403 con
->http
.fd
, con
->servername
, con
->serverport
);
406 * Using TCP_NODELAY improves responsiveness, especially on systems
407 * with a slow loopback interface... Since we write large buffers
408 * when sending print files and requests, there shouldn't be any
409 * performance penalty for this...
413 setsockopt(con
->http
.fd
, IPPROTO_TCP
, TCP_NODELAY
, &val
, sizeof(val
));
416 * Close this file on all execs...
419 fcntl(con
->http
.fd
, F_SETFD
, fcntl(con
->http
.fd
, F_GETFD
) | FD_CLOEXEC
);
422 * Add the socket to the select() input mask.
425 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
428 * Temporarily suspend accept()'s until we lose a client...
431 if (cupsArrayCount(Clients
) == MaxClients
)
432 cupsdPauseListening();
436 * See if we are connecting on a secure port...
439 if (lis
->encryption
== HTTP_ENCRYPT_ALWAYS
)
442 * https connection; go secure...
445 con
->http
.encryption
= HTTP_ENCRYPT_ALWAYS
;
447 if (!encrypt_client(con
))
448 cupsdCloseClient(con
);
452 #endif /* HAVE_SSL */
457 * 'cupsdCloseAllClients()' - Close all remote clients immediately.
461 cupsdCloseAllClients(void)
463 cupsd_client_t
*con
; /* Current client */
466 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
468 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
469 cupsdCloseClient(con
);
474 * 'cupsdCloseClient()' - Close a remote client.
477 int /* O - 1 if partial close, 0 if fully closed */
478 cupsdCloseClient(cupsd_client_t
*con
) /* I - Client to close */
480 int partial
; /* Do partial close for SSL? */
482 SSL_CTX
*context
; /* Context for encryption */
483 SSL
*conn
; /* Connection for encryption */
484 unsigned long error
; /* Error code */
485 #elif defined(HAVE_GNUTLS)
486 http_tls_t
*conn
; /* TLS connection information */
487 int error
; /* Error code */
488 gnutls_certificate_server_credentials
*credentials
;
489 /* TLS credentials */
490 # elif defined(HAVE_CDSASSL)
491 http_tls_t
*conn
; /* CDSA connection information */
492 #endif /* HAVE_LIBSSL */
495 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdCloseClient: %d", con
->http
.fd
);
498 * Flush pending writes before closing...
501 httpFlushWrite(HTTP(con
));
507 * Shutdown encryption as needed...
515 conn
= (SSL
*)(con
->http
.tls
);
516 context
= SSL_get_SSL_CTX(conn
);
518 switch (SSL_shutdown(conn
))
521 cupsdLogMessage(CUPSD_LOG_INFO
,
522 "cupsdCloseClient: SSL shutdown successful!");
525 cupsdLogMessage(CUPSD_LOG_ERROR
,
526 "cupsdCloseClient: Fatal error during SSL shutdown!");
528 while ((error
= ERR_get_error()) != 0)
529 cupsdLogMessage(CUPSD_LOG_ERROR
, "cupsdCloseClient: %s",
530 ERR_error_string(error
, NULL
));
534 SSL_CTX_free(context
);
537 # elif defined(HAVE_GNUTLS)
538 conn
= (http_tls_t
*)(con
->http
.tls
);
539 credentials
= (gnutls_certificate_server_credentials
*)(conn
->credentials
);
541 error
= gnutls_bye(conn
->session
, GNUTLS_SHUT_WR
);
544 case GNUTLS_E_SUCCESS
:
545 cupsdLogMessage(CUPSD_LOG_INFO
,
546 "cupsdCloseClient: SSL shutdown successful!");
549 cupsdLogMessage(CUPSD_LOG_ERROR
,
550 "cupsdCloseClient: %s", gnutls_strerror(error
));
554 gnutls_deinit(conn
->session
);
555 gnutls_certificate_free_credentials(*credentials
);
559 # elif defined(HAVE_CDSASSL)
560 conn
= (http_tls_t
*)(con
->http
.tls
);
562 while (SSLClose(conn
->session
) == errSSLWouldBlock
)
565 SSLDisposeContext(conn
->session
);
567 if (conn
->certsArray
)
568 CFRelease(conn
->certsArray
);
571 # endif /* HAVE_LIBSSL */
573 con
->http
.tls
= NULL
;
575 #endif /* HAVE_SSL */
577 if (con
->pipe_pid
!= 0)
580 * Stop any CGI process...
583 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
584 "cupsdCloseClient: %d Killing process ID %d...",
585 con
->http
.fd
, con
->pipe_pid
);
586 cupsdEndProcess(con
->pipe_pid
, 1);
592 cupsdRemoveSelect(con
->file
);
594 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
595 "cupsdCloseClient: %d Closing data file %d.",
596 con
->http
.fd
, con
->file
);
603 * Close the socket and clear the file from the input set for select()...
606 if (con
->http
.fd
> 0)
611 * Only do a partial close so that the encrypted client gets everything.
614 shutdown(con
->http
.fd
, 0);
615 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
620 * Shut the socket down fully...
623 cupsdRemoveSelect(con
->http
.fd
);
635 if (con
->http
.input_set
)
636 free(con
->http
.input_set
);
638 httpClearCookie(HTTP(con
));
640 cupsdClearString(&con
->filename
);
641 cupsdClearString(&con
->command
);
642 cupsdClearString(&con
->options
);
643 cupsdClearString(&con
->query_string
);
647 ippDelete(con
->request
);
653 ippDelete(con
->response
);
654 con
->response
= NULL
;
659 cupsLangFree(con
->language
);
660 con
->language
= NULL
;
663 #ifdef HAVE_AUTHORIZATION_H
666 AuthorizationFree(con
->authref
, kAuthorizationFlagDefaults
);
669 #endif /* HAVE_AUTHORIZATION_H */
672 * Re-enable new client connections if we are going back under the
676 if (cupsArrayCount(Clients
) == MaxClients
)
677 cupsdResumeListening();
680 * Compact the list of clients as necessary...
683 cupsArrayRemove(Clients
, con
);
693 * 'cupsdFlushHeader()' - Flush the header fields to the client.
696 int /* I - Bytes written or -1 on error */
697 cupsdFlushHeader(cupsd_client_t
*con
) /* I - Client to flush to */
699 int bytes
= httpFlushWrite(HTTP(con
));
701 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
708 * 'cupsdReadClient()' - Read data from a client.
712 cupsdReadClient(cupsd_client_t
*con
) /* I - Client to read from */
714 char line
[32768], /* Line from client... */
715 operation
[64], /* Operation code from socket */
716 version
[64], /* HTTP version number string */
717 locale
[64], /* Locale */
718 *ptr
; /* Pointer into strings */
719 int major
, minor
; /* HTTP version numbers */
720 http_status_t status
; /* Transfer status */
721 ipp_state_t ipp_state
; /* State of IPP transfer */
722 int bytes
; /* Number of bytes to POST */
723 char *filename
; /* Name of file for GET/HEAD */
724 char buf
[1024]; /* Buffer for real filename */
725 struct stat filestats
; /* File information */
726 mime_type_t
*type
; /* MIME type of file */
727 cupsd_printer_t
*p
; /* Printer */
728 static unsigned request_id
= 0; /* Request ID for temp files */
731 status
= HTTP_CONTINUE
;
733 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
734 "cupsdReadClient: %d, used=%d, file=%d state=%d",
735 con
->http
.fd
, con
->http
.used
, con
->file
, con
->http
.state
);
739 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdReadClient: http error seen...");
740 cupsdCloseClient(con
);
748 * Automatically check for a SSL/TLS handshake...
753 if (recv(con
->http
.fd
, buf
, 1, MSG_PEEK
) == 1 &&
754 (!buf
[0] || !strchr("DGHOPT", buf
[0])))
757 * Encrypt this connection...
760 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
761 "cupsdReadClient: Saw first byte %02X, auto-negotiating SSL/TLS session...",
764 if (!encrypt_client(con
))
765 cupsdCloseClient(con
);
770 #endif /* HAVE_SSL */
772 switch (con
->http
.state
)
776 * See if we've received a request line...
779 if (httpGets(line
, sizeof(line
) - 1, HTTP(con
)) == NULL
)
781 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
782 "cupsdReadClient: httpGets returned EOF...");
783 cupsdCloseClient(con
);
788 * Ignore blank request lines...
795 * Clear other state variables...
798 httpClearFields(HTTP(con
));
800 con
->http
.activity
= time(NULL
);
801 con
->http
.version
= HTTP_1_0
;
802 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
803 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
804 con
->http
.data_remaining
= 0;
805 con
->http
._data_remaining
= 0;
806 con
->operation
= HTTP_WAITING
;
811 con
->username
[0] = '\0';
812 con
->password
[0] = '\0';
815 cupsdClearString(&con
->command
);
816 cupsdClearString(&con
->options
);
817 cupsdClearString(&con
->query_string
);
821 ippDelete(con
->request
);
827 ippDelete(con
->response
);
828 con
->response
= NULL
;
833 cupsLangFree(con
->language
);
834 con
->language
= NULL
;
838 * Grab the request line...
841 switch (sscanf(line
, "%63s%1023s%63s", operation
, con
->uri
, version
))
844 cupsdLogMessage(CUPSD_LOG_ERROR
,
845 "Bad request line \"%s\" from %s!", line
,
847 cupsdSendError(con
, HTTP_BAD_REQUEST
, AUTH_NONE
);
848 cupsdCloseClient(con
);
851 con
->http
.version
= HTTP_0_9
;
854 if (sscanf(version
, "HTTP/%d.%d", &major
, &minor
) != 2)
856 cupsdLogMessage(CUPSD_LOG_ERROR
,
857 "Bad request line \"%s\" from %s!", line
,
859 cupsdSendError(con
, HTTP_BAD_REQUEST
, AUTH_NONE
);
860 cupsdCloseClient(con
);
866 con
->http
.version
= (http_version_t
)(major
* 100 + minor
);
867 if (con
->http
.version
== HTTP_1_1
&& KeepAlive
)
868 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
870 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
874 cupsdSendError(con
, HTTP_NOT_SUPPORTED
, AUTH_NONE
);
875 cupsdCloseClient(con
);
882 * Handle full URLs in the request line...
885 if (strcmp(con
->uri
, "*"))
887 char method
[HTTP_MAX_URI
], /* Method/scheme */
888 userpass
[HTTP_MAX_URI
], /* Username:password */
889 hostname
[HTTP_MAX_URI
], /* Hostname */
890 resource
[HTTP_MAX_URI
]; /* Resource path */
891 int port
; /* Port number */
895 * Separate the URI into its components...
898 httpSeparateURI(HTTP_URI_CODING_MOST
, con
->uri
,
899 method
, sizeof(method
),
900 userpass
, sizeof(userpass
),
901 hostname
, sizeof(hostname
), &port
,
902 resource
, sizeof(resource
));
905 * Only allow URIs with the servername, localhost, or an IP
909 if (strcmp(method
, "file") &&
910 strcasecmp(hostname
, ServerName
) &&
911 strcasecmp(hostname
, "localhost") &&
912 !isdigit(hostname
[0]))
915 * Nope, we don't do proxies...
918 cupsdLogMessage(CUPSD_LOG_ERROR
, "Bad URI \"%s\" in request!",
920 cupsdSendError(con
, HTTP_METHOD_NOT_ALLOWED
, AUTH_NONE
);
921 cupsdCloseClient(con
);
926 * Copy the resource portion back into the URI; both resource and
927 * con->uri are HTTP_MAX_URI bytes in size...
930 strcpy(con
->uri
, resource
);
934 * Process the request...
937 if (!strcmp(operation
, "GET"))
938 con
->http
.state
= HTTP_GET
;
939 else if (!strcmp(operation
, "PUT"))
940 con
->http
.state
= HTTP_PUT
;
941 else if (!strcmp(operation
, "POST"))
942 con
->http
.state
= HTTP_POST
;
943 else if (!strcmp(operation
, "DELETE"))
944 con
->http
.state
= HTTP_DELETE
;
945 else if (!strcmp(operation
, "TRACE"))
946 con
->http
.state
= HTTP_TRACE
;
947 else if (!strcmp(operation
, "OPTIONS"))
948 con
->http
.state
= HTTP_OPTIONS
;
949 else if (!strcmp(operation
, "HEAD"))
950 con
->http
.state
= HTTP_HEAD
;
953 cupsdLogMessage(CUPSD_LOG_ERROR
, "Bad operation \"%s\"!", operation
);
954 cupsdSendError(con
, HTTP_BAD_REQUEST
, AUTH_NONE
);
955 cupsdCloseClient(con
);
959 con
->start
= time(NULL
);
960 con
->operation
= con
->http
.state
;
962 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdReadClient: %d %s %s HTTP/%d.%d",
963 con
->http
.fd
, operation
, con
->uri
,
964 con
->http
.version
/ 100, con
->http
.version
% 100);
966 con
->http
.status
= HTTP_OK
;
976 * Parse incoming parameters until the status changes...
979 while ((status
= httpUpdate(HTTP(con
))) == HTTP_CONTINUE
)
980 if (con
->http
.used
== 0 ||
981 !memchr(con
->http
.buffer
, '\n', con
->http
.used
))
984 if (status
!= HTTP_OK
&& status
!= HTTP_CONTINUE
)
986 cupsdSendError(con
, HTTP_BAD_REQUEST
, AUTH_NONE
);
987 cupsdCloseClient(con
);
993 break; /* Anti-compiler-warning-code */
997 * Handle new transfers...
1000 if (status
== HTTP_OK
)
1002 if (con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
][0])
1005 * Figure out the locale from the Accept-Language and Content-Type
1009 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ',')) != NULL
)
1012 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ';')) != NULL
)
1015 if ((ptr
= strstr(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
], "charset=")) != NULL
)
1018 * Combine language and charset, and trim any extra params in the
1022 snprintf(locale
, sizeof(locale
), "%s.%s",
1023 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ptr
+ 8);
1025 if ((ptr
= strchr(locale
, ',')) != NULL
)
1029 snprintf(locale
, sizeof(locale
), "%s.%s",
1030 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], DefaultCharset
);
1032 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1033 "cupsdReadClient: %d Browser asked for language \"%s\"...",
1034 con
->http
.fd
, locale
);
1036 con
->language
= cupsLangGet(locale
);
1039 con
->language
= cupsLangGet(DefaultLocale
);
1041 cupsdAuthorize(con
);
1043 if (!strncmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Keep-Alive", 10) &&
1045 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
1047 if (!con
->http
.fields
[HTTP_FIELD_HOST
][0] &&
1048 con
->http
.version
>= HTTP_1_1
)
1051 * HTTP/1.1 and higher require the "Host:" field...
1054 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, AUTH_NONE
))
1056 cupsdCloseClient(con
);
1060 else if (con
->operation
== HTTP_OPTIONS
)
1063 * Do OPTIONS command...
1066 if (con
->best
&& con
->best
->type
!= AUTH_NONE
)
1068 if (!cupsdSendHeader(con
, HTTP_UNAUTHORIZED
, NULL
, AUTH_NONE
))
1070 cupsdCloseClient(con
);
1075 if (!strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") &&
1076 con
->http
.tls
== NULL
)
1080 * Do encryption stuff...
1083 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
, AUTH_NONE
))
1085 cupsdCloseClient(con
);
1089 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1090 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1091 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1092 httpPrintf(HTTP(con
), "\r\n");
1094 if (cupsdFlushHeader(con
) < 0)
1096 cupsdCloseClient(con
);
1100 if (!encrypt_client(con
))
1102 cupsdCloseClient(con
);
1106 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, AUTH_NONE
))
1108 cupsdCloseClient(con
);
1111 #endif /* HAVE_SSL */
1114 if (!cupsdSendHeader(con
, HTTP_OK
, NULL
, AUTH_NONE
))
1116 cupsdCloseClient(con
);
1120 httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n");
1121 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1122 httpPrintf(HTTP(con
), "\r\n");
1124 if (cupsdFlushHeader(con
) < 0)
1126 cupsdCloseClient(con
);
1130 else if (!is_path_absolute(con
->uri
))
1133 * Protect against malicious users!
1136 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, AUTH_NONE
))
1138 cupsdCloseClient(con
);
1144 if (!strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") &&
1145 con
->http
.tls
== NULL
)
1149 * Do encryption stuff...
1152 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
, AUTH_NONE
))
1154 cupsdCloseClient(con
);
1158 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1159 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1160 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1161 httpPrintf(HTTP(con
), "\r\n");
1163 if (cupsdFlushHeader(con
) < 0)
1165 cupsdCloseClient(con
);
1169 if (!encrypt_client(con
))
1171 cupsdCloseClient(con
);
1175 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, AUTH_NONE
))
1177 cupsdCloseClient(con
);
1180 #endif /* HAVE_SSL */
1183 if ((status
= cupsdIsAuthorized(con
, NULL
)) != HTTP_OK
)
1185 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1186 "cupsdReadClient: Unauthorized request for %s...\n",
1188 cupsdSendError(con
, status
, AUTH_NONE
);
1189 cupsdCloseClient(con
);
1193 if (con
->http
.expect
&&
1194 (con
->operation
== HTTP_POST
|| con
->operation
== HTTP_PUT
))
1196 if (con
->http
.expect
== HTTP_CONTINUE
)
1199 * Send 100-continue header...
1202 if (!cupsdSendHeader(con
, HTTP_CONTINUE
, NULL
, AUTH_NONE
))
1204 cupsdCloseClient(con
);
1211 * Send 417-expectation-failed header...
1214 if (!cupsdSendHeader(con
, HTTP_EXPECTATION_FAILED
, NULL
, AUTH_NONE
))
1216 cupsdCloseClient(con
);
1220 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1221 httpPrintf(HTTP(con
), "\r\n");
1223 if (cupsdFlushHeader(con
) < 0)
1225 cupsdCloseClient(con
);
1231 switch (con
->http
.state
)
1233 case HTTP_GET_SEND
:
1234 if (!strncmp(con
->uri
, "/printers/", 10) &&
1235 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1238 * Send PPD file - get the real printer name since printer
1239 * names are not case sensitive but filenames can be...
1242 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1244 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1245 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1248 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, AUTH_NONE
))
1250 cupsdCloseClient(con
);
1258 if ((!strncmp(con
->uri
, "/admin", 6) &&
1259 strncmp(con
->uri
, "/admin/conf/", 12) &&
1260 strncmp(con
->uri
, "/admin/log/", 11)) ||
1261 !strncmp(con
->uri
, "/printers", 9) ||
1262 !strncmp(con
->uri
, "/classes", 8) ||
1263 !strncmp(con
->uri
, "/help", 5) ||
1264 !strncmp(con
->uri
, "/jobs", 5))
1267 * Send CGI output...
1270 if (!strncmp(con
->uri
, "/admin", 6))
1272 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1275 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1277 else if (!strncmp(con
->uri
, "/printers", 9))
1279 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1282 if (con
->uri
[9] && con
->uri
[10])
1283 cupsdSetString(&con
->options
, con
->uri
+ 9);
1285 cupsdSetString(&con
->options
, NULL
);
1287 else if (!strncmp(con
->uri
, "/classes", 8))
1289 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1292 if (con
->uri
[8] && con
->uri
[9])
1293 cupsdSetString(&con
->options
, con
->uri
+ 8);
1295 cupsdSetString(&con
->options
, NULL
);
1297 else if (!strncmp(con
->uri
, "/jobs", 5))
1299 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1302 if (con
->uri
[5] && con
->uri
[6])
1303 cupsdSetString(&con
->options
, con
->uri
+ 5);
1305 cupsdSetString(&con
->options
, NULL
);
1309 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1312 if (con
->uri
[5] && con
->uri
[6])
1313 cupsdSetString(&con
->options
, con
->uri
+ 5);
1315 cupsdSetString(&con
->options
, NULL
);
1318 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1320 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, AUTH_NONE
))
1322 cupsdCloseClient(con
);
1327 cupsdLogRequest(con
, HTTP_OK
);
1329 if (con
->http
.version
<= HTTP_1_0
)
1330 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1332 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1333 (strchr(con
->uri
+ 12, '/') ||
1334 strlen(con
->uri
) == 12)) ||
1335 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1336 (strchr(con
->uri
+ 11, '/') ||
1337 strlen(con
->uri
) == 11)))
1340 * GET can only be done to configuration files under
1344 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, AUTH_NONE
))
1346 cupsdCloseClient(con
);
1358 if ((filename
= get_file(con
, &filestats
, buf
,
1359 sizeof(buf
))) == NULL
)
1361 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, AUTH_NONE
))
1363 cupsdCloseClient(con
);
1370 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1372 if (is_cgi(con
, filename
, &filestats
, type
))
1375 * Note: con->command and con->options were set by
1379 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1381 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, AUTH_NONE
))
1383 cupsdCloseClient(con
);
1388 cupsdLogRequest(con
, HTTP_OK
);
1390 if (con
->http
.version
<= HTTP_1_0
)
1391 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1395 if (!check_if_modified(con
, &filestats
))
1397 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
, AUTH_NONE
))
1399 cupsdCloseClient(con
);
1406 strcpy(line
, "text/plain");
1408 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1410 if (!write_file(con
, HTTP_OK
, filename
, line
, &filestats
))
1412 cupsdCloseClient(con
);
1419 case HTTP_POST_RECV
:
1421 * See if the POST request includes a Content-Length field, and if
1422 * so check the length against any limits that are set...
1425 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "POST %s", con
->uri
);
1426 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "CONTENT_TYPE = %s",
1427 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
1429 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1430 MaxRequestSize
> 0 &&
1431 con
->http
.data_remaining
> MaxRequestSize
)
1434 * Request too large...
1437 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, AUTH_NONE
))
1439 cupsdCloseClient(con
);
1445 else if (con
->http
.data_remaining
< 0)
1448 * Negative content lengths are invalid!
1451 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, AUTH_NONE
))
1453 cupsdCloseClient(con
);
1461 * See what kind of POST request this is; for IPP requests the
1462 * content-type field will be "application/ipp"...
1465 if (!strcmp(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
],
1467 con
->request
= ippNew();
1468 else if ((!strncmp(con
->uri
, "/admin", 6) &&
1469 strncmp(con
->uri
, "/admin/conf/", 12) &&
1470 strncmp(con
->uri
, "/admin/log/", 11)) ||
1471 !strncmp(con
->uri
, "/printers", 9) ||
1472 !strncmp(con
->uri
, "/classes", 8) ||
1473 !strncmp(con
->uri
, "/help", 5) ||
1474 !strncmp(con
->uri
, "/jobs", 5))
1480 if (!strncmp(con
->uri
, "/admin", 6))
1482 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1485 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1487 else if (!strncmp(con
->uri
, "/printers", 9))
1489 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1492 if (con
->uri
[9] && con
->uri
[10])
1493 cupsdSetString(&con
->options
, con
->uri
+ 9);
1495 cupsdSetString(&con
->options
, NULL
);
1497 else if (!strncmp(con
->uri
, "/classes", 8))
1499 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1502 if (con
->uri
[8] && con
->uri
[9])
1503 cupsdSetString(&con
->options
, con
->uri
+ 8);
1505 cupsdSetString(&con
->options
, NULL
);
1507 else if (!strncmp(con
->uri
, "/jobs", 5))
1509 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1512 if (con
->uri
[5] && con
->uri
[6])
1513 cupsdSetString(&con
->options
, con
->uri
+ 5);
1515 cupsdSetString(&con
->options
, NULL
);
1519 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1522 if (con
->uri
[5] && con
->uri
[6])
1523 cupsdSetString(&con
->options
, con
->uri
+ 5);
1525 cupsdSetString(&con
->options
, NULL
);
1528 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1529 "cupsdReadClient: %d command=\"%s\", "
1531 con
->http
.fd
, con
->command
,
1532 con
->options
? con
->options
: "(null)");
1534 if (con
->http
.version
<= HTTP_1_0
)
1535 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1543 if ((filename
= get_file(con
, &filestats
, buf
,
1544 sizeof(buf
))) == NULL
)
1546 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, AUTH_NONE
))
1548 cupsdCloseClient(con
);
1555 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1557 if (!is_cgi(con
, filename
, &filestats
, type
))
1560 * Only POST to CGI's...
1563 if (!cupsdSendError(con
, HTTP_UNAUTHORIZED
, AUTH_NONE
))
1565 cupsdCloseClient(con
);
1572 case HTTP_PUT_RECV
:
1574 * Validate the resource name...
1577 if (strncmp(con
->uri
, "/admin/conf/", 12) ||
1578 strchr(con
->uri
+ 12, '/') ||
1579 strlen(con
->uri
) == 12)
1582 * PUT can only be done to configuration files under
1586 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, AUTH_NONE
))
1588 cupsdCloseClient(con
);
1596 * See if the PUT request includes a Content-Length field, and if
1597 * so check the length against any limits that are set...
1600 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "PUT %s", con
->uri
);
1601 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "CONTENT_TYPE = %s",
1602 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
1604 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1605 MaxRequestSize
> 0 &&
1606 con
->http
.data_remaining
> MaxRequestSize
)
1609 * Request too large...
1612 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, AUTH_NONE
))
1614 cupsdCloseClient(con
);
1620 else if (con
->http
.data_remaining
< 0)
1623 * Negative content lengths are invalid!
1626 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, AUTH_NONE
))
1628 cupsdCloseClient(con
);
1636 * Open a temporary file to hold the request...
1639 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
1641 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1643 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1644 "cupsdReadClient: %d REQUEST %s=%d", con
->http
.fd
,
1645 con
->filename
, con
->file
);
1649 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, AUTH_NONE
))
1651 cupsdCloseClient(con
);
1656 fchmod(con
->file
, 0640);
1657 fchown(con
->file
, RunUser
, Group
);
1658 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1663 cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, AUTH_NONE
);
1664 cupsdCloseClient(con
);
1668 if (!strncmp(con
->uri
, "/printers/", 10) &&
1669 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1672 * Send PPD file - get the real printer name since printer
1673 * names are not case sensitive but filenames can be...
1676 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1678 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1679 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1682 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, AUTH_NONE
))
1684 cupsdCloseClient(con
);
1692 if ((!strncmp(con
->uri
, "/admin", 6) &&
1693 strncmp(con
->uri
, "/admin/conf/", 12) &&
1694 strncmp(con
->uri
, "/admin/log/", 11)) ||
1695 !strncmp(con
->uri
, "/printers", 9) ||
1696 !strncmp(con
->uri
, "/classes", 8) ||
1697 !strncmp(con
->uri
, "/help", 5) ||
1698 !strncmp(con
->uri
, "/jobs", 5))
1704 if (!cupsdSendHeader(con
, HTTP_OK
, "text/html", AUTH_NONE
))
1706 cupsdCloseClient(con
);
1710 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1712 cupsdCloseClient(con
);
1716 if (cupsdFlushHeader(con
) < 0)
1718 cupsdCloseClient(con
);
1722 cupsdLogRequest(con
, HTTP_OK
);
1724 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1725 (strchr(con
->uri
+ 12, '/') ||
1726 strlen(con
->uri
) == 12)) ||
1727 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1728 (strchr(con
->uri
+ 11, '/') ||
1729 strlen(con
->uri
) == 11)))
1732 * HEAD can only be done to configuration files under
1736 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, AUTH_NONE
))
1738 cupsdCloseClient(con
);
1744 else if ((filename
= get_file(con
, &filestats
, buf
,
1745 sizeof(buf
))) == NULL
)
1747 if (!cupsdSendHeader(con
, HTTP_NOT_FOUND
, "text/html", AUTH_NONE
))
1749 cupsdCloseClient(con
);
1753 cupsdLogRequest(con
, HTTP_NOT_FOUND
);
1755 else if (!check_if_modified(con
, &filestats
))
1757 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
, AUTH_NONE
))
1759 cupsdCloseClient(con
);
1763 cupsdLogRequest(con
, HTTP_NOT_MODIFIED
);
1771 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1773 strcpy(line
, "text/plain");
1775 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1777 if (!cupsdSendHeader(con
, HTTP_OK
, line
, AUTH_NONE
))
1779 cupsdCloseClient(con
);
1783 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
1784 httpGetDateString(filestats
.st_mtime
)) < 0)
1786 cupsdCloseClient(con
);
1790 if (httpPrintf(HTTP(con
), "Content-Length: %lu\r\n",
1791 (unsigned long)filestats
.st_size
) < 0)
1793 cupsdCloseClient(con
);
1797 cupsdLogRequest(con
, HTTP_OK
);
1800 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1802 cupsdCloseClient(con
);
1806 if (cupsdFlushHeader(con
) < 0)
1808 cupsdCloseClient(con
);
1812 con
->http
.state
= HTTP_WAITING
;
1816 break; /* Anti-compiler-warning-code */
1822 * Handle any incoming data...
1825 switch (con
->http
.state
)
1827 case HTTP_PUT_RECV
:
1828 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1829 "cupsdReadClient: %d con->data_encoding=HTTP_ENCODE_%s, "
1830 "con->data_remaining=" CUPS_LLFMT
", con->file=%d",
1832 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
?
1833 "CHUNKED" : "LENGTH",
1834 CUPS_LLCAST con
->http
.data_remaining
, con
->file
);
1838 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
1840 cupsdCloseClient(con
);
1845 con
->bytes
+= bytes
;
1847 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1848 "cupsdReadClient: %d writing %d bytes to %d",
1849 con
->http
.fd
, bytes
, con
->file
);
1851 if (write(con
->file
, line
, bytes
) < bytes
)
1853 cupsdLogMessage(CUPSD_LOG_ERROR
,
1854 "cupsdReadClient: Unable to write %d bytes to %s: %s",
1855 bytes
, con
->filename
, strerror(errno
));
1857 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1858 "cupsdReadClient: Closing data file %d...",
1863 unlink(con
->filename
);
1864 cupsdClearString(&con
->filename
);
1866 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, AUTH_NONE
))
1868 cupsdCloseClient(con
);
1874 while (con
->http
.state
== HTTP_PUT_RECV
&& con
->http
.used
> 0);
1876 if (con
->http
.state
== HTTP_WAITING
)
1879 * End of file, see how big it is...
1882 fstat(con
->file
, &filestats
);
1884 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1885 "cupsdReadClient: %d Closing data file %d, size="
1887 con
->http
.fd
, con
->file
,
1888 CUPS_LLCAST filestats
.st_size
);
1893 if (filestats
.st_size
> MaxRequestSize
&&
1897 * Request is too big; remove it and send an error...
1900 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1901 "cupsdReadClient: %d Removing temp file %s",
1902 con
->http
.fd
, con
->filename
);
1903 unlink(con
->filename
);
1904 cupsdClearString(&con
->filename
);
1906 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, AUTH_NONE
))
1908 cupsdCloseClient(con
);
1914 * Install the configuration file...
1917 status
= install_conf_file(con
);
1920 * Return the status to the client...
1923 if (!cupsdSendError(con
, status
, AUTH_NONE
))
1925 cupsdCloseClient(con
);
1931 case HTTP_POST_RECV
:
1932 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1933 "cupsdReadClient: %d con->data_encoding=HTTP_ENCODE_"
1934 "%s, con->data_remaining=" CUPS_LLFMT
", con->file=%d",
1936 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
?
1937 "CHUNKED" : "LENGTH",
1938 CUPS_LLCAST con
->http
.data_remaining
, con
->file
);
1945 * Grab any request data from the connection...
1948 if ((ipp_state
= ippRead(&(con
->http
), con
->request
)) == IPP_ERROR
)
1950 cupsdLogMessage(CUPSD_LOG_ERROR
,
1951 "cupsdReadClient: %d IPP Read Error!",
1954 cupsdSendError(con
, HTTP_BAD_REQUEST
, AUTH_NONE
);
1955 cupsdCloseClient(con
);
1958 else if (ipp_state
!= IPP_DATA
)
1960 if (con
->http
.state
== HTTP_POST_SEND
)
1962 cupsdSendError(con
, HTTP_BAD_REQUEST
, AUTH_NONE
);
1963 cupsdCloseClient(con
);
1970 con
->bytes
+= ippLength(con
->request
);
1973 if (con
->file
< 0 && con
->http
.state
!= HTTP_POST_SEND
)
1976 * Create a file as needed for the request data...
1979 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
, request_id
++);
1980 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1982 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdReadClient: %d REQUEST %s=%d", con
->http
.fd
,
1983 con
->filename
, con
->file
);
1987 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, AUTH_NONE
))
1989 cupsdCloseClient(con
);
1994 fchmod(con
->file
, 0640);
1995 fchown(con
->file
, RunUser
, Group
);
1996 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1999 if (con
->http
.state
!= HTTP_POST_SEND
)
2001 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
2003 cupsdCloseClient(con
);
2008 con
->bytes
+= bytes
;
2010 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2011 "cupsdReadClient: %d writing %d bytes to %d",
2012 con
->http
.fd
, bytes
, con
->file
);
2014 if (write(con
->file
, line
, bytes
) < bytes
)
2016 cupsdLogMessage(CUPSD_LOG_ERROR
,
2017 "cupsdReadClient: Unable to write %d bytes to %s: %s",
2018 bytes
, con
->filename
, strerror(errno
));
2020 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2021 "cupsdReadClient: Closing file %d...",
2026 unlink(con
->filename
);
2027 cupsdClearString(&con
->filename
);
2029 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, AUTH_NONE
))
2031 cupsdCloseClient(con
);
2036 else if (con
->http
.state
== HTTP_POST_RECV
)
2038 else if (con
->http
.state
!= HTTP_POST_SEND
)
2040 cupsdCloseClient(con
);
2045 while (con
->http
.state
== HTTP_POST_RECV
&& con
->http
.used
> 0);
2047 if (con
->http
.state
== HTTP_POST_SEND
)
2051 fstat(con
->file
, &filestats
);
2053 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2054 "cupsdReadClient: %d Closing data file %d, "
2055 "size=" CUPS_LLFMT
".",
2056 con
->http
.fd
, con
->file
,
2057 CUPS_LLCAST filestats
.st_size
);
2062 if (filestats
.st_size
> MaxRequestSize
&&
2066 * Request is too big; remove it and send an error...
2069 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2070 "cupsdReadClient: %d Removing temp file %s",
2071 con
->http
.fd
, con
->filename
);
2072 unlink(con
->filename
);
2073 cupsdClearString(&con
->filename
);
2078 * Delete any IPP request data...
2081 ippDelete(con
->request
);
2082 con
->request
= NULL
;
2085 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, AUTH_NONE
))
2087 cupsdCloseClient(con
);
2094 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
2096 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, AUTH_NONE
))
2098 cupsdCloseClient(con
);
2103 cupsdLogRequest(con
, HTTP_OK
);
2109 cupsdProcessIPPRequest(con
);
2116 break; /* Anti-compiler-warning-code */
2119 if (!con
->http
.keep_alive
&& con
->http
.state
== HTTP_WAITING
)
2120 cupsdCloseClient(con
);
2125 * 'cupsdSendCommand()' - Send output from a command via HTTP.
2128 int /* O - 1 on success, 0 on failure */
2130 cupsd_client_t
*con
, /* I - Client connection */
2131 char *command
, /* I - Command to run */
2132 char *options
, /* I - Command-line options */
2133 int root
) /* I - Run as root? */
2135 int fd
; /* Standard input file descriptor */
2140 fd
= open(con
->filename
, O_RDONLY
);
2144 cupsdLogMessage(CUPSD_LOG_ERROR
,
2145 "cupsdSendCommand: %d Unable to open \"%s\" for reading: %s",
2146 con
->http
.fd
, con
->filename
? con
->filename
: "/dev/null",
2151 fcntl(fd
, F_SETFD
, fcntl(fd
, F_GETFD
) | FD_CLOEXEC
);
2156 con
->pipe_pid
= pipe_command(con
, fd
, &(con
->file
), command
, options
, root
);
2161 cupsdLogMessage(CUPSD_LOG_INFO
, "Started \"%s\" (pid=%d)", command
,
2164 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendCommand: %d file=%d",
2165 con
->http
.fd
, con
->file
);
2167 if (con
->pipe_pid
== 0)
2170 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2172 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2174 con
->sent_header
= 0;
2175 con
->file_ready
= 0;
2176 con
->got_fields
= 0;
2184 * 'cupsdSendError()' - Send an error message via HTTP.
2187 int /* O - 1 if successful, 0 otherwise */
2188 cupsdSendError(cupsd_client_t
*con
, /* I - Connection */
2189 http_status_t code
, /* I - Error code */
2190 int auth_type
)/* I - Authentication type */
2194 * Force client to upgrade for authentication if that is how the
2195 * server is configured...
2198 if (code
== HTTP_UNAUTHORIZED
&&
2199 DefaultEncryption
== HTTP_ENCRYPT_REQUIRED
&&
2200 strcasecmp(con
->http
.hostname
, "localhost") &&
2203 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2204 "cupsdSendError: Encryption before authentication!");
2205 code
= HTTP_UPGRADE_REQUIRED
;
2207 #endif /* HAVE_SSL */
2210 * Put the request in the access_log file...
2213 cupsdLogRequest(con
, code
);
2215 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendError: %d code=%d (%s)",
2216 con
->http
.fd
, code
, httpStatus(code
));
2219 * To work around bugs in some proxies, don't use Keep-Alive for some
2222 * Kerberos authentication doesn't work without Keep-Alive, so
2223 * never disable it in that case.
2226 if (code
>= HTTP_BAD_REQUEST
&& con
->http
.auth_type
!= AUTH_NEGOTIATE
)
2227 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
2230 * Send an error message back to the client. If the error code is a
2231 * 400 or 500 series, make sure the message contains some text, too!
2234 if (!cupsdSendHeader(con
, code
, NULL
, auth_type
))
2238 if (code
== HTTP_UPGRADE_REQUIRED
)
2239 if (httpPrintf(HTTP(con
), "Connection: Upgrade\r\n") < 0)
2242 if (httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n") < 0)
2244 #endif /* HAVE_SSL */
2246 if (con
->http
.version
>= HTTP_1_1
&&
2247 con
->http
.keep_alive
== HTTP_KEEPALIVE_OFF
)
2249 if (httpPrintf(HTTP(con
), "Connection: close\r\n") < 0)
2253 if (code
>= HTTP_BAD_REQUEST
)
2256 * Send a human-readable error message.
2259 char message
[4096], /* Message for user */
2260 urltext
[1024], /* URL redirection text */
2261 redirect
[1024]; /* Redirection link */
2262 const char *text
; /* Status-specific text */
2267 if (code
== HTTP_UNAUTHORIZED
)
2268 text
= _cupsLangString(con
->language
,
2269 _("Enter your username and password or the "
2270 "root username and password to access this "
2271 "page. If you are using Kerberos authentication, "
2272 "make sure you have a valid Kerberos ticket."));
2273 else if (code
== HTTP_UPGRADE_REQUIRED
)
2277 snprintf(urltext
, sizeof(urltext
),
2278 _cupsLangString(con
->language
,
2279 _("You must access this page using the URL "
2280 "<A HREF=\"https://%s:%d%s\">"
2281 "https://%s:%d%s</A>.")),
2282 con
->servername
, con
->serverport
, con
->uri
,
2283 con
->servername
, con
->serverport
, con
->uri
);
2285 snprintf(redirect
, sizeof(redirect
),
2286 "<META HTTP-EQUIV=\"Refresh\" "
2287 "CONTENT=\"3;URL=https://%s:%d%s\">\n",
2288 con
->servername
, con
->serverport
, con
->uri
);
2293 snprintf(message
, sizeof(message
),
2294 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" "
2295 "\"http://www.w3.org/TR/REC-html40/loose.dtd\">\n"
2298 "\t<META HTTP-EQUIV=\"Content-Type\" "
2299 "CONTENT=\"text/html; charset=utf-8\">\n"
2300 "\t<TITLE>%d %s</TITLE>\n"
2301 "\t<LINK REL=\"STYLESHEET\" TYPE=\"text/css\" "
2302 "HREF=\"/cups.css\">\n"
2310 code
, httpStatus(code
), redirect
, code
, httpStatus(code
), text
);
2312 if (httpPrintf(HTTP(con
), "Content-Type: text/html; charset=utf-8\r\n") < 0)
2314 if (httpPrintf(HTTP(con
), "Content-Length: %d\r\n",
2315 (int)strlen(message
)) < 0)
2317 if (httpPrintf(HTTP(con
), "\r\n") < 0)
2319 if (httpPrintf(HTTP(con
), "%s", message
) < 0)
2322 else if (httpPrintf(HTTP(con
), "\r\n") < 0)
2325 if (cupsdFlushHeader(con
) < 0)
2328 con
->http
.state
= HTTP_WAITING
;
2335 * 'cupsdSendHeader()' - Send an HTTP request.
2338 int /* O - 1 on success, 0 on failure */
2340 cupsd_client_t
*con
, /* I - Client to send to */
2341 http_status_t code
, /* I - HTTP status code */
2342 char *type
, /* I - MIME type of document */
2343 int auth_type
) /* I - Type of authentication */
2345 char auth_str
[1024]; /* Authorization string */
2349 * Send the HTTP status header...
2352 if (code
== HTTP_CONTINUE
)
2355 * 100-continue doesn't send any headers...
2358 return (httpPrintf(HTTP(con
), "HTTP/%d.%d 100 Continue\r\n\r\n",
2359 con
->http
.version
/ 100, con
->http
.version
% 100) > 0);
2362 httpFlushWrite(HTTP(con
));
2364 con
->http
.data_encoding
= HTTP_ENCODE_FIELDS
;
2366 if (httpPrintf(HTTP(con
), "HTTP/%d.%d %d %s\r\n", con
->http
.version
/ 100,
2367 con
->http
.version
% 100, code
, httpStatus(code
)) < 0)
2369 if (httpPrintf(HTTP(con
), "Date: %s\r\n", httpGetDateString(time(NULL
))) < 0)
2372 if (httpPrintf(HTTP(con
), "Server: %s\r\n", ServerHeader
) < 0)
2374 if (con
->http
.keep_alive
&& con
->http
.version
>= HTTP_1_0
)
2376 if (httpPrintf(HTTP(con
), "Connection: Keep-Alive\r\n") < 0)
2378 if (httpPrintf(HTTP(con
), "Keep-Alive: timeout=%d\r\n",
2379 KeepAliveTimeout
) < 0)
2382 if (code
== HTTP_METHOD_NOT_ALLOWED
)
2383 if (httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST\r\n") < 0)
2386 if (code
== HTTP_UNAUTHORIZED
)
2388 if (auth_type
== AUTH_NONE
)
2390 if (!con
->best
|| con
->best
->type
== AUTH_NONE
)
2391 auth_type
= DefaultAuthType
;
2393 auth_type
= con
->best
->type
;
2398 if (auth_type
== AUTH_BASIC
|| auth_type
== AUTH_BASICDIGEST
)
2399 strlcpy(auth_str
, "Basic realm=\"CUPS\"", sizeof(auth_str
));
2400 else if (auth_type
== AUTH_DIGEST
)
2401 snprintf(auth_str
, sizeof(auth_str
), "Digest realm=\"CUPS\", nonce=\"%s\"",
2402 con
->http
.hostname
);
2404 else if (auth_type
== AUTH_NEGOTIATE
&& !con
->no_negotiate
&&
2405 con
->gss_output_token
.length
== 0)
2406 strlcpy(auth_str
, "Negotiate", sizeof(auth_str
));
2407 #endif /* HAVE_GSSAPI */
2409 #ifdef HAVE_AUTHORIZATION_H
2412 int i
; /* Looping var */
2413 char *auth_key
; /* Auth key buffer */
2414 size_t auth_size
; /* Size of remaining buffer */
2417 auth_key
= auth_str
+ strlen(auth_str
);
2418 auth_size
= sizeof(auth_str
) - (auth_key
- auth_str
);
2420 for (i
= 0; i
< con
->best
->num_names
; i
++)
2422 if (!strncasecmp(con
->best
->names
[i
], "@AUTHKEY(", 9))
2424 snprintf(auth_key
, auth_size
, ", authkey=\"%s\"",
2425 con
->best
->names
[i
] + 9);
2426 /* end parenthesis is stripped in conf.c */
2429 else if (!strcasecmp(con
->best
->names
[i
], "@SYSTEM") &&
2432 snprintf(auth_key
, auth_size
, ", authkey=\"%s\"", SystemGroupAuthKey
);
2437 #endif /* HAVE_AUTHORIZATION_H */
2440 httpPrintf(HTTP(con
), "WWW-Authenticate: %s\r\n", auth_str
) < 0)
2446 * WWW-Authenticate: Negotiate can be included even for
2447 * non-401 replies...
2450 if (con
->gss_output_token
.length
> 0)
2452 char buf
[2048]; /* Output token buffer */
2453 OM_uint32 minor_status
; /* Minor status code */
2456 httpEncode64_2(buf
, sizeof(buf
),
2457 con
->gss_output_token
.value
,
2458 con
->gss_output_token
.length
);
2459 gss_release_buffer(&minor_status
, &con
->gss_output_token
);
2461 if (httpPrintf(HTTP(con
), "WWW-Authenticate: Negotiate %s\r\n", buf
) < 0)
2464 #endif /* HAVE_GSSAPI */
2466 if (con
->language
&& strcmp(con
->language
->language
, "C"))
2468 if (httpPrintf(HTTP(con
), "Content-Language: %s\r\n",
2469 con
->language
->language
) < 0)
2475 if (!strcmp(type
, "text/html"))
2477 if (httpPrintf(HTTP(con
),
2478 "Content-Type: text/html; charset=utf-8\r\n") < 0)
2481 else if (httpPrintf(HTTP(con
), "Content-Type: %s\r\n", type
) < 0)
2490 * 'cupsdUpdateCGI()' - Read status messages from CGI scripts and programs.
2494 cupsdUpdateCGI(void)
2496 char *ptr
, /* Pointer to end of line in buffer */
2497 message
[1024]; /* Pointer to message text */
2498 int loglevel
; /* Log level for message */
2501 while ((ptr
= cupsdStatBufUpdate(CGIStatusBuffer
, &loglevel
,
2502 message
, sizeof(message
))) != NULL
)
2503 if (!strchr(CGIStatusBuffer
->buffer
, '\n'))
2506 if (ptr
== NULL
&& !CGIStatusBuffer
->bufused
)
2509 * Fatal error on pipe - should never happen!
2512 cupsdLogMessage(CUPSD_LOG_CRIT
,
2513 "cupsdUpdateCGI: error reading from CGI error pipe - %s",
2520 * 'cupsdWriteClient()' - Write data to a client as needed.
2524 cupsdWriteClient(cupsd_client_t
*con
) /* I - Client connection */
2526 int bytes
; /* Number of bytes written */
2527 char buf
[16385]; /* Data buffer */
2528 char *bufptr
; /* Pointer into buffer */
2529 ipp_state_t ipp_state
; /* IPP state value */
2533 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2534 "cupsdWriteClient(con=%p) %d response=%p(%d), file=%d "
2535 "pipe_pid=%d state=%d",
2536 con
, con
->http
.fd
, con
->response
, con
->response
->state
,
2537 con
->file
, con
->pipe_pid
, con
->http
.state
);
2540 if (con
->http
.state
!= HTTP_GET_SEND
&&
2541 con
->http
.state
!= HTTP_POST_SEND
)
2547 * Make sure we select on the CGI output...
2550 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2552 if (!con
->file_ready
)
2555 * Try again later when there is CGI output available...
2558 cupsdRemoveSelect(con
->http
.fd
);
2562 con
->file_ready
= 0;
2565 if (con
->response
&& con
->response
->state
!= IPP_DATA
)
2567 ipp_state
= ippWrite(HTTP(con
), con
->response
);
2568 bytes
= ipp_state
!= IPP_ERROR
&&
2569 (con
->file
>= 0 || ipp_state
!= IPP_DATA
);
2571 else if ((bytes
= read(con
->file
, buf
, sizeof(buf
) - 1)) > 0)
2573 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2574 "cupsdWriteClient: Read %d bytes from file %d...",
2577 if (con
->pipe_pid
&& !con
->got_fields
)
2580 * Inspect the data for Content-Type and other fields.
2585 for (bufptr
= buf
; !con
->got_fields
&& *bufptr
; bufptr
++)
2586 if (*bufptr
== '\n')
2589 * Send line to client...
2592 if (bufptr
> buf
&& bufptr
[-1] == '\r')
2596 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "Script header: %s", buf
);
2598 if (!con
->sent_header
)
2601 * Handle redirection and CGI status codes...
2604 if (!strncasecmp(buf
, "Location:", 9))
2606 cupsdSendHeader(con
, HTTP_SEE_OTHER
, NULL
, AUTH_NONE
);
2607 con
->sent_header
= 2;
2609 if (httpPrintf(HTTP(con
), "Content-Length: 0\r\n") < 0)
2612 else if (!strncasecmp(buf
, "Status:", 7))
2614 cupsdSendError(con
, (http_status_t
)atoi(buf
+ 7), AUTH_NONE
);
2615 con
->sent_header
= 2;
2619 cupsdSendHeader(con
, HTTP_OK
, NULL
, AUTH_NONE
);
2620 con
->sent_header
= 1;
2622 if (con
->http
.version
== HTTP_1_1
)
2624 if (httpPrintf(HTTP(con
), "Transfer-Encoding: chunked\r\n") < 0)
2630 if (strncasecmp(buf
, "Status:", 7))
2631 httpPrintf(HTTP(con
), "%s\r\n", buf
);
2633 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdWriteClient: %d %s",
2640 bytes
-= (bufptr
- buf
);
2641 memmove(buf
, bufptr
, bytes
+ 1);
2645 * See if the line was empty...
2648 if (con
->field_col
== 0)
2650 con
->got_fields
= 1;
2652 if (cupsdFlushHeader(con
) < 0)
2654 cupsdCloseClient(con
);
2658 if (con
->http
.version
== HTTP_1_1
)
2659 con
->http
.data_encoding
= HTTP_ENCODE_CHUNKED
;
2664 else if (*bufptr
!= '\r')
2667 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2668 "cupsdWriteClient: %d bytes=%d, got_fields=%d",
2669 con
->http
.fd
, bytes
, con
->got_fields
);
2671 if (bytes
> 0 && !con
->got_fields
)
2674 * Remaining text needs to go out...
2677 httpPrintf(HTTP(con
), "%s", buf
);
2679 con
->http
.activity
= time(NULL
);
2682 else if (bytes
== 0)
2683 con
->http
.activity
= time(NULL
);
2688 if (httpWrite2(HTTP(con
), buf
, bytes
) < 0)
2690 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2691 "cupsdWriteClient: %d Write of %d bytes failed!",
2692 con
->http
.fd
, bytes
);
2694 cupsdCloseClient(con
);
2698 con
->bytes
+= bytes
;
2700 if (con
->http
.state
== HTTP_WAITING
)
2707 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdWriteClient: %d bytes < 0",
2710 cupsdLogRequest(con
, HTTP_OK
);
2712 httpFlushWrite(HTTP(con
));
2714 if (con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
&& con
->sent_header
== 1)
2716 if (httpWrite2(HTTP(con
), "", 0) < 0)
2718 cupsdCloseClient(con
);
2723 con
->http
.state
= HTTP_WAITING
;
2725 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
2729 cupsdRemoveSelect(con
->file
);
2732 cupsdEndProcess(con
->pipe_pid
, 0);
2734 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2735 "cupsdWriteClient: %d Closing data file %d.",
2736 con
->http
.fd
, con
->file
);
2745 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2746 "cupsdWriteClient: %d Removing temp file %s",
2747 con
->http
.fd
, con
->filename
);
2748 unlink(con
->filename
);
2749 cupsdClearString(&con
->filename
);
2754 ippDelete(con
->request
);
2755 con
->request
= NULL
;
2760 ippDelete(con
->response
);
2761 con
->response
= NULL
;
2764 cupsdClearString(&con
->command
);
2765 cupsdClearString(&con
->options
);
2766 cupsdClearString(&con
->query_string
);
2768 if (!con
->http
.keep_alive
)
2770 cupsdCloseClient(con
);
2775 con
->http
.activity
= time(NULL
);
2780 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
2783 static int /* O - 1 if modified since */
2785 cupsd_client_t
*con
, /* I - Client connection */
2786 struct stat
*filestats
) /* I - File information */
2788 char *ptr
; /* Pointer into field */
2789 time_t date
; /* Time/date value */
2790 off_t size
; /* Size/length value */
2795 ptr
= con
->http
.fields
[HTTP_FIELD_IF_MODIFIED_SINCE
];
2800 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2801 "check_if_modified: %d If-Modified-Since=\"%s\"",
2804 while (*ptr
!= '\0')
2806 while (isspace(*ptr
) || *ptr
== ';')
2809 if (strncasecmp(ptr
, "length=", 7) == 0)
2812 size
= strtoll(ptr
, NULL
, 10);
2814 while (isdigit(*ptr
))
2817 else if (isalpha(*ptr
))
2819 date
= httpGetDateTime(ptr
);
2820 while (*ptr
!= '\0' && *ptr
!= ';')
2827 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2828 "check_if_modified: %d sizes=" CUPS_LLFMT
","
2829 CUPS_LLFMT
" dates=%d,%d",
2830 con
->http
.fd
, CUPS_LLCAST size
,
2831 CUPS_LLCAST filestats
->st_size
, (int)date
,
2832 (int)filestats
->st_mtime
);
2834 return ((size
!= filestats
->st_size
&& size
!= 0) ||
2835 (date
< filestats
->st_mtime
&& date
!= 0) ||
2836 (size
== 0 && date
== 0));
2842 * 'encrypt_client()' - Enable encryption for the client...
2845 static int /* O - 1 on success, 0 on error */
2846 encrypt_client(cupsd_client_t
*con
) /* I - Client to encrypt */
2849 SSL_CTX
*context
; /* Context for encryption */
2850 SSL
*conn
; /* Connection for encryption */
2851 BIO
*bio
; /* BIO data */
2852 unsigned long error
; /* Error code */
2856 * Verify that we have a certificate...
2859 if (access(ServerKey
, 0) || access(ServerCertificate
, 0))
2862 * Nope, make a self-signed certificate...
2865 if (!make_certificate(con
))
2870 * Create the SSL context and accept the connection...
2873 context
= SSL_CTX_new(SSLv23_server_method());
2875 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
2876 SSL_CTX_use_PrivateKey_file(context
, ServerKey
, SSL_FILETYPE_PEM
);
2877 SSL_CTX_use_certificate_file(context
, ServerCertificate
, SSL_FILETYPE_PEM
);
2879 bio
= BIO_new(_httpBIOMethods());
2880 BIO_ctrl(bio
, BIO_C_SET_FILE_PTR
, 0, (char *)HTTP(con
));
2882 conn
= SSL_new(context
);
2883 SSL_set_bio(conn
, bio
, bio
);
2885 if (SSL_accept(conn
) != 1)
2887 cupsdLogMessage(CUPSD_LOG_ERROR
,
2888 "encrypt_client: Unable to encrypt connection from %s!",
2889 con
->http
.hostname
);
2891 while ((error
= ERR_get_error()) != 0)
2892 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s",
2893 ERR_error_string(error
, NULL
));
2895 SSL_CTX_free(context
);
2900 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2901 "encrypt_client: %d Connection from %s now encrypted.",
2902 con
->http
.fd
, con
->http
.hostname
);
2904 con
->http
.tls
= conn
;
2907 # elif defined(HAVE_GNUTLS)
2908 http_tls_t
*conn
; /* TLS session object */
2909 int error
; /* Error code */
2910 gnutls_certificate_server_credentials
*credentials
;
2911 /* TLS credentials */
2915 * Verify that we have a certificate...
2918 if (access(ServerKey
, 0) || access(ServerCertificate
, 0))
2921 * Nope, make a self-signed certificate...
2924 if (!make_certificate(con
))
2929 * Create the SSL object and perform the SSL handshake...
2932 conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
));
2937 credentials
= (gnutls_certificate_server_credentials
*)
2938 malloc(sizeof(gnutls_certificate_server_credentials
));
2939 if (credentials
== NULL
)
2941 cupsdLogMessage(CUPSD_LOG_ERROR
,
2942 "encrypt_client: Unable to encrypt connection from %s!",
2943 con
->http
.hostname
);
2944 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s", strerror(errno
));
2950 gnutls_certificate_allocate_credentials(credentials
);
2951 gnutls_certificate_set_x509_key_file(*credentials
, ServerCertificate
,
2952 ServerKey
, GNUTLS_X509_FMT_PEM
);
2954 gnutls_init(&(conn
->session
), GNUTLS_SERVER
);
2955 gnutls_set_default_priority(conn
->session
);
2956 gnutls_credentials_set(conn
->session
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
2957 gnutls_transport_set_ptr(conn
->session
, (gnutls_transport_ptr
)HTTP(con
));
2958 gnutls_transport_set_pull_function(conn
->session
, _httpReadGNUTLS
);
2959 gnutls_transport_set_push_function(conn
->session
, _httpWriteGNUTLS
);
2961 error
= gnutls_handshake(conn
->session
);
2963 if (error
!= GNUTLS_E_SUCCESS
)
2965 cupsdLogMessage(CUPSD_LOG_ERROR
,
2966 "encrypt_client: Unable to encrypt connection from %s!",
2967 con
->http
.hostname
);
2968 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s",
2969 gnutls_strerror(error
));
2971 gnutls_deinit(conn
->session
);
2972 gnutls_certificate_free_credentials(*credentials
);
2978 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2979 "encrypt_client: %d Connection from %s now encrypted.",
2980 con
->http
.fd
, con
->http
.hostname
);
2982 conn
->credentials
= credentials
;
2983 con
->http
.tls
= conn
;
2986 # elif defined(HAVE_CDSASSL)
2987 OSStatus error
; /* Error code */
2988 http_tls_t
*conn
; /* CDSA connection information */
2991 if ((conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
))) == NULL
)
2995 conn
->session
= NULL
;
2996 conn
->certsArray
= get_cdsa_certificate(con
);
2998 if (!conn
->certsArray
)
3001 * No keychain (yet), make a self-signed certificate...
3004 if (make_certificate(con
))
3005 conn
->certsArray
= get_cdsa_certificate(con
);
3008 if (!conn
->certsArray
)
3010 cupsdLogMessage(CUPSD_LOG_ERROR
,
3011 "encrypt_client: Could not find signing key in keychain "
3012 "\"%s\"", ServerCertificate
);
3013 error
= errSSLBadCert
; /* errSSLBadConfiguration is a better choice, but not available on 10.2.x */
3017 error
= SSLNewContext(true, &conn
->session
);
3020 error
= SSLSetIOFuncs(conn
->session
, _httpReadCDSA
, _httpWriteCDSA
);
3023 error
= SSLSetProtocolVersionEnabled(conn
->session
, kSSLProtocol2
, false);
3026 error
= SSLSetConnection(conn
->session
, HTTP(con
));
3029 error
= SSLSetAllowsExpiredCerts(conn
->session
, true);
3032 error
= SSLSetAllowsAnyRoot(conn
->session
, true);
3035 error
= SSLSetCertificate(conn
->session
, conn
->certsArray
);
3040 * Perform SSL/TLS handshake
3043 while ((error
= SSLHandshake(conn
->session
)) == errSSLWouldBlock
)
3049 cupsdLogMessage(CUPSD_LOG_ERROR
,
3050 "encrypt_client: Unable to encrypt connection from %s!",
3051 con
->http
.hostname
);
3053 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s (%d)",
3054 cssmErrorString(error
), (int)error
);
3056 con
->http
.error
= error
;
3057 con
->http
.status
= HTTP_ERROR
;
3060 SSLDisposeContext(conn
->session
);
3062 if (conn
->certsArray
)
3063 CFRelease(conn
->certsArray
);
3070 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3071 "encrypt_client: %d Connection from %s now encrypted.",
3072 con
->http
.fd
, con
->http
.hostname
);
3074 con
->http
.tls
= conn
;
3077 # endif /* HAVE_LIBSSL */
3079 #endif /* HAVE_SSL */
3084 * 'get_cdsa_certificate()' - Get a SSL/TLS certificate from the System keychain.
3087 static CFArrayRef
/* O - Array of certificates */
3088 get_cdsa_certificate(cupsd_client_t
*con
) /* I - Client connection */
3090 OSStatus err
; /* Error info */
3091 SecKeychainRef keychain
; /* Keychain reference */
3092 SecIdentitySearchRef search
; /* Search reference */
3093 SecIdentityRef identity
; /* Identity */
3094 CFArrayRef certificates
= NULL
;
3095 /* Certificate array */
3098 if ((err
= SecKeychainOpen(ServerCertificate
, &keychain
)))
3100 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot open keychain \"%s\", %s",
3101 ServerCertificate
, cssmErrorString(err
));
3105 # if HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY
3107 * Use a policy to search for valid certificates who's common name matches the
3111 SecPolicySearchRef policy_search
; /* Policy search ref */
3112 SecPolicyRef policy
; /* Policy ref */
3113 CSSM_DATA options
; /* Policy options */
3114 CSSM_APPLE_TP_SSL_OPTIONS
3115 ssl_options
; /* SSL Option for hostname */
3118 if ((err
= SecPolicySearchCreate(CSSM_CERT_X_509v3
, &CSSMOID_APPLE_TP_SSL
,
3119 NULL
, &policy_search
)))
3121 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot create a policy search reference");
3122 CFRelease(keychain
);
3126 if ((err
= SecPolicySearchCopyNext(policy_search
, &policy
)))
3128 cupsdLogMessage(CUPSD_LOG_ERROR
,
3129 "Cannot find a policy to use for searching");
3130 CFRelease(keychain
);
3131 CFRelease(policy_search
);
3135 memset(&ssl_options
, 0, sizeof(ssl_options
));
3136 ssl_options
.Version
= CSSM_APPLE_TP_SSL_OPTS_VERSION
;
3137 ssl_options
.ServerName
= con
->servername
;
3138 ssl_options
.ServerNameLen
= strlen(con
->servername
);
3140 options
.Data
= (uint8
*)&ssl_options
;
3141 options
.Length
= sizeof(ssl_options
);
3143 if ((err
= SecPolicySetValue(policy
, &options
)))
3145 cupsdLogMessage(CUPSD_LOG_ERROR
,
3146 "Cannot set policy value to use for searching");
3147 CFRelease(keychain
);
3148 CFRelease(policy_search
);
3152 err
= SecIdentitySearchCreateWithPolicy(policy
, NULL
, CSSM_KEYUSE_SIGN
,
3153 keychain
, FALSE
, &search
);
3156 * Assume there is exactly one SecIdentity in the keychain...
3159 err
= SecIdentitySearchCreate(keychain
, CSSM_KEYUSE_SIGN
, &search
);
3160 # endif /* HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY */
3163 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3164 "Cannot create keychain search reference: %s",
3165 cssmErrorString(err
));
3168 if ((err
= SecIdentitySearchCopyNext(search
, &identity
)))
3170 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3171 "Cannot find signing key in keychain \"%s\", error %d",
3172 ServerCertificate
, (int)err
);
3176 if (CFGetTypeID(identity
) != SecIdentityGetTypeID())
3177 cupsdLogMessage(CUPSD_LOG_ERROR
,
3178 "SecIdentitySearchCopyNext CFTypeID failure!");
3181 if ((certificates
= CFArrayCreate(NULL
, (const void **)&identity
,
3182 1, &kCFTypeArrayCallBacks
)) == NULL
)
3183 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot create certificate array");
3186 CFRelease(identity
);
3192 # if HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY
3194 CFRelease(policy_search
);
3195 # endif /* HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY */
3197 return (certificates
);
3199 #endif /* HAVE_CDSASSL */
3203 * 'get_file()' - Get a filename and state info.
3206 static char * /* O - Real filename */
3207 get_file(cupsd_client_t
*con
, /* I - Client connection */
3208 struct stat
*filestats
, /* O - File information */
3209 char *filename
, /* IO - Filename buffer */
3210 int len
) /* I - Buffer length */
3212 int status
; /* Status of filesystem calls */
3213 char *ptr
; /* Pointer info filename */
3214 int plen
; /* Remaining length after pointer */
3218 * Figure out the real filename...
3221 if (!strncmp(con
->uri
, "/ppd/", 5))
3222 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
);
3223 else if (!strncmp(con
->uri
, "/rss/", 5) && !strchr(con
->uri
+ 5, '/'))
3224 snprintf(filename
, len
, "%s/rss/%s", CacheDir
, con
->uri
+ 5);
3225 else if (!strncmp(con
->uri
, "/admin/conf/", 12))
3226 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
+ 11);
3227 else if (!strncmp(con
->uri
, "/admin/log/", 11))
3229 if (!strcmp(con
->uri
+ 11, "access_log") && AccessLog
[0] == '/')
3230 strlcpy(filename
, AccessLog
, len
);
3231 else if (!strcmp(con
->uri
+ 11, "error_log") && ErrorLog
[0] == '/')
3232 strlcpy(filename
, ErrorLog
, len
);
3233 else if (!strcmp(con
->uri
+ 11, "page_log") && PageLog
[0] == '/')
3234 strlcpy(filename
, PageLog
, len
);
3238 else if (con
->language
)
3239 snprintf(filename
, len
, "%s/%s%s", DocumentRoot
, con
->language
->language
,
3242 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3244 if ((ptr
= strchr(filename
, '?')) != NULL
)
3248 * Grab the status for this language; if there isn't a language-specific file
3249 * then fallback to the default one...
3252 if ((status
= stat(filename
, filestats
)) != 0 && con
->language
&&
3253 strncmp(con
->uri
, "/ppd/", 5) &&
3254 strncmp(con
->uri
, "/admin/conf/", 12) &&
3255 strncmp(con
->uri
, "/admin/log/", 11))
3258 * Drop the country code...
3261 char ll
[3]; /* Short language name */
3264 strlcpy(ll
, con
->language
->language
, sizeof(ll
));
3265 snprintf(filename
, len
, "%s/%s%s", DocumentRoot
, ll
, con
->uri
);
3267 if ((ptr
= strchr(filename
, '?')) != NULL
)
3270 if ((status
= stat(filename
, filestats
)) != 0)
3273 * Drop the language prefix and try the root directory...
3276 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3278 if ((ptr
= strchr(filename
, '?')) != NULL
)
3281 status
= stat(filename
, filestats
);
3286 * If we're found a directory, get the index.html file instead...
3289 if (!status
&& S_ISDIR(filestats
->st_mode
))
3291 if (filename
[strlen(filename
) - 1] != '/')
3292 strlcat(filename
, "/", len
);
3294 ptr
= filename
+ strlen(filename
);
3295 plen
= len
- (ptr
- filename
);
3297 strlcpy(ptr
, "index.html", plen
);
3298 status
= stat(filename
, filestats
);
3303 strlcpy(ptr
, "index.class", plen
);
3304 status
= stat(filename
, filestats
);
3306 #endif /* HAVE_JAVA */
3311 strlcpy(ptr
, "index.pl", plen
);
3312 status
= stat(filename
, filestats
);
3314 #endif /* HAVE_PERL */
3319 strlcpy(ptr
, "index.php", plen
);
3320 status
= stat(filename
, filestats
);
3322 #endif /* HAVE_PHP */
3327 strlcpy(ptr
, "index.pyc", plen
);
3328 status
= stat(filename
, filestats
);
3333 strlcpy(ptr
, "index.py", plen
);
3334 status
= stat(filename
, filestats
);
3336 #endif /* HAVE_PYTHON */
3339 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "get_file: %d filename=%s size=%d",
3340 con
->http
.fd
, filename
,
3341 status
? -1 : (int)filestats
->st_size
);
3344 con
->http
.data_remaining
= (int)filestats
->st_size
;
3354 * 'install_conf_file()' - Install a configuration file.
3357 static http_status_t
/* O - Status */
3358 install_conf_file(cupsd_client_t
*con
) /* I - Connection */
3360 cups_file_t
*in
, /* Input file */
3361 *out
; /* Output file */
3362 char buffer
[1024]; /* Copy buffer */
3363 int bytes
; /* Number of bytes */
3364 char conffile
[1024], /* Configuration filename */
3365 newfile
[1024], /* New config filename */
3366 oldfile
[1024]; /* Old config filename */
3367 struct stat confinfo
; /* Config file info */
3371 * First construct the filenames...
3374 snprintf(conffile
, sizeof(conffile
), "%s%s", ServerRoot
, con
->uri
+ 11);
3375 snprintf(newfile
, sizeof(newfile
), "%s%s.N", ServerRoot
, con
->uri
+ 11);
3376 snprintf(oldfile
, sizeof(oldfile
), "%s%s.O", ServerRoot
, con
->uri
+ 11);
3378 cupsdLogMessage(CUPSD_LOG_INFO
, "Installing config file \"%s\"...", conffile
);
3381 * Get the owner, group, and permissions of the configuration file.
3382 * If it doesn't exist, assign it to the User and Group in the
3383 * cupsd.conf file with mode 0640 permissions.
3386 if (stat(conffile
, &confinfo
))
3388 confinfo
.st_uid
= User
;
3389 confinfo
.st_gid
= Group
;
3390 confinfo
.st_mode
= ConfigFilePerm
;
3394 * Open the request file and new config file...
3397 if ((in
= cupsFileOpen(con
->filename
, "rb")) == NULL
)
3399 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open request file \"%s\" - %s",
3400 con
->filename
, strerror(errno
));
3401 return (HTTP_SERVER_ERROR
);
3404 if ((out
= cupsFileOpen(newfile
, "wb")) == NULL
)
3407 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open config file \"%s\" - %s",
3408 newfile
, strerror(errno
));
3409 return (HTTP_SERVER_ERROR
);
3412 fchmod(cupsFileNumber(out
), confinfo
.st_mode
);
3413 fchown(cupsFileNumber(out
), confinfo
.st_uid
, confinfo
.st_gid
);
3416 * Copy from the request to the new config file...
3419 while ((bytes
= cupsFileRead(in
, buffer
, sizeof(buffer
))) > 0)
3420 if (cupsFileWrite(out
, buffer
, bytes
) < bytes
)
3422 cupsdLogMessage(CUPSD_LOG_ERROR
,
3423 "Unable to copy to config file \"%s\" - %s",
3424 newfile
, strerror(errno
));
3430 return (HTTP_SERVER_ERROR
);
3434 * Close the files...
3438 if (cupsFileClose(out
))
3440 cupsdLogMessage(CUPSD_LOG_ERROR
,
3441 "Error file closing config file \"%s\" - %s",
3442 newfile
, strerror(errno
));
3446 return (HTTP_SERVER_ERROR
);
3450 * Remove the request file...
3453 unlink(con
->filename
);
3454 cupsdClearString(&con
->filename
);
3457 * Unlink the old backup, rename the current config file to the backup
3458 * filename, and rename the new config file to the config file name...
3461 if (unlink(oldfile
))
3462 if (errno
!= ENOENT
)
3464 cupsdLogMessage(CUPSD_LOG_ERROR
,
3465 "Unable to remove backup config file \"%s\" - %s",
3466 oldfile
, strerror(errno
));
3470 return (HTTP_SERVER_ERROR
);
3473 if (rename(conffile
, oldfile
))
3474 if (errno
!= ENOENT
)
3476 cupsdLogMessage(CUPSD_LOG_ERROR
,
3477 "Unable to rename old config file \"%s\" - %s",
3478 conffile
, strerror(errno
));
3482 return (HTTP_SERVER_ERROR
);
3485 if (rename(newfile
, conffile
))
3487 cupsdLogMessage(CUPSD_LOG_ERROR
,
3488 "Unable to rename new config file \"%s\" - %s",
3489 newfile
, strerror(errno
));
3491 rename(oldfile
, conffile
);
3494 return (HTTP_SERVER_ERROR
);
3498 * If the cupsd.conf file was updated, set the NeedReload flag...
3501 if (!strcmp(con
->uri
, "/admin/conf/cupsd.conf"))
3502 NeedReload
= RELOAD_CUPSD
;
3504 NeedReload
= RELOAD_ALL
;
3506 ReloadTime
= time(NULL
);
3509 * Return that the file was created successfully...
3512 return (HTTP_CREATED
);
3517 * 'is_cgi()' - Is the resource a CGI script/program?
3520 static int /* O - 1 = CGI, 0 = file */
3521 is_cgi(cupsd_client_t
*con
, /* I - Client connection */
3522 const char *filename
, /* I - Real filename */
3523 struct stat
*filestats
, /* I - File information */
3524 mime_type_t
*type
) /* I - MIME type */
3526 const char *options
; /* Options on URL */
3529 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3530 "is_cgi(con=%p, filename=\"%s\", filestats=%p, type=%s/%s)\n",
3531 con
, filename
, filestats
, type
? type
->super
: "unknown",
3532 type
? type
->type
: "unknown");
3535 * Get the options, if any...
3538 if ((options
= strchr(con
->uri
, '?')) != NULL
)
3542 if (strchr(options
, '='))
3543 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", options
);
3547 * Check for known types...
3550 if (!type
|| strcasecmp(type
->super
, "application"))
3552 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "is_cgi: Returning 0...");
3556 if (!strcasecmp(type
->type
, "x-httpd-cgi") &&
3557 (filestats
->st_mode
& 0111))
3560 * "application/x-httpd-cgi" is a CGI script.
3563 cupsdSetString(&con
->command
, filename
);
3565 filename
= strrchr(filename
, '/') + 1; /* Filename always absolute */
3567 cupsdSetString(&con
->options
, options
);
3569 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3570 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3571 con
->command
, con
->options
);
3576 else if (!strcasecmp(type
->type
, "x-httpd-java"))
3579 * "application/x-httpd-java" is a Java servlet.
3582 cupsdSetString(&con
->command
, CUPS_JAVA
);
3585 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3587 cupsdSetStringf(&con
->options
, " %s", filename
);
3589 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3590 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3591 con
->command
, con
->options
);
3595 #endif /* HAVE_JAVA */
3597 else if (!strcasecmp(type
->type
, "x-httpd-perl"))
3600 * "application/x-httpd-perl" is a Perl page.
3603 cupsdSetString(&con
->command
, CUPS_PERL
);
3606 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3608 cupsdSetStringf(&con
->options
, " %s", filename
);
3610 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3611 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3612 con
->command
, con
->options
);
3616 #endif /* HAVE_PERL */
3618 else if (!strcasecmp(type
->type
, "x-httpd-php"))
3621 * "application/x-httpd-php" is a PHP page.
3624 cupsdSetString(&con
->command
, CUPS_PHP
);
3627 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3629 cupsdSetStringf(&con
->options
, " %s", filename
);
3631 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3632 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3633 con
->command
, con
->options
);
3637 #endif /* HAVE_PHP */
3639 else if (!strcasecmp(type
->type
, "x-httpd-python"))
3642 * "application/x-httpd-python" is a Python page.
3645 cupsdSetString(&con
->command
, CUPS_PYTHON
);
3648 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3650 cupsdSetStringf(&con
->options
, " %s", filename
);
3652 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3653 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3654 con
->command
, con
->options
);
3658 #endif /* HAVE_PYTHON */
3660 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "is_cgi: Returning 0...");
3667 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
3670 static int /* O - 0 if relative, 1 if absolute */
3671 is_path_absolute(const char *path
) /* I - Input path */
3674 * Check for a leading slash...
3681 * Check for "/.." in the path...
3684 while ((path
= strstr(path
, "/..")) != NULL
)
3686 if (!path
[3] || path
[3] == '/')
3693 * If we haven't found any relative paths, return 1 indicating an
3703 * 'make_certificate()' - Make a self-signed SSL/TLS certificate.
3706 static int /* O - 1 on success, 0 on failure */
3707 make_certificate(cupsd_client_t
*con
) /* I - Client connection */
3709 #if defined(HAVE_LIBSSL) && defined(HAVE_WAITPID)
3710 int pid
, /* Process ID of command */
3711 status
; /* Status of command */
3712 char command
[1024], /* Command */
3713 *argv
[12], /* Command-line arguments */
3714 *envp
[MAX_ENV
+ 1], /* Environment variables */
3715 home
[1024], /* HOME environment variable */
3716 infofile
[1024], /* Type-in information for cert */
3717 seedfile
[1024]; /* Random number seed file */
3718 int envc
, /* Number of environment variables */
3719 bytes
; /* Bytes written */
3720 cups_file_t
*fp
; /* Seed/info file */
3721 int infofd
; /* Info file descriptor */
3725 * Run the "openssl" command to seed the random number generator and
3726 * generate a self-signed certificate that is good for 10 years:
3728 * openssl rand -rand seedfile 1
3730 * openssl req -new -x509 -keyout ServerKey \
3731 * -out ServerCertificate -days 3650 -nodes
3733 * The seeding step is crucial in ensuring that the openssl command
3734 * does not block on systems without sufficient entropy...
3737 if (!cupsFileFind("openssl", getenv("PATH"), 1, command
, sizeof(command
)))
3739 cupsdLogMessage(CUPSD_LOG_ERROR
,
3740 "No SSL certificate and openssl command not found!");
3744 if (access("/dev/urandom", 0))
3747 * If the system doesn't provide /dev/urandom, then any random source
3748 * will probably be blocking-style, so generate some random data to
3749 * use as a seed for the certificate. Note that we have already
3750 * seeded the random number generator in cupsdInitCerts()...
3753 cupsdLogMessage(CUPSD_LOG_INFO
,
3754 "Seeding the random number generator...");
3756 snprintf(home
, sizeof(home
), "HOME=%s", TempDir
);
3759 * Write the seed file...
3762 if ((fp
= cupsTempFile2(seedfile
, sizeof(seedfile
))) == NULL
)
3764 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to create seed file %s - %s",
3765 seedfile
, strerror(errno
));
3769 for (bytes
= 0; bytes
< 262144; bytes
++)
3770 cupsFilePutChar(fp
, random());
3775 * Run the openssl command to seed its random number generator...
3778 argv
[0] = "openssl";
3785 envc
= cupsdLoadEnv(envp
, MAX_ENV
);
3786 envp
[envc
++] = home
;
3789 if (!cupsdStartProcess(command
, argv
, envp
, -1, -1, -1, -1, -1, 1, &pid
))
3795 while (waitpid(pid
, &status
, 0) < 0)
3802 cupsdFinishProcess(pid
, command
, sizeof(command
));
3805 * Remove the seed file, as it is no longer needed...
3812 if (WIFEXITED(status
))
3813 cupsdLogMessage(CUPSD_LOG_ERROR
,
3814 "Unable to seed random number generator - "
3815 "the openssl command stopped with status %d!",
3816 WEXITSTATUS(status
));
3818 cupsdLogMessage(CUPSD_LOG_ERROR
,
3819 "Unable to seed random number generator - "
3820 "the openssl command crashed on signal %d!",
3828 * Create a file with the certificate information fields...
3830 * Note: This assumes that the default questions are asked by the openssl
3834 if ((fp
= cupsTempFile2(infofile
, sizeof(infofile
))) == NULL
)
3836 cupsdLogMessage(CUPSD_LOG_ERROR
,
3837 "Unable to create certificate information file %s - %s",
3838 infofile
, strerror(errno
));
3842 cupsFilePrintf(fp
, ".\n.\n.\n%s\n.\n%s\n%s\n",
3843 ServerName
, ServerName
, ServerAdmin
);
3846 cupsdLogMessage(CUPSD_LOG_INFO
,
3847 "Generating SSL server key and certificate...");
3849 argv
[0] = "openssl";
3853 argv
[4] = "-keyout";
3854 argv
[5] = ServerKey
;
3856 argv
[7] = ServerCertificate
;
3859 argv
[10] = "-nodes";
3862 cupsdLoadEnv(envp
, MAX_ENV
);
3864 infofd
= open(infofile
, O_RDONLY
);
3866 if (!cupsdStartProcess(command
, argv
, envp
, infofd
, -1, -1, -1, -1, 1, &pid
))
3876 while (waitpid(pid
, &status
, 0) < 0)
3883 cupsdFinishProcess(pid
, command
, sizeof(command
));
3887 if (WIFEXITED(status
))
3888 cupsdLogMessage(CUPSD_LOG_ERROR
,
3889 "Unable to create SSL server key and certificate - "
3890 "the openssl command stopped with status %d!",
3891 WEXITSTATUS(status
));
3893 cupsdLogMessage(CUPSD_LOG_ERROR
,
3894 "Unable to create SSL server key and certificate - "
3895 "the openssl command crashed on signal %d!",
3900 cupsdLogMessage(CUPSD_LOG_INFO
, "Created SSL server key file \"%s\"...",
3902 cupsdLogMessage(CUPSD_LOG_INFO
,
3903 "Created SSL server certificate file \"%s\"...",
3909 #elif defined(HAVE_GNUTLS)
3910 gnutls_x509_crt crt
; /* Self-signed certificate */
3911 gnutls_x509_privkey key
; /* Encryption key */
3912 cups_lang_t
*language
; /* Default language info */
3913 cups_file_t
*fp
; /* Key/cert file */
3914 unsigned char buffer
[8192]; /* Buffer for x509 data */
3915 size_t bytes
; /* Number of bytes of data */
3916 unsigned char serial
[4]; /* Serial number buffer */
3917 time_t curtime
; /* Current time */
3918 int result
; /* Result of GNU TLS calls */
3922 * Create the encryption key...
3925 cupsdLogMessage(CUPSD_LOG_INFO
, "Generating SSL server key...");
3927 gnutls_x509_privkey_init(&key
);
3928 gnutls_x509_privkey_generate(key
, GNUTLS_PK_RSA
, 2048, 0);
3934 bytes
= sizeof(buffer
);
3936 if ((result
= gnutls_x509_privkey_export(key
, GNUTLS_X509_FMT_PEM
,
3937 buffer
, &bytes
)) < 0)
3939 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to export SSL server key - %s",
3940 gnutls_strerror(result
));
3941 gnutls_x509_privkey_deinit(key
);
3944 else if ((fp
= cupsFileOpen(ServerKey
, "w")) != NULL
)
3946 cupsFileWrite(fp
, (char *)buffer
, bytes
);
3949 cupsdLogMessage(CUPSD_LOG_INFO
, "Created SSL server key file \"%s\"...",
3954 cupsdLogMessage(CUPSD_LOG_ERROR
,
3955 "Unable to create SSL server key file \"%s\" - %s",
3956 ServerKey
, strerror(errno
));
3957 gnutls_x509_privkey_deinit(key
);
3962 * Create the self-signed certificate...
3965 cupsdLogMessage(CUPSD_LOG_INFO
, "Generating self-signed SSL certificate...");
3967 language
= cupsLangDefault();
3968 curtime
= time(NULL
);
3969 serial
[0] = curtime
>> 24;
3970 serial
[1] = curtime
>> 16;
3971 serial
[2] = curtime
>> 8;
3972 serial
[3] = curtime
;
3974 gnutls_x509_crt_init(&crt
);
3975 if (strlen(language
->language
) == 5)
3976 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
3977 language
->language
+ 3, 2);
3979 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
3981 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COMMON_NAME
, 0,
3982 ServerName
, strlen(ServerName
));
3983 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATION_NAME
, 0,
3984 ServerName
, strlen(ServerName
));
3985 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATIONAL_UNIT_NAME
,
3987 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_STATE_OR_PROVINCE_NAME
, 0,
3989 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_LOCALITY_NAME
, 0,
3991 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_PKCS9_EMAIL
, 0,
3992 ServerAdmin
, strlen(ServerAdmin
));
3993 gnutls_x509_crt_set_key(crt
, key
);
3994 gnutls_x509_crt_set_serial(crt
, serial
, sizeof(serial
));
3995 gnutls_x509_crt_set_activation_time(crt
, curtime
);
3996 gnutls_x509_crt_set_expiration_time(crt
, curtime
+ 10 * 365 * 86400);
3997 gnutls_x509_crt_set_ca_status(crt
, 0);
3998 gnutls_x509_crt_set_subject_alternative_name(crt
, GNUTLS_SAN_DNSNAME
,
4000 gnutls_x509_crt_set_key_purpose_oid(crt
, GNUTLS_KP_TLS_WWW_SERVER
, 0);
4001 gnutls_x509_crt_set_key_usage(crt
, GNUTLS_KEY_KEY_ENCIPHERMENT
);
4002 gnutls_x509_crt_set_version(crt
, 3);
4004 bytes
= sizeof(buffer
);
4005 if (gnutls_x509_crt_get_key_id(crt
, 0, buffer
, &bytes
) >= 0)
4006 gnutls_x509_crt_set_subject_key_id(crt
, buffer
, bytes
);
4008 gnutls_x509_crt_sign(crt
, crt
, key
);
4014 bytes
= sizeof(buffer
);
4015 if ((result
= gnutls_x509_crt_export(crt
, GNUTLS_X509_FMT_PEM
,
4016 buffer
, &bytes
)) < 0)
4017 cupsdLogMessage(CUPSD_LOG_ERROR
,
4018 "Unable to export SSL server certificate - %s",
4019 gnutls_strerror(result
));
4020 else if ((fp
= cupsFileOpen(ServerCertificate
, "w")) != NULL
)
4022 cupsFileWrite(fp
, (char *)buffer
, bytes
);
4025 cupsdLogMessage(CUPSD_LOG_INFO
,
4026 "Created SSL server certificate file \"%s\"...",
4030 cupsdLogMessage(CUPSD_LOG_ERROR
,
4031 "Unable to create SSL server certificate file \"%s\" - %s",
4032 ServerCertificate
, strerror(errno
));
4038 gnutls_x509_crt_deinit(crt
);
4039 gnutls_x509_privkey_deinit(key
);
4043 #elif defined(HAVE_CDSASSL) && defined(HAVE_WAITPID)
4044 int pid
, /* Process ID of command */
4045 status
; /* Status of command */
4046 char command
[1024], /* Command */
4047 *argv
[4], /* Command-line arguments */
4048 *envp
[MAX_ENV
+ 1], /* Environment variables */
4049 keychain
[1024], /* Keychain argument */
4050 infofile
[1024]; /* Type-in information for cert */
4051 cups_file_t
*fp
; /* Seed/info file */
4052 int infofd
; /* Info file descriptor */
4056 * Run the "certtool" command to generate a self-signed certificate...
4059 if (!cupsFileFind("certtool", getenv("PATH"), 1, command
, sizeof(command
)))
4061 cupsdLogMessage(CUPSD_LOG_ERROR
,
4062 "No SSL certificate and certtool command not found!");
4067 * Create a file with the certificate information fields...
4069 * Note: This assumes that the default questions are asked by the certtool
4073 if ((fp
= cupsTempFile2(infofile
, sizeof(infofile
))) == NULL
)
4075 cupsdLogMessage(CUPSD_LOG_ERROR
,
4076 "Unable to create certificate information file %s - %s",
4077 infofile
, strerror(errno
));
4081 cupsFilePrintf(fp
, "%s\nr\n\ny\nb\ns\ny\n%s\n\n\n\n\n%s\ny\n",
4082 con
->servername
, con
->servername
, ServerAdmin
);
4085 cupsdLogMessage(CUPSD_LOG_INFO
,
4086 "Generating SSL server key and certificate...");
4088 snprintf(keychain
, sizeof(keychain
), "k=%s", ServerCertificate
);
4090 argv
[0] = "certtool";
4095 cupsdLoadEnv(envp
, MAX_ENV
);
4097 infofd
= open(infofile
, O_RDONLY
);
4099 if (!cupsdStartProcess(command
, argv
, envp
, infofd
, -1, -1, -1, -1, 1, &pid
))
4109 while (waitpid(pid
, &status
, 0) < 0)
4116 cupsdFinishProcess(pid
, command
, sizeof(command
));
4120 if (WIFEXITED(status
))
4121 cupsdLogMessage(CUPSD_LOG_ERROR
,
4122 "Unable to create SSL server key and certificate - "
4123 "the certtool command stopped with status %d!",
4124 WEXITSTATUS(status
));
4126 cupsdLogMessage(CUPSD_LOG_ERROR
,
4127 "Unable to create SSL server key and certificate - "
4128 "the certtool command crashed on signal %d!",
4133 cupsdLogMessage(CUPSD_LOG_INFO
,
4134 "Created SSL server certificate file \"%s\"...",
4142 #endif /* HAVE_LIBSSL && HAVE_WAITPID */
4144 #endif /* HAVE_SSL */
4148 * 'pipe_command()' - Pipe the output of a command to the remote client.
4151 static int /* O - Process ID */
4152 pipe_command(cupsd_client_t
*con
, /* I - Client connection */
4153 int infile
, /* I - Standard input for command */
4154 int *outfile
, /* O - Standard output for command */
4155 char *command
, /* I - Command to run */
4156 char *options
, /* I - Options for command */
4157 int root
) /* I - Run as root? */
4159 int i
; /* Looping var */
4160 int pid
; /* Process ID */
4161 char *commptr
, /* Command string pointer */
4162 commch
; /* Command string character */
4163 char *uriptr
; /* URI string pointer */
4164 int fds
[2]; /* Pipe FDs */
4165 int argc
; /* Number of arguments */
4166 int envc
; /* Number of environment variables */
4167 char argbuf
[10240], /* Argument buffer */
4168 *argv
[100], /* Argument strings */
4169 *envp
[MAX_ENV
+ 20]; /* Environment variables */
4170 char auth_type
[256], /* AUTH_TYPE environment variable */
4171 content_length
[1024], /* CONTENT_LENGTH environment variable */
4172 content_type
[1024], /* CONTENT_TYPE environment variable */
4173 http_cookie
[32768], /* HTTP_COOKIE environment variable */
4174 http_referer
[1024], /* HTTP_REFERER environment variable */
4175 http_user_agent
[1024], /* HTTP_USER_AGENT environment variable */
4176 lang
[1024], /* LANG environment variable */
4177 path_info
[1024], /* PATH_INFO environment variable */
4178 remote_addr
[1024], /* REMOTE_ADDR environment variable */
4179 remote_host
[1024], /* REMOTE_HOST environment variable */
4180 remote_user
[1024], /* REMOTE_USER environment variable */
4181 script_filename
[1024], /* SCRIPT_FILENAME environment variable */
4182 script_name
[1024], /* SCRIPT_NAME environment variable */
4183 server_name
[1024], /* SERVER_NAME environment variable */
4184 server_port
[1024]; /* SERVER_PORT environment variable */
4188 * Parse a copy of the options string, which is of the form:
4190 * argument+argument+argument
4191 * ?argument+argument+argument
4192 * param=value¶m=value
4193 * ?param=value¶m=value
4194 * /name?argument+argument+argument
4195 * /name?param=value¶m=value
4197 * If the string contains an "=" character after the initial name,
4198 * then we treat it as a HTTP GET form request and make a copy of
4199 * the remaining string for the environment variable.
4201 * The string is always parsed out as command-line arguments, to
4202 * be consistent with Apache...
4205 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4206 "pipe_command: command=\"%s\", options=\"%s\"",
4207 command
, options
? options
: "(null)");
4212 strlcpy(argbuf
, options
, sizeof(argbuf
));
4216 if (argbuf
[0] == '/')
4219 * Found some trailing path information, set PATH_INFO...
4222 if ((commptr
= strchr(argbuf
, '?')) == NULL
)
4223 commptr
= argbuf
+ strlen(argbuf
);
4227 snprintf(path_info
, sizeof(path_info
), "PATH_INFO=%s", argbuf
);
4233 path_info
[0] = '\0';
4235 if (*commptr
== ' ')
4239 cupsdLogMessage(CUPSD_LOG_INFO
, "commptr=\"%s\"", commptr
);
4241 if (*commptr
== '?' && con
->operation
== HTTP_GET
&& !con
->query_string
)
4244 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", commptr
);
4251 argv
[argc
++] = commptr
;
4253 for (; *commptr
&& argc
< 99; commptr
++)
4256 * Break arguments whenever we see a + or space...
4259 if (*commptr
== ' ' || *commptr
== '+')
4261 while (*commptr
== ' ' || *commptr
== '+')
4265 * If we don't have a blank string, save it as another argument...
4270 argv
[argc
] = commptr
;
4276 else if (*commptr
== '%' && isxdigit(commptr
[1] & 255) &&
4277 isxdigit(commptr
[2] & 255))
4280 * Convert the %xx notation to the individual character.
4283 if (commptr
[1] >= '0' && commptr
[1] <= '9')
4284 *commptr
= (commptr
[1] - '0') << 4;
4286 *commptr
= (tolower(commptr
[1]) - 'a' + 10) << 4;
4288 if (commptr
[2] >= '0' && commptr
[2] <= '9')
4289 *commptr
|= commptr
[2] - '0';
4291 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
4293 _cups_strcpy(commptr
+ 1, commptr
+ 3);
4296 * Check for a %00 and break if that is the case...
4308 * Setup the environment variables as needed...
4311 if (con
->username
[0])
4313 snprintf(auth_type
, sizeof(auth_type
), "AUTH_TYPE=%s",
4314 httpGetField(HTTP(con
), HTTP_FIELD_AUTHORIZATION
));
4316 if ((uriptr
= strchr(auth_type
+ 10, ' ')) != NULL
)
4320 auth_type
[0] = '\0';
4323 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF-8", con
->language
->language
);
4325 strcpy(lang
, "LANG=C");
4327 strcpy(remote_addr
, "REMOTE_ADDR=");
4328 httpAddrString(con
->http
.hostaddr
, remote_addr
+ 12,
4329 sizeof(remote_addr
) - 12);
4331 snprintf(remote_host
, sizeof(remote_host
), "REMOTE_HOST=%s",
4332 con
->http
.hostname
);
4334 snprintf(script_name
, sizeof(script_name
), "SCRIPT_NAME=%s", con
->uri
);
4335 if ((uriptr
= strchr(script_name
, '?')) != NULL
)
4338 snprintf(script_filename
, sizeof(script_filename
), "SCRIPT_FILENAME=%s%s",
4339 DocumentRoot
, script_name
+ 12);
4341 sprintf(server_port
, "SERVER_PORT=%d", con
->serverport
);
4343 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
4346 envc
= cupsdLoadEnv(envp
, (int)(sizeof(envp
) / sizeof(envp
[0])));
4349 envp
[envc
++] = auth_type
;
4351 envp
[envc
++] = lang
;
4352 envp
[envc
++] = "REDIRECT_STATUS=1";
4353 envp
[envc
++] = "GATEWAY_INTERFACE=CGI/1.1";
4354 envp
[envc
++] = server_name
;
4355 envp
[envc
++] = server_port
;
4356 envp
[envc
++] = remote_addr
;
4357 envp
[envc
++] = remote_host
;
4358 envp
[envc
++] = script_name
;
4359 envp
[envc
++] = script_filename
;
4362 envp
[envc
++] = path_info
;
4364 if (con
->username
[0])
4366 snprintf(remote_user
, sizeof(remote_user
), "REMOTE_USER=%s", con
->username
);
4368 envp
[envc
++] = remote_user
;
4371 if (con
->http
.version
== HTTP_1_1
)
4372 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.1";
4373 else if (con
->http
.version
== HTTP_1_0
)
4374 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.0";
4376 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/0.9";
4378 if (con
->http
.cookie
)
4380 snprintf(http_cookie
, sizeof(http_cookie
), "HTTP_COOKIE=%s",
4382 envp
[envc
++] = http_cookie
;
4385 if (con
->http
.fields
[HTTP_FIELD_USER_AGENT
][0])
4387 snprintf(http_user_agent
, sizeof(http_user_agent
), "HTTP_USER_AGENT=%s",
4388 con
->http
.fields
[HTTP_FIELD_USER_AGENT
]);
4389 envp
[envc
++] = http_user_agent
;
4392 if (con
->http
.fields
[HTTP_FIELD_REFERER
][0])
4394 snprintf(http_referer
, sizeof(http_referer
), "HTTP_REFERER=%s",
4395 con
->http
.fields
[HTTP_FIELD_REFERER
]);
4396 envp
[envc
++] = http_referer
;
4399 if (con
->operation
== HTTP_GET
)
4401 envp
[envc
++] = "REQUEST_METHOD=GET";
4403 if (con
->query_string
)
4406 * Add GET form variables after ?...
4409 envp
[envc
++] = con
->query_string
;
4414 sprintf(content_length
, "CONTENT_LENGTH=" CUPS_LLFMT
,
4415 CUPS_LLCAST con
->bytes
);
4416 snprintf(content_type
, sizeof(content_type
), "CONTENT_TYPE=%s",
4417 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
4419 envp
[envc
++] = "REQUEST_METHOD=POST";
4420 envp
[envc
++] = content_length
;
4421 envp
[envc
++] = content_type
;
4425 * Tell the CGI if we are using encryption...
4429 envp
[envc
++] = "HTTPS=ON";
4432 * Terminate the environment array...
4437 if (LogLevel
== CUPSD_LOG_DEBUG2
)
4439 for (i
= 0; i
< argc
; i
++)
4440 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4441 "pipe_command: argv[%d] = \"%s\"", i
, argv
[i
]);
4442 for (i
= 0; i
< envc
; i
++)
4443 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4444 "pipe_command: envp[%d] = \"%s\"", i
, envp
[i
]);
4448 * Create a pipe for the output...
4451 if (cupsdOpenPipe(fds
))
4453 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to create pipes for CGI %s - %s",
4454 argv
[0], strerror(errno
));
4459 * Then execute the command...
4462 if (cupsdStartProcess(command
, argv
, envp
, infile
, fds
[1], CGIPipes
[1],
4463 -1, -1, root
, &pid
) < 0)
4466 * Error - can't fork!
4469 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to fork for CGI %s - %s", argv
[0],
4472 cupsdClosePipe(fds
);
4478 * Fork successful - return the PID...
4481 if (con
->username
[0])
4482 cupsdAddCert(pid
, con
->username
);
4484 cupsdLogMessage(CUPSD_LOG_DEBUG
, "CGI %s started - PID = %d", command
, pid
);
4495 * 'write_file()' - Send a file via HTTP.
4498 static int /* O - 0 on failure, 1 on success */
4499 write_file(cupsd_client_t
*con
, /* I - Client connection */
4500 http_status_t code
, /* I - HTTP status */
4501 char *filename
, /* I - Filename */
4502 char *type
, /* I - File type */
4503 struct stat
*filestats
) /* O - File information */
4505 con
->file
= open(filename
, O_RDONLY
);
4507 cupsdLogMessage(CUPSD_LOG_DEBUG
, "write_file: %d file=%d", con
->http
.fd
,
4513 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
4517 if (!cupsdSendHeader(con
, code
, type
, AUTH_NONE
))
4520 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
4521 httpGetDateString(filestats
->st_mtime
)) < 0)
4523 if (httpPrintf(HTTP(con
), "Content-Length: " CUPS_LLFMT
"\r\n",
4524 CUPS_LLCAST filestats
->st_size
) < 0)
4526 if (httpPrintf(HTTP(con
), "\r\n") < 0)
4529 if (cupsdFlushHeader(con
) < 0)
4532 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
4533 con
->http
.data_remaining
= filestats
->st_size
;
4535 if (con
->http
.data_remaining
<= INT_MAX
)
4536 con
->http
._data_remaining
= con
->http
.data_remaining
;
4538 con
->http
._data_remaining
= INT_MAX
;
4540 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
,
4541 (cupsd_selfunc_t
)cupsdWriteClient
, con
);
4548 * 'write_pipe()' - Flag that data is available on the CGI pipe.
4552 write_pipe(cupsd_client_t
*con
) /* I - Client connection */
4554 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "write_pipe: CGI output on fd %d...",
4557 con
->file_ready
= 1;
4559 cupsdRemoveSelect(con
->file
);
4560 cupsdAddSelect(con
->http
.fd
, NULL
, (cupsd_selfunc_t
)cupsdWriteClient
, con
);
4565 * End of "$Id: client.c 6504 2007-05-02 00:14:56Z mike $".