2 * "$Id: client.c 6383 2007-03-21 20:01:20Z mike $"
4 * Client routines for the Common UNIX Printing System (CUPS) scheduler.
6 * Copyright 1997-2007 by Easy Software Products, all rights reserved.
8 * This file contains Kerberos support code, copyright 2006 by
11 * These coded instructions, statements, and computer programs are the
12 * property of Easy Software Products and are protected by Federal
13 * copyright law. Distribution and use rights are outlined in the file
14 * "LICENSE.txt" which should have been included with this file. If this
15 * file is missing or damaged please contact Easy Software Products
18 * Attn: CUPS Licensing Information
19 * Easy Software Products
20 * 44141 Airport View Drive, Suite 204
21 * Hollywood, Maryland 20636 USA
23 * Voice: (301) 373-9600
24 * EMail: cups-info@cups.org
25 * WWW: http://www.cups.org
29 * cupsdAcceptClient() - Accept a new client.
30 * cupsdCloseAllClients() - Close all remote clients immediately.
31 * cupsdCloseClient() - Close a remote client.
32 * cupsdFlushHeader() - Flush the header fields to the client.
33 * cupsdReadClient() - Read data from a client.
34 * cupsdSendCommand() - Send output from a command via HTTP.
35 * cupsdSendError() - Send an error message via HTTP.
36 * cupsdSendHeader() - Send an HTTP request.
37 * cupsdUpdateCGI() - Read status messages from CGI scripts and programs.
38 * cupsdWriteClient() - Write data to a client as needed.
39 * check_if_modified() - Decode an "If-Modified-Since" line.
40 * encrypt_client() - Enable encryption for the client...
41 * get_cdsa_certificate() - Convert a keychain name into the CFArrayRef
42 * required by SSLSetCertificate.
43 * get_file() - Get a filename and state info.
44 * install_conf_file() - Install a configuration file.
45 * is_cgi() - Is the resource a CGI script/program?
46 * is_path_absolute() - Is a path absolute and free of relative elements.
47 * make_certificate() - Make a self-signed SSL/TLS certificate.
48 * pipe_command() - Pipe the output of a command to the remote client.
49 * write_file() - Send a file via HTTP.
50 * write_pipe() - Flag that data is available on the CGI pipe.
54 * Include necessary headers...
57 #include <cups/http-private.h>
61 # include <Security/Security.h>
62 # ifdef HAVE_SECIDENTITYSEARCHPRIV_H
63 # include <Security/SecIdentitySearchPriv.h>
64 # else /* Declare prototype for function in that header... */
65 extern OSStatus
SecIdentitySearchCreateWithPolicy(SecPolicyRef policy
,
66 CFStringRef idString
, CSSM_KEYUSE keyUsage
,
67 CFTypeRef keychainOrArray
,
68 Boolean returnOnlyValidIdentities
,
69 SecIdentitySearchRef
* searchRef
);
70 # endif /* HAVE_SECIDENTITYSEARCHPRIV_H */
71 # ifdef HAVE_SECPOLICYPRIV_H
72 # include <Security/SecPolicyPriv.h>
73 # else /* Declare prototype for function in that header... */
74 extern OSStatus
SecPolicySetValue(SecPolicyRef policyRef
,
75 const CSSM_DATA
*value
);
76 # endif /* HAVE_SECPOLICYPRIV_H */
77 # ifdef HAVE_SECBASEPRIV_H
78 # include <Security/SecBasePriv.h>
79 # else /* Declare prototype for function in that header... */
80 extern const char *cssmErrorString(int error
);
81 # endif /* HAVE_SECBASEPRIV_H */
82 #endif /* HAVE_CDSASSL */
85 # include <gnutls/x509.h>
86 #endif /* HAVE_GNUTLS */
93 static int check_if_modified(cupsd_client_t
*con
,
94 struct stat
*filestats
);
96 static int encrypt_client(cupsd_client_t
*con
);
99 static CFArrayRef
get_cdsa_certificate(cupsd_client_t
*con
);
100 #endif /* HAVE_CDSASSL */
101 static char *get_file(cupsd_client_t
*con
, struct stat
*filestats
,
102 char *filename
, int len
);
103 static http_status_t
install_conf_file(cupsd_client_t
*con
);
104 static int is_cgi(cupsd_client_t
*con
, const char *filename
,
105 struct stat
*filestats
, mime_type_t
*type
);
106 static int is_path_absolute(const char *path
);
108 static int make_certificate(cupsd_client_t
*con
);
109 #endif /* HAVE_SSL */
110 static int pipe_command(cupsd_client_t
*con
, int infile
, int *outfile
,
111 char *command
, char *options
, int root
);
112 static int write_file(cupsd_client_t
*con
, http_status_t code
,
113 char *filename
, char *type
,
114 struct stat
*filestats
);
115 static void write_pipe(cupsd_client_t
*con
);
119 * 'cupsdAcceptClient()' - Accept a new client.
123 cupsdAcceptClient(cupsd_listener_t
*lis
)/* I - Listener socket */
125 int count
; /* Count of connections on a host */
126 int val
; /* Parameter value */
127 cupsd_client_t
*con
, /* New client pointer */
128 *tempcon
; /* Temporary client pointer */
129 http_addrlist_t
*addrlist
, /* List of adddresses for host */
130 *addr
; /* Current address */
131 socklen_t addrlen
; /* Length of address */
132 char *hostname
; /* Hostname for address */
133 http_addr_t temp
; /* Temporary address variable */
134 static time_t last_dos
= 0; /* Time of last DoS attack */
137 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
138 "cupsdAcceptClient(lis=%p) %d Clients = %d",
139 lis
, lis
->fd
, cupsArrayCount(Clients
));
142 * Make sure we don't have a full set of clients already...
145 if (cupsArrayCount(Clients
) == MaxClients
)
149 * Get a pointer to the next available client...
153 Clients
= cupsArrayNew(NULL
, NULL
);
158 con
= calloc(1, sizeof(cupsd_client_t
));
160 con
->http
.activity
= time(NULL
);
162 con
->http
.hostaddr
= &(con
->clientaddr
);
165 * Accept the client and get the remote address...
168 addrlen
= sizeof(http_addr_t
);
170 if ((con
->http
.fd
= accept(lis
->fd
, (struct sockaddr
*)con
->http
.hostaddr
,
173 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to accept client connection - %s.",
180 if (lis
->address
.addr
.sa_family
== AF_INET6
)
183 * Save the connected port number...
186 con
->http
.hostaddr
->ipv6
.sin6_port
= lis
->address
.ipv6
.sin6_port
;
189 * Convert IPv4 over IPv6 addresses (::ffff:n.n.n.n) to IPv4 forms we
190 * can more easily use...
193 if (con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[0] == 0 &&
194 con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[1] == 0 &&
195 ntohl(con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[2]) == 0xffff)
196 con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[2] = 0;
199 #endif /* AF_INET6 */
200 if (lis
->address
.addr
.sa_family
== AF_INET
)
201 con
->http
.hostaddr
->ipv4
.sin_port
= lis
->address
.ipv4
.sin_port
;
204 * Check the number of clients on the same address...
207 for (count
= 0, tempcon
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
209 tempcon
= (cupsd_client_t
*)cupsArrayNext(Clients
))
210 if (httpAddrEqual(tempcon
->http
.hostaddr
, con
->http
.hostaddr
))
213 if (count
>= MaxClientsPerHost
)
217 if (count
>= MaxClientsPerHost
)
219 if ((time(NULL
) - last_dos
) >= 60)
221 last_dos
= time(NULL
);
222 cupsdLogMessage(CUPSD_LOG_WARN
,
223 "Possible DoS attack - more than %d clients connecting "
225 MaxClientsPerHost
, tempcon
->http
.hostname
);
229 closesocket(con
->http
.fd
);
239 * Get the hostname or format the IP address as needed...
242 if (httpAddrLocalhost(con
->http
.hostaddr
))
245 * Map accesses from the loopback interface to "localhost"...
248 strlcpy(con
->http
.hostname
, "localhost", sizeof(con
->http
.hostname
));
249 hostname
= con
->http
.hostname
;
254 * Map accesses from the same host to the server name.
257 for (addr
= ServerAddrs
; addr
; addr
= addr
->next
)
258 if (httpAddrEqual(con
->http
.hostaddr
, &(addr
->addr
)))
263 strlcpy(con
->http
.hostname
, ServerName
, sizeof(con
->http
.hostname
));
264 hostname
= con
->http
.hostname
;
266 else if (HostNameLookups
)
267 hostname
= httpAddrLookup(con
->http
.hostaddr
, con
->http
.hostname
,
268 sizeof(con
->http
.hostname
));
272 httpAddrString(con
->http
.hostaddr
, con
->http
.hostname
,
273 sizeof(con
->http
.hostname
));
277 if (hostname
== NULL
&& HostNameLookups
== 2)
280 * Can't have an unresolved IP address with double-lookups enabled...
283 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
284 "cupsdAcceptClient: Closing connection %d...",
288 closesocket(con
->http
.fd
);
293 cupsdLogMessage(CUPSD_LOG_WARN
,
294 "Name lookup failed - connection from %s closed!",
301 if (HostNameLookups
== 2)
304 * Do double lookups as needed...
307 if ((addrlist
= httpAddrGetList(con
->http
.hostname
, AF_UNSPEC
, NULL
)) != NULL
)
310 * See if the hostname maps to the same IP address...
313 for (addr
= addrlist
; addr
; addr
= addr
->next
)
314 if (httpAddrEqual(con
->http
.hostaddr
, &(addr
->addr
)))
320 httpAddrFreeList(addrlist
);
325 * Can't have a hostname that doesn't resolve to the same IP address
326 * with double-lookups enabled...
329 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
330 "cupsdAcceptClient: Closing connection %d...",
334 closesocket(con
->http
.fd
);
339 cupsdLogMessage(CUPSD_LOG_WARN
,
340 "IP lookup failed - connection from %s closed!",
348 if (con
->http
.hostaddr
->addr
.sa_family
== AF_INET6
)
349 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdAcceptClient: %d from %s:%d (IPv6)",
350 con
->http
.fd
, con
->http
.hostname
,
351 ntohs(con
->http
.hostaddr
->ipv6
.sin6_port
));
353 #endif /* AF_INET6 */
355 if (con
->http
.hostaddr
->addr
.sa_family
== AF_LOCAL
)
356 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdAcceptClient: %d from %s (Domain)",
357 con
->http
.fd
, con
->http
.hostname
);
359 #endif /* AF_LOCAL */
360 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdAcceptClient: %d from %s:%d (IPv4)",
361 con
->http
.fd
, con
->http
.hostname
,
362 ntohs(con
->http
.hostaddr
->ipv4
.sin_port
));
365 * Get the local address the client connected to...
368 addrlen
= sizeof(temp
);
369 if (getsockname(con
->http
.fd
, (struct sockaddr
*)&temp
, &addrlen
))
371 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to get local address - %s",
374 strcpy(con
->servername
, "localhost");
375 con
->serverport
= LocalPort
;
380 if (temp
.addr
.sa_family
== AF_INET6
)
382 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
383 con
->serverport
= ntohs(lis
->address
.ipv6
.sin6_port
);
386 #endif /* AF_INET6 */
387 if (temp
.addr
.sa_family
== AF_INET
)
389 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
390 con
->serverport
= ntohs(lis
->address
.ipv4
.sin_port
);
394 strcpy(con
->servername
, "localhost");
395 con
->serverport
= LocalPort
;
399 cupsArrayAdd(Clients
, con
);
401 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
402 "cupsdAcceptClient: %d connected to server on %s:%d",
403 con
->http
.fd
, con
->servername
, con
->serverport
);
406 * Using TCP_NODELAY improves responsiveness, especially on systems
407 * with a slow loopback interface... Since we write large buffers
408 * when sending print files and requests, there shouldn't be any
409 * performance penalty for this...
413 setsockopt(con
->http
.fd
, IPPROTO_TCP
, TCP_NODELAY
, &val
, sizeof(val
));
416 * Close this file on all execs...
419 fcntl(con
->http
.fd
, F_SETFD
, fcntl(con
->http
.fd
, F_GETFD
) | FD_CLOEXEC
);
422 * Add the socket to the select() input mask.
425 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
428 * Temporarily suspend accept()'s until we lose a client...
431 if (cupsArrayCount(Clients
) == MaxClients
)
432 cupsdPauseListening();
436 * See if we are connecting on a secure port...
439 if (lis
->encryption
== HTTP_ENCRYPT_ALWAYS
)
442 * https connection; go secure...
445 con
->http
.encryption
= HTTP_ENCRYPT_ALWAYS
;
447 if (!encrypt_client(con
))
448 cupsdCloseClient(con
);
452 #endif /* HAVE_SSL */
457 * 'cupsdCloseAllClients()' - Close all remote clients immediately.
461 cupsdCloseAllClients(void)
463 cupsd_client_t
*con
; /* Current client */
466 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
468 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
469 cupsdCloseClient(con
);
474 * 'cupsdCloseClient()' - Close a remote client.
477 int /* O - 1 if partial close, 0 if fully closed */
478 cupsdCloseClient(cupsd_client_t
*con
) /* I - Client to close */
480 int partial
; /* Do partial close for SSL? */
482 SSL_CTX
*context
; /* Context for encryption */
483 SSL
*conn
; /* Connection for encryption */
484 unsigned long error
; /* Error code */
485 #elif defined(HAVE_GNUTLS)
486 http_tls_t
*conn
; /* TLS connection information */
487 int error
; /* Error code */
488 gnutls_certificate_server_credentials
*credentials
;
489 /* TLS credentials */
490 # elif defined(HAVE_CDSASSL)
491 http_tls_t
*conn
; /* CDSA connection information */
492 #endif /* HAVE_LIBSSL */
495 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdCloseClient: %d", con
->http
.fd
);
498 * Flush pending writes before closing...
501 httpFlushWrite(HTTP(con
));
507 * Shutdown encryption as needed...
515 conn
= (SSL
*)(con
->http
.tls
);
516 context
= SSL_get_SSL_CTX(conn
);
518 switch (SSL_shutdown(conn
))
521 cupsdLogMessage(CUPSD_LOG_INFO
,
522 "cupsdCloseClient: SSL shutdown successful!");
525 cupsdLogMessage(CUPSD_LOG_ERROR
,
526 "cupsdCloseClient: Fatal error during SSL shutdown!");
528 while ((error
= ERR_get_error()) != 0)
529 cupsdLogMessage(CUPSD_LOG_ERROR
, "cupsdCloseClient: %s",
530 ERR_error_string(error
, NULL
));
534 SSL_CTX_free(context
);
537 # elif defined(HAVE_GNUTLS)
538 conn
= (http_tls_t
*)(con
->http
.tls
);
539 credentials
= (gnutls_certificate_server_credentials
*)(conn
->credentials
);
541 error
= gnutls_bye(conn
->session
, GNUTLS_SHUT_WR
);
544 case GNUTLS_E_SUCCESS
:
545 cupsdLogMessage(CUPSD_LOG_INFO
,
546 "cupsdCloseClient: SSL shutdown successful!");
549 cupsdLogMessage(CUPSD_LOG_ERROR
,
550 "cupsdCloseClient: %s", gnutls_strerror(error
));
554 gnutls_deinit(conn
->session
);
555 gnutls_certificate_free_credentials(*credentials
);
559 # elif defined(HAVE_CDSASSL)
560 conn
= (http_tls_t
*)(con
->http
.tls
);
562 while (SSLClose(conn
->session
) == errSSLWouldBlock
)
565 SSLDisposeContext(conn
->session
);
567 if (conn
->certsArray
)
568 CFRelease(conn
->certsArray
);
571 # endif /* HAVE_LIBSSL */
573 con
->http
.tls
= NULL
;
575 #endif /* HAVE_SSL */
577 if (con
->pipe_pid
!= 0)
580 * Stop any CGI process...
583 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
584 "cupsdCloseClient: %d Killing process ID %d...",
585 con
->http
.fd
, con
->pipe_pid
);
586 cupsdEndProcess(con
->pipe_pid
, 1);
592 cupsdRemoveSelect(con
->file
);
594 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
595 "cupsdCloseClient: %d Closing data file %d.",
596 con
->http
.fd
, con
->file
);
603 * Close the socket and clear the file from the input set for select()...
606 if (con
->http
.fd
> 0)
611 * Only do a partial close so that the encrypted client gets everything.
614 shutdown(con
->http
.fd
, 0);
615 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
620 * Shut the socket down fully...
623 cupsdRemoveSelect(con
->http
.fd
);
635 if (con
->http
.input_set
)
636 free(con
->http
.input_set
);
638 httpClearCookie(HTTP(con
));
640 cupsdClearString(&con
->filename
);
641 cupsdClearString(&con
->command
);
642 cupsdClearString(&con
->options
);
643 cupsdClearString(&con
->query_string
);
647 ippDelete(con
->request
);
653 ippDelete(con
->response
);
654 con
->response
= NULL
;
659 cupsLangFree(con
->language
);
660 con
->language
= NULL
;
663 #ifdef HAVE_AUTHORIZATION_H
666 AuthorizationFree(con
->authref
, kAuthorizationFlagDefaults
);
669 #endif /* HAVE_AUTHORIZATION_H */
672 * Re-enable new client connections if we are going back under the
676 if (cupsArrayCount(Clients
) == MaxClients
)
677 cupsdResumeListening();
680 * Compact the list of clients as necessary...
683 cupsArrayRemove(Clients
, con
);
693 * 'cupsdFlushHeader()' - Flush the header fields to the client.
696 int /* I - Bytes written or -1 on error */
697 cupsdFlushHeader(cupsd_client_t
*con
) /* I - Client to flush to */
699 int bytes
= httpFlushWrite(HTTP(con
));
701 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
708 * 'cupsdReadClient()' - Read data from a client.
712 cupsdReadClient(cupsd_client_t
*con
) /* I - Client to read from */
714 char line
[32768], /* Line from client... */
715 operation
[64], /* Operation code from socket */
716 version
[64], /* HTTP version number string */
717 locale
[64], /* Locale */
718 *ptr
; /* Pointer into strings */
719 int major
, minor
; /* HTTP version numbers */
720 http_status_t status
; /* Transfer status */
721 ipp_state_t ipp_state
; /* State of IPP transfer */
722 int bytes
; /* Number of bytes to POST */
723 char *filename
; /* Name of file for GET/HEAD */
724 char buf
[1024]; /* Buffer for real filename */
725 struct stat filestats
; /* File information */
726 mime_type_t
*type
; /* MIME type of file */
727 cupsd_printer_t
*p
; /* Printer */
728 static unsigned request_id
= 0; /* Request ID for temp files */
731 status
= HTTP_CONTINUE
;
733 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
734 "cupsdReadClient: %d, used=%d, file=%d state=%d",
735 con
->http
.fd
, con
->http
.used
, con
->file
, con
->http
.state
);
739 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdReadClient: http error seen...");
740 cupsdCloseClient(con
);
748 * Automatically check for a SSL/TLS handshake...
753 if (recv(con
->http
.fd
, buf
, 1, MSG_PEEK
) == 1 &&
754 (!buf
[0] || !strchr("DGHOPT", buf
[0])))
757 * Encrypt this connection...
760 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
761 "cupsdReadClient: Saw first byte %02X, auto-negotiating SSL/TLS session...",
764 if (!encrypt_client(con
))
765 cupsdCloseClient(con
);
770 #endif /* HAVE_SSL */
772 switch (con
->http
.state
)
776 * See if we've received a request line...
779 if (httpGets(line
, sizeof(line
) - 1, HTTP(con
)) == NULL
)
781 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
782 "cupsdReadClient: httpGets returned EOF...");
783 cupsdCloseClient(con
);
788 * Ignore blank request lines...
795 * Clear other state variables...
798 httpClearFields(HTTP(con
));
800 con
->http
.activity
= time(NULL
);
801 con
->http
.version
= HTTP_1_0
;
802 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
803 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
804 con
->http
.data_remaining
= 0;
805 con
->http
._data_remaining
= 0;
806 con
->operation
= HTTP_WAITING
;
811 con
->username
[0] = '\0';
812 con
->password
[0] = '\0';
815 cupsdClearString(&con
->command
);
816 cupsdClearString(&con
->options
);
817 cupsdClearString(&con
->query_string
);
821 ippDelete(con
->request
);
827 ippDelete(con
->response
);
828 con
->response
= NULL
;
833 cupsLangFree(con
->language
);
834 con
->language
= NULL
;
838 * Grab the request line...
841 switch (sscanf(line
, "%63s%1023s%63s", operation
, con
->uri
, version
))
844 cupsdLogMessage(CUPSD_LOG_ERROR
,
845 "Bad request line \"%s\" from %s!", line
,
847 cupsdSendError(con
, HTTP_BAD_REQUEST
, AUTH_NONE
);
848 cupsdCloseClient(con
);
851 con
->http
.version
= HTTP_0_9
;
854 if (sscanf(version
, "HTTP/%d.%d", &major
, &minor
) != 2)
856 cupsdLogMessage(CUPSD_LOG_ERROR
,
857 "Bad request line \"%s\" from %s!", line
,
859 cupsdSendError(con
, HTTP_BAD_REQUEST
, AUTH_NONE
);
860 cupsdCloseClient(con
);
866 con
->http
.version
= (http_version_t
)(major
* 100 + minor
);
867 if (con
->http
.version
== HTTP_1_1
&& KeepAlive
)
868 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
870 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
874 cupsdSendError(con
, HTTP_NOT_SUPPORTED
, AUTH_NONE
);
875 cupsdCloseClient(con
);
882 * Handle full URLs in the request line...
885 if (strcmp(con
->uri
, "*"))
887 char method
[HTTP_MAX_URI
], /* Method/scheme */
888 userpass
[HTTP_MAX_URI
], /* Username:password */
889 hostname
[HTTP_MAX_URI
], /* Hostname */
890 resource
[HTTP_MAX_URI
]; /* Resource path */
891 int port
; /* Port number */
895 * Separate the URI into its components...
898 httpSeparateURI(HTTP_URI_CODING_MOST
, con
->uri
,
899 method
, sizeof(method
),
900 userpass
, sizeof(userpass
),
901 hostname
, sizeof(hostname
), &port
,
902 resource
, sizeof(resource
));
905 * Only allow URIs with the servername, localhost, or an IP
909 if (strcmp(method
, "file") &&
910 strcasecmp(hostname
, ServerName
) &&
911 strcasecmp(hostname
, "localhost") &&
912 !isdigit(hostname
[0]))
915 * Nope, we don't do proxies...
918 cupsdLogMessage(CUPSD_LOG_ERROR
, "Bad URI \"%s\" in request!",
920 cupsdSendError(con
, HTTP_METHOD_NOT_ALLOWED
, AUTH_NONE
);
921 cupsdCloseClient(con
);
926 * Copy the resource portion back into the URI; both resource and
927 * con->uri are HTTP_MAX_URI bytes in size...
930 strcpy(con
->uri
, resource
);
934 * Process the request...
937 if (!strcmp(operation
, "GET"))
938 con
->http
.state
= HTTP_GET
;
939 else if (!strcmp(operation
, "PUT"))
940 con
->http
.state
= HTTP_PUT
;
941 else if (!strcmp(operation
, "POST"))
942 con
->http
.state
= HTTP_POST
;
943 else if (!strcmp(operation
, "DELETE"))
944 con
->http
.state
= HTTP_DELETE
;
945 else if (!strcmp(operation
, "TRACE"))
946 con
->http
.state
= HTTP_TRACE
;
947 else if (!strcmp(operation
, "OPTIONS"))
948 con
->http
.state
= HTTP_OPTIONS
;
949 else if (!strcmp(operation
, "HEAD"))
950 con
->http
.state
= HTTP_HEAD
;
953 cupsdLogMessage(CUPSD_LOG_ERROR
, "Bad operation \"%s\"!", operation
);
954 cupsdSendError(con
, HTTP_BAD_REQUEST
, AUTH_NONE
);
955 cupsdCloseClient(con
);
959 con
->start
= time(NULL
);
960 con
->operation
= con
->http
.state
;
962 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdReadClient: %d %s %s HTTP/%d.%d",
963 con
->http
.fd
, operation
, con
->uri
,
964 con
->http
.version
/ 100, con
->http
.version
% 100);
966 con
->http
.status
= HTTP_OK
;
976 * Parse incoming parameters until the status changes...
979 while ((status
= httpUpdate(HTTP(con
))) == HTTP_CONTINUE
)
980 if (con
->http
.used
== 0 ||
981 !memchr(con
->http
.buffer
, '\n', con
->http
.used
))
984 if (status
!= HTTP_OK
&& status
!= HTTP_CONTINUE
)
986 cupsdSendError(con
, HTTP_BAD_REQUEST
, AUTH_NONE
);
987 cupsdCloseClient(con
);
993 break; /* Anti-compiler-warning-code */
997 * Handle new transfers...
1000 if (status
== HTTP_OK
)
1002 if (con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
][0])
1005 * Figure out the locale from the Accept-Language and Content-Type
1009 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ',')) != NULL
)
1012 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ';')) != NULL
)
1015 if ((ptr
= strstr(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
], "charset=")) != NULL
)
1018 * Combine language and charset, and trim any extra params in the
1022 snprintf(locale
, sizeof(locale
), "%s.%s",
1023 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ptr
+ 8);
1025 if ((ptr
= strchr(locale
, ',')) != NULL
)
1029 snprintf(locale
, sizeof(locale
), "%s.%s",
1030 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], DefaultCharset
);
1032 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1033 "cupsdReadClient: %d Browser asked for language \"%s\"...",
1034 con
->http
.fd
, locale
);
1036 con
->language
= cupsLangGet(locale
);
1039 con
->language
= cupsLangGet(DefaultLocale
);
1041 cupsdAuthorize(con
);
1043 if (!strncmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Keep-Alive", 10) &&
1045 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
1047 if (!con
->http
.fields
[HTTP_FIELD_HOST
][0] &&
1048 con
->http
.version
>= HTTP_1_1
)
1051 * HTTP/1.1 and higher require the "Host:" field...
1054 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, AUTH_NONE
))
1056 cupsdCloseClient(con
);
1060 else if (con
->operation
== HTTP_OPTIONS
)
1063 * Do OPTIONS command...
1066 if (con
->best
&& con
->best
->type
!= AUTH_NONE
)
1068 if (!cupsdSendHeader(con
, HTTP_UNAUTHORIZED
, NULL
, AUTH_NONE
))
1070 cupsdCloseClient(con
);
1075 if (!strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") &&
1076 con
->http
.tls
== NULL
)
1080 * Do encryption stuff...
1083 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
, AUTH_NONE
))
1085 cupsdCloseClient(con
);
1089 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1090 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1091 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1092 httpPrintf(HTTP(con
), "\r\n");
1094 if (cupsdFlushHeader(con
) < 0)
1096 cupsdCloseClient(con
);
1100 if (!encrypt_client(con
))
1102 cupsdCloseClient(con
);
1106 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, AUTH_NONE
))
1108 cupsdCloseClient(con
);
1111 #endif /* HAVE_SSL */
1114 if (!cupsdSendHeader(con
, HTTP_OK
, NULL
, AUTH_NONE
))
1116 cupsdCloseClient(con
);
1120 httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n");
1121 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1122 httpPrintf(HTTP(con
), "\r\n");
1124 if (cupsdFlushHeader(con
) < 0)
1126 cupsdCloseClient(con
);
1130 else if (!is_path_absolute(con
->uri
))
1133 * Protect against malicious users!
1136 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, AUTH_NONE
))
1138 cupsdCloseClient(con
);
1144 if (!strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") &&
1145 con
->http
.tls
== NULL
)
1149 * Do encryption stuff...
1152 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
, AUTH_NONE
))
1154 cupsdCloseClient(con
);
1158 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1159 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1160 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1161 httpPrintf(HTTP(con
), "\r\n");
1163 if (cupsdFlushHeader(con
) < 0)
1165 cupsdCloseClient(con
);
1169 if (!encrypt_client(con
))
1171 cupsdCloseClient(con
);
1175 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, AUTH_NONE
))
1177 cupsdCloseClient(con
);
1180 #endif /* HAVE_SSL */
1183 if ((status
= cupsdIsAuthorized(con
, NULL
)) != HTTP_OK
)
1185 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1186 "cupsdReadClient: Unauthorized request for %s...\n",
1188 cupsdSendError(con
, status
, AUTH_NONE
);
1189 cupsdCloseClient(con
);
1193 if (con
->http
.expect
&&
1194 (con
->operation
== HTTP_POST
|| con
->operation
== HTTP_PUT
))
1196 if (con
->http
.expect
== HTTP_CONTINUE
)
1199 * Send 100-continue header...
1202 if (!cupsdSendHeader(con
, HTTP_CONTINUE
, NULL
, AUTH_NONE
))
1204 cupsdCloseClient(con
);
1211 * Send 417-expectation-failed header...
1214 if (!cupsdSendHeader(con
, HTTP_EXPECTATION_FAILED
, NULL
, AUTH_NONE
))
1216 cupsdCloseClient(con
);
1220 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1221 httpPrintf(HTTP(con
), "\r\n");
1223 if (cupsdFlushHeader(con
) < 0)
1225 cupsdCloseClient(con
);
1231 switch (con
->http
.state
)
1233 case HTTP_GET_SEND
:
1234 if (!strncmp(con
->uri
, "/printers/", 10) &&
1235 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1238 * Send PPD file - get the real printer name since printer
1239 * names are not case sensitive but filenames can be...
1242 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1244 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1245 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1248 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, AUTH_NONE
))
1250 cupsdCloseClient(con
);
1258 if ((!strncmp(con
->uri
, "/admin", 6) &&
1259 strncmp(con
->uri
, "/admin/conf/", 12) &&
1260 strncmp(con
->uri
, "/admin/log/", 11)) ||
1261 !strncmp(con
->uri
, "/printers", 9) ||
1262 !strncmp(con
->uri
, "/classes", 8) ||
1263 !strncmp(con
->uri
, "/help", 5) ||
1264 !strncmp(con
->uri
, "/jobs", 5))
1267 * Send CGI output...
1270 if (!strncmp(con
->uri
, "/admin", 6))
1272 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1275 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1277 else if (!strncmp(con
->uri
, "/printers", 9))
1279 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1282 if (con
->uri
[9] && con
->uri
[10])
1283 cupsdSetString(&con
->options
, con
->uri
+ 9);
1285 cupsdSetString(&con
->options
, NULL
);
1287 else if (!strncmp(con
->uri
, "/classes", 8))
1289 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1292 if (con
->uri
[8] && con
->uri
[9])
1293 cupsdSetString(&con
->options
, con
->uri
+ 8);
1295 cupsdSetString(&con
->options
, NULL
);
1297 else if (!strncmp(con
->uri
, "/jobs", 5))
1299 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1302 if (con
->uri
[5] && con
->uri
[6])
1303 cupsdSetString(&con
->options
, con
->uri
+ 5);
1305 cupsdSetString(&con
->options
, NULL
);
1309 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1312 if (con
->uri
[5] && con
->uri
[6])
1313 cupsdSetString(&con
->options
, con
->uri
+ 5);
1315 cupsdSetString(&con
->options
, NULL
);
1318 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1320 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, AUTH_NONE
))
1322 cupsdCloseClient(con
);
1327 cupsdLogRequest(con
, HTTP_OK
);
1329 if (con
->http
.version
<= HTTP_1_0
)
1330 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1332 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1333 (strchr(con
->uri
+ 12, '/') ||
1334 strlen(con
->uri
) == 12)) ||
1335 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1336 (strchr(con
->uri
+ 11, '/') ||
1337 strlen(con
->uri
) == 11)))
1340 * GET can only be done to configuration files under
1344 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, AUTH_NONE
))
1346 cupsdCloseClient(con
);
1358 if ((filename
= get_file(con
, &filestats
, buf
,
1359 sizeof(buf
))) == NULL
)
1361 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, AUTH_NONE
))
1363 cupsdCloseClient(con
);
1370 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1372 if (is_cgi(con
, filename
, &filestats
, type
))
1375 * Note: con->command and con->options were set by
1379 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1381 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, AUTH_NONE
))
1383 cupsdCloseClient(con
);
1388 cupsdLogRequest(con
, HTTP_OK
);
1390 if (con
->http
.version
<= HTTP_1_0
)
1391 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1395 if (!check_if_modified(con
, &filestats
))
1397 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
, AUTH_NONE
))
1399 cupsdCloseClient(con
);
1406 strcpy(line
, "text/plain");
1408 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1410 if (!write_file(con
, HTTP_OK
, filename
, line
, &filestats
))
1412 cupsdCloseClient(con
);
1419 case HTTP_POST_RECV
:
1421 * See if the POST request includes a Content-Length field, and if
1422 * so check the length against any limits that are set...
1425 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "POST %s", con
->uri
);
1426 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "CONTENT_TYPE = %s",
1427 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
1429 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1430 MaxRequestSize
> 0 &&
1431 con
->http
.data_remaining
> MaxRequestSize
)
1434 * Request too large...
1437 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, AUTH_NONE
))
1439 cupsdCloseClient(con
);
1445 else if (con
->http
.data_remaining
< 0)
1448 * Negative content lengths are invalid!
1451 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, AUTH_NONE
))
1453 cupsdCloseClient(con
);
1461 * See what kind of POST request this is; for IPP requests the
1462 * content-type field will be "application/ipp"...
1465 if (!strcmp(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
],
1467 con
->request
= ippNew();
1468 else if ((!strncmp(con
->uri
, "/admin", 6) &&
1469 strncmp(con
->uri
, "/admin/conf/", 12) &&
1470 strncmp(con
->uri
, "/admin/log/", 11)) ||
1471 !strncmp(con
->uri
, "/printers", 9) ||
1472 !strncmp(con
->uri
, "/classes", 8) ||
1473 !strncmp(con
->uri
, "/help", 5) ||
1474 !strncmp(con
->uri
, "/jobs", 5))
1480 if (!strncmp(con
->uri
, "/admin", 6))
1482 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1485 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1487 else if (!strncmp(con
->uri
, "/printers", 9))
1489 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1492 if (con
->uri
[9] && con
->uri
[10])
1493 cupsdSetString(&con
->options
, con
->uri
+ 9);
1495 cupsdSetString(&con
->options
, NULL
);
1497 else if (!strncmp(con
->uri
, "/classes", 8))
1499 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1502 if (con
->uri
[8] && con
->uri
[9])
1503 cupsdSetString(&con
->options
, con
->uri
+ 8);
1505 cupsdSetString(&con
->options
, NULL
);
1507 else if (!strncmp(con
->uri
, "/jobs", 5))
1509 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1512 if (con
->uri
[5] && con
->uri
[6])
1513 cupsdSetString(&con
->options
, con
->uri
+ 5);
1515 cupsdSetString(&con
->options
, NULL
);
1519 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1522 if (con
->uri
[5] && con
->uri
[6])
1523 cupsdSetString(&con
->options
, con
->uri
+ 5);
1525 cupsdSetString(&con
->options
, NULL
);
1528 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1529 "cupsdReadClient: %d command=\"%s\", "
1531 con
->http
.fd
, con
->command
,
1532 con
->options
? con
->options
: "(null)");
1534 if (con
->http
.version
<= HTTP_1_0
)
1535 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1543 if ((filename
= get_file(con
, &filestats
, buf
,
1544 sizeof(buf
))) == NULL
)
1546 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, AUTH_NONE
))
1548 cupsdCloseClient(con
);
1555 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1557 if (!is_cgi(con
, filename
, &filestats
, type
))
1560 * Only POST to CGI's...
1563 if (!cupsdSendError(con
, HTTP_UNAUTHORIZED
, AUTH_NONE
))
1565 cupsdCloseClient(con
);
1572 case HTTP_PUT_RECV
:
1574 * Validate the resource name...
1577 if (strncmp(con
->uri
, "/admin/conf/", 12) ||
1578 strchr(con
->uri
+ 12, '/') ||
1579 strlen(con
->uri
) == 12)
1582 * PUT can only be done to configuration files under
1586 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, AUTH_NONE
))
1588 cupsdCloseClient(con
);
1596 * See if the PUT request includes a Content-Length field, and if
1597 * so check the length against any limits that are set...
1600 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "PUT %s", con
->uri
);
1601 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "CONTENT_TYPE = %s",
1602 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
1604 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1605 MaxRequestSize
> 0 &&
1606 con
->http
.data_remaining
> MaxRequestSize
)
1609 * Request too large...
1612 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, AUTH_NONE
))
1614 cupsdCloseClient(con
);
1620 else if (con
->http
.data_remaining
< 0)
1623 * Negative content lengths are invalid!
1626 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, AUTH_NONE
))
1628 cupsdCloseClient(con
);
1636 * Open a temporary file to hold the request...
1639 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
1641 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1643 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1644 "cupsdReadClient: %d REQUEST %s=%d", con
->http
.fd
,
1645 con
->filename
, con
->file
);
1649 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, AUTH_NONE
))
1651 cupsdCloseClient(con
);
1656 fchmod(con
->file
, 0640);
1657 fchown(con
->file
, RunUser
, Group
);
1658 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1663 cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, AUTH_NONE
);
1664 cupsdCloseClient(con
);
1668 if (!strncmp(con
->uri
, "/printers/", 10) &&
1669 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1672 * Send PPD file - get the real printer name since printer
1673 * names are not case sensitive but filenames can be...
1676 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1678 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1679 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1682 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, AUTH_NONE
))
1684 cupsdCloseClient(con
);
1692 if ((!strncmp(con
->uri
, "/admin", 6) &&
1693 strncmp(con
->uri
, "/admin/conf/", 12) &&
1694 strncmp(con
->uri
, "/admin/log/", 11)) ||
1695 !strncmp(con
->uri
, "/printers", 9) ||
1696 !strncmp(con
->uri
, "/classes", 8) ||
1697 !strncmp(con
->uri
, "/help", 5) ||
1698 !strncmp(con
->uri
, "/jobs", 5))
1704 if (!cupsdSendHeader(con
, HTTP_OK
, "text/html", AUTH_NONE
))
1706 cupsdCloseClient(con
);
1710 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1712 cupsdCloseClient(con
);
1716 if (cupsdFlushHeader(con
) < 0)
1718 cupsdCloseClient(con
);
1722 cupsdLogRequest(con
, HTTP_OK
);
1724 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1725 (strchr(con
->uri
+ 12, '/') ||
1726 strlen(con
->uri
) == 12)) ||
1727 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1728 (strchr(con
->uri
+ 11, '/') ||
1729 strlen(con
->uri
) == 11)))
1732 * HEAD can only be done to configuration files under
1736 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, AUTH_NONE
))
1738 cupsdCloseClient(con
);
1744 else if ((filename
= get_file(con
, &filestats
, buf
,
1745 sizeof(buf
))) == NULL
)
1747 if (!cupsdSendHeader(con
, HTTP_NOT_FOUND
, "text/html", AUTH_NONE
))
1749 cupsdCloseClient(con
);
1753 cupsdLogRequest(con
, HTTP_NOT_FOUND
);
1755 else if (!check_if_modified(con
, &filestats
))
1757 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
, AUTH_NONE
))
1759 cupsdCloseClient(con
);
1763 cupsdLogRequest(con
, HTTP_NOT_MODIFIED
);
1771 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1773 strcpy(line
, "text/plain");
1775 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1777 if (!cupsdSendHeader(con
, HTTP_OK
, line
, AUTH_NONE
))
1779 cupsdCloseClient(con
);
1783 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
1784 httpGetDateString(filestats
.st_mtime
)) < 0)
1786 cupsdCloseClient(con
);
1790 if (httpPrintf(HTTP(con
), "Content-Length: %lu\r\n",
1791 (unsigned long)filestats
.st_size
) < 0)
1793 cupsdCloseClient(con
);
1797 cupsdLogRequest(con
, HTTP_OK
);
1800 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1802 cupsdCloseClient(con
);
1806 if (cupsdFlushHeader(con
) < 0)
1808 cupsdCloseClient(con
);
1812 con
->http
.state
= HTTP_WAITING
;
1816 break; /* Anti-compiler-warning-code */
1822 * Handle any incoming data...
1825 switch (con
->http
.state
)
1827 case HTTP_PUT_RECV
:
1828 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1829 "cupsdReadClient: %d con->data_encoding=HTTP_ENCODE_%s, "
1830 "con->data_remaining=" CUPS_LLFMT
", con->file=%d",
1832 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
?
1833 "CHUNKED" : "LENGTH",
1834 CUPS_LLCAST con
->http
.data_remaining
, con
->file
);
1838 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
1840 cupsdCloseClient(con
);
1845 con
->bytes
+= bytes
;
1847 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1848 "cupsdReadClient: %d writing %d bytes to %d",
1849 con
->http
.fd
, bytes
, con
->file
);
1851 if (write(con
->file
, line
, bytes
) < bytes
)
1853 cupsdLogMessage(CUPSD_LOG_ERROR
,
1854 "cupsdReadClient: Unable to write %d bytes to %s: %s",
1855 bytes
, con
->filename
, strerror(errno
));
1857 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1858 "cupsdReadClient: Closing data file %d...",
1863 unlink(con
->filename
);
1864 cupsdClearString(&con
->filename
);
1866 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, AUTH_NONE
))
1868 cupsdCloseClient(con
);
1874 while (con
->http
.state
== HTTP_PUT_RECV
&& con
->http
.used
> 0);
1876 if (con
->http
.state
== HTTP_WAITING
)
1879 * End of file, see how big it is...
1882 fstat(con
->file
, &filestats
);
1884 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1885 "cupsdReadClient: %d Closing data file %d, size="
1887 con
->http
.fd
, con
->file
,
1888 CUPS_LLCAST filestats
.st_size
);
1893 if (filestats
.st_size
> MaxRequestSize
&&
1897 * Request is too big; remove it and send an error...
1900 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1901 "cupsdReadClient: %d Removing temp file %s",
1902 con
->http
.fd
, con
->filename
);
1903 unlink(con
->filename
);
1904 cupsdClearString(&con
->filename
);
1906 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, AUTH_NONE
))
1908 cupsdCloseClient(con
);
1914 * Install the configuration file...
1917 status
= install_conf_file(con
);
1920 * Return the status to the client...
1923 if (!cupsdSendError(con
, status
, AUTH_NONE
))
1925 cupsdCloseClient(con
);
1931 case HTTP_POST_RECV
:
1932 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1933 "cupsdReadClient: %d con->data_encoding=HTTP_ENCODE_"
1934 "%s, con->data_remaining=" CUPS_LLFMT
", con->file=%d",
1936 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
?
1937 "CHUNKED" : "LENGTH",
1938 CUPS_LLCAST con
->http
.data_remaining
, con
->file
);
1945 * Grab any request data from the connection...
1948 if ((ipp_state
= ippRead(&(con
->http
), con
->request
)) == IPP_ERROR
)
1950 cupsdLogMessage(CUPSD_LOG_ERROR
,
1951 "cupsdReadClient: %d IPP Read Error!",
1954 cupsdSendError(con
, HTTP_BAD_REQUEST
, AUTH_NONE
);
1955 cupsdCloseClient(con
);
1958 else if (ipp_state
!= IPP_DATA
)
1960 if (con
->http
.state
== HTTP_POST_SEND
)
1962 cupsdSendError(con
, HTTP_BAD_REQUEST
, AUTH_NONE
);
1963 cupsdCloseClient(con
);
1970 con
->bytes
+= ippLength(con
->request
);
1973 if (con
->file
< 0 && con
->http
.state
!= HTTP_POST_SEND
)
1976 * Create a file as needed for the request data...
1979 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
, request_id
++);
1980 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1982 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdReadClient: %d REQUEST %s=%d", con
->http
.fd
,
1983 con
->filename
, con
->file
);
1987 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, AUTH_NONE
))
1989 cupsdCloseClient(con
);
1994 fchmod(con
->file
, 0640);
1995 fchown(con
->file
, RunUser
, Group
);
1996 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1999 if (con
->http
.state
!= HTTP_POST_SEND
)
2001 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
2003 cupsdCloseClient(con
);
2008 con
->bytes
+= bytes
;
2010 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2011 "cupsdReadClient: %d writing %d bytes to %d",
2012 con
->http
.fd
, bytes
, con
->file
);
2014 if (write(con
->file
, line
, bytes
) < bytes
)
2016 cupsdLogMessage(CUPSD_LOG_ERROR
,
2017 "cupsdReadClient: Unable to write %d bytes to %s: %s",
2018 bytes
, con
->filename
, strerror(errno
));
2020 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2021 "cupsdReadClient: Closing file %d...",
2026 unlink(con
->filename
);
2027 cupsdClearString(&con
->filename
);
2029 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, AUTH_NONE
))
2031 cupsdCloseClient(con
);
2036 else if (con
->http
.state
== HTTP_POST_RECV
)
2038 else if (con
->http
.state
!= HTTP_POST_SEND
)
2040 cupsdCloseClient(con
);
2045 while (con
->http
.state
== HTTP_POST_RECV
&& con
->http
.used
> 0);
2047 if (con
->http
.state
== HTTP_POST_SEND
)
2051 fstat(con
->file
, &filestats
);
2053 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2054 "cupsdReadClient: %d Closing data file %d, "
2055 "size=" CUPS_LLFMT
".",
2056 con
->http
.fd
, con
->file
,
2057 CUPS_LLCAST filestats
.st_size
);
2062 if (filestats
.st_size
> MaxRequestSize
&&
2066 * Request is too big; remove it and send an error...
2069 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2070 "cupsdReadClient: %d Removing temp file %s",
2071 con
->http
.fd
, con
->filename
);
2072 unlink(con
->filename
);
2073 cupsdClearString(&con
->filename
);
2078 * Delete any IPP request data...
2081 ippDelete(con
->request
);
2082 con
->request
= NULL
;
2085 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, AUTH_NONE
))
2087 cupsdCloseClient(con
);
2094 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
2096 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, AUTH_NONE
))
2098 cupsdCloseClient(con
);
2103 cupsdLogRequest(con
, HTTP_OK
);
2109 cupsdProcessIPPRequest(con
);
2116 break; /* Anti-compiler-warning-code */
2119 if (!con
->http
.keep_alive
&& con
->http
.state
== HTTP_WAITING
)
2120 cupsdCloseClient(con
);
2125 * 'cupsdSendCommand()' - Send output from a command via HTTP.
2128 int /* O - 1 on success, 0 on failure */
2130 cupsd_client_t
*con
, /* I - Client connection */
2131 char *command
, /* I - Command to run */
2132 char *options
, /* I - Command-line options */
2133 int root
) /* I - Run as root? */
2135 int fd
; /* Standard input file descriptor */
2140 fd
= open(con
->filename
, O_RDONLY
);
2144 cupsdLogMessage(CUPSD_LOG_ERROR
,
2145 "cupsdSendCommand: %d Unable to open \"%s\" for reading: %s",
2146 con
->http
.fd
, con
->filename
? con
->filename
: "/dev/null",
2151 fcntl(fd
, F_SETFD
, fcntl(fd
, F_GETFD
) | FD_CLOEXEC
);
2156 con
->pipe_pid
= pipe_command(con
, fd
, &(con
->file
), command
, options
, root
);
2161 cupsdLogMessage(CUPSD_LOG_INFO
, "Started \"%s\" (pid=%d)", command
,
2164 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendCommand: %d file=%d",
2165 con
->http
.fd
, con
->file
);
2167 if (con
->pipe_pid
== 0)
2170 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2172 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2174 con
->sent_header
= 0;
2175 con
->file_ready
= 0;
2176 con
->got_fields
= 0;
2184 * 'cupsdSendError()' - Send an error message via HTTP.
2187 int /* O - 1 if successful, 0 otherwise */
2188 cupsdSendError(cupsd_client_t
*con
, /* I - Connection */
2189 http_status_t code
, /* I - Error code */
2190 int auth_type
)/* I - Authentication type */
2194 * Force client to upgrade for authentication if that is how the
2195 * server is configured...
2198 if (code
== HTTP_UNAUTHORIZED
&&
2199 DefaultEncryption
== HTTP_ENCRYPT_REQUIRED
&&
2200 strcasecmp(con
->http
.hostname
, "localhost") &&
2203 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2204 "cupsdSendError: Encryption before authentication!");
2205 code
= HTTP_UPGRADE_REQUIRED
;
2207 #endif /* HAVE_SSL */
2210 * Put the request in the access_log file...
2213 cupsdLogRequest(con
, code
);
2215 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendError: %d code=%d (%s)",
2216 con
->http
.fd
, code
, httpStatus(code
));
2219 * To work around bugs in some proxies, don't use Keep-Alive for some
2222 * Kerberos authentication doesn't work without Keep-Alive, so
2223 * never disable it in that case.
2226 if (code
>= HTTP_BAD_REQUEST
&& con
->http
.auth_type
!= AUTH_NEGOTIATE
)
2227 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
2230 * Send an error message back to the client. If the error code is a
2231 * 400 or 500 series, make sure the message contains some text, too!
2234 if (!cupsdSendHeader(con
, code
, NULL
, auth_type
))
2238 if (code
== HTTP_UPGRADE_REQUIRED
)
2239 if (httpPrintf(HTTP(con
), "Connection: Upgrade\r\n") < 0)
2242 if (httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n") < 0)
2244 #endif /* HAVE_SSL */
2246 if (con
->http
.version
>= HTTP_1_1
&&
2247 con
->http
.keep_alive
== HTTP_KEEPALIVE_OFF
)
2249 if (httpPrintf(HTTP(con
), "Connection: close\r\n") < 0)
2253 if (code
>= HTTP_BAD_REQUEST
)
2256 * Send a human-readable error message.
2259 char message
[4096], /* Message for user */
2260 urltext
[1024], /* URL redirection text */
2261 redirect
[1024]; /* Redirection link */
2262 const char *text
; /* Status-specific text */
2267 if (code
== HTTP_UNAUTHORIZED
)
2268 text
= _cupsLangString(con
->language
,
2269 _("Enter your username and password or the "
2270 "root username and password to access this "
2271 "page. If you are using Kerberos authentication, "
2272 "make sure you have a valid Kerberos ticket."));
2273 else if (code
== HTTP_UPGRADE_REQUIRED
)
2277 snprintf(urltext
, sizeof(urltext
),
2278 _cupsLangString(con
->language
,
2279 _("You must access this page using the URL "
2280 "<A HREF=\"https://%s:%d%s\">"
2281 "https://%s:%d%s</A>.")),
2282 con
->servername
, con
->serverport
, con
->uri
,
2283 con
->servername
, con
->serverport
, con
->uri
);
2285 snprintf(redirect
, sizeof(redirect
),
2286 "<META HTTP-EQUIV=\"Refresh\" "
2287 "CONTENT=\"3;URL=https://%s:%d%s\">\n",
2288 con
->servername
, con
->serverport
, con
->uri
);
2293 snprintf(message
, sizeof(message
),
2294 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" "
2295 "\"http://www.w3.org/TR/REC-html40/loose.dtd\">\n"
2298 "\t<META HTTP-EQUIV=\"Content-Type\" "
2299 "CONTENT=\"text/html; charset=utf-8\">\n"
2300 "\t<TITLE>%d %s</TITLE>\n"
2301 "\t<LINK REL=\"STYLESHEET\" TYPE=\"text/css\" "
2302 "HREF=\"/cups.css\">\n"
2310 code
, httpStatus(code
), redirect
, code
, httpStatus(code
), text
);
2312 if (httpPrintf(HTTP(con
), "Content-Type: text/html; charset=utf-8\r\n") < 0)
2314 if (httpPrintf(HTTP(con
), "Content-Length: %d\r\n",
2315 (int)strlen(message
)) < 0)
2317 if (httpPrintf(HTTP(con
), "\r\n") < 0)
2319 if (httpPrintf(HTTP(con
), "%s", message
) < 0)
2322 else if (httpPrintf(HTTP(con
), "\r\n") < 0)
2325 if (cupsdFlushHeader(con
) < 0)
2328 con
->http
.state
= HTTP_WAITING
;
2335 * 'cupsdSendHeader()' - Send an HTTP request.
2338 int /* O - 1 on success, 0 on failure */
2340 cupsd_client_t
*con
, /* I - Client to send to */
2341 http_status_t code
, /* I - HTTP status code */
2342 char *type
, /* I - MIME type of document */
2343 int auth_type
) /* I - Type of authentication */
2345 char auth_str
[1024]; /* Authorization string */
2349 * Send the HTTP status header...
2352 if (code
== HTTP_CONTINUE
)
2355 * 100-continue doesn't send any headers...
2358 return (httpPrintf(HTTP(con
), "HTTP/%d.%d 100 Continue\r\n\r\n",
2359 con
->http
.version
/ 100, con
->http
.version
% 100) > 0);
2362 httpFlushWrite(HTTP(con
));
2364 con
->http
.data_encoding
= HTTP_ENCODE_FIELDS
;
2366 if (httpPrintf(HTTP(con
), "HTTP/%d.%d %d %s\r\n", con
->http
.version
/ 100,
2367 con
->http
.version
% 100, code
, httpStatus(code
)) < 0)
2369 if (httpPrintf(HTTP(con
), "Date: %s\r\n", httpGetDateString(time(NULL
))) < 0)
2372 if (httpPrintf(HTTP(con
), "Server: %s\r\n", ServerHeader
) < 0)
2374 if (con
->http
.keep_alive
&& con
->http
.version
>= HTTP_1_0
)
2376 if (httpPrintf(HTTP(con
), "Connection: Keep-Alive\r\n") < 0)
2378 if (httpPrintf(HTTP(con
), "Keep-Alive: timeout=%d\r\n",
2379 KeepAliveTimeout
) < 0)
2382 if (code
== HTTP_METHOD_NOT_ALLOWED
)
2383 if (httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST\r\n") < 0)
2386 if (code
== HTTP_UNAUTHORIZED
)
2388 if (auth_type
== AUTH_NONE
)
2390 if (!con
->best
|| con
->best
->type
== AUTH_NONE
)
2391 auth_type
= DefaultAuthType
;
2393 auth_type
= con
->best
->type
;
2398 if (auth_type
== AUTH_BASIC
|| auth_type
== AUTH_BASICDIGEST
)
2399 strlcpy(auth_str
, "Basic realm=\"CUPS\"", sizeof(auth_str
));
2400 else if (auth_type
== AUTH_DIGEST
)
2401 snprintf(auth_str
, sizeof(auth_str
), "Digest realm=\"CUPS\", nonce=\"%s\"",
2402 con
->http
.hostname
);
2404 else if (auth_type
== AUTH_NEGOTIATE
&& !con
->no_negotiate
&&
2405 con
->gss_output_token
.length
== 0)
2406 strlcpy(auth_str
, "Negotiate", sizeof(auth_str
));
2407 #endif /* HAVE_GSSAPI */
2409 #ifdef HAVE_AUTHORIZATION_H
2412 int i
; /* Looping var */
2413 char *auth_key
; /* Auth key buffer */
2414 size_t auth_size
; /* Size of remaining buffer */
2417 auth_key
= auth_str
+ strlen(auth_str
);
2418 auth_size
= sizeof(auth_str
) - (auth_key
- auth_str
);
2420 for (i
= 0; i
< con
->best
->num_names
; i
++)
2422 if (!strncasecmp(con
->best
->names
[i
], "@AUTHKEY(", 9))
2424 snprintf(auth_key
, auth_size
, ", authkey=\"%s\"",
2425 con
->best
->names
[i
] + 9);
2426 /* end parenthesis is stripped in conf.c */
2429 else if (!strcasecmp(con
->best
->names
[i
], "@SYSTEM") &&
2432 snprintf(auth_key
, auth_size
, ", authkey=\"%s\"", SystemGroupAuthKey
);
2437 #endif /* HAVE_AUTHORIZATION_H */
2440 httpPrintf(HTTP(con
), "WWW-Authenticate: %s\r\n", auth_str
) < 0)
2446 * WWW-Authenticate: Negotiate can be included even for
2447 * non-401 replies...
2450 if (con
->gss_output_token
.length
> 0)
2452 char buf
[2048]; /* Output token buffer */
2453 OM_uint32 minor_status
; /* Minor status code */
2456 httpEncode64_2(buf
, sizeof(buf
),
2457 con
->gss_output_token
.value
,
2458 con
->gss_output_token
.length
);
2459 gss_release_buffer(&minor_status
, &con
->gss_output_token
);
2461 if (httpPrintf(HTTP(con
), "WWW-Authenticate: Negotiate %s\r\n", buf
) < 0)
2464 #endif /* HAVE_GSSAPI */
2466 if (con
->language
&& strcmp(con
->language
->language
, "C"))
2468 if (httpPrintf(HTTP(con
), "Content-Language: %s\r\n",
2469 con
->language
->language
) < 0)
2475 if (!strcmp(type
, "text/html"))
2477 if (httpPrintf(HTTP(con
),
2478 "Content-Type: text/html; charset=utf-8\r\n") < 0)
2481 else if (httpPrintf(HTTP(con
), "Content-Type: %s\r\n", type
) < 0)
2490 * 'cupsdUpdateCGI()' - Read status messages from CGI scripts and programs.
2494 cupsdUpdateCGI(void)
2496 char *ptr
, /* Pointer to end of line in buffer */
2497 message
[1024]; /* Pointer to message text */
2498 int loglevel
; /* Log level for message */
2501 while ((ptr
= cupsdStatBufUpdate(CGIStatusBuffer
, &loglevel
,
2502 message
, sizeof(message
))) != NULL
)
2503 if (!strchr(CGIStatusBuffer
->buffer
, '\n'))
2506 if (ptr
== NULL
&& !CGIStatusBuffer
->bufused
)
2509 * Fatal error on pipe - should never happen!
2512 cupsdLogMessage(CUPSD_LOG_CRIT
,
2513 "cupsdUpdateCGI: error reading from CGI error pipe - %s",
2520 * 'cupsdWriteClient()' - Write data to a client as needed.
2524 cupsdWriteClient(cupsd_client_t
*con
) /* I - Client connection */
2526 int bytes
; /* Number of bytes written */
2527 char buf
[16385]; /* Data buffer */
2528 char *bufptr
; /* Pointer into buffer */
2529 ipp_state_t ipp_state
; /* IPP state value */
2533 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2534 "cupsdWriteClient(con=%p) %d response=%p, file=%d "
2535 "pipe_pid=%d state=%d",
2536 con
, con
->http
.fd
, con
->response
, con
->file
, con
->pipe_pid
,
2540 if (con
->http
.state
!= HTTP_GET_SEND
&&
2541 con
->http
.state
!= HTTP_POST_SEND
)
2547 * Make sure we select on the CGI output...
2550 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2552 if (!con
->file_ready
)
2555 * Try again later when there is CGI output available...
2558 cupsdRemoveSelect(con
->http
.fd
);
2562 con
->file_ready
= 0;
2567 ipp_state
= ippWrite(HTTP(con
), con
->response
);
2568 bytes
= ipp_state
!= IPP_ERROR
&& ipp_state
!= IPP_DATA
;
2570 else if ((bytes
= read(con
->file
, buf
, sizeof(buf
) - 1)) > 0)
2572 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2573 "cupsdWriteClient: Read %d bytes from file %d...",
2576 if (con
->pipe_pid
&& !con
->got_fields
)
2579 * Inspect the data for Content-Type and other fields.
2584 for (bufptr
= buf
; !con
->got_fields
&& *bufptr
; bufptr
++)
2585 if (*bufptr
== '\n')
2588 * Send line to client...
2591 if (bufptr
> buf
&& bufptr
[-1] == '\r')
2595 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "Script header: %s", buf
);
2597 if (!con
->sent_header
)
2600 * Handle redirection and CGI status codes...
2603 if (!strncasecmp(buf
, "Location:", 9))
2605 cupsdSendHeader(con
, HTTP_SEE_OTHER
, NULL
, AUTH_NONE
);
2606 con
->sent_header
= 2;
2608 if (httpPrintf(HTTP(con
), "Content-Length: 0\r\n") < 0)
2611 else if (!strncasecmp(buf
, "Status:", 7))
2613 cupsdSendError(con
, (http_status_t
)atoi(buf
+ 7), AUTH_NONE
);
2614 con
->sent_header
= 2;
2618 cupsdSendHeader(con
, HTTP_OK
, NULL
, AUTH_NONE
);
2619 con
->sent_header
= 1;
2621 if (con
->http
.version
== HTTP_1_1
)
2623 if (httpPrintf(HTTP(con
), "Transfer-Encoding: chunked\r\n") < 0)
2629 if (strncasecmp(buf
, "Status:", 7))
2630 httpPrintf(HTTP(con
), "%s\r\n", buf
);
2632 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdWriteClient: %d %s",
2639 bytes
-= (bufptr
- buf
);
2640 memmove(buf
, bufptr
, bytes
+ 1);
2644 * See if the line was empty...
2647 if (con
->field_col
== 0)
2649 con
->got_fields
= 1;
2651 if (cupsdFlushHeader(con
) < 0)
2653 cupsdCloseClient(con
);
2657 if (con
->http
.version
== HTTP_1_1
)
2658 con
->http
.data_encoding
= HTTP_ENCODE_CHUNKED
;
2663 else if (*bufptr
!= '\r')
2666 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2667 "cupsdWriteClient: %d bytes=%d, got_fields=%d",
2668 con
->http
.fd
, bytes
, con
->got_fields
);
2670 if (bytes
> 0 && !con
->got_fields
)
2673 * Remaining text needs to go out...
2676 httpPrintf(HTTP(con
), "%s", buf
);
2678 con
->http
.activity
= time(NULL
);
2681 else if (bytes
== 0)
2682 con
->http
.activity
= time(NULL
);
2687 if (httpWrite2(HTTP(con
), buf
, bytes
) < 0)
2689 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2690 "cupsdWriteClient: %d Write of %d bytes failed!",
2691 con
->http
.fd
, bytes
);
2693 cupsdCloseClient(con
);
2697 con
->bytes
+= bytes
;
2699 if (con
->http
.state
== HTTP_WAITING
)
2706 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdWriteClient: %d bytes < 0",
2709 cupsdLogRequest(con
, HTTP_OK
);
2711 httpFlushWrite(HTTP(con
));
2713 if (con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
&& con
->sent_header
== 1)
2715 if (httpWrite2(HTTP(con
), "", 0) < 0)
2717 cupsdCloseClient(con
);
2722 con
->http
.state
= HTTP_WAITING
;
2724 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
2728 cupsdRemoveSelect(con
->file
);
2731 cupsdEndProcess(con
->pipe_pid
, 0);
2733 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2734 "cupsdWriteClient: %d Closing data file %d.",
2735 con
->http
.fd
, con
->file
);
2744 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2745 "cupsdWriteClient: %d Removing temp file %s",
2746 con
->http
.fd
, con
->filename
);
2747 unlink(con
->filename
);
2748 cupsdClearString(&con
->filename
);
2753 ippDelete(con
->request
);
2754 con
->request
= NULL
;
2759 ippDelete(con
->response
);
2760 con
->response
= NULL
;
2763 cupsdClearString(&con
->command
);
2764 cupsdClearString(&con
->options
);
2765 cupsdClearString(&con
->query_string
);
2767 if (!con
->http
.keep_alive
)
2769 cupsdCloseClient(con
);
2774 con
->http
.activity
= time(NULL
);
2779 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
2782 static int /* O - 1 if modified since */
2784 cupsd_client_t
*con
, /* I - Client connection */
2785 struct stat
*filestats
) /* I - File information */
2787 char *ptr
; /* Pointer into field */
2788 time_t date
; /* Time/date value */
2789 off_t size
; /* Size/length value */
2794 ptr
= con
->http
.fields
[HTTP_FIELD_IF_MODIFIED_SINCE
];
2799 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2800 "check_if_modified: %d If-Modified-Since=\"%s\"",
2803 while (*ptr
!= '\0')
2805 while (isspace(*ptr
) || *ptr
== ';')
2808 if (strncasecmp(ptr
, "length=", 7) == 0)
2811 size
= strtoll(ptr
, NULL
, 10);
2813 while (isdigit(*ptr
))
2816 else if (isalpha(*ptr
))
2818 date
= httpGetDateTime(ptr
);
2819 while (*ptr
!= '\0' && *ptr
!= ';')
2826 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2827 "check_if_modified: %d sizes=" CUPS_LLFMT
","
2828 CUPS_LLFMT
" dates=%d,%d",
2829 con
->http
.fd
, CUPS_LLCAST size
,
2830 CUPS_LLCAST filestats
->st_size
, (int)date
,
2831 (int)filestats
->st_mtime
);
2833 return ((size
!= filestats
->st_size
&& size
!= 0) ||
2834 (date
< filestats
->st_mtime
&& date
!= 0) ||
2835 (size
== 0 && date
== 0));
2841 * 'encrypt_client()' - Enable encryption for the client...
2844 static int /* O - 1 on success, 0 on error */
2845 encrypt_client(cupsd_client_t
*con
) /* I - Client to encrypt */
2848 SSL_CTX
*context
; /* Context for encryption */
2849 SSL
*conn
; /* Connection for encryption */
2850 BIO
*bio
; /* BIO data */
2851 unsigned long error
; /* Error code */
2855 * Verify that we have a certificate...
2858 if (access(ServerKey
, 0) || access(ServerCertificate
, 0))
2861 * Nope, make a self-signed certificate...
2864 if (!make_certificate(con
))
2869 * Create the SSL context and accept the connection...
2872 context
= SSL_CTX_new(SSLv23_server_method());
2874 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
2875 SSL_CTX_use_PrivateKey_file(context
, ServerKey
, SSL_FILETYPE_PEM
);
2876 SSL_CTX_use_certificate_file(context
, ServerCertificate
, SSL_FILETYPE_PEM
);
2878 bio
= BIO_new(_httpBIOMethods());
2879 BIO_ctrl(bio
, BIO_C_SET_FILE_PTR
, 0, (char *)HTTP(con
));
2881 conn
= SSL_new(context
);
2882 SSL_set_bio(conn
, bio
, bio
);
2884 if (SSL_accept(conn
) != 1)
2886 cupsdLogMessage(CUPSD_LOG_ERROR
,
2887 "encrypt_client: Unable to encrypt connection from %s!",
2888 con
->http
.hostname
);
2890 while ((error
= ERR_get_error()) != 0)
2891 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s",
2892 ERR_error_string(error
, NULL
));
2894 SSL_CTX_free(context
);
2899 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2900 "encrypt_client: %d Connection from %s now encrypted.",
2901 con
->http
.fd
, con
->http
.hostname
);
2903 con
->http
.tls
= conn
;
2906 # elif defined(HAVE_GNUTLS)
2907 http_tls_t
*conn
; /* TLS session object */
2908 int error
; /* Error code */
2909 gnutls_certificate_server_credentials
*credentials
;
2910 /* TLS credentials */
2914 * Verify that we have a certificate...
2917 if (access(ServerKey
, 0) || access(ServerCertificate
, 0))
2920 * Nope, make a self-signed certificate...
2923 if (!make_certificate(con
))
2928 * Create the SSL object and perform the SSL handshake...
2931 conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
));
2936 credentials
= (gnutls_certificate_server_credentials
*)
2937 malloc(sizeof(gnutls_certificate_server_credentials
));
2938 if (credentials
== NULL
)
2940 cupsdLogMessage(CUPSD_LOG_ERROR
,
2941 "encrypt_client: Unable to encrypt connection from %s!",
2942 con
->http
.hostname
);
2943 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s", strerror(errno
));
2949 gnutls_certificate_allocate_credentials(credentials
);
2950 gnutls_certificate_set_x509_key_file(*credentials
, ServerCertificate
,
2951 ServerKey
, GNUTLS_X509_FMT_PEM
);
2953 gnutls_init(&(conn
->session
), GNUTLS_SERVER
);
2954 gnutls_set_default_priority(conn
->session
);
2955 gnutls_credentials_set(conn
->session
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
2956 gnutls_transport_set_ptr(conn
->session
, (gnutls_transport_ptr
)HTTP(con
));
2957 gnutls_transport_set_pull_function(conn
->session
, _httpReadGNUTLS
);
2958 gnutls_transport_set_push_function(conn
->session
, _httpWriteGNUTLS
);
2960 error
= gnutls_handshake(conn
->session
);
2962 if (error
!= GNUTLS_E_SUCCESS
)
2964 cupsdLogMessage(CUPSD_LOG_ERROR
,
2965 "encrypt_client: Unable to encrypt connection from %s!",
2966 con
->http
.hostname
);
2967 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s",
2968 gnutls_strerror(error
));
2970 gnutls_deinit(conn
->session
);
2971 gnutls_certificate_free_credentials(*credentials
);
2977 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2978 "encrypt_client: %d Connection from %s now encrypted.",
2979 con
->http
.fd
, con
->http
.hostname
);
2981 conn
->credentials
= credentials
;
2982 con
->http
.tls
= conn
;
2985 # elif defined(HAVE_CDSASSL)
2986 OSStatus error
; /* Error code */
2987 http_tls_t
*conn
; /* CDSA connection information */
2990 if ((conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
))) == NULL
)
2994 conn
->session
= NULL
;
2995 conn
->certsArray
= get_cdsa_certificate(con
);
2997 if (!conn
->certsArray
)
3000 * No keychain (yet), make a self-signed certificate...
3003 if (make_certificate(con
))
3004 conn
->certsArray
= get_cdsa_certificate(con
);
3007 if (!conn
->certsArray
)
3009 cupsdLogMessage(CUPSD_LOG_ERROR
,
3010 "encrypt_client: Could not find signing key in keychain "
3011 "\"%s\"", ServerCertificate
);
3012 error
= errSSLBadCert
; /* errSSLBadConfiguration is a better choice, but not available on 10.2.x */
3016 error
= SSLNewContext(true, &conn
->session
);
3019 error
= SSLSetIOFuncs(conn
->session
, _httpReadCDSA
, _httpWriteCDSA
);
3022 error
= SSLSetProtocolVersionEnabled(conn
->session
, kSSLProtocol2
, false);
3025 error
= SSLSetConnection(conn
->session
, HTTP(con
));
3028 error
= SSLSetAllowsExpiredCerts(conn
->session
, true);
3031 error
= SSLSetAllowsAnyRoot(conn
->session
, true);
3034 error
= SSLSetCertificate(conn
->session
, conn
->certsArray
);
3039 * Perform SSL/TLS handshake
3042 while ((error
= SSLHandshake(conn
->session
)) == errSSLWouldBlock
)
3048 cupsdLogMessage(CUPSD_LOG_ERROR
,
3049 "encrypt_client: Unable to encrypt connection from %s!",
3050 con
->http
.hostname
);
3052 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s (%d)",
3053 cssmErrorString(error
), (int)error
);
3055 con
->http
.error
= error
;
3056 con
->http
.status
= HTTP_ERROR
;
3059 SSLDisposeContext(conn
->session
);
3061 if (conn
->certsArray
)
3062 CFRelease(conn
->certsArray
);
3069 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3070 "encrypt_client: %d Connection from %s now encrypted.",
3071 con
->http
.fd
, con
->http
.hostname
);
3073 con
->http
.tls
= conn
;
3076 # endif /* HAVE_LIBSSL */
3078 #endif /* HAVE_SSL */
3083 * 'get_cdsa_certificate()' - Get a SSL/TLS certificate from the System keychain.
3086 static CFArrayRef
/* O - Array of certificates */
3087 get_cdsa_certificate(cupsd_client_t
*con
) /* I - Client connection */
3089 OSStatus err
; /* Error info */
3090 SecKeychainRef keychain
; /* Keychain reference */
3091 SecIdentitySearchRef search
; /* Search reference */
3092 SecIdentityRef identity
; /* Identity */
3093 CFArrayRef certificates
= NULL
;
3094 /* Certificate array */
3097 if ((err
= SecKeychainOpen(ServerCertificate
, &keychain
)))
3099 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot open keychain \"%s\", %s",
3100 ServerCertificate
, cssmErrorString(err
));
3104 # if HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY
3106 * Use a policy to search for valid certificates who's common name matches the
3110 SecPolicySearchRef policy_search
; /* Policy search ref */
3111 SecPolicyRef policy
; /* Policy ref */
3112 CSSM_DATA options
; /* Policy options */
3113 CSSM_APPLE_TP_SSL_OPTIONS
3114 ssl_options
; /* SSL Option for hostname */
3117 if ((err
= SecPolicySearchCreate(CSSM_CERT_X_509v3
, &CSSMOID_APPLE_TP_SSL
,
3118 NULL
, &policy_search
)))
3120 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot create a policy search reference");
3121 CFRelease(keychain
);
3125 if ((err
= SecPolicySearchCopyNext(policy_search
, &policy
)))
3127 cupsdLogMessage(CUPSD_LOG_ERROR
,
3128 "Cannot find a policy to use for searching");
3129 CFRelease(keychain
);
3130 CFRelease(policy_search
);
3134 memset(&ssl_options
, 0, sizeof(ssl_options
));
3135 ssl_options
.Version
= CSSM_APPLE_TP_SSL_OPTS_VERSION
;
3136 ssl_options
.ServerName
= con
->servername
;
3137 ssl_options
.ServerNameLen
= strlen(con
->servername
);
3139 options
.Data
= (uint8
*)&ssl_options
;
3140 options
.Length
= sizeof(ssl_options
);
3142 if ((err
= SecPolicySetValue(policy
, &options
)))
3144 cupsdLogMessage(CUPSD_LOG_ERROR
,
3145 "Cannot set policy value to use for searching");
3146 CFRelease(keychain
);
3147 CFRelease(policy_search
);
3151 err
= SecIdentitySearchCreateWithPolicy(policy
, NULL
, CSSM_KEYUSE_SIGN
,
3152 keychain
, FALSE
, &search
);
3155 * Assume there is exactly one SecIdentity in the keychain...
3158 err
= SecIdentitySearchCreate(keychain
, CSSM_KEYUSE_SIGN
, &search
);
3159 # endif /* HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY */
3162 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3163 "Cannot create keychain search reference: %s",
3164 cssmErrorString(err
));
3167 if ((err
= SecIdentitySearchCopyNext(search
, &identity
)))
3169 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3170 "Cannot find signing key in keychain \"%s\", error %d",
3171 ServerCertificate
, (int)err
);
3175 if (CFGetTypeID(identity
) != SecIdentityGetTypeID())
3176 cupsdLogMessage(CUPSD_LOG_ERROR
,
3177 "SecIdentitySearchCopyNext CFTypeID failure!");
3180 if ((certificates
= CFArrayCreate(NULL
, (const void **)&identity
,
3181 1, &kCFTypeArrayCallBacks
)) == NULL
)
3182 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot create certificate array");
3185 CFRelease(identity
);
3191 # if HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY
3193 CFRelease(policy_search
);
3194 # endif /* HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY */
3196 return (certificates
);
3198 #endif /* HAVE_CDSASSL */
3202 * 'get_file()' - Get a filename and state info.
3205 static char * /* O - Real filename */
3206 get_file(cupsd_client_t
*con
, /* I - Client connection */
3207 struct stat
*filestats
, /* O - File information */
3208 char *filename
, /* IO - Filename buffer */
3209 int len
) /* I - Buffer length */
3211 int status
; /* Status of filesystem calls */
3212 char *ptr
; /* Pointer info filename */
3213 int plen
; /* Remaining length after pointer */
3217 * Figure out the real filename...
3220 if (!strncmp(con
->uri
, "/ppd/", 5))
3221 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
);
3222 else if (!strncmp(con
->uri
, "/rss/", 5) && !strchr(con
->uri
+ 5, '/'))
3223 snprintf(filename
, len
, "%s/rss/%s", CacheDir
, con
->uri
+ 5);
3224 else if (!strncmp(con
->uri
, "/admin/conf/", 12))
3225 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
+ 11);
3226 else if (!strncmp(con
->uri
, "/admin/log/", 11))
3228 if (!strcmp(con
->uri
+ 11, "access_log") && AccessLog
[0] == '/')
3229 strlcpy(filename
, AccessLog
, len
);
3230 else if (!strcmp(con
->uri
+ 11, "error_log") && ErrorLog
[0] == '/')
3231 strlcpy(filename
, ErrorLog
, len
);
3232 else if (!strcmp(con
->uri
+ 11, "page_log") && PageLog
[0] == '/')
3233 strlcpy(filename
, PageLog
, len
);
3237 else if (con
->language
)
3238 snprintf(filename
, len
, "%s/%s%s", DocumentRoot
, con
->language
->language
,
3241 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3243 if ((ptr
= strchr(filename
, '?')) != NULL
)
3247 * Grab the status for this language; if there isn't a language-specific file
3248 * then fallback to the default one...
3251 if ((status
= stat(filename
, filestats
)) != 0 && con
->language
&&
3252 strncmp(con
->uri
, "/ppd/", 5) &&
3253 strncmp(con
->uri
, "/admin/conf/", 12) &&
3254 strncmp(con
->uri
, "/admin/log/", 11))
3257 * Drop the country code...
3260 char ll
[3]; /* Short language name */
3263 strlcpy(ll
, con
->language
->language
, sizeof(ll
));
3264 snprintf(filename
, len
, "%s/%s%s", DocumentRoot
, ll
, con
->uri
);
3266 if ((ptr
= strchr(filename
, '?')) != NULL
)
3269 if ((status
= stat(filename
, filestats
)) != 0)
3272 * Drop the language prefix and try the root directory...
3275 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3277 if ((ptr
= strchr(filename
, '?')) != NULL
)
3280 status
= stat(filename
, filestats
);
3285 * If we're found a directory, get the index.html file instead...
3288 if (!status
&& S_ISDIR(filestats
->st_mode
))
3290 if (filename
[strlen(filename
) - 1] != '/')
3291 strlcat(filename
, "/", len
);
3293 ptr
= filename
+ strlen(filename
);
3294 plen
= len
- (ptr
- filename
);
3296 strlcpy(ptr
, "index.html", plen
);
3297 status
= stat(filename
, filestats
);
3302 strlcpy(ptr
, "index.class", plen
);
3303 status
= stat(filename
, filestats
);
3305 #endif /* HAVE_JAVA */
3310 strlcpy(ptr
, "index.pl", plen
);
3311 status
= stat(filename
, filestats
);
3313 #endif /* HAVE_PERL */
3318 strlcpy(ptr
, "index.php", plen
);
3319 status
= stat(filename
, filestats
);
3321 #endif /* HAVE_PHP */
3326 strlcpy(ptr
, "index.pyc", plen
);
3327 status
= stat(filename
, filestats
);
3332 strlcpy(ptr
, "index.py", plen
);
3333 status
= stat(filename
, filestats
);
3335 #endif /* HAVE_PYTHON */
3338 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "get_file: %d filename=%s size=%d",
3339 con
->http
.fd
, filename
,
3340 status
? -1 : (int)filestats
->st_size
);
3343 con
->http
.data_remaining
= (int)filestats
->st_size
;
3353 * 'install_conf_file()' - Install a configuration file.
3356 static http_status_t
/* O - Status */
3357 install_conf_file(cupsd_client_t
*con
) /* I - Connection */
3359 cups_file_t
*in
, /* Input file */
3360 *out
; /* Output file */
3361 char buffer
[1024]; /* Copy buffer */
3362 int bytes
; /* Number of bytes */
3363 char conffile
[1024], /* Configuration filename */
3364 newfile
[1024], /* New config filename */
3365 oldfile
[1024]; /* Old config filename */
3366 struct stat confinfo
; /* Config file info */
3370 * First construct the filenames...
3373 snprintf(conffile
, sizeof(conffile
), "%s%s", ServerRoot
, con
->uri
+ 11);
3374 snprintf(newfile
, sizeof(newfile
), "%s%s.N", ServerRoot
, con
->uri
+ 11);
3375 snprintf(oldfile
, sizeof(oldfile
), "%s%s.O", ServerRoot
, con
->uri
+ 11);
3377 cupsdLogMessage(CUPSD_LOG_INFO
, "Installing config file \"%s\"...", conffile
);
3380 * Get the owner, group, and permissions of the configuration file.
3381 * If it doesn't exist, assign it to the User and Group in the
3382 * cupsd.conf file with mode 0640 permissions.
3385 if (stat(conffile
, &confinfo
))
3387 confinfo
.st_uid
= User
;
3388 confinfo
.st_gid
= Group
;
3389 confinfo
.st_mode
= ConfigFilePerm
;
3393 * Open the request file and new config file...
3396 if ((in
= cupsFileOpen(con
->filename
, "rb")) == NULL
)
3398 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open request file \"%s\" - %s",
3399 con
->filename
, strerror(errno
));
3400 return (HTTP_SERVER_ERROR
);
3403 if ((out
= cupsFileOpen(newfile
, "wb")) == NULL
)
3406 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open config file \"%s\" - %s",
3407 newfile
, strerror(errno
));
3408 return (HTTP_SERVER_ERROR
);
3411 fchmod(cupsFileNumber(out
), confinfo
.st_mode
);
3412 fchown(cupsFileNumber(out
), confinfo
.st_uid
, confinfo
.st_gid
);
3415 * Copy from the request to the new config file...
3418 while ((bytes
= cupsFileRead(in
, buffer
, sizeof(buffer
))) > 0)
3419 if (cupsFileWrite(out
, buffer
, bytes
) < bytes
)
3421 cupsdLogMessage(CUPSD_LOG_ERROR
,
3422 "Unable to copy to config file \"%s\" - %s",
3423 newfile
, strerror(errno
));
3429 return (HTTP_SERVER_ERROR
);
3433 * Close the files...
3437 if (cupsFileClose(out
))
3439 cupsdLogMessage(CUPSD_LOG_ERROR
,
3440 "Error file closing config file \"%s\" - %s",
3441 newfile
, strerror(errno
));
3445 return (HTTP_SERVER_ERROR
);
3449 * Remove the request file...
3452 unlink(con
->filename
);
3453 cupsdClearString(&con
->filename
);
3456 * Unlink the old backup, rename the current config file to the backup
3457 * filename, and rename the new config file to the config file name...
3460 if (unlink(oldfile
))
3461 if (errno
!= ENOENT
)
3463 cupsdLogMessage(CUPSD_LOG_ERROR
,
3464 "Unable to remove backup config file \"%s\" - %s",
3465 oldfile
, strerror(errno
));
3469 return (HTTP_SERVER_ERROR
);
3472 if (rename(conffile
, oldfile
))
3473 if (errno
!= ENOENT
)
3475 cupsdLogMessage(CUPSD_LOG_ERROR
,
3476 "Unable to rename old config file \"%s\" - %s",
3477 conffile
, strerror(errno
));
3481 return (HTTP_SERVER_ERROR
);
3484 if (rename(newfile
, conffile
))
3486 cupsdLogMessage(CUPSD_LOG_ERROR
,
3487 "Unable to rename new config file \"%s\" - %s",
3488 newfile
, strerror(errno
));
3490 rename(oldfile
, conffile
);
3493 return (HTTP_SERVER_ERROR
);
3497 * If the cupsd.conf file was updated, set the NeedReload flag...
3500 if (!strcmp(con
->uri
, "/admin/conf/cupsd.conf"))
3501 NeedReload
= RELOAD_CUPSD
;
3503 NeedReload
= RELOAD_ALL
;
3505 ReloadTime
= time(NULL
);
3508 * Return that the file was created successfully...
3511 return (HTTP_CREATED
);
3516 * 'is_cgi()' - Is the resource a CGI script/program?
3519 static int /* O - 1 = CGI, 0 = file */
3520 is_cgi(cupsd_client_t
*con
, /* I - Client connection */
3521 const char *filename
, /* I - Real filename */
3522 struct stat
*filestats
, /* I - File information */
3523 mime_type_t
*type
) /* I - MIME type */
3525 const char *options
; /* Options on URL */
3528 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3529 "is_cgi(con=%p, filename=\"%s\", filestats=%p, type=%s/%s)\n",
3530 con
, filename
, filestats
, type
? type
->super
: "unknown",
3531 type
? type
->type
: "unknown");
3534 * Get the options, if any...
3537 if ((options
= strchr(con
->uri
, '?')) != NULL
)
3541 if (strchr(options
, '='))
3542 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", options
);
3546 * Check for known types...
3549 if (!type
|| strcasecmp(type
->super
, "application"))
3551 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "is_cgi: Returning 0...");
3555 if (!strcasecmp(type
->type
, "x-httpd-cgi") &&
3556 (filestats
->st_mode
& 0111))
3559 * "application/x-httpd-cgi" is a CGI script.
3562 cupsdSetString(&con
->command
, filename
);
3564 filename
= strrchr(filename
, '/') + 1; /* Filename always absolute */
3566 cupsdSetString(&con
->options
, options
);
3568 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3569 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3570 con
->command
, con
->options
);
3575 else if (!strcasecmp(type
->type
, "x-httpd-java"))
3578 * "application/x-httpd-java" is a Java servlet.
3581 cupsdSetString(&con
->command
, CUPS_JAVA
);
3584 cupsdSetStringf(&con
->options
, "%s %s", filename
, options
);
3586 cupsdSetString(&con
->options
, filename
);
3588 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3589 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3590 con
->command
, con
->options
);
3594 #endif /* HAVE_JAVA */
3596 else if (!strcasecmp(type
->type
, "x-httpd-perl"))
3599 * "application/x-httpd-perl" is a Perl page.
3602 cupsdSetString(&con
->command
, CUPS_PERL
);
3605 cupsdSetStringf(&con
->options
, "%s %s", filename
, options
);
3607 cupsdSetString(&con
->options
, filename
);
3609 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3610 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3611 con
->command
, con
->options
);
3615 #endif /* HAVE_PERL */
3617 else if (!strcasecmp(type
->type
, "x-httpd-php"))
3620 * "application/x-httpd-php" is a PHP page.
3623 cupsdSetString(&con
->command
, CUPS_PHP
);
3626 cupsdSetStringf(&con
->options
, "%s %s", filename
, options
);
3628 cupsdSetString(&con
->options
, filename
);
3630 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3631 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3632 con
->command
, con
->options
);
3636 #endif /* HAVE_PHP */
3638 else if (!strcasecmp(type
->type
, "x-httpd-python"))
3641 * "application/x-httpd-python" is a Python page.
3644 cupsdSetString(&con
->command
, CUPS_PYTHON
);
3647 cupsdSetStringf(&con
->options
, "%s %s", filename
, options
);
3649 cupsdSetString(&con
->options
, filename
);
3651 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3652 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3653 con
->command
, con
->options
);
3657 #endif /* HAVE_PYTHON */
3659 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "is_cgi: Returning 0...");
3666 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
3669 static int /* O - 0 if relative, 1 if absolute */
3670 is_path_absolute(const char *path
) /* I - Input path */
3673 * Check for a leading slash...
3680 * Check for "/.." in the path...
3683 while ((path
= strstr(path
, "/..")) != NULL
)
3685 if (!path
[3] || path
[3] == '/')
3692 * If we haven't found any relative paths, return 1 indicating an
3702 * 'make_certificate()' - Make a self-signed SSL/TLS certificate.
3705 static int /* O - 1 on success, 0 on failure */
3706 make_certificate(cupsd_client_t
*con
) /* I - Client connection */
3708 #if defined(HAVE_LIBSSL) && defined(HAVE_WAITPID)
3709 int pid
, /* Process ID of command */
3710 status
; /* Status of command */
3711 char command
[1024], /* Command */
3712 *argv
[12], /* Command-line arguments */
3713 *envp
[MAX_ENV
+ 1], /* Environment variables */
3714 home
[1024], /* HOME environment variable */
3715 infofile
[1024], /* Type-in information for cert */
3716 seedfile
[1024]; /* Random number seed file */
3717 int envc
, /* Number of environment variables */
3718 bytes
; /* Bytes written */
3719 cups_file_t
*fp
; /* Seed/info file */
3720 int infofd
; /* Info file descriptor */
3724 * Run the "openssl" command to seed the random number generator and
3725 * generate a self-signed certificate that is good for 10 years:
3727 * openssl rand -rand seedfile 1
3729 * openssl req -new -x509 -keyout ServerKey \
3730 * -out ServerCertificate -days 3650 -nodes
3732 * The seeding step is crucial in ensuring that the openssl command
3733 * does not block on systems without sufficient entropy...
3736 if (!cupsFileFind("openssl", getenv("PATH"), 1, command
, sizeof(command
)))
3738 cupsdLogMessage(CUPSD_LOG_ERROR
,
3739 "No SSL certificate and openssl command not found!");
3743 if (access("/dev/urandom", 0))
3746 * If the system doesn't provide /dev/urandom, then any random source
3747 * will probably be blocking-style, so generate some random data to
3748 * use as a seed for the certificate. Note that we have already
3749 * seeded the random number generator in cupsdInitCerts()...
3752 cupsdLogMessage(CUPSD_LOG_INFO
,
3753 "Seeding the random number generator...");
3755 snprintf(home
, sizeof(home
), "HOME=%s", TempDir
);
3758 * Write the seed file...
3761 if ((fp
= cupsTempFile2(seedfile
, sizeof(seedfile
))) == NULL
)
3763 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to create seed file %s - %s",
3764 seedfile
, strerror(errno
));
3768 for (bytes
= 0; bytes
< 262144; bytes
++)
3769 cupsFilePutChar(fp
, random());
3774 * Run the openssl command to seed its random number generator...
3777 argv
[0] = "openssl";
3784 envc
= cupsdLoadEnv(envp
, MAX_ENV
);
3785 envp
[envc
++] = home
;
3788 if (!cupsdStartProcess(command
, argv
, envp
, -1, -1, -1, -1, -1, 1, &pid
))
3794 while (waitpid(pid
, &status
, 0) < 0)
3801 cupsdFinishProcess(pid
, command
, sizeof(command
));
3804 * Remove the seed file, as it is no longer needed...
3811 if (WIFEXITED(status
))
3812 cupsdLogMessage(CUPSD_LOG_ERROR
,
3813 "Unable to seed random number generator - "
3814 "the openssl command stopped with status %d!",
3815 WEXITSTATUS(status
));
3817 cupsdLogMessage(CUPSD_LOG_ERROR
,
3818 "Unable to seed random number generator - "
3819 "the openssl command crashed on signal %d!",
3827 * Create a file with the certificate information fields...
3829 * Note: This assumes that the default questions are asked by the openssl
3833 if ((fp
= cupsTempFile2(infofile
, sizeof(infofile
))) == NULL
)
3835 cupsdLogMessage(CUPSD_LOG_ERROR
,
3836 "Unable to create certificate information file %s - %s",
3837 infofile
, strerror(errno
));
3841 cupsFilePrintf(fp
, ".\n.\n.\n%s\n.\n%s\n%s\n",
3842 ServerName
, ServerName
, ServerAdmin
);
3845 cupsdLogMessage(CUPSD_LOG_INFO
,
3846 "Generating SSL server key and certificate...");
3848 argv
[0] = "openssl";
3852 argv
[4] = "-keyout";
3853 argv
[5] = ServerKey
;
3855 argv
[7] = ServerCertificate
;
3858 argv
[10] = "-nodes";
3861 cupsdLoadEnv(envp
, MAX_ENV
);
3863 infofd
= open(infofile
, O_RDONLY
);
3865 if (!cupsdStartProcess(command
, argv
, envp
, infofd
, -1, -1, -1, -1, 1, &pid
))
3875 while (waitpid(pid
, &status
, 0) < 0)
3882 cupsdFinishProcess(pid
, command
, sizeof(command
));
3886 if (WIFEXITED(status
))
3887 cupsdLogMessage(CUPSD_LOG_ERROR
,
3888 "Unable to create SSL server key and certificate - "
3889 "the openssl command stopped with status %d!",
3890 WEXITSTATUS(status
));
3892 cupsdLogMessage(CUPSD_LOG_ERROR
,
3893 "Unable to create SSL server key and certificate - "
3894 "the openssl command crashed on signal %d!",
3899 cupsdLogMessage(CUPSD_LOG_INFO
, "Created SSL server key file \"%s\"...",
3901 cupsdLogMessage(CUPSD_LOG_INFO
,
3902 "Created SSL server certificate file \"%s\"...",
3908 #elif defined(HAVE_GNUTLS)
3909 gnutls_x509_crt crt
; /* Self-signed certificate */
3910 gnutls_x509_privkey key
; /* Encryption key */
3911 cups_lang_t
*language
; /* Default language info */
3912 cups_file_t
*fp
; /* Key/cert file */
3913 unsigned char buffer
[8192]; /* Buffer for x509 data */
3914 size_t bytes
; /* Number of bytes of data */
3915 unsigned char serial
[4]; /* Serial number buffer */
3916 time_t curtime
; /* Current time */
3917 int result
; /* Result of GNU TLS calls */
3921 * Create the encryption key...
3924 cupsdLogMessage(CUPSD_LOG_INFO
, "Generating SSL server key...");
3926 gnutls_x509_privkey_init(&key
);
3927 gnutls_x509_privkey_generate(key
, GNUTLS_PK_RSA
, 2048, 0);
3933 bytes
= sizeof(buffer
);
3935 if ((result
= gnutls_x509_privkey_export(key
, GNUTLS_X509_FMT_PEM
,
3936 buffer
, &bytes
)) < 0)
3938 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to export SSL server key - %s",
3939 gnutls_strerror(result
));
3940 gnutls_x509_privkey_deinit(key
);
3943 else if ((fp
= cupsFileOpen(ServerKey
, "w")) != NULL
)
3945 cupsFileWrite(fp
, (char *)buffer
, bytes
);
3948 cupsdLogMessage(CUPSD_LOG_INFO
, "Created SSL server key file \"%s\"...",
3953 cupsdLogMessage(CUPSD_LOG_ERROR
,
3954 "Unable to create SSL server key file \"%s\" - %s",
3955 ServerKey
, strerror(errno
));
3956 gnutls_x509_privkey_deinit(key
);
3961 * Create the self-signed certificate...
3964 cupsdLogMessage(CUPSD_LOG_INFO
, "Generating self-signed SSL certificate...");
3966 language
= cupsLangDefault();
3967 curtime
= time(NULL
);
3968 serial
[0] = curtime
>> 24;
3969 serial
[1] = curtime
>> 16;
3970 serial
[2] = curtime
>> 8;
3971 serial
[3] = curtime
;
3973 gnutls_x509_crt_init(&crt
);
3974 if (strlen(language
->language
) == 5)
3975 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
3976 language
->language
+ 3, 2);
3978 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
3980 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COMMON_NAME
, 0,
3981 ServerName
, strlen(ServerName
));
3982 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATION_NAME
, 0,
3983 ServerName
, strlen(ServerName
));
3984 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATIONAL_UNIT_NAME
,
3986 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_STATE_OR_PROVINCE_NAME
, 0,
3988 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_LOCALITY_NAME
, 0,
3990 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_PKCS9_EMAIL
, 0,
3991 ServerAdmin
, strlen(ServerAdmin
));
3992 gnutls_x509_crt_set_key(crt
, key
);
3993 gnutls_x509_crt_set_serial(crt
, serial
, sizeof(serial
));
3994 gnutls_x509_crt_set_activation_time(crt
, curtime
);
3995 gnutls_x509_crt_set_expiration_time(crt
, curtime
+ 10 * 365 * 86400);
3996 gnutls_x509_crt_set_ca_status(crt
, 0);
3997 gnutls_x509_crt_set_subject_alternative_name(crt
, GNUTLS_SAN_DNSNAME
,
3999 gnutls_x509_crt_set_key_purpose_oid(crt
, GNUTLS_KP_TLS_WWW_SERVER
, 0);
4000 gnutls_x509_crt_set_key_usage(crt
, GNUTLS_KEY_KEY_ENCIPHERMENT
);
4001 gnutls_x509_crt_set_version(crt
, 3);
4003 bytes
= sizeof(buffer
);
4004 if (gnutls_x509_crt_get_key_id(crt
, 0, buffer
, &bytes
) >= 0)
4005 gnutls_x509_crt_set_subject_key_id(crt
, buffer
, bytes
);
4007 gnutls_x509_crt_sign(crt
, crt
, key
);
4013 bytes
= sizeof(buffer
);
4014 if ((result
= gnutls_x509_crt_export(crt
, GNUTLS_X509_FMT_PEM
,
4015 buffer
, &bytes
)) < 0)
4016 cupsdLogMessage(CUPSD_LOG_ERROR
,
4017 "Unable to export SSL server certificate - %s",
4018 gnutls_strerror(result
));
4019 else if ((fp
= cupsFileOpen(ServerCertificate
, "w")) != NULL
)
4021 cupsFileWrite(fp
, (char *)buffer
, bytes
);
4024 cupsdLogMessage(CUPSD_LOG_INFO
,
4025 "Created SSL server certificate file \"%s\"...",
4029 cupsdLogMessage(CUPSD_LOG_ERROR
,
4030 "Unable to create SSL server certificate file \"%s\" - %s",
4031 ServerCertificate
, strerror(errno
));
4037 gnutls_x509_crt_deinit(crt
);
4038 gnutls_x509_privkey_deinit(key
);
4042 #elif defined(HAVE_CDSASSL) && defined(HAVE_WAITPID)
4043 int pid
, /* Process ID of command */
4044 status
; /* Status of command */
4045 char command
[1024], /* Command */
4046 *argv
[4], /* Command-line arguments */
4047 *envp
[MAX_ENV
+ 1], /* Environment variables */
4048 keychain
[1024], /* Keychain argument */
4049 infofile
[1024]; /* Type-in information for cert */
4050 cups_file_t
*fp
; /* Seed/info file */
4051 int infofd
; /* Info file descriptor */
4055 * Run the "certtool" command to generate a self-signed certificate...
4058 if (!cupsFileFind("certtool", getenv("PATH"), 1, command
, sizeof(command
)))
4060 cupsdLogMessage(CUPSD_LOG_ERROR
,
4061 "No SSL certificate and certtool command not found!");
4066 * Create a file with the certificate information fields...
4068 * Note: This assumes that the default questions are asked by the certtool
4072 if ((fp
= cupsTempFile2(infofile
, sizeof(infofile
))) == NULL
)
4074 cupsdLogMessage(CUPSD_LOG_ERROR
,
4075 "Unable to create certificate information file %s - %s",
4076 infofile
, strerror(errno
));
4080 cupsFilePrintf(fp
, "%s\nr\n\ny\nb\ns\ny\n%s\n\n\n\n\n%s\ny\n",
4081 con
->servername
, con
->servername
, ServerAdmin
);
4084 cupsdLogMessage(CUPSD_LOG_INFO
,
4085 "Generating SSL server key and certificate...");
4087 snprintf(keychain
, sizeof(keychain
), "k=%s", ServerCertificate
);
4089 argv
[0] = "certtool";
4094 cupsdLoadEnv(envp
, MAX_ENV
);
4096 infofd
= open(infofile
, O_RDONLY
);
4098 if (!cupsdStartProcess(command
, argv
, envp
, infofd
, -1, -1, -1, -1, 1, &pid
))
4108 while (waitpid(pid
, &status
, 0) < 0)
4115 cupsdFinishProcess(pid
, command
, sizeof(command
));
4119 if (WIFEXITED(status
))
4120 cupsdLogMessage(CUPSD_LOG_ERROR
,
4121 "Unable to create SSL server key and certificate - "
4122 "the certtool command stopped with status %d!",
4123 WEXITSTATUS(status
));
4125 cupsdLogMessage(CUPSD_LOG_ERROR
,
4126 "Unable to create SSL server key and certificate - "
4127 "the certtool command crashed on signal %d!",
4132 cupsdLogMessage(CUPSD_LOG_INFO
,
4133 "Created SSL server certificate file \"%s\"...",
4141 #endif /* HAVE_LIBSSL && HAVE_WAITPID */
4143 #endif /* HAVE_SSL */
4147 * 'pipe_command()' - Pipe the output of a command to the remote client.
4150 static int /* O - Process ID */
4151 pipe_command(cupsd_client_t
*con
, /* I - Client connection */
4152 int infile
, /* I - Standard input for command */
4153 int *outfile
, /* O - Standard output for command */
4154 char *command
, /* I - Command to run */
4155 char *options
, /* I - Options for command */
4156 int root
) /* I - Run as root? */
4158 int i
; /* Looping var */
4159 int pid
; /* Process ID */
4160 char *commptr
, /* Command string pointer */
4161 commch
; /* Command string character */
4162 char *uriptr
; /* URI string pointer */
4163 int fds
[2]; /* Pipe FDs */
4164 int argc
; /* Number of arguments */
4165 int envc
; /* Number of environment variables */
4166 char argbuf
[10240], /* Argument buffer */
4167 *argv
[100], /* Argument strings */
4168 *envp
[MAX_ENV
+ 18]; /* Environment variables */
4169 char content_length
[1024], /* CONTENT_LENGTH environment variable */
4170 content_type
[1024], /* CONTENT_TYPE environment variable */
4171 http_cookie
[32768], /* HTTP_COOKIE environment variable */
4172 http_referer
[1024], /* HTTP_REFERER environment variable */
4173 http_user_agent
[1024], /* HTTP_USER_AGENT environment variable */
4174 lang
[1024], /* LANG environment variable */
4175 path_info
[1024], /* PATH_INFO environment variable */
4176 remote_addr
[1024], /* REMOTE_ADDR environment variable */
4177 remote_host
[1024], /* REMOTE_HOST environment variable */
4178 remote_user
[1024], /* REMOTE_USER environment variable */
4179 script_name
[1024], /* SCRIPT_NAME environment variable */
4180 server_name
[1024], /* SERVER_NAME environment variable */
4181 server_port
[1024]; /* SERVER_PORT environment variable */
4185 * Parse a copy of the options string, which is of the form:
4187 * argument+argument+argument
4188 * ?argument+argument+argument
4189 * param=value¶m=value
4190 * ?param=value¶m=value
4191 * /name?argument+argument+argument
4192 * /name?param=value¶m=value
4194 * If the string contains an "=" character after the initial name,
4195 * then we treat it as a HTTP GET form request and make a copy of
4196 * the remaining string for the environment variable.
4198 * The string is always parsed out as command-line arguments, to
4199 * be consistent with Apache...
4202 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4203 "pipe_command: command=\"%s\", options=\"%s\"",
4204 command
, options
? options
: "(null)");
4209 strlcpy(argbuf
, options
, sizeof(argbuf
));
4213 if (argbuf
[0] == '/')
4216 * Found some trailing path information, set PATH_INFO...
4219 if ((commptr
= strchr(argbuf
, '?')) == NULL
)
4220 commptr
= argbuf
+ strlen(argbuf
);
4224 snprintf(path_info
, sizeof(path_info
), "PATH_INFO=%s", argbuf
);
4230 path_info
[0] = '\0';
4233 cupsdLogMessage(CUPSD_LOG_INFO
, "commptr=\"%s\"", commptr
);
4235 if (*commptr
== '?' && con
->operation
== HTTP_GET
&& !con
->query_string
)
4238 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", commptr
);
4245 argv
[argc
++] = commptr
;
4247 for (; *commptr
&& argc
< 99; commptr
++)
4250 * Break arguments whenever we see a + or space...
4253 if (*commptr
== ' ' || *commptr
== '+')
4255 while (*commptr
== ' ' || *commptr
== '+')
4259 * If we don't have a blank string, save it as another argument...
4264 argv
[argc
] = commptr
;
4270 else if (*commptr
== '%' && isxdigit(commptr
[1] & 255) &&
4271 isxdigit(commptr
[2] & 255))
4274 * Convert the %xx notation to the individual character.
4277 if (commptr
[1] >= '0' && commptr
[1] <= '9')
4278 *commptr
= (commptr
[1] - '0') << 4;
4280 *commptr
= (tolower(commptr
[1]) - 'a' + 10) << 4;
4282 if (commptr
[2] >= '0' && commptr
[2] <= '9')
4283 *commptr
|= commptr
[2] - '0';
4285 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
4287 _cups_strcpy(commptr
+ 1, commptr
+ 3);
4290 * Check for a %00 and break if that is the case...
4302 * Setup the environment variables as needed...
4306 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF-8", con
->language
->language
);
4308 strcpy(lang
, "LANG=C");
4310 strcpy(remote_addr
, "REMOTE_ADDR=");
4311 httpAddrString(con
->http
.hostaddr
, remote_addr
+ 12,
4312 sizeof(remote_addr
) - 12);
4314 snprintf(remote_host
, sizeof(remote_host
), "REMOTE_HOST=%s",
4315 con
->http
.hostname
);
4317 snprintf(script_name
, sizeof(script_name
), "SCRIPT_NAME=%s", con
->uri
);
4318 if ((uriptr
= strchr(script_name
, '?')) != NULL
)
4321 sprintf(server_port
, "SERVER_PORT=%d", con
->serverport
);
4323 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
4326 envc
= cupsdLoadEnv(envp
, (int)(sizeof(envp
) / sizeof(envp
[0])));
4328 envp
[envc
++] = lang
;
4329 envp
[envc
++] = "REDIRECT_STATUS=1";
4330 envp
[envc
++] = server_name
;
4331 envp
[envc
++] = server_port
;
4332 envp
[envc
++] = remote_addr
;
4333 envp
[envc
++] = remote_host
;
4334 envp
[envc
++] = script_name
;
4337 envp
[envc
++] = path_info
;
4339 if (con
->username
[0])
4341 snprintf(remote_user
, sizeof(remote_user
), "REMOTE_USER=%s", con
->username
);
4343 envp
[envc
++] = remote_user
;
4346 if (con
->http
.version
== HTTP_1_1
)
4347 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.1";
4348 else if (con
->http
.version
== HTTP_1_0
)
4349 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.0";
4351 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/0.9";
4353 if (con
->http
.cookie
)
4355 snprintf(http_cookie
, sizeof(http_cookie
), "HTTP_COOKIE=%s",
4357 envp
[envc
++] = http_cookie
;
4360 if (con
->http
.fields
[HTTP_FIELD_USER_AGENT
][0])
4362 snprintf(http_user_agent
, sizeof(http_user_agent
), "HTTP_USER_AGENT=%s",
4363 con
->http
.fields
[HTTP_FIELD_USER_AGENT
]);
4364 envp
[envc
++] = http_user_agent
;
4367 if (con
->http
.fields
[HTTP_FIELD_REFERER
][0])
4369 snprintf(http_referer
, sizeof(http_referer
), "HTTP_REFERER=%s",
4370 con
->http
.fields
[HTTP_FIELD_REFERER
]);
4371 envp
[envc
++] = http_referer
;
4374 if (con
->operation
== HTTP_GET
)
4376 envp
[envc
++] = "REQUEST_METHOD=GET";
4378 if (con
->query_string
)
4381 * Add GET form variables after ?...
4384 envp
[envc
++] = con
->query_string
;
4389 sprintf(content_length
, "CONTENT_LENGTH=" CUPS_LLFMT
,
4390 CUPS_LLCAST con
->bytes
);
4391 snprintf(content_type
, sizeof(content_type
), "CONTENT_TYPE=%s",
4392 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
4394 envp
[envc
++] = "REQUEST_METHOD=POST";
4395 envp
[envc
++] = content_length
;
4396 envp
[envc
++] = content_type
;
4400 * Tell the CGI if we are using encryption...
4404 envp
[envc
++] = "HTTPS=ON";
4407 * Terminate the environment array...
4412 if (LogLevel
== CUPSD_LOG_DEBUG2
)
4414 for (i
= 0; i
< argc
; i
++)
4415 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4416 "pipe_command: argv[%d] = \"%s\"", i
, argv
[i
]);
4417 for (i
= 0; i
< envc
; i
++)
4418 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4419 "pipe_command: envp[%d] = \"%s\"", i
, envp
[i
]);
4423 * Create a pipe for the output...
4426 if (cupsdOpenPipe(fds
))
4428 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to create pipes for CGI %s - %s",
4429 argv
[0], strerror(errno
));
4434 * Then execute the command...
4437 if (cupsdStartProcess(command
, argv
, envp
, infile
, fds
[1], CGIPipes
[1],
4438 -1, -1, root
, &pid
) < 0)
4441 * Error - can't fork!
4444 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to fork for CGI %s - %s", argv
[0],
4447 cupsdClosePipe(fds
);
4453 * Fork successful - return the PID...
4456 if (con
->username
[0])
4457 cupsdAddCert(pid
, con
->username
);
4459 cupsdLogMessage(CUPSD_LOG_DEBUG
, "CGI %s started - PID = %d", command
, pid
);
4470 * 'write_file()' - Send a file via HTTP.
4473 static int /* O - 0 on failure, 1 on success */
4474 write_file(cupsd_client_t
*con
, /* I - Client connection */
4475 http_status_t code
, /* I - HTTP status */
4476 char *filename
, /* I - Filename */
4477 char *type
, /* I - File type */
4478 struct stat
*filestats
) /* O - File information */
4480 con
->file
= open(filename
, O_RDONLY
);
4482 cupsdLogMessage(CUPSD_LOG_DEBUG
, "write_file: %d file=%d", con
->http
.fd
,
4488 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
4492 if (!cupsdSendHeader(con
, code
, type
, AUTH_NONE
))
4495 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
4496 httpGetDateString(filestats
->st_mtime
)) < 0)
4498 if (httpPrintf(HTTP(con
), "Content-Length: " CUPS_LLFMT
"\r\n",
4499 CUPS_LLCAST filestats
->st_size
) < 0)
4501 if (httpPrintf(HTTP(con
), "\r\n") < 0)
4504 if (cupsdFlushHeader(con
) < 0)
4507 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
4508 con
->http
.data_remaining
= filestats
->st_size
;
4510 if (con
->http
.data_remaining
<= INT_MAX
)
4511 con
->http
._data_remaining
= con
->http
.data_remaining
;
4513 con
->http
._data_remaining
= INT_MAX
;
4515 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
,
4516 (cupsd_selfunc_t
)cupsdWriteClient
, con
);
4523 * 'write_pipe()' - Flag that data is available on the CGI pipe.
4527 write_pipe(cupsd_client_t
*con
) /* I - Client connection */
4529 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "write_pipe: CGI output on fd %d...",
4532 con
->file_ready
= 1;
4534 cupsdRemoveSelect(con
->file
);
4535 cupsdAddSelect(con
->http
.fd
, NULL
, (cupsd_selfunc_t
)cupsdWriteClient
, con
);
4540 * End of "$Id: client.c 6383 2007-03-21 20:01:20Z mike $".