2 * "$Id: client.c 6361 2007-03-19 16:01:28Z 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 * cupsdWritePipe() - Flag that data is available on the CGI pipe.
40 * check_if_modified() - Decode an "If-Modified-Since" line.
41 * encrypt_client() - Enable encryption for the client...
42 * get_cdsa_certificate() - Convert a keychain name into the CFArrayRef
43 * required by SSLSetCertificate.
44 * get_file() - Get a filename and state info.
45 * install_conf_file() - Install a configuration file.
46 * is_cgi() - Is the resource a CGI script/program?
47 * is_path_absolute() - Is a path absolute and free of relative elements.
48 * make_certificate() - Make a self-signed SSL/TLS certificate.
49 * pipe_command() - Pipe the output of a command to the remote client.
50 * write_file() - Send a file via HTTP.
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
);
118 * 'cupsdAcceptClient()' - Accept a new client.
122 cupsdAcceptClient(cupsd_listener_t
*lis
)/* I - Listener socket */
124 int count
; /* Count of connections on a host */
125 int val
; /* Parameter value */
126 cupsd_client_t
*con
, /* New client pointer */
127 *tempcon
; /* Temporary client pointer */
128 http_addrlist_t
*addrlist
, /* List of adddresses for host */
129 *addr
; /* Current address */
130 socklen_t addrlen
; /* Length of address */
131 char *hostname
; /* Hostname for address */
132 http_addr_t temp
; /* Temporary address variable */
133 static time_t last_dos
= 0; /* Time of last DoS attack */
136 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
137 "cupsdAcceptClient(lis=%p) %d Clients = %d",
138 lis
, lis
->fd
, cupsArrayCount(Clients
));
141 * Make sure we don't have a full set of clients already...
144 if (cupsArrayCount(Clients
) == MaxClients
)
148 * Get a pointer to the next available client...
152 Clients
= cupsArrayNew(NULL
, NULL
);
157 con
= calloc(1, sizeof(cupsd_client_t
));
159 con
->http
.activity
= time(NULL
);
161 con
->http
.hostaddr
= &(con
->clientaddr
);
164 * Accept the client and get the remote address...
167 addrlen
= sizeof(http_addr_t
);
169 if ((con
->http
.fd
= accept(lis
->fd
, (struct sockaddr
*)con
->http
.hostaddr
,
172 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to accept client connection - %s.",
179 if (lis
->address
.addr
.sa_family
== AF_INET6
)
182 * Save the connected port number...
185 con
->http
.hostaddr
->ipv6
.sin6_port
= lis
->address
.ipv6
.sin6_port
;
188 * Convert IPv4 over IPv6 addresses (::ffff:n.n.n.n) to IPv4 forms we
189 * can more easily use...
192 if (con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[0] == 0 &&
193 con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[1] == 0 &&
194 ntohl(con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[2]) == 0xffff)
195 con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[2] = 0;
198 #endif /* AF_INET6 */
199 if (lis
->address
.addr
.sa_family
== AF_INET
)
200 con
->http
.hostaddr
->ipv4
.sin_port
= lis
->address
.ipv4
.sin_port
;
203 * Check the number of clients on the same address...
206 for (count
= 0, tempcon
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
208 tempcon
= (cupsd_client_t
*)cupsArrayNext(Clients
))
209 if (httpAddrEqual(tempcon
->http
.hostaddr
, con
->http
.hostaddr
))
212 if (count
>= MaxClientsPerHost
)
216 if (count
>= MaxClientsPerHost
)
218 if ((time(NULL
) - last_dos
) >= 60)
220 last_dos
= time(NULL
);
221 cupsdLogMessage(CUPSD_LOG_WARN
,
222 "Possible DoS attack - more than %d clients connecting "
224 MaxClientsPerHost
, tempcon
->http
.hostname
);
228 closesocket(con
->http
.fd
);
238 * Get the hostname or format the IP address as needed...
241 if (httpAddrLocalhost(con
->http
.hostaddr
))
244 * Map accesses from the loopback interface to "localhost"...
247 strlcpy(con
->http
.hostname
, "localhost", sizeof(con
->http
.hostname
));
248 hostname
= con
->http
.hostname
;
253 * Map accesses from the same host to the server name.
256 for (addr
= ServerAddrs
; addr
; addr
= addr
->next
)
257 if (httpAddrEqual(con
->http
.hostaddr
, &(addr
->addr
)))
262 strlcpy(con
->http
.hostname
, ServerName
, sizeof(con
->http
.hostname
));
263 hostname
= con
->http
.hostname
;
265 else if (HostNameLookups
)
266 hostname
= httpAddrLookup(con
->http
.hostaddr
, con
->http
.hostname
,
267 sizeof(con
->http
.hostname
));
271 httpAddrString(con
->http
.hostaddr
, con
->http
.hostname
,
272 sizeof(con
->http
.hostname
));
276 if (hostname
== NULL
&& HostNameLookups
== 2)
279 * Can't have an unresolved IP address with double-lookups enabled...
282 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
283 "cupsdAcceptClient: Closing connection %d...",
287 closesocket(con
->http
.fd
);
292 cupsdLogMessage(CUPSD_LOG_WARN
,
293 "Name lookup failed - connection from %s closed!",
300 if (HostNameLookups
== 2)
303 * Do double lookups as needed...
306 if ((addrlist
= httpAddrGetList(con
->http
.hostname
, AF_UNSPEC
, NULL
)) != NULL
)
309 * See if the hostname maps to the same IP address...
312 for (addr
= addrlist
; addr
; addr
= addr
->next
)
313 if (httpAddrEqual(con
->http
.hostaddr
, &(addr
->addr
)))
319 httpAddrFreeList(addrlist
);
324 * Can't have a hostname that doesn't resolve to the same IP address
325 * with double-lookups enabled...
328 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
329 "cupsdAcceptClient: Closing connection %d...",
333 closesocket(con
->http
.fd
);
338 cupsdLogMessage(CUPSD_LOG_WARN
,
339 "IP lookup failed - connection from %s closed!",
347 if (con
->http
.hostaddr
->addr
.sa_family
== AF_INET6
)
348 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdAcceptClient: %d from %s:%d (IPv6)",
349 con
->http
.fd
, con
->http
.hostname
,
350 ntohs(con
->http
.hostaddr
->ipv6
.sin6_port
));
352 #endif /* AF_INET6 */
354 if (con
->http
.hostaddr
->addr
.sa_family
== AF_LOCAL
)
355 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdAcceptClient: %d from %s (Domain)",
356 con
->http
.fd
, con
->http
.hostname
);
358 #endif /* AF_LOCAL */
359 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdAcceptClient: %d from %s:%d (IPv4)",
360 con
->http
.fd
, con
->http
.hostname
,
361 ntohs(con
->http
.hostaddr
->ipv4
.sin_port
));
364 * Get the local address the client connected to...
367 addrlen
= sizeof(temp
);
368 if (getsockname(con
->http
.fd
, (struct sockaddr
*)&temp
, &addrlen
))
370 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to get local address - %s",
373 strcpy(con
->servername
, "localhost");
374 con
->serverport
= LocalPort
;
379 if (temp
.addr
.sa_family
== AF_INET6
)
381 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
382 con
->serverport
= ntohs(lis
->address
.ipv6
.sin6_port
);
385 #endif /* AF_INET6 */
386 if (temp
.addr
.sa_family
== AF_INET
)
388 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
389 con
->serverport
= ntohs(lis
->address
.ipv4
.sin_port
);
393 strcpy(con
->servername
, "localhost");
394 con
->serverport
= LocalPort
;
398 cupsArrayAdd(Clients
, con
);
400 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
401 "cupsdAcceptClient: %d connected to server on %s:%d",
402 con
->http
.fd
, con
->servername
, con
->serverport
);
405 * Using TCP_NODELAY improves responsiveness, especially on systems
406 * with a slow loopback interface... Since we write large buffers
407 * when sending print files and requests, there shouldn't be any
408 * performance penalty for this...
412 setsockopt(con
->http
.fd
, IPPROTO_TCP
, TCP_NODELAY
, &val
, sizeof(val
));
415 * Close this file on all execs...
418 fcntl(con
->http
.fd
, F_SETFD
, fcntl(con
->http
.fd
, F_GETFD
) | FD_CLOEXEC
);
421 * Add the socket to the select() input mask.
424 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
427 * Temporarily suspend accept()'s until we lose a client...
430 if (cupsArrayCount(Clients
) == MaxClients
)
431 cupsdPauseListening();
435 * See if we are connecting on a secure port...
438 if (lis
->encryption
== HTTP_ENCRYPT_ALWAYS
)
441 * https connection; go secure...
444 con
->http
.encryption
= HTTP_ENCRYPT_ALWAYS
;
446 if (!encrypt_client(con
))
447 cupsdCloseClient(con
);
451 #endif /* HAVE_SSL */
456 * 'cupsdCloseAllClients()' - Close all remote clients immediately.
460 cupsdCloseAllClients(void)
462 cupsd_client_t
*con
; /* Current client */
465 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
467 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
468 cupsdCloseClient(con
);
473 * 'cupsdCloseClient()' - Close a remote client.
476 int /* O - 1 if partial close, 0 if fully closed */
477 cupsdCloseClient(cupsd_client_t
*con
) /* I - Client to close */
479 int partial
; /* Do partial close for SSL? */
481 SSL_CTX
*context
; /* Context for encryption */
482 SSL
*conn
; /* Connection for encryption */
483 unsigned long error
; /* Error code */
484 #elif defined(HAVE_GNUTLS)
485 http_tls_t
*conn
; /* TLS connection information */
486 int error
; /* Error code */
487 gnutls_certificate_server_credentials
*credentials
;
488 /* TLS credentials */
489 # elif defined(HAVE_CDSASSL)
490 http_tls_t
*conn
; /* CDSA connection information */
491 #endif /* HAVE_LIBSSL */
494 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdCloseClient: %d", con
->http
.fd
);
497 * Flush pending writes before closing...
500 httpFlushWrite(HTTP(con
));
506 * Shutdown encryption as needed...
514 conn
= (SSL
*)(con
->http
.tls
);
515 context
= SSL_get_SSL_CTX(conn
);
517 switch (SSL_shutdown(conn
))
520 cupsdLogMessage(CUPSD_LOG_INFO
,
521 "cupsdCloseClient: SSL shutdown successful!");
524 cupsdLogMessage(CUPSD_LOG_ERROR
,
525 "cupsdCloseClient: Fatal error during SSL shutdown!");
527 while ((error
= ERR_get_error()) != 0)
528 cupsdLogMessage(CUPSD_LOG_ERROR
, "cupsdCloseClient: %s",
529 ERR_error_string(error
, NULL
));
533 SSL_CTX_free(context
);
536 # elif defined(HAVE_GNUTLS)
537 conn
= (http_tls_t
*)(con
->http
.tls
);
538 credentials
= (gnutls_certificate_server_credentials
*)(conn
->credentials
);
540 error
= gnutls_bye(conn
->session
, GNUTLS_SHUT_WR
);
543 case GNUTLS_E_SUCCESS
:
544 cupsdLogMessage(CUPSD_LOG_INFO
,
545 "cupsdCloseClient: SSL shutdown successful!");
548 cupsdLogMessage(CUPSD_LOG_ERROR
,
549 "cupsdCloseClient: %s", gnutls_strerror(error
));
553 gnutls_deinit(conn
->session
);
554 gnutls_certificate_free_credentials(*credentials
);
558 # elif defined(HAVE_CDSASSL)
559 conn
= (http_tls_t
*)(con
->http
.tls
);
561 while (SSLClose(conn
->session
) == errSSLWouldBlock
)
564 SSLDisposeContext(conn
->session
);
566 if (conn
->certsArray
)
567 CFRelease(conn
->certsArray
);
570 # endif /* HAVE_LIBSSL */
572 con
->http
.tls
= NULL
;
574 #endif /* HAVE_SSL */
576 if (con
->pipe_pid
!= 0)
579 * Stop any CGI process...
582 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
583 "cupsdCloseClient: %d Killing process ID %d...",
584 con
->http
.fd
, con
->pipe_pid
);
585 cupsdEndProcess(con
->pipe_pid
, 1);
591 cupsdRemoveSelect(con
->file
);
593 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
594 "cupsdCloseClient: %d Closing data file %d.",
595 con
->http
.fd
, con
->file
);
602 * Close the socket and clear the file from the input set for select()...
605 if (con
->http
.fd
> 0)
610 * Only do a partial close so that the encrypted client gets everything.
613 shutdown(con
->http
.fd
, 0);
614 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
619 * Shut the socket down fully...
622 cupsdRemoveSelect(con
->http
.fd
);
634 if (con
->http
.input_set
)
635 free(con
->http
.input_set
);
637 httpClearCookie(HTTP(con
));
639 cupsdClearString(&con
->filename
);
640 cupsdClearString(&con
->command
);
641 cupsdClearString(&con
->options
);
642 cupsdClearString(&con
->query_string
);
646 ippDelete(con
->request
);
652 ippDelete(con
->response
);
653 con
->response
= NULL
;
658 cupsLangFree(con
->language
);
659 con
->language
= NULL
;
662 #ifdef HAVE_AUTHORIZATION_H
665 AuthorizationFree(con
->authref
, kAuthorizationFlagDefaults
);
668 #endif /* HAVE_AUTHORIZATION_H */
671 * Re-enable new client connections if we are going back under the
675 if (cupsArrayCount(Clients
) == MaxClients
)
676 cupsdResumeListening();
679 * Compact the list of clients as necessary...
682 cupsArrayRemove(Clients
, con
);
692 * 'cupsdFlushHeader()' - Flush the header fields to the client.
695 int /* I - Bytes written or -1 on error */
696 cupsdFlushHeader(cupsd_client_t
*con
) /* I - Client to flush to */
698 int bytes
= httpFlushWrite(HTTP(con
));
700 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
707 * 'cupsdReadClient()' - Read data from a client.
711 cupsdReadClient(cupsd_client_t
*con
) /* I - Client to read from */
713 char line
[32768], /* Line from client... */
714 operation
[64], /* Operation code from socket */
715 version
[64], /* HTTP version number string */
716 locale
[64], /* Locale */
717 *ptr
; /* Pointer into strings */
718 int major
, minor
; /* HTTP version numbers */
719 http_status_t status
; /* Transfer status */
720 ipp_state_t ipp_state
; /* State of IPP transfer */
721 int bytes
; /* Number of bytes to POST */
722 char *filename
; /* Name of file for GET/HEAD */
723 char buf
[1024]; /* Buffer for real filename */
724 struct stat filestats
; /* File information */
725 mime_type_t
*type
; /* MIME type of file */
726 cupsd_printer_t
*p
; /* Printer */
727 static unsigned request_id
= 0; /* Request ID for temp files */
730 status
= HTTP_CONTINUE
;
732 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
733 "cupsdReadClient: %d, used=%d, file=%d state=%d",
734 con
->http
.fd
, con
->http
.used
, con
->file
, con
->http
.state
);
738 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdReadClient: http error seen...");
739 cupsdCloseClient(con
);
747 * Automatically check for a SSL/TLS handshake...
752 if (recv(con
->http
.fd
, buf
, 1, MSG_PEEK
) == 1 &&
753 (!buf
[0] || !strchr("DGHOPT", buf
[0])))
756 * Encrypt this connection...
759 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
760 "cupsdReadClient: Saw first byte %02X, auto-negotiating SSL/TLS session...",
763 if (!encrypt_client(con
))
764 cupsdCloseClient(con
);
769 #endif /* HAVE_SSL */
771 switch (con
->http
.state
)
775 * See if we've received a request line...
778 if (httpGets(line
, sizeof(line
) - 1, HTTP(con
)) == NULL
)
780 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
781 "cupsdReadClient: httpGets returned EOF...");
782 cupsdCloseClient(con
);
787 * Ignore blank request lines...
794 * Clear other state variables...
797 httpClearFields(HTTP(con
));
799 con
->http
.activity
= time(NULL
);
800 con
->http
.version
= HTTP_1_0
;
801 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
802 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
803 con
->http
.data_remaining
= 0;
804 con
->http
._data_remaining
= 0;
805 con
->operation
= HTTP_WAITING
;
810 con
->username
[0] = '\0';
811 con
->password
[0] = '\0';
814 cupsdClearString(&con
->command
);
815 cupsdClearString(&con
->options
);
816 cupsdClearString(&con
->query_string
);
820 ippDelete(con
->request
);
826 ippDelete(con
->response
);
827 con
->response
= NULL
;
832 cupsLangFree(con
->language
);
833 con
->language
= NULL
;
837 * Grab the request line...
840 switch (sscanf(line
, "%63s%1023s%63s", operation
, con
->uri
, version
))
843 cupsdLogMessage(CUPSD_LOG_ERROR
,
844 "Bad request line \"%s\" from %s!", line
,
846 cupsdSendError(con
, HTTP_BAD_REQUEST
);
847 cupsdCloseClient(con
);
850 con
->http
.version
= HTTP_0_9
;
853 if (sscanf(version
, "HTTP/%d.%d", &major
, &minor
) != 2)
855 cupsdLogMessage(CUPSD_LOG_ERROR
,
856 "Bad request line \"%s\" from %s!", line
,
858 cupsdSendError(con
, HTTP_BAD_REQUEST
);
859 cupsdCloseClient(con
);
865 con
->http
.version
= (http_version_t
)(major
* 100 + minor
);
866 if (con
->http
.version
== HTTP_1_1
&& KeepAlive
)
867 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
869 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
873 cupsdSendError(con
, HTTP_NOT_SUPPORTED
);
874 cupsdCloseClient(con
);
881 * Handle full URLs in the request line...
884 if (strcmp(con
->uri
, "*"))
886 char method
[HTTP_MAX_URI
], /* Method/scheme */
887 userpass
[HTTP_MAX_URI
], /* Username:password */
888 hostname
[HTTP_MAX_URI
], /* Hostname */
889 resource
[HTTP_MAX_URI
]; /* Resource path */
890 int port
; /* Port number */
894 * Separate the URI into its components...
897 httpSeparateURI(HTTP_URI_CODING_MOST
, con
->uri
,
898 method
, sizeof(method
),
899 userpass
, sizeof(userpass
),
900 hostname
, sizeof(hostname
), &port
,
901 resource
, sizeof(resource
));
904 * Only allow URIs with the servername, localhost, or an IP
908 if (strcmp(method
, "file") &&
909 strcasecmp(hostname
, ServerName
) &&
910 strcasecmp(hostname
, "localhost") &&
911 !isdigit(hostname
[0]))
914 * Nope, we don't do proxies...
917 cupsdLogMessage(CUPSD_LOG_ERROR
, "Bad URI \"%s\" in request!",
919 cupsdSendError(con
, HTTP_METHOD_NOT_ALLOWED
);
920 cupsdCloseClient(con
);
925 * Copy the resource portion back into the URI; both resource and
926 * con->uri are HTTP_MAX_URI bytes in size...
929 strcpy(con
->uri
, resource
);
933 * Process the request...
936 if (!strcmp(operation
, "GET"))
937 con
->http
.state
= HTTP_GET
;
938 else if (!strcmp(operation
, "PUT"))
939 con
->http
.state
= HTTP_PUT
;
940 else if (!strcmp(operation
, "POST"))
941 con
->http
.state
= HTTP_POST
;
942 else if (!strcmp(operation
, "DELETE"))
943 con
->http
.state
= HTTP_DELETE
;
944 else if (!strcmp(operation
, "TRACE"))
945 con
->http
.state
= HTTP_TRACE
;
946 else if (!strcmp(operation
, "OPTIONS"))
947 con
->http
.state
= HTTP_OPTIONS
;
948 else if (!strcmp(operation
, "HEAD"))
949 con
->http
.state
= HTTP_HEAD
;
952 cupsdLogMessage(CUPSD_LOG_ERROR
, "Bad operation \"%s\"!", operation
);
953 cupsdSendError(con
, HTTP_BAD_REQUEST
);
954 cupsdCloseClient(con
);
958 con
->start
= time(NULL
);
959 con
->operation
= con
->http
.state
;
961 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdReadClient: %d %s %s HTTP/%d.%d",
962 con
->http
.fd
, operation
, con
->uri
,
963 con
->http
.version
/ 100, con
->http
.version
% 100);
965 con
->http
.status
= HTTP_OK
;
975 * Parse incoming parameters until the status changes...
978 while ((status
= httpUpdate(HTTP(con
))) == HTTP_CONTINUE
)
979 if (con
->http
.used
== 0 ||
980 !memchr(con
->http
.buffer
, '\n', con
->http
.used
))
983 if (status
!= HTTP_OK
&& status
!= HTTP_CONTINUE
)
985 cupsdSendError(con
, HTTP_BAD_REQUEST
);
986 cupsdCloseClient(con
);
992 break; /* Anti-compiler-warning-code */
996 * Handle new transfers...
999 if (status
== HTTP_OK
)
1001 if (con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
][0])
1004 * Figure out the locale from the Accept-Language and Content-Type
1008 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ',')) != NULL
)
1011 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ';')) != NULL
)
1014 if ((ptr
= strstr(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
], "charset=")) != NULL
)
1017 * Combine language and charset, and trim any extra params in the
1021 snprintf(locale
, sizeof(locale
), "%s.%s",
1022 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ptr
+ 8);
1024 if ((ptr
= strchr(locale
, ',')) != NULL
)
1028 snprintf(locale
, sizeof(locale
), "%s.%s",
1029 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], DefaultCharset
);
1031 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1032 "cupsdReadClient: %d Browser asked for language \"%s\"...",
1033 con
->http
.fd
, locale
);
1035 con
->language
= cupsLangGet(locale
);
1038 con
->language
= cupsLangGet(DefaultLocale
);
1040 cupsdAuthorize(con
);
1042 if (!strncmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Keep-Alive", 10) &&
1044 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
1046 if (!con
->http
.fields
[HTTP_FIELD_HOST
][0] &&
1047 con
->http
.version
>= HTTP_1_1
)
1050 * HTTP/1.1 and higher require the "Host:" field...
1053 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
))
1055 cupsdCloseClient(con
);
1059 else if (con
->operation
== HTTP_OPTIONS
)
1062 * Do OPTIONS command...
1065 if (con
->best
&& con
->best
->type
!= AUTH_NONE
)
1067 if (!cupsdSendHeader(con
, HTTP_UNAUTHORIZED
, NULL
))
1069 cupsdCloseClient(con
);
1074 if (!strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") &&
1075 con
->http
.tls
== NULL
)
1079 * Do encryption stuff...
1082 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
))
1084 cupsdCloseClient(con
);
1088 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1089 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1090 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1091 httpPrintf(HTTP(con
), "\r\n");
1093 if (cupsdFlushHeader(con
) < 0)
1095 cupsdCloseClient(con
);
1099 if (!encrypt_client(con
))
1101 cupsdCloseClient(con
);
1105 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
))
1107 cupsdCloseClient(con
);
1110 #endif /* HAVE_SSL */
1113 if (!cupsdSendHeader(con
, HTTP_OK
, NULL
))
1115 cupsdCloseClient(con
);
1119 httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n");
1120 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1121 httpPrintf(HTTP(con
), "\r\n");
1123 if (cupsdFlushHeader(con
) < 0)
1125 cupsdCloseClient(con
);
1129 else if (!is_path_absolute(con
->uri
))
1132 * Protect against malicious users!
1135 if (!cupsdSendError(con
, HTTP_FORBIDDEN
))
1137 cupsdCloseClient(con
);
1143 if (!strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") &&
1144 con
->http
.tls
== NULL
)
1148 * Do encryption stuff...
1151 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
))
1153 cupsdCloseClient(con
);
1157 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1158 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1159 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1160 httpPrintf(HTTP(con
), "\r\n");
1162 if (cupsdFlushHeader(con
) < 0)
1164 cupsdCloseClient(con
);
1168 if (!encrypt_client(con
))
1170 cupsdCloseClient(con
);
1174 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
))
1176 cupsdCloseClient(con
);
1179 #endif /* HAVE_SSL */
1182 if ((status
= cupsdIsAuthorized(con
, NULL
)) != HTTP_OK
)
1184 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1185 "cupsdReadClient: Unauthorized request for %s...\n",
1187 cupsdSendError(con
, status
);
1188 cupsdCloseClient(con
);
1192 if (con
->http
.expect
&&
1193 (con
->operation
== HTTP_POST
|| con
->operation
== HTTP_PUT
))
1195 if (con
->http
.expect
== HTTP_CONTINUE
)
1198 * Send 100-continue header...
1201 if (!cupsdSendHeader(con
, HTTP_CONTINUE
, NULL
))
1203 cupsdCloseClient(con
);
1210 * Send 417-expectation-failed header...
1213 if (!cupsdSendHeader(con
, HTTP_EXPECTATION_FAILED
, NULL
))
1215 cupsdCloseClient(con
);
1219 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1220 httpPrintf(HTTP(con
), "\r\n");
1222 if (cupsdFlushHeader(con
) < 0)
1224 cupsdCloseClient(con
);
1230 switch (con
->http
.state
)
1232 case HTTP_GET_SEND
:
1233 if (!strncmp(con
->uri
, "/printers/", 10) &&
1234 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1237 * Send PPD file - get the real printer name since printer
1238 * names are not case sensitive but filenames can be...
1241 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1243 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1244 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1247 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
1249 cupsdCloseClient(con
);
1257 if ((!strncmp(con
->uri
, "/admin", 6) &&
1258 strncmp(con
->uri
, "/admin/conf/", 12) &&
1259 strncmp(con
->uri
, "/admin/log/", 11)) ||
1260 !strncmp(con
->uri
, "/printers", 9) ||
1261 !strncmp(con
->uri
, "/classes", 8) ||
1262 !strncmp(con
->uri
, "/help", 5) ||
1263 !strncmp(con
->uri
, "/jobs", 5))
1266 * Send CGI output...
1269 if (!strncmp(con
->uri
, "/admin", 6))
1271 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1274 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1276 else if (!strncmp(con
->uri
, "/printers", 9))
1278 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1281 if (con
->uri
[9] && con
->uri
[10])
1282 cupsdSetString(&con
->options
, con
->uri
+ 9);
1284 cupsdSetString(&con
->options
, NULL
);
1286 else if (!strncmp(con
->uri
, "/classes", 8))
1288 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1291 if (con
->uri
[8] && con
->uri
[9])
1292 cupsdSetString(&con
->options
, con
->uri
+ 8);
1294 cupsdSetString(&con
->options
, NULL
);
1296 else if (!strncmp(con
->uri
, "/jobs", 5))
1298 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1301 if (con
->uri
[5] && con
->uri
[6])
1302 cupsdSetString(&con
->options
, con
->uri
+ 5);
1304 cupsdSetString(&con
->options
, NULL
);
1308 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1311 if (con
->uri
[5] && con
->uri
[6])
1312 cupsdSetString(&con
->options
, con
->uri
+ 5);
1314 cupsdSetString(&con
->options
, NULL
);
1317 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1319 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
1321 cupsdCloseClient(con
);
1326 cupsdLogRequest(con
, HTTP_OK
);
1328 if (con
->http
.version
<= HTTP_1_0
)
1329 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1331 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1332 (strchr(con
->uri
+ 12, '/') ||
1333 strlen(con
->uri
) == 12)) ||
1334 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1335 (strchr(con
->uri
+ 11, '/') ||
1336 strlen(con
->uri
) == 11)))
1339 * GET can only be done to configuration files under
1343 if (!cupsdSendError(con
, HTTP_FORBIDDEN
))
1345 cupsdCloseClient(con
);
1357 if ((filename
= get_file(con
, &filestats
, buf
,
1358 sizeof(buf
))) == NULL
)
1360 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
1362 cupsdCloseClient(con
);
1369 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1371 if (is_cgi(con
, filename
, &filestats
, type
))
1374 * Note: con->command and con->options were set by
1378 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1380 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
1382 cupsdCloseClient(con
);
1387 cupsdLogRequest(con
, HTTP_OK
);
1389 if (con
->http
.version
<= HTTP_1_0
)
1390 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1394 if (!check_if_modified(con
, &filestats
))
1396 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
))
1398 cupsdCloseClient(con
);
1405 strcpy(line
, "text/plain");
1407 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1409 if (!write_file(con
, HTTP_OK
, filename
, line
, &filestats
))
1411 cupsdCloseClient(con
);
1418 case HTTP_POST_RECV
:
1420 * See if the POST request includes a Content-Length field, and if
1421 * so check the length against any limits that are set...
1424 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "POST %s", con
->uri
);
1425 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "CONTENT_TYPE = %s",
1426 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
1428 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1429 MaxRequestSize
> 0 &&
1430 con
->http
.data_remaining
> MaxRequestSize
)
1433 * Request too large...
1436 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1438 cupsdCloseClient(con
);
1444 else if (con
->http
.data_remaining
< 0)
1447 * Negative content lengths are invalid!
1450 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
))
1452 cupsdCloseClient(con
);
1460 * See what kind of POST request this is; for IPP requests the
1461 * content-type field will be "application/ipp"...
1464 if (!strcmp(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
],
1466 con
->request
= ippNew();
1467 else if ((!strncmp(con
->uri
, "/admin", 6) &&
1468 strncmp(con
->uri
, "/admin/conf/", 12) &&
1469 strncmp(con
->uri
, "/admin/log/", 11)) ||
1470 !strncmp(con
->uri
, "/printers", 9) ||
1471 !strncmp(con
->uri
, "/classes", 8) ||
1472 !strncmp(con
->uri
, "/help", 5) ||
1473 !strncmp(con
->uri
, "/jobs", 5))
1479 if (!strncmp(con
->uri
, "/admin", 6))
1481 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1484 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1486 else if (!strncmp(con
->uri
, "/printers", 9))
1488 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1491 if (con
->uri
[9] && con
->uri
[10])
1492 cupsdSetString(&con
->options
, con
->uri
+ 9);
1494 cupsdSetString(&con
->options
, NULL
);
1496 else if (!strncmp(con
->uri
, "/classes", 8))
1498 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1501 if (con
->uri
[8] && con
->uri
[9])
1502 cupsdSetString(&con
->options
, con
->uri
+ 8);
1504 cupsdSetString(&con
->options
, NULL
);
1506 else if (!strncmp(con
->uri
, "/jobs", 5))
1508 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1511 if (con
->uri
[5] && con
->uri
[6])
1512 cupsdSetString(&con
->options
, con
->uri
+ 5);
1514 cupsdSetString(&con
->options
, NULL
);
1518 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1521 if (con
->uri
[5] && con
->uri
[6])
1522 cupsdSetString(&con
->options
, con
->uri
+ 5);
1524 cupsdSetString(&con
->options
, NULL
);
1527 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1528 "cupsdReadClient: %d command=\"%s\", "
1530 con
->http
.fd
, con
->command
,
1531 con
->options
? con
->options
: "(null)");
1533 if (con
->http
.version
<= HTTP_1_0
)
1534 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1542 if ((filename
= get_file(con
, &filestats
, buf
,
1543 sizeof(buf
))) == NULL
)
1545 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
1547 cupsdCloseClient(con
);
1554 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1556 if (!is_cgi(con
, filename
, &filestats
, type
))
1559 * Only POST to CGI's...
1562 if (!cupsdSendError(con
, HTTP_UNAUTHORIZED
))
1564 cupsdCloseClient(con
);
1571 case HTTP_PUT_RECV
:
1573 * Validate the resource name...
1576 if (strncmp(con
->uri
, "/admin/conf/", 12) ||
1577 strchr(con
->uri
+ 12, '/') ||
1578 strlen(con
->uri
) == 12)
1581 * PUT can only be done to configuration files under
1585 if (!cupsdSendError(con
, HTTP_FORBIDDEN
))
1587 cupsdCloseClient(con
);
1595 * See if the PUT request includes a Content-Length field, and if
1596 * so check the length against any limits that are set...
1599 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "PUT %s", con
->uri
);
1600 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "CONTENT_TYPE = %s",
1601 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
1603 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1604 MaxRequestSize
> 0 &&
1605 con
->http
.data_remaining
> MaxRequestSize
)
1608 * Request too large...
1611 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1613 cupsdCloseClient(con
);
1619 else if (con
->http
.data_remaining
< 0)
1622 * Negative content lengths are invalid!
1625 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
))
1627 cupsdCloseClient(con
);
1635 * Open a temporary file to hold the request...
1638 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
1640 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1642 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1643 "cupsdReadClient: %d REQUEST %s=%d", con
->http
.fd
,
1644 con
->filename
, con
->file
);
1648 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1650 cupsdCloseClient(con
);
1655 fchmod(con
->file
, 0640);
1656 fchown(con
->file
, RunUser
, Group
);
1657 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1662 cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
);
1663 cupsdCloseClient(con
);
1667 if (!strncmp(con
->uri
, "/printers/", 10) &&
1668 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1671 * Send PPD file - get the real printer name since printer
1672 * names are not case sensitive but filenames can be...
1675 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1677 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1678 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1681 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
1683 cupsdCloseClient(con
);
1691 if ((!strncmp(con
->uri
, "/admin", 6) &&
1692 strncmp(con
->uri
, "/admin/conf/", 12) &&
1693 strncmp(con
->uri
, "/admin/log/", 11)) ||
1694 !strncmp(con
->uri
, "/printers", 9) ||
1695 !strncmp(con
->uri
, "/classes", 8) ||
1696 !strncmp(con
->uri
, "/help", 5) ||
1697 !strncmp(con
->uri
, "/jobs", 5))
1703 if (!cupsdSendHeader(con
, HTTP_OK
, "text/html"))
1705 cupsdCloseClient(con
);
1709 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1711 cupsdCloseClient(con
);
1715 if (cupsdFlushHeader(con
) < 0)
1717 cupsdCloseClient(con
);
1721 cupsdLogRequest(con
, HTTP_OK
);
1723 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1724 (strchr(con
->uri
+ 12, '/') ||
1725 strlen(con
->uri
) == 12)) ||
1726 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1727 (strchr(con
->uri
+ 11, '/') ||
1728 strlen(con
->uri
) == 11)))
1731 * HEAD can only be done to configuration files under
1735 if (!cupsdSendError(con
, HTTP_FORBIDDEN
))
1737 cupsdCloseClient(con
);
1743 else if ((filename
= get_file(con
, &filestats
, buf
,
1744 sizeof(buf
))) == NULL
)
1746 if (!cupsdSendHeader(con
, HTTP_NOT_FOUND
, "text/html"))
1748 cupsdCloseClient(con
);
1752 cupsdLogRequest(con
, HTTP_NOT_FOUND
);
1754 else if (!check_if_modified(con
, &filestats
))
1756 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
))
1758 cupsdCloseClient(con
);
1762 cupsdLogRequest(con
, HTTP_NOT_MODIFIED
);
1770 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1772 strcpy(line
, "text/plain");
1774 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1776 if (!cupsdSendHeader(con
, HTTP_OK
, line
))
1778 cupsdCloseClient(con
);
1782 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
1783 httpGetDateString(filestats
.st_mtime
)) < 0)
1785 cupsdCloseClient(con
);
1789 if (httpPrintf(HTTP(con
), "Content-Length: %lu\r\n",
1790 (unsigned long)filestats
.st_size
) < 0)
1792 cupsdCloseClient(con
);
1796 cupsdLogRequest(con
, HTTP_OK
);
1799 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1801 cupsdCloseClient(con
);
1805 if (cupsdFlushHeader(con
) < 0)
1807 cupsdCloseClient(con
);
1811 con
->http
.state
= HTTP_WAITING
;
1815 break; /* Anti-compiler-warning-code */
1821 * Handle any incoming data...
1824 switch (con
->http
.state
)
1826 case HTTP_PUT_RECV
:
1827 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1828 "cupsdReadClient: %d con->data_encoding=HTTP_ENCODE_%s, "
1829 "con->data_remaining=" CUPS_LLFMT
", con->file=%d",
1831 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
?
1832 "CHUNKED" : "LENGTH",
1833 CUPS_LLCAST con
->http
.data_remaining
, con
->file
);
1837 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
1839 cupsdCloseClient(con
);
1844 con
->bytes
+= bytes
;
1846 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1847 "cupsdReadClient: %d writing %d bytes to %d",
1848 con
->http
.fd
, bytes
, con
->file
);
1850 if (write(con
->file
, line
, bytes
) < bytes
)
1852 cupsdLogMessage(CUPSD_LOG_ERROR
,
1853 "cupsdReadClient: Unable to write %d bytes to %s: %s",
1854 bytes
, con
->filename
, strerror(errno
));
1856 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1857 "cupsdReadClient: Closing data file %d...",
1862 unlink(con
->filename
);
1863 cupsdClearString(&con
->filename
);
1865 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1867 cupsdCloseClient(con
);
1873 while (con
->http
.state
== HTTP_PUT_RECV
&& con
->http
.used
> 0);
1875 if (con
->http
.state
== HTTP_WAITING
)
1878 * End of file, see how big it is...
1881 fstat(con
->file
, &filestats
);
1883 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1884 "cupsdReadClient: %d Closing data file %d, size="
1886 con
->http
.fd
, con
->file
,
1887 CUPS_LLCAST filestats
.st_size
);
1892 if (filestats
.st_size
> MaxRequestSize
&&
1896 * Request is too big; remove it and send an error...
1899 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1900 "cupsdReadClient: %d Removing temp file %s",
1901 con
->http
.fd
, con
->filename
);
1902 unlink(con
->filename
);
1903 cupsdClearString(&con
->filename
);
1905 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1907 cupsdCloseClient(con
);
1913 * Install the configuration file...
1916 status
= install_conf_file(con
);
1919 * Return the status to the client...
1922 if (!cupsdSendError(con
, status
))
1924 cupsdCloseClient(con
);
1930 case HTTP_POST_RECV
:
1931 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1932 "cupsdReadClient: %d con->data_encoding=HTTP_ENCODE_"
1933 "%s, con->data_remaining=" CUPS_LLFMT
", con->file=%d",
1935 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
?
1936 "CHUNKED" : "LENGTH",
1937 CUPS_LLCAST con
->http
.data_remaining
, con
->file
);
1944 * Grab any request data from the connection...
1947 if ((ipp_state
= ippRead(&(con
->http
), con
->request
)) == IPP_ERROR
)
1949 cupsdLogMessage(CUPSD_LOG_ERROR
,
1950 "cupsdReadClient: %d IPP Read Error!",
1953 cupsdSendError(con
, HTTP_BAD_REQUEST
);
1954 cupsdCloseClient(con
);
1957 else if (ipp_state
!= IPP_DATA
)
1959 if (con
->http
.state
== HTTP_POST_SEND
)
1961 cupsdSendError(con
, HTTP_BAD_REQUEST
);
1962 cupsdCloseClient(con
);
1969 con
->bytes
+= ippLength(con
->request
);
1972 if (con
->file
< 0 && con
->http
.state
!= HTTP_POST_SEND
)
1975 * Create a file as needed for the request data...
1978 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
, request_id
++);
1979 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1981 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdReadClient: %d REQUEST %s=%d", con
->http
.fd
,
1982 con
->filename
, con
->file
);
1986 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1988 cupsdCloseClient(con
);
1993 fchmod(con
->file
, 0640);
1994 fchown(con
->file
, RunUser
, Group
);
1995 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1998 if (con
->http
.state
!= HTTP_POST_SEND
)
2000 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
2002 cupsdCloseClient(con
);
2007 con
->bytes
+= bytes
;
2009 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2010 "cupsdReadClient: %d writing %d bytes to %d",
2011 con
->http
.fd
, bytes
, con
->file
);
2013 if (write(con
->file
, line
, bytes
) < bytes
)
2015 cupsdLogMessage(CUPSD_LOG_ERROR
,
2016 "cupsdReadClient: Unable to write %d bytes to %s: %s",
2017 bytes
, con
->filename
, strerror(errno
));
2019 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2020 "cupsdReadClient: Closing file %d...",
2025 unlink(con
->filename
);
2026 cupsdClearString(&con
->filename
);
2028 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
2030 cupsdCloseClient(con
);
2035 else if (con
->http
.state
== HTTP_POST_RECV
)
2037 else if (con
->http
.state
!= HTTP_POST_SEND
)
2039 cupsdCloseClient(con
);
2044 while (con
->http
.state
== HTTP_POST_RECV
&& con
->http
.used
> 0);
2046 if (con
->http
.state
== HTTP_POST_SEND
)
2050 fstat(con
->file
, &filestats
);
2052 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2053 "cupsdReadClient: %d Closing data file %d, "
2054 "size=" CUPS_LLFMT
".",
2055 con
->http
.fd
, con
->file
,
2056 CUPS_LLCAST filestats
.st_size
);
2061 if (filestats
.st_size
> MaxRequestSize
&&
2065 * Request is too big; remove it and send an error...
2068 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2069 "cupsdReadClient: %d Removing temp file %s",
2070 con
->http
.fd
, con
->filename
);
2071 unlink(con
->filename
);
2072 cupsdClearString(&con
->filename
);
2077 * Delete any IPP request data...
2080 ippDelete(con
->request
);
2081 con
->request
= NULL
;
2084 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
2086 cupsdCloseClient(con
);
2093 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
2095 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
2097 cupsdCloseClient(con
);
2102 cupsdLogRequest(con
, HTTP_OK
);
2108 cupsdProcessIPPRequest(con
);
2115 break; /* Anti-compiler-warning-code */
2118 if (!con
->http
.keep_alive
&& con
->http
.state
== HTTP_WAITING
)
2119 cupsdCloseClient(con
);
2124 * 'cupsdSendCommand()' - Send output from a command via HTTP.
2127 int /* O - 1 on success, 0 on failure */
2129 cupsd_client_t
*con
, /* I - Client connection */
2130 char *command
, /* I - Command to run */
2131 char *options
, /* I - Command-line options */
2132 int root
) /* I - Run as root? */
2134 int fd
; /* Standard input file descriptor */
2139 fd
= open(con
->filename
, O_RDONLY
);
2143 cupsdLogMessage(CUPSD_LOG_ERROR
,
2144 "cupsdSendCommand: %d Unable to open \"%s\" for reading: %s",
2145 con
->http
.fd
, con
->filename
? con
->filename
: "/dev/null",
2150 fcntl(fd
, F_SETFD
, fcntl(fd
, F_GETFD
) | FD_CLOEXEC
);
2155 con
->pipe_pid
= pipe_command(con
, fd
, &(con
->file
), command
, options
, root
);
2160 cupsdLogMessage(CUPSD_LOG_INFO
, "Started \"%s\" (pid=%d)", command
,
2163 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendCommand: %d file=%d",
2164 con
->http
.fd
, con
->file
);
2166 if (con
->pipe_pid
== 0)
2169 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2171 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)cupsdWritePipe
, NULL
, con
);
2173 con
->sent_header
= 0;
2174 con
->file_ready
= 0;
2175 con
->got_fields
= 0;
2183 * 'cupsdSendError()' - Send an error message via HTTP.
2186 int /* O - 1 if successful, 0 otherwise */
2187 cupsdSendError(cupsd_client_t
*con
, /* I - Connection */
2188 http_status_t code
) /* I - Error code */
2192 * Force client to upgrade for authentication if that is how the
2193 * server is configured...
2196 if (code
== HTTP_UNAUTHORIZED
&&
2197 DefaultEncryption
== HTTP_ENCRYPT_REQUIRED
&&
2198 strcasecmp(con
->http
.hostname
, "localhost") &&
2201 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2202 "cupsdSendError: Encryption before authentication!");
2203 code
= HTTP_UPGRADE_REQUIRED
;
2205 #endif /* HAVE_SSL */
2208 * Put the request in the access_log file...
2211 cupsdLogRequest(con
, code
);
2213 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendError: %d code=%d (%s)",
2214 con
->http
.fd
, code
, httpStatus(code
));
2217 * To work around bugs in some proxies, don't use Keep-Alive for some
2220 * Kerberos authentication doesn't work without Keep-Alive, so
2221 * never disable it in that case.
2224 if (code
>= HTTP_BAD_REQUEST
&& con
->http
.auth_type
!= AUTH_NEGOTIATE
)
2225 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
2228 * Send an error message back to the client. If the error code is a
2229 * 400 or 500 series, make sure the message contains some text, too!
2232 if (!cupsdSendHeader(con
, code
, NULL
))
2236 if (code
== HTTP_UPGRADE_REQUIRED
)
2237 if (httpPrintf(HTTP(con
), "Connection: Upgrade\r\n") < 0)
2240 if (httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n") < 0)
2242 #endif /* HAVE_SSL */
2244 if (con
->http
.version
>= HTTP_1_1
&&
2245 con
->http
.keep_alive
== HTTP_KEEPALIVE_OFF
)
2247 if (httpPrintf(HTTP(con
), "Connection: close\r\n") < 0)
2251 if (code
>= HTTP_BAD_REQUEST
)
2254 * Send a human-readable error message.
2257 char message
[4096], /* Message for user */
2258 urltext
[1024], /* URL redirection text */
2259 redirect
[1024]; /* Redirection link */
2260 const char *text
; /* Status-specific text */
2265 if (code
== HTTP_UNAUTHORIZED
)
2266 text
= _cupsLangString(con
->language
,
2267 _("Enter your username and password or the "
2268 "root username and password to access this "
2269 "page. If you are using Kerberos authentication, "
2270 "make sure you have a valid Kerberos ticket."));
2271 else if (code
== HTTP_UPGRADE_REQUIRED
)
2275 snprintf(urltext
, sizeof(urltext
),
2276 _cupsLangString(con
->language
,
2277 _("You must access this page using the URL "
2278 "<A HREF=\"https://%s:%d%s\">"
2279 "https://%s:%d%s</A>.")),
2280 con
->servername
, con
->serverport
, con
->uri
,
2281 con
->servername
, con
->serverport
, con
->uri
);
2283 snprintf(redirect
, sizeof(redirect
),
2284 "<META HTTP-EQUIV=\"Refresh\" "
2285 "CONTENT=\"3;URL=https://%s:%d%s\">\n",
2286 con
->servername
, con
->serverport
, con
->uri
);
2291 snprintf(message
, sizeof(message
),
2292 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" "
2293 "\"http://www.w3.org/TR/REC-html40/loose.dtd\">\n"
2296 "\t<META HTTP-EQUIV=\"Content-Type\" "
2297 "CONTENT=\"text/html; charset=utf-8\">\n"
2298 "\t<TITLE>%d %s</TITLE>\n"
2299 "\t<LINK REL=\"STYLESHEET\" TYPE=\"text/css\" "
2300 "HREF=\"/cups.css\">\n"
2308 code
, httpStatus(code
), redirect
, code
, httpStatus(code
), text
);
2310 if (httpPrintf(HTTP(con
), "Content-Type: text/html; charset=utf-8\r\n") < 0)
2312 if (httpPrintf(HTTP(con
), "Content-Length: %d\r\n",
2313 (int)strlen(message
)) < 0)
2315 if (httpPrintf(HTTP(con
), "\r\n") < 0)
2317 if (httpPrintf(HTTP(con
), "%s", message
) < 0)
2320 else if (httpPrintf(HTTP(con
), "\r\n") < 0)
2323 if (cupsdFlushHeader(con
) < 0)
2326 con
->http
.state
= HTTP_WAITING
;
2333 * 'cupsdSendHeader()' - Send an HTTP request.
2336 int /* O - 1 on success, 0 on failure */
2337 cupsdSendHeader(cupsd_client_t
*con
, /* I - Client to send to */
2338 http_status_t code
, /* I - HTTP status code */
2339 char *type
) /* I - MIME type of document */
2341 char auth_str
[1024]; /* Authorization string */
2345 * Send the HTTP status header...
2348 if (code
== HTTP_CONTINUE
)
2351 * 100-continue doesn't send any headers...
2354 return (httpPrintf(HTTP(con
), "HTTP/%d.%d 100 Continue\r\n\r\n",
2355 con
->http
.version
/ 100, con
->http
.version
% 100) > 0);
2358 httpFlushWrite(HTTP(con
));
2360 con
->http
.data_encoding
= HTTP_ENCODE_FIELDS
;
2362 if (httpPrintf(HTTP(con
), "HTTP/%d.%d %d %s\r\n", con
->http
.version
/ 100,
2363 con
->http
.version
% 100, code
, httpStatus(code
)) < 0)
2365 if (httpPrintf(HTTP(con
), "Date: %s\r\n", httpGetDateString(time(NULL
))) < 0)
2368 if (httpPrintf(HTTP(con
), "Server: %s\r\n", ServerHeader
) < 0)
2370 if (con
->http
.keep_alive
&& con
->http
.version
>= HTTP_1_0
)
2372 if (httpPrintf(HTTP(con
), "Connection: Keep-Alive\r\n") < 0)
2374 if (httpPrintf(HTTP(con
), "Keep-Alive: timeout=%d\r\n",
2375 KeepAliveTimeout
) < 0)
2378 if (code
== HTTP_METHOD_NOT_ALLOWED
)
2379 if (httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST\r\n") < 0)
2382 if (code
== HTTP_UNAUTHORIZED
)
2384 int auth_type
; /* Authentication type */
2387 if (!con
->best
|| con
->best
->type
== AUTH_NONE
)
2388 auth_type
= DefaultAuthType
;
2390 auth_type
= con
->best
->type
;
2394 if (auth_type
== AUTH_BASIC
|| auth_type
== AUTH_BASICDIGEST
)
2395 strlcpy(auth_str
, "Basic realm=\"CUPS\"", sizeof(auth_str
));
2396 else if (auth_type
== AUTH_DIGEST
)
2397 snprintf(auth_str
, sizeof(auth_str
), "Digest realm=\"CUPS\", nonce=\"%s\"",
2398 con
->http
.hostname
);
2400 else if (auth_type
== AUTH_NEGOTIATE
&& !con
->no_negotiate
&&
2401 con
->gss_output_token
.length
== 0)
2402 strlcpy(auth_str
, "Negotiate", sizeof(auth_str
));
2403 #endif /* HAVE_GSSAPI */
2405 #ifdef HAVE_AUTHORIZATION_H
2408 int i
; /* Looping var */
2409 char *auth_key
; /* Auth key buffer */
2410 size_t auth_size
; /* Size of remaining buffer */
2413 auth_key
= auth_str
+ strlen(auth_str
);
2414 auth_size
= sizeof(auth_str
) - (auth_key
- auth_str
);
2416 for (i
= 0; i
< con
->best
->num_names
; i
++)
2418 if (!strncasecmp(con
->best
->names
[i
], "@AUTHKEY(", 9))
2420 snprintf(auth_key
, auth_size
, ", authkey=\"%s\"",
2421 con
->best
->names
[i
] + 9);
2422 /* end parenthesis is stripped in conf.c */
2425 else if (!strcasecmp(con
->best
->names
[i
], "@SYSTEM") &&
2428 snprintf(auth_key
, auth_size
, ", authkey=\"%s\"", SystemGroupAuthKey
);
2433 #endif /* HAVE_AUTHORIZATION_H */
2436 httpPrintf(HTTP(con
), "WWW-Authenticate: %s\r\n", auth_str
) < 0)
2442 * WWW-Authenticate: Negotiate can be included even for
2443 * non-401 replies...
2446 if (con
->gss_output_token
.length
> 0)
2448 char buf
[2048]; /* Output token buffer */
2449 OM_uint32 minor_status
; /* Minor status code */
2452 httpEncode64_2(buf
, sizeof(buf
),
2453 con
->gss_output_token
.value
,
2454 con
->gss_output_token
.length
);
2455 gss_release_buffer(&minor_status
, &con
->gss_output_token
);
2457 if (httpPrintf(HTTP(con
), "WWW-Authenticate: Negotiate %s\r\n", buf
) < 0)
2460 #endif /* HAVE_GSSAPI */
2462 if (con
->language
&& strcmp(con
->language
->language
, "C"))
2464 if (httpPrintf(HTTP(con
), "Content-Language: %s\r\n",
2465 con
->language
->language
) < 0)
2471 if (!strcmp(type
, "text/html"))
2473 if (httpPrintf(HTTP(con
),
2474 "Content-Type: text/html; charset=utf-8\r\n") < 0)
2477 else if (httpPrintf(HTTP(con
), "Content-Type: %s\r\n", type
) < 0)
2486 * 'cupsdUpdateCGI()' - Read status messages from CGI scripts and programs.
2490 cupsdUpdateCGI(void)
2492 char *ptr
, /* Pointer to end of line in buffer */
2493 message
[1024]; /* Pointer to message text */
2494 int loglevel
; /* Log level for message */
2497 while ((ptr
= cupsdStatBufUpdate(CGIStatusBuffer
, &loglevel
,
2498 message
, sizeof(message
))) != NULL
)
2499 if (!strchr(CGIStatusBuffer
->buffer
, '\n'))
2502 if (ptr
== NULL
&& !CGIStatusBuffer
->bufused
)
2505 * Fatal error on pipe - should never happen!
2508 cupsdLogMessage(CUPSD_LOG_CRIT
,
2509 "cupsdUpdateCGI: error reading from CGI error pipe - %s",
2516 * 'cupsdWriteClient()' - Write data to a client as needed.
2520 cupsdWriteClient(cupsd_client_t
*con
) /* I - Client connection */
2522 int bytes
; /* Number of bytes written */
2523 char buf
[16385]; /* Data buffer */
2524 char *bufptr
; /* Pointer into buffer */
2525 ipp_state_t ipp_state
; /* IPP state value */
2529 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2530 "cupsdWriteClient(con=%p) %d response=%p, file=%d "
2531 "pipe_pid=%d state=%d",
2532 con
, con
->http
.fd
, con
->response
, con
->file
, con
->pipe_pid
,
2536 if (con
->http
.state
!= HTTP_GET_SEND
&&
2537 con
->http
.state
!= HTTP_POST_SEND
)
2543 * Make sure we select on the CGI output...
2546 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)cupsdWritePipe
, NULL
, con
);
2548 if (!con
->file_ready
)
2551 * Try again later when there is CGI output available...
2554 cupsdRemoveSelect(con
->http
.fd
);
2558 con
->file_ready
= 0;
2563 ipp_state
= ippWrite(HTTP(con
), con
->response
);
2564 bytes
= ipp_state
!= IPP_ERROR
&& ipp_state
!= IPP_DATA
;
2566 else if ((bytes
= read(con
->file
, buf
, sizeof(buf
) - 1)) > 0)
2568 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2569 "cupsdWriteClient: Read %d bytes from file %d...",
2572 if (con
->pipe_pid
&& !con
->got_fields
)
2575 * Inspect the data for Content-Type and other fields.
2580 for (bufptr
= buf
; !con
->got_fields
&& *bufptr
; bufptr
++)
2581 if (*bufptr
== '\n')
2584 * Send line to client...
2587 if (bufptr
> buf
&& bufptr
[-1] == '\r')
2591 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "Script header: %s", buf
);
2593 if (!con
->sent_header
)
2596 * Handle redirection and CGI status codes...
2599 if (!strncasecmp(buf
, "Location:", 9))
2601 cupsdSendHeader(con
, HTTP_SEE_OTHER
, NULL
);
2602 con
->sent_header
= 2;
2604 if (httpPrintf(HTTP(con
), "Content-Length: 0\r\n") < 0)
2607 else if (!strncasecmp(buf
, "Status:", 7))
2609 cupsdSendError(con
, (http_status_t
)atoi(buf
+ 7));
2610 con
->sent_header
= 2;
2614 cupsdSendHeader(con
, HTTP_OK
, NULL
);
2615 con
->sent_header
= 1;
2617 if (con
->http
.version
== HTTP_1_1
)
2619 if (httpPrintf(HTTP(con
), "Transfer-Encoding: chunked\r\n") < 0)
2625 if (strncasecmp(buf
, "Status:", 7))
2626 httpPrintf(HTTP(con
), "%s\r\n", buf
);
2628 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdWriteClient: %d %s",
2635 bytes
-= (bufptr
- buf
);
2636 memmove(buf
, bufptr
, bytes
+ 1);
2640 * See if the line was empty...
2643 if (con
->field_col
== 0)
2645 con
->got_fields
= 1;
2647 if (cupsdFlushHeader(con
) < 0)
2649 cupsdCloseClient(con
);
2653 if (con
->http
.version
== HTTP_1_1
)
2654 con
->http
.data_encoding
= HTTP_ENCODE_CHUNKED
;
2659 else if (*bufptr
!= '\r')
2662 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2663 "cupsdWriteClient: %d bytes=%d, got_fields=%d",
2664 con
->http
.fd
, bytes
, con
->got_fields
);
2666 if (bytes
> 0 && !con
->got_fields
)
2669 * Remaining text needs to go out...
2672 httpPrintf(HTTP(con
), "%s", buf
);
2674 con
->http
.activity
= time(NULL
);
2677 else if (bytes
== 0)
2678 con
->http
.activity
= time(NULL
);
2683 if (httpWrite2(HTTP(con
), buf
, bytes
) < 0)
2685 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2686 "cupsdWriteClient: %d Write of %d bytes failed!",
2687 con
->http
.fd
, bytes
);
2689 cupsdCloseClient(con
);
2693 con
->bytes
+= bytes
;
2695 if (con
->http
.state
== HTTP_WAITING
)
2702 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdWriteClient: %d bytes < 0",
2705 cupsdLogRequest(con
, HTTP_OK
);
2707 httpFlushWrite(HTTP(con
));
2709 if (con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
&& con
->sent_header
== 1)
2711 if (httpWrite2(HTTP(con
), "", 0) < 0)
2713 cupsdCloseClient(con
);
2718 con
->http
.state
= HTTP_WAITING
;
2720 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
2724 cupsdRemoveSelect(con
->file
);
2727 cupsdEndProcess(con
->pipe_pid
, 0);
2729 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2730 "cupsdWriteClient: %d Closing data file %d.",
2731 con
->http
.fd
, con
->file
);
2740 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2741 "cupsdWriteClient: %d Removing temp file %s",
2742 con
->http
.fd
, con
->filename
);
2743 unlink(con
->filename
);
2744 cupsdClearString(&con
->filename
);
2749 ippDelete(con
->request
);
2750 con
->request
= NULL
;
2755 ippDelete(con
->response
);
2756 con
->response
= NULL
;
2759 cupsdClearString(&con
->command
);
2760 cupsdClearString(&con
->options
);
2761 cupsdClearString(&con
->query_string
);
2763 if (!con
->http
.keep_alive
)
2765 cupsdCloseClient(con
);
2770 con
->http
.activity
= time(NULL
);
2775 * 'cupsdWritePipe()' - Flag that data is available on the CGI pipe.
2779 cupsdWritePipe(cupsd_client_t
*con
) /* I - Client connection */
2781 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdWritePipe: CGI output on fd %d...",
2784 con
->file_ready
= 1;
2786 cupsdRemoveSelect(con
->file
);
2787 cupsdAddSelect(con
->http
.fd
, NULL
, (cupsd_selfunc_t
)cupsdWriteClient
, con
);
2792 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
2795 static int /* O - 1 if modified since */
2797 cupsd_client_t
*con
, /* I - Client connection */
2798 struct stat
*filestats
) /* I - File information */
2800 char *ptr
; /* Pointer into field */
2801 time_t date
; /* Time/date value */
2802 off_t size
; /* Size/length value */
2807 ptr
= con
->http
.fields
[HTTP_FIELD_IF_MODIFIED_SINCE
];
2812 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2813 "check_if_modified: %d If-Modified-Since=\"%s\"",
2816 while (*ptr
!= '\0')
2818 while (isspace(*ptr
) || *ptr
== ';')
2821 if (strncasecmp(ptr
, "length=", 7) == 0)
2824 size
= strtoll(ptr
, NULL
, 10);
2826 while (isdigit(*ptr
))
2829 else if (isalpha(*ptr
))
2831 date
= httpGetDateTime(ptr
);
2832 while (*ptr
!= '\0' && *ptr
!= ';')
2839 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2840 "check_if_modified: %d sizes=" CUPS_LLFMT
","
2841 CUPS_LLFMT
" dates=%d,%d",
2842 con
->http
.fd
, CUPS_LLCAST size
,
2843 CUPS_LLCAST filestats
->st_size
, (int)date
,
2844 (int)filestats
->st_mtime
);
2846 return ((size
!= filestats
->st_size
&& size
!= 0) ||
2847 (date
< filestats
->st_mtime
&& date
!= 0) ||
2848 (size
== 0 && date
== 0));
2854 * 'encrypt_client()' - Enable encryption for the client...
2857 static int /* O - 1 on success, 0 on error */
2858 encrypt_client(cupsd_client_t
*con
) /* I - Client to encrypt */
2861 SSL_CTX
*context
; /* Context for encryption */
2862 SSL
*conn
; /* Connection for encryption */
2863 BIO
*bio
; /* BIO data */
2864 unsigned long error
; /* Error code */
2868 * Verify that we have a certificate...
2871 if (access(ServerKey
, 0) || access(ServerCertificate
, 0))
2874 * Nope, make a self-signed certificate...
2877 if (!make_certificate(con
))
2882 * Create the SSL context and accept the connection...
2885 context
= SSL_CTX_new(SSLv23_server_method());
2887 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
2888 SSL_CTX_use_PrivateKey_file(context
, ServerKey
, SSL_FILETYPE_PEM
);
2889 SSL_CTX_use_certificate_file(context
, ServerCertificate
, SSL_FILETYPE_PEM
);
2891 bio
= BIO_new(_httpBIOMethods());
2892 BIO_ctrl(bio
, BIO_C_SET_FILE_PTR
, 0, (char *)HTTP(con
));
2894 conn
= SSL_new(context
);
2895 SSL_set_bio(conn
, bio
, bio
);
2897 if (SSL_accept(conn
) != 1)
2899 cupsdLogMessage(CUPSD_LOG_ERROR
,
2900 "encrypt_client: Unable to encrypt connection from %s!",
2901 con
->http
.hostname
);
2903 while ((error
= ERR_get_error()) != 0)
2904 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s",
2905 ERR_error_string(error
, NULL
));
2907 SSL_CTX_free(context
);
2912 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2913 "encrypt_client: %d Connection from %s now encrypted.",
2914 con
->http
.fd
, con
->http
.hostname
);
2916 con
->http
.tls
= conn
;
2919 # elif defined(HAVE_GNUTLS)
2920 http_tls_t
*conn
; /* TLS session object */
2921 int error
; /* Error code */
2922 gnutls_certificate_server_credentials
*credentials
;
2923 /* TLS credentials */
2927 * Verify that we have a certificate...
2930 if (access(ServerKey
, 0) || access(ServerCertificate
, 0))
2933 * Nope, make a self-signed certificate...
2936 if (!make_certificate(con
))
2941 * Create the SSL object and perform the SSL handshake...
2944 conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
));
2949 credentials
= (gnutls_certificate_server_credentials
*)
2950 malloc(sizeof(gnutls_certificate_server_credentials
));
2951 if (credentials
== NULL
)
2953 cupsdLogMessage(CUPSD_LOG_ERROR
,
2954 "encrypt_client: Unable to encrypt connection from %s!",
2955 con
->http
.hostname
);
2956 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s", strerror(errno
));
2962 gnutls_certificate_allocate_credentials(credentials
);
2963 gnutls_certificate_set_x509_key_file(*credentials
, ServerCertificate
,
2964 ServerKey
, GNUTLS_X509_FMT_PEM
);
2966 gnutls_init(&(conn
->session
), GNUTLS_SERVER
);
2967 gnutls_set_default_priority(conn
->session
);
2968 gnutls_credentials_set(conn
->session
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
2969 gnutls_transport_set_ptr(conn
->session
, (gnutls_transport_ptr
)HTTP(con
));
2970 gnutls_transport_set_pull_function(conn
->session
, _httpReadGNUTLS
);
2971 gnutls_transport_set_push_function(conn
->session
, _httpWriteGNUTLS
);
2973 error
= gnutls_handshake(conn
->session
);
2975 if (error
!= GNUTLS_E_SUCCESS
)
2977 cupsdLogMessage(CUPSD_LOG_ERROR
,
2978 "encrypt_client: Unable to encrypt connection from %s!",
2979 con
->http
.hostname
);
2980 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s",
2981 gnutls_strerror(error
));
2983 gnutls_deinit(conn
->session
);
2984 gnutls_certificate_free_credentials(*credentials
);
2990 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2991 "encrypt_client: %d Connection from %s now encrypted.",
2992 con
->http
.fd
, con
->http
.hostname
);
2994 conn
->credentials
= credentials
;
2995 con
->http
.tls
= conn
;
2998 # elif defined(HAVE_CDSASSL)
2999 OSStatus error
; /* Error code */
3000 http_tls_t
*conn
; /* CDSA connection information */
3003 if ((conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
))) == NULL
)
3007 conn
->session
= NULL
;
3008 conn
->certsArray
= get_cdsa_certificate(con
);
3010 if (!conn
->certsArray
)
3013 * No keychain (yet), make a self-signed certificate...
3016 if (make_certificate(con
))
3017 conn
->certsArray
= get_cdsa_certificate(con
);
3020 if (!conn
->certsArray
)
3022 cupsdLogMessage(CUPSD_LOG_ERROR
,
3023 "encrypt_client: Could not find signing key in keychain "
3024 "\"%s\"", ServerCertificate
);
3025 error
= errSSLBadCert
; /* errSSLBadConfiguration is a better choice, but not available on 10.2.x */
3029 error
= SSLNewContext(true, &conn
->session
);
3032 error
= SSLSetIOFuncs(conn
->session
, _httpReadCDSA
, _httpWriteCDSA
);
3035 error
= SSLSetProtocolVersionEnabled(conn
->session
, kSSLProtocol2
, false);
3038 error
= SSLSetConnection(conn
->session
, HTTP(con
));
3041 error
= SSLSetAllowsExpiredCerts(conn
->session
, true);
3044 error
= SSLSetAllowsAnyRoot(conn
->session
, true);
3047 error
= SSLSetCertificate(conn
->session
, conn
->certsArray
);
3052 * Perform SSL/TLS handshake
3055 while ((error
= SSLHandshake(conn
->session
)) == errSSLWouldBlock
)
3061 cupsdLogMessage(CUPSD_LOG_ERROR
,
3062 "encrypt_client: Unable to encrypt connection from %s!",
3063 con
->http
.hostname
);
3065 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s (%d)",
3066 cssmErrorString(error
), (int)error
);
3068 con
->http
.error
= error
;
3069 con
->http
.status
= HTTP_ERROR
;
3072 SSLDisposeContext(conn
->session
);
3074 if (conn
->certsArray
)
3075 CFRelease(conn
->certsArray
);
3082 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3083 "encrypt_client: %d Connection from %s now encrypted.",
3084 con
->http
.fd
, con
->http
.hostname
);
3086 con
->http
.tls
= conn
;
3089 # endif /* HAVE_LIBSSL */
3091 #endif /* HAVE_SSL */
3096 * 'get_cdsa_certificate()' - Get a SSL/TLS certificate from the System keychain.
3099 static CFArrayRef
/* O - Array of certificates */
3100 get_cdsa_certificate(cupsd_client_t
*con
) /* I - Client connection */
3102 OSStatus err
; /* Error info */
3103 SecKeychainRef keychain
; /* Keychain reference */
3104 SecIdentitySearchRef search
; /* Search reference */
3105 SecIdentityRef identity
; /* Identity */
3106 CFArrayRef certificates
= NULL
;
3107 /* Certificate array */
3110 if ((err
= SecKeychainOpen(ServerCertificate
, &keychain
)))
3112 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot open keychain \"%s\", %s",
3113 ServerCertificate
, cssmErrorString(err
));
3117 # if HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY
3119 * Use a policy to search for valid certificates who's common name matches the
3123 SecPolicySearchRef policy_search
; /* Policy search ref */
3124 SecPolicyRef policy
; /* Policy ref */
3125 CSSM_DATA options
; /* Policy options */
3126 CSSM_APPLE_TP_SSL_OPTIONS
3127 ssl_options
; /* SSL Option for hostname */
3130 if ((err
= SecPolicySearchCreate(CSSM_CERT_X_509v3
, &CSSMOID_APPLE_TP_SSL
,
3131 NULL
, &policy_search
)))
3133 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot create a policy search reference");
3134 CFRelease(keychain
);
3138 if ((err
= SecPolicySearchCopyNext(policy_search
, &policy
)))
3140 cupsdLogMessage(CUPSD_LOG_ERROR
,
3141 "Cannot find a policy to use for searching");
3142 CFRelease(keychain
);
3143 CFRelease(policy_search
);
3147 memset(&ssl_options
, 0, sizeof(ssl_options
));
3148 ssl_options
.Version
= CSSM_APPLE_TP_SSL_OPTS_VERSION
;
3149 ssl_options
.ServerName
= con
->servername
;
3150 ssl_options
.ServerNameLen
= strlen(con
->servername
);
3152 options
.Data
= (uint8
*)&ssl_options
;
3153 options
.Length
= sizeof(ssl_options
);
3155 if ((err
= SecPolicySetValue(policy
, &options
)))
3157 cupsdLogMessage(CUPSD_LOG_ERROR
,
3158 "Cannot set policy value to use for searching");
3159 CFRelease(keychain
);
3160 CFRelease(policy_search
);
3164 err
= SecIdentitySearchCreateWithPolicy(policy
, NULL
, CSSM_KEYUSE_SIGN
,
3165 keychain
, FALSE
, &search
);
3168 * Assume there is exactly one SecIdentity in the keychain...
3171 err
= SecIdentitySearchCreate(keychain
, CSSM_KEYUSE_SIGN
, &search
);
3172 # endif /* HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY */
3175 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3176 "Cannot create keychain search reference: %s",
3177 cssmErrorString(err
));
3180 if ((err
= SecIdentitySearchCopyNext(search
, &identity
)))
3182 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3183 "Cannot find signing key in keychain \"%s\", error %d",
3184 ServerCertificate
, (int)err
);
3188 if (CFGetTypeID(identity
) != SecIdentityGetTypeID())
3189 cupsdLogMessage(CUPSD_LOG_ERROR
,
3190 "SecIdentitySearchCopyNext CFTypeID failure!");
3193 if ((certificates
= CFArrayCreate(NULL
, (const void **)&identity
,
3194 1, &kCFTypeArrayCallBacks
)) == NULL
)
3195 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot create certificate array");
3198 CFRelease(identity
);
3204 # if HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY
3206 CFRelease(policy_search
);
3207 # endif /* HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY */
3209 return (certificates
);
3211 #endif /* HAVE_CDSASSL */
3215 * 'get_file()' - Get a filename and state info.
3218 static char * /* O - Real filename */
3219 get_file(cupsd_client_t
*con
, /* I - Client connection */
3220 struct stat
*filestats
, /* O - File information */
3221 char *filename
, /* IO - Filename buffer */
3222 int len
) /* I - Buffer length */
3224 int status
; /* Status of filesystem calls */
3225 char *ptr
; /* Pointer info filename */
3226 int plen
; /* Remaining length after pointer */
3230 * Figure out the real filename...
3233 if (!strncmp(con
->uri
, "/ppd/", 5))
3234 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
);
3235 else if (!strncmp(con
->uri
, "/rss/", 5) && !strchr(con
->uri
+ 5, '/'))
3236 snprintf(filename
, len
, "%s/rss/%s", CacheDir
, con
->uri
+ 5);
3237 else if (!strncmp(con
->uri
, "/admin/conf/", 12))
3238 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
+ 11);
3239 else if (!strncmp(con
->uri
, "/admin/log/", 11))
3241 if (!strcmp(con
->uri
+ 11, "access_log") && AccessLog
[0] == '/')
3242 strlcpy(filename
, AccessLog
, len
);
3243 else if (!strcmp(con
->uri
+ 11, "error_log") && ErrorLog
[0] == '/')
3244 strlcpy(filename
, ErrorLog
, len
);
3245 else if (!strcmp(con
->uri
+ 11, "page_log") && PageLog
[0] == '/')
3246 strlcpy(filename
, PageLog
, len
);
3250 else if (con
->language
)
3251 snprintf(filename
, len
, "%s/%s%s", DocumentRoot
, con
->language
->language
,
3254 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3256 if ((ptr
= strchr(filename
, '?')) != NULL
)
3260 * Grab the status for this language; if there isn't a language-specific file
3261 * then fallback to the default one...
3264 if ((status
= stat(filename
, filestats
)) != 0 && con
->language
&&
3265 strncmp(con
->uri
, "/ppd/", 5) &&
3266 strncmp(con
->uri
, "/admin/conf/", 12) &&
3267 strncmp(con
->uri
, "/admin/log/", 11))
3270 * Drop the country code...
3273 char ll
[3]; /* Short language name */
3276 strlcpy(ll
, con
->language
->language
, sizeof(ll
));
3277 snprintf(filename
, len
, "%s/%s%s", DocumentRoot
, ll
, con
->uri
);
3279 if ((ptr
= strchr(filename
, '?')) != NULL
)
3282 if ((status
= stat(filename
, filestats
)) != 0)
3285 * Drop the language prefix and try the root directory...
3288 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3290 if ((ptr
= strchr(filename
, '?')) != NULL
)
3293 status
= stat(filename
, filestats
);
3298 * If we're found a directory, get the index.html file instead...
3301 if (!status
&& S_ISDIR(filestats
->st_mode
))
3303 if (filename
[strlen(filename
) - 1] != '/')
3304 strlcat(filename
, "/", len
);
3306 ptr
= filename
+ strlen(filename
);
3307 plen
= len
- (ptr
- filename
);
3309 strlcpy(ptr
, "index.html", plen
);
3310 status
= stat(filename
, filestats
);
3315 strlcpy(ptr
, "index.class", plen
);
3316 status
= stat(filename
, filestats
);
3318 #endif /* HAVE_JAVA */
3323 strlcpy(ptr
, "index.pl", plen
);
3324 status
= stat(filename
, filestats
);
3326 #endif /* HAVE_PERL */
3331 strlcpy(ptr
, "index.php", plen
);
3332 status
= stat(filename
, filestats
);
3334 #endif /* HAVE_PHP */
3339 strlcpy(ptr
, "index.pyc", plen
);
3340 status
= stat(filename
, filestats
);
3345 strlcpy(ptr
, "index.py", plen
);
3346 status
= stat(filename
, filestats
);
3348 #endif /* HAVE_PYTHON */
3351 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "get_file: %d filename=%s size=%d",
3352 con
->http
.fd
, filename
,
3353 status
? -1 : (int)filestats
->st_size
);
3356 con
->http
.data_remaining
= (int)filestats
->st_size
;
3366 * 'install_conf_file()' - Install a configuration file.
3369 static http_status_t
/* O - Status */
3370 install_conf_file(cupsd_client_t
*con
) /* I - Connection */
3372 cups_file_t
*in
, /* Input file */
3373 *out
; /* Output file */
3374 char buffer
[1024]; /* Copy buffer */
3375 int bytes
; /* Number of bytes */
3376 char conffile
[1024], /* Configuration filename */
3377 newfile
[1024], /* New config filename */
3378 oldfile
[1024]; /* Old config filename */
3379 struct stat confinfo
; /* Config file info */
3383 * First construct the filenames...
3386 snprintf(conffile
, sizeof(conffile
), "%s%s", ServerRoot
, con
->uri
+ 11);
3387 snprintf(newfile
, sizeof(newfile
), "%s%s.N", ServerRoot
, con
->uri
+ 11);
3388 snprintf(oldfile
, sizeof(oldfile
), "%s%s.O", ServerRoot
, con
->uri
+ 11);
3390 cupsdLogMessage(CUPSD_LOG_INFO
, "Installing config file \"%s\"...", conffile
);
3393 * Get the owner, group, and permissions of the configuration file.
3394 * If it doesn't exist, assign it to the User and Group in the
3395 * cupsd.conf file with mode 0640 permissions.
3398 if (stat(conffile
, &confinfo
))
3400 confinfo
.st_uid
= User
;
3401 confinfo
.st_gid
= Group
;
3402 confinfo
.st_mode
= ConfigFilePerm
;
3406 * Open the request file and new config file...
3409 if ((in
= cupsFileOpen(con
->filename
, "rb")) == NULL
)
3411 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open request file \"%s\" - %s",
3412 con
->filename
, strerror(errno
));
3413 return (HTTP_SERVER_ERROR
);
3416 if ((out
= cupsFileOpen(newfile
, "wb")) == NULL
)
3419 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open config file \"%s\" - %s",
3420 newfile
, strerror(errno
));
3421 return (HTTP_SERVER_ERROR
);
3424 fchmod(cupsFileNumber(out
), confinfo
.st_mode
);
3425 fchown(cupsFileNumber(out
), confinfo
.st_uid
, confinfo
.st_gid
);
3428 * Copy from the request to the new config file...
3431 while ((bytes
= cupsFileRead(in
, buffer
, sizeof(buffer
))) > 0)
3432 if (cupsFileWrite(out
, buffer
, bytes
) < bytes
)
3434 cupsdLogMessage(CUPSD_LOG_ERROR
,
3435 "Unable to copy to config file \"%s\" - %s",
3436 newfile
, strerror(errno
));
3442 return (HTTP_SERVER_ERROR
);
3446 * Close the files...
3450 if (cupsFileClose(out
))
3452 cupsdLogMessage(CUPSD_LOG_ERROR
,
3453 "Error file closing config file \"%s\" - %s",
3454 newfile
, strerror(errno
));
3458 return (HTTP_SERVER_ERROR
);
3462 * Remove the request file...
3465 unlink(con
->filename
);
3466 cupsdClearString(&con
->filename
);
3469 * Unlink the old backup, rename the current config file to the backup
3470 * filename, and rename the new config file to the config file name...
3473 if (unlink(oldfile
))
3474 if (errno
!= ENOENT
)
3476 cupsdLogMessage(CUPSD_LOG_ERROR
,
3477 "Unable to remove backup config file \"%s\" - %s",
3478 oldfile
, strerror(errno
));
3482 return (HTTP_SERVER_ERROR
);
3485 if (rename(conffile
, oldfile
))
3486 if (errno
!= ENOENT
)
3488 cupsdLogMessage(CUPSD_LOG_ERROR
,
3489 "Unable to rename old config file \"%s\" - %s",
3490 conffile
, strerror(errno
));
3494 return (HTTP_SERVER_ERROR
);
3497 if (rename(newfile
, conffile
))
3499 cupsdLogMessage(CUPSD_LOG_ERROR
,
3500 "Unable to rename new config file \"%s\" - %s",
3501 newfile
, strerror(errno
));
3503 rename(oldfile
, conffile
);
3506 return (HTTP_SERVER_ERROR
);
3510 * If the cupsd.conf file was updated, set the NeedReload flag...
3513 if (!strcmp(con
->uri
, "/admin/conf/cupsd.conf"))
3514 NeedReload
= RELOAD_CUPSD
;
3516 NeedReload
= RELOAD_ALL
;
3518 ReloadTime
= time(NULL
);
3521 * Return that the file was created successfully...
3524 return (HTTP_CREATED
);
3529 * 'is_cgi()' - Is the resource a CGI script/program?
3532 static int /* O - 1 = CGI, 0 = file */
3533 is_cgi(cupsd_client_t
*con
, /* I - Client connection */
3534 const char *filename
, /* I - Real filename */
3535 struct stat
*filestats
, /* I - File information */
3536 mime_type_t
*type
) /* I - MIME type */
3538 const char *options
; /* Options on URL */
3541 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3542 "is_cgi(con=%p, filename=\"%s\", filestats=%p, type=%s/%s)\n",
3543 con
, filename
, filestats
, type
? type
->super
: "unknown",
3544 type
? type
->type
: "unknown");
3547 * Get the options, if any...
3550 if ((options
= strchr(con
->uri
, '?')) != NULL
)
3554 if (strchr(options
, '='))
3555 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", options
);
3559 * Check for known types...
3562 if (!type
|| strcasecmp(type
->super
, "application"))
3564 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "is_cgi: Returning 0...");
3568 if (!strcasecmp(type
->type
, "x-httpd-cgi") &&
3569 (filestats
->st_mode
& 0111))
3572 * "application/x-httpd-cgi" is a CGI script.
3575 cupsdSetString(&con
->command
, filename
);
3577 filename
= strrchr(filename
, '/') + 1; /* Filename always absolute */
3579 cupsdSetString(&con
->options
, options
);
3581 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3582 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3583 con
->command
, con
->options
);
3588 else if (!strcasecmp(type
->type
, "x-httpd-java"))
3591 * "application/x-httpd-java" is a Java servlet.
3594 cupsdSetString(&con
->command
, CUPS_JAVA
);
3597 cupsdSetStringf(&con
->options
, "%s %s", filename
, options
);
3599 cupsdSetString(&con
->options
, filename
);
3601 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3602 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3603 con
->command
, con
->options
);
3607 #endif /* HAVE_JAVA */
3609 else if (!strcasecmp(type
->type
, "x-httpd-perl"))
3612 * "application/x-httpd-perl" is a Perl page.
3615 cupsdSetString(&con
->command
, CUPS_PERL
);
3618 cupsdSetStringf(&con
->options
, "%s %s", filename
, options
);
3620 cupsdSetString(&con
->options
, filename
);
3622 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3623 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3624 con
->command
, con
->options
);
3628 #endif /* HAVE_PERL */
3630 else if (!strcasecmp(type
->type
, "x-httpd-php"))
3633 * "application/x-httpd-php" is a PHP page.
3636 cupsdSetString(&con
->command
, CUPS_PHP
);
3639 cupsdSetStringf(&con
->options
, "%s %s", filename
, options
);
3641 cupsdSetString(&con
->options
, filename
);
3643 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3644 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3645 con
->command
, con
->options
);
3649 #endif /* HAVE_PHP */
3651 else if (!strcasecmp(type
->type
, "x-httpd-python"))
3654 * "application/x-httpd-python" is a Python page.
3657 cupsdSetString(&con
->command
, CUPS_PYTHON
);
3660 cupsdSetStringf(&con
->options
, "%s %s", filename
, options
);
3662 cupsdSetString(&con
->options
, filename
);
3664 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3665 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3666 con
->command
, con
->options
);
3670 #endif /* HAVE_PYTHON */
3672 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "is_cgi: Returning 0...");
3679 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
3682 static int /* O - 0 if relative, 1 if absolute */
3683 is_path_absolute(const char *path
) /* I - Input path */
3686 * Check for a leading slash...
3693 * Check for "/.." in the path...
3696 while ((path
= strstr(path
, "/..")) != NULL
)
3698 if (!path
[3] || path
[3] == '/')
3705 * If we haven't found any relative paths, return 1 indicating an
3715 * 'make_certificate()' - Make a self-signed SSL/TLS certificate.
3718 static int /* O - 1 on success, 0 on failure */
3719 make_certificate(cupsd_client_t
*con
) /* I - Client connection */
3721 #if defined(HAVE_LIBSSL) && defined(HAVE_WAITPID)
3722 int pid
, /* Process ID of command */
3723 status
; /* Status of command */
3724 char command
[1024], /* Command */
3725 *argv
[12], /* Command-line arguments */
3726 *envp
[MAX_ENV
+ 1], /* Environment variables */
3727 home
[1024], /* HOME environment variable */
3728 infofile
[1024], /* Type-in information for cert */
3729 seedfile
[1024]; /* Random number seed file */
3730 int envc
, /* Number of environment variables */
3731 bytes
; /* Bytes written */
3732 cups_file_t
*fp
; /* Seed/info file */
3733 int infofd
; /* Info file descriptor */
3737 * Run the "openssl" command to seed the random number generator and
3738 * generate a self-signed certificate that is good for 10 years:
3740 * openssl rand -rand seedfile 1
3742 * openssl req -new -x509 -keyout ServerKey \
3743 * -out ServerCertificate -days 3650 -nodes
3745 * The seeding step is crucial in ensuring that the openssl command
3746 * does not block on systems without sufficient entropy...
3749 if (!cupsFileFind("openssl", getenv("PATH"), 1, command
, sizeof(command
)))
3751 cupsdLogMessage(CUPSD_LOG_ERROR
,
3752 "No SSL certificate and openssl command not found!");
3756 if (access("/dev/urandom", 0))
3759 * If the system doesn't provide /dev/urandom, then any random source
3760 * will probably be blocking-style, so generate some random data to
3761 * use as a seed for the certificate. Note that we have already
3762 * seeded the random number generator in cupsdInitCerts()...
3765 cupsdLogMessage(CUPSD_LOG_INFO
,
3766 "Seeding the random number generator...");
3768 snprintf(home
, sizeof(home
), "HOME=%s", TempDir
);
3771 * Write the seed file...
3774 if ((fp
= cupsTempFile2(seedfile
, sizeof(seedfile
))) == NULL
)
3776 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to create seed file %s - %s",
3777 seedfile
, strerror(errno
));
3781 for (bytes
= 0; bytes
< 262144; bytes
++)
3782 cupsFilePutChar(fp
, random());
3787 * Run the openssl command to seed its random number generator...
3790 argv
[0] = "openssl";
3797 envc
= cupsdLoadEnv(envp
, MAX_ENV
);
3798 envp
[envc
++] = home
;
3801 if (!cupsdStartProcess(command
, argv
, envp
, -1, -1, -1, -1, -1, 1, &pid
))
3807 while (waitpid(pid
, &status
, 0) < 0)
3814 cupsdFinishProcess(pid
, command
, sizeof(command
));
3817 * Remove the seed file, as it is no longer needed...
3824 if (WIFEXITED(status
))
3825 cupsdLogMessage(CUPSD_LOG_ERROR
,
3826 "Unable to seed random number generator - "
3827 "the openssl command stopped with status %d!",
3828 WEXITSTATUS(status
));
3830 cupsdLogMessage(CUPSD_LOG_ERROR
,
3831 "Unable to seed random number generator - "
3832 "the openssl command crashed on signal %d!",
3840 * Create a file with the certificate information fields...
3842 * Note: This assumes that the default questions are asked by the openssl
3846 if ((fp
= cupsTempFile2(infofile
, sizeof(infofile
))) == NULL
)
3848 cupsdLogMessage(CUPSD_LOG_ERROR
,
3849 "Unable to create certificate information file %s - %s",
3850 infofile
, strerror(errno
));
3854 cupsFilePrintf(fp
, ".\n.\n.\n%s\n.\n%s\n%s\n",
3855 ServerName
, ServerName
, ServerAdmin
);
3858 cupsdLogMessage(CUPSD_LOG_INFO
,
3859 "Generating SSL server key and certificate...");
3861 argv
[0] = "openssl";
3865 argv
[4] = "-keyout";
3866 argv
[5] = ServerKey
;
3868 argv
[7] = ServerCertificate
;
3871 argv
[10] = "-nodes";
3874 cupsdLoadEnv(envp
, MAX_ENV
);
3876 infofd
= open(infofile
, O_RDONLY
);
3878 if (!cupsdStartProcess(command
, argv
, envp
, infofd
, -1, -1, -1, -1, 1, &pid
))
3888 while (waitpid(pid
, &status
, 0) < 0)
3895 cupsdFinishProcess(pid
, command
, sizeof(command
));
3899 if (WIFEXITED(status
))
3900 cupsdLogMessage(CUPSD_LOG_ERROR
,
3901 "Unable to create SSL server key and certificate - "
3902 "the openssl command stopped with status %d!",
3903 WEXITSTATUS(status
));
3905 cupsdLogMessage(CUPSD_LOG_ERROR
,
3906 "Unable to create SSL server key and certificate - "
3907 "the openssl command crashed on signal %d!",
3912 cupsdLogMessage(CUPSD_LOG_INFO
, "Created SSL server key file \"%s\"...",
3914 cupsdLogMessage(CUPSD_LOG_INFO
,
3915 "Created SSL server certificate file \"%s\"...",
3921 #elif defined(HAVE_GNUTLS)
3922 gnutls_x509_crt crt
; /* Self-signed certificate */
3923 gnutls_x509_privkey key
; /* Encryption key */
3924 cups_lang_t
*language
; /* Default language info */
3925 cups_file_t
*fp
; /* Key/cert file */
3926 unsigned char buffer
[8192]; /* Buffer for x509 data */
3927 size_t bytes
; /* Number of bytes of data */
3928 unsigned char serial
[4]; /* Serial number buffer */
3929 time_t curtime
; /* Current time */
3930 int result
; /* Result of GNU TLS calls */
3934 * Create the encryption key...
3937 cupsdLogMessage(CUPSD_LOG_INFO
, "Generating SSL server key...");
3939 gnutls_x509_privkey_init(&key
);
3940 gnutls_x509_privkey_generate(key
, GNUTLS_PK_RSA
, 2048, 0);
3946 bytes
= sizeof(buffer
);
3948 if ((result
= gnutls_x509_privkey_export(key
, GNUTLS_X509_FMT_PEM
,
3949 buffer
, &bytes
)) < 0)
3951 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to export SSL server key - %s",
3952 gnutls_strerror(result
));
3953 gnutls_x509_privkey_deinit(key
);
3956 else if ((fp
= cupsFileOpen(ServerKey
, "w")) != NULL
)
3958 cupsFileWrite(fp
, (char *)buffer
, bytes
);
3961 cupsdLogMessage(CUPSD_LOG_INFO
, "Created SSL server key file \"%s\"...",
3966 cupsdLogMessage(CUPSD_LOG_ERROR
,
3967 "Unable to create SSL server key file \"%s\" - %s",
3968 ServerKey
, strerror(errno
));
3969 gnutls_x509_privkey_deinit(key
);
3974 * Create the self-signed certificate...
3977 cupsdLogMessage(CUPSD_LOG_INFO
, "Generating self-signed SSL certificate...");
3979 language
= cupsLangDefault();
3980 curtime
= time(NULL
);
3981 serial
[0] = curtime
>> 24;
3982 serial
[1] = curtime
>> 16;
3983 serial
[2] = curtime
>> 8;
3984 serial
[3] = curtime
;
3986 gnutls_x509_crt_init(&crt
);
3987 if (strlen(language
->language
) == 5)
3988 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
3989 language
->language
+ 3, 2);
3991 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
3993 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COMMON_NAME
, 0,
3994 ServerName
, strlen(ServerName
));
3995 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATION_NAME
, 0,
3996 ServerName
, strlen(ServerName
));
3997 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATIONAL_UNIT_NAME
,
3999 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_STATE_OR_PROVINCE_NAME
, 0,
4001 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_LOCALITY_NAME
, 0,
4003 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_PKCS9_EMAIL
, 0,
4004 ServerAdmin
, strlen(ServerAdmin
));
4005 gnutls_x509_crt_set_key(crt
, key
);
4006 gnutls_x509_crt_set_serial(crt
, serial
, sizeof(serial
));
4007 gnutls_x509_crt_set_activation_time(crt
, curtime
);
4008 gnutls_x509_crt_set_expiration_time(crt
, curtime
+ 10 * 365 * 86400);
4009 gnutls_x509_crt_set_ca_status(crt
, 0);
4010 gnutls_x509_crt_set_subject_alternative_name(crt
, GNUTLS_SAN_DNSNAME
,
4012 gnutls_x509_crt_set_key_purpose_oid(crt
, GNUTLS_KP_TLS_WWW_SERVER
, 0);
4013 gnutls_x509_crt_set_key_usage(crt
, GNUTLS_KEY_KEY_ENCIPHERMENT
);
4014 gnutls_x509_crt_set_version(crt
, 3);
4016 bytes
= sizeof(buffer
);
4017 if (gnutls_x509_crt_get_key_id(crt
, 0, buffer
, &bytes
) >= 0)
4018 gnutls_x509_crt_set_subject_key_id(crt
, buffer
, bytes
);
4020 gnutls_x509_crt_sign(crt
, crt
, key
);
4026 bytes
= sizeof(buffer
);
4027 if ((result
= gnutls_x509_crt_export(crt
, GNUTLS_X509_FMT_PEM
,
4028 buffer
, &bytes
)) < 0)
4029 cupsdLogMessage(CUPSD_LOG_ERROR
,
4030 "Unable to export SSL server certificate - %s",
4031 gnutls_strerror(result
));
4032 else if ((fp
= cupsFileOpen(ServerCertificate
, "w")) != NULL
)
4034 cupsFileWrite(fp
, (char *)buffer
, bytes
);
4037 cupsdLogMessage(CUPSD_LOG_INFO
,
4038 "Created SSL server certificate file \"%s\"...",
4042 cupsdLogMessage(CUPSD_LOG_ERROR
,
4043 "Unable to create SSL server certificate file \"%s\" - %s",
4044 ServerCertificate
, strerror(errno
));
4050 gnutls_x509_crt_deinit(crt
);
4051 gnutls_x509_privkey_deinit(key
);
4055 #elif defined(HAVE_CDSASSL) && defined(HAVE_WAITPID)
4056 int pid
, /* Process ID of command */
4057 status
; /* Status of command */
4058 char command
[1024], /* Command */
4059 *argv
[4], /* Command-line arguments */
4060 *envp
[MAX_ENV
+ 1], /* Environment variables */
4061 keychain
[1024], /* Keychain argument */
4062 infofile
[1024]; /* Type-in information for cert */
4063 cups_file_t
*fp
; /* Seed/info file */
4064 int infofd
; /* Info file descriptor */
4068 * Run the "certtool" command to generate a self-signed certificate...
4071 if (!cupsFileFind("certtool", getenv("PATH"), 1, command
, sizeof(command
)))
4073 cupsdLogMessage(CUPSD_LOG_ERROR
,
4074 "No SSL certificate and certtool command not found!");
4079 * Create a file with the certificate information fields...
4081 * Note: This assumes that the default questions are asked by the certtool
4085 if ((fp
= cupsTempFile2(infofile
, sizeof(infofile
))) == NULL
)
4087 cupsdLogMessage(CUPSD_LOG_ERROR
,
4088 "Unable to create certificate information file %s - %s",
4089 infofile
, strerror(errno
));
4093 cupsFilePrintf(fp
, "%s\nr\n\ny\nb\ns\ny\n%s\n\n\n\n\n%s\ny\n",
4094 con
->servername
, con
->servername
, ServerAdmin
);
4097 cupsdLogMessage(CUPSD_LOG_INFO
,
4098 "Generating SSL server key and certificate...");
4100 snprintf(keychain
, sizeof(keychain
), "k=%s", ServerCertificate
);
4102 argv
[0] = "certtool";
4107 cupsdLoadEnv(envp
, MAX_ENV
);
4109 infofd
= open(infofile
, O_RDONLY
);
4111 if (!cupsdStartProcess(command
, argv
, envp
, infofd
, -1, -1, -1, -1, 1, &pid
))
4121 while (waitpid(pid
, &status
, 0) < 0)
4128 cupsdFinishProcess(pid
, command
, sizeof(command
));
4132 if (WIFEXITED(status
))
4133 cupsdLogMessage(CUPSD_LOG_ERROR
,
4134 "Unable to create SSL server key and certificate - "
4135 "the certtool command stopped with status %d!",
4136 WEXITSTATUS(status
));
4138 cupsdLogMessage(CUPSD_LOG_ERROR
,
4139 "Unable to create SSL server key and certificate - "
4140 "the certtool command crashed on signal %d!",
4145 cupsdLogMessage(CUPSD_LOG_INFO
,
4146 "Created SSL server certificate file \"%s\"...",
4154 #endif /* HAVE_LIBSSL && HAVE_WAITPID */
4156 #endif /* HAVE_SSL */
4160 * 'pipe_command()' - Pipe the output of a command to the remote client.
4163 static int /* O - Process ID */
4164 pipe_command(cupsd_client_t
*con
, /* I - Client connection */
4165 int infile
, /* I - Standard input for command */
4166 int *outfile
, /* O - Standard output for command */
4167 char *command
, /* I - Command to run */
4168 char *options
, /* I - Options for command */
4169 int root
) /* I - Run as root? */
4171 int i
; /* Looping var */
4172 int pid
; /* Process ID */
4173 char *commptr
, /* Command string pointer */
4174 commch
; /* Command string character */
4175 char *uriptr
; /* URI string pointer */
4176 int fds
[2]; /* Pipe FDs */
4177 int argc
; /* Number of arguments */
4178 int envc
; /* Number of environment variables */
4179 char argbuf
[10240], /* Argument buffer */
4180 *argv
[100], /* Argument strings */
4181 *envp
[MAX_ENV
+ 18]; /* Environment variables */
4182 char content_length
[1024], /* CONTENT_LENGTH environment variable */
4183 content_type
[1024], /* CONTENT_TYPE environment variable */
4184 http_cookie
[32768], /* HTTP_COOKIE environment variable */
4185 http_referer
[1024], /* HTTP_REFERER environment variable */
4186 http_user_agent
[1024], /* HTTP_USER_AGENT environment variable */
4187 lang
[1024], /* LANG environment variable */
4188 path_info
[1024], /* PATH_INFO environment variable */
4189 remote_addr
[1024], /* REMOTE_ADDR environment variable */
4190 remote_host
[1024], /* REMOTE_HOST environment variable */
4191 remote_user
[1024], /* REMOTE_USER environment variable */
4192 script_name
[1024], /* SCRIPT_NAME environment variable */
4193 server_name
[1024], /* SERVER_NAME environment variable */
4194 server_port
[1024]; /* SERVER_PORT environment variable */
4198 * Parse a copy of the options string, which is of the form:
4200 * argument+argument+argument
4201 * ?argument+argument+argument
4202 * param=value¶m=value
4203 * ?param=value¶m=value
4204 * /name?argument+argument+argument
4205 * /name?param=value¶m=value
4207 * If the string contains an "=" character after the initial name,
4208 * then we treat it as a HTTP GET form request and make a copy of
4209 * the remaining string for the environment variable.
4211 * The string is always parsed out as command-line arguments, to
4212 * be consistent with Apache...
4215 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4216 "pipe_command: command=\"%s\", options=\"%s\"",
4217 command
, options
? options
: "(null)");
4222 strlcpy(argbuf
, options
, sizeof(argbuf
));
4226 if (argbuf
[0] == '/')
4229 * Found some trailing path information, set PATH_INFO...
4232 if ((commptr
= strchr(argbuf
, '?')) == NULL
)
4233 commptr
= argbuf
+ strlen(argbuf
);
4237 snprintf(path_info
, sizeof(path_info
), "PATH_INFO=%s", argbuf
);
4243 path_info
[0] = '\0';
4246 cupsdLogMessage(CUPSD_LOG_INFO
, "commptr=\"%s\"", commptr
);
4248 if (*commptr
== '?' && con
->operation
== HTTP_GET
&& !con
->query_string
)
4251 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", commptr
);
4258 argv
[argc
++] = commptr
;
4260 for (; *commptr
&& argc
< 99; commptr
++)
4263 * Break arguments whenever we see a + or space...
4266 if (*commptr
== ' ' || *commptr
== '+')
4268 while (*commptr
== ' ' || *commptr
== '+')
4272 * If we don't have a blank string, save it as another argument...
4277 argv
[argc
] = commptr
;
4283 else if (*commptr
== '%' && isxdigit(commptr
[1] & 255) &&
4284 isxdigit(commptr
[2] & 255))
4287 * Convert the %xx notation to the individual character.
4290 if (commptr
[1] >= '0' && commptr
[1] <= '9')
4291 *commptr
= (commptr
[1] - '0') << 4;
4293 *commptr
= (tolower(commptr
[1]) - 'a' + 10) << 4;
4295 if (commptr
[2] >= '0' && commptr
[2] <= '9')
4296 *commptr
|= commptr
[2] - '0';
4298 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
4300 _cups_strcpy(commptr
+ 1, commptr
+ 3);
4303 * Check for a %00 and break if that is the case...
4315 * Setup the environment variables as needed...
4319 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF-8", con
->language
->language
);
4321 strcpy(lang
, "LANG=C");
4323 strcpy(remote_addr
, "REMOTE_ADDR=");
4324 httpAddrString(con
->http
.hostaddr
, remote_addr
+ 12,
4325 sizeof(remote_addr
) - 12);
4327 snprintf(remote_host
, sizeof(remote_host
), "REMOTE_HOST=%s",
4328 con
->http
.hostname
);
4330 snprintf(script_name
, sizeof(script_name
), "SCRIPT_NAME=%s", con
->uri
);
4331 if ((uriptr
= strchr(script_name
, '?')) != NULL
)
4334 sprintf(server_port
, "SERVER_PORT=%d", con
->serverport
);
4336 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
4339 envc
= cupsdLoadEnv(envp
, (int)(sizeof(envp
) / sizeof(envp
[0])));
4341 envp
[envc
++] = lang
;
4342 envp
[envc
++] = "REDIRECT_STATUS=1";
4343 envp
[envc
++] = server_name
;
4344 envp
[envc
++] = server_port
;
4345 envp
[envc
++] = remote_addr
;
4346 envp
[envc
++] = remote_host
;
4347 envp
[envc
++] = script_name
;
4350 envp
[envc
++] = path_info
;
4352 if (con
->username
[0])
4354 snprintf(remote_user
, sizeof(remote_user
), "REMOTE_USER=%s", con
->username
);
4356 envp
[envc
++] = remote_user
;
4359 if (con
->http
.version
== HTTP_1_1
)
4360 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.1";
4361 else if (con
->http
.version
== HTTP_1_0
)
4362 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.0";
4364 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/0.9";
4366 if (con
->http
.cookie
)
4368 snprintf(http_cookie
, sizeof(http_cookie
), "HTTP_COOKIE=%s",
4370 envp
[envc
++] = http_cookie
;
4373 if (con
->http
.fields
[HTTP_FIELD_USER_AGENT
][0])
4375 snprintf(http_user_agent
, sizeof(http_user_agent
), "HTTP_USER_AGENT=%s",
4376 con
->http
.fields
[HTTP_FIELD_USER_AGENT
]);
4377 envp
[envc
++] = http_user_agent
;
4380 if (con
->http
.fields
[HTTP_FIELD_REFERER
][0])
4382 snprintf(http_referer
, sizeof(http_referer
), "HTTP_REFERER=%s",
4383 con
->http
.fields
[HTTP_FIELD_REFERER
]);
4384 envp
[envc
++] = http_referer
;
4387 if (con
->operation
== HTTP_GET
)
4389 envp
[envc
++] = "REQUEST_METHOD=GET";
4391 if (con
->query_string
)
4394 * Add GET form variables after ?...
4397 envp
[envc
++] = con
->query_string
;
4402 sprintf(content_length
, "CONTENT_LENGTH=" CUPS_LLFMT
,
4403 CUPS_LLCAST con
->bytes
);
4404 snprintf(content_type
, sizeof(content_type
), "CONTENT_TYPE=%s",
4405 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
4407 envp
[envc
++] = "REQUEST_METHOD=POST";
4408 envp
[envc
++] = content_length
;
4409 envp
[envc
++] = content_type
;
4413 * Tell the CGI if we are using encryption...
4417 envp
[envc
++] = "HTTPS=ON";
4420 * Terminate the environment array...
4425 if (LogLevel
== CUPSD_LOG_DEBUG2
)
4427 for (i
= 0; i
< argc
; i
++)
4428 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4429 "pipe_command: argv[%d] = \"%s\"", i
, argv
[i
]);
4430 for (i
= 0; i
< envc
; i
++)
4431 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4432 "pipe_command: envp[%d] = \"%s\"", i
, envp
[i
]);
4436 * Create a pipe for the output...
4439 if (cupsdOpenPipe(fds
))
4441 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to create pipes for CGI %s - %s",
4442 argv
[0], strerror(errno
));
4447 * Then execute the command...
4450 if (cupsdStartProcess(command
, argv
, envp
, infile
, fds
[1], CGIPipes
[1],
4451 -1, -1, root
, &pid
) < 0)
4454 * Error - can't fork!
4457 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to fork for CGI %s - %s", argv
[0],
4460 cupsdClosePipe(fds
);
4466 * Fork successful - return the PID...
4469 if (con
->username
[0])
4470 cupsdAddCert(pid
, con
->username
);
4472 cupsdLogMessage(CUPSD_LOG_DEBUG
, "CGI %s started - PID = %d", command
, pid
);
4483 * 'write_file()' - Send a file via HTTP.
4486 static int /* O - 0 on failure, 1 on success */
4487 write_file(cupsd_client_t
*con
, /* I - Client connection */
4488 http_status_t code
, /* I - HTTP status */
4489 char *filename
, /* I - Filename */
4490 char *type
, /* I - File type */
4491 struct stat
*filestats
) /* O - File information */
4493 con
->file
= open(filename
, O_RDONLY
);
4495 cupsdLogMessage(CUPSD_LOG_DEBUG
, "write_file: %d file=%d", con
->http
.fd
,
4501 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
4505 if (!cupsdSendHeader(con
, code
, type
))
4508 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
4509 httpGetDateString(filestats
->st_mtime
)) < 0)
4511 if (httpPrintf(HTTP(con
), "Content-Length: " CUPS_LLFMT
"\r\n",
4512 CUPS_LLCAST filestats
->st_size
) < 0)
4514 if (httpPrintf(HTTP(con
), "\r\n") < 0)
4517 if (cupsdFlushHeader(con
) < 0)
4520 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
4521 con
->http
.data_remaining
= filestats
->st_size
;
4523 if (con
->http
.data_remaining
<= INT_MAX
)
4524 con
->http
._data_remaining
= con
->http
.data_remaining
;
4526 con
->http
._data_remaining
= INT_MAX
;
4528 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
,
4529 (cupsd_selfunc_t
)cupsdWriteClient
, con
);
4536 * End of "$Id: client.c 6361 2007-03-19 16:01:28Z mike $".