2 * "$Id: client.c 6681 2007-07-16 20:11:52Z mike $"
4 * Client routines for the Common UNIX Printing System (CUPS) scheduler.
6 * Copyright 2007 by Apple Inc.
7 * Copyright 1997-2007 by Easy Software Products, all rights reserved.
9 * This file contains Kerberos support code, copyright 2006 by
12 * These coded instructions, statements, and computer programs are the
13 * property of Apple Inc. and are protected by Federal copyright
14 * law. Distribution and use rights are outlined in the file "LICENSE.txt"
15 * which should have been included with this file. If this file is
16 * file is missing or damaged, see the license at "http://www.cups.org/".
20 * cupsdAcceptClient() - Accept a new client.
21 * cupsdCloseAllClients() - Close all remote clients immediately.
22 * cupsdCloseClient() - Close a remote client.
23 * cupsdFlushHeader() - Flush the header fields to the client.
24 * cupsdReadClient() - Read data from a client.
25 * cupsdSendCommand() - Send output from a command via HTTP.
26 * cupsdSendError() - Send an error message via HTTP.
27 * cupsdSendHeader() - Send an HTTP request.
28 * cupsdUpdateCGI() - Read status messages from CGI scripts and programs.
29 * cupsdWriteClient() - Write data to a client as needed.
30 * check_if_modified() - Decode an "If-Modified-Since" line.
31 * encrypt_client() - Enable encryption for the client...
32 * get_cdsa_certificate() - Convert a keychain name into the CFArrayRef
33 * required by SSLSetCertificate.
34 * get_file() - Get a filename and state info.
35 * install_conf_file() - Install a configuration file.
36 * is_cgi() - Is the resource a CGI script/program?
37 * is_path_absolute() - Is a path absolute and free of relative elements.
38 * make_certificate() - Make a self-signed SSL/TLS certificate.
39 * pipe_command() - Pipe the output of a command to the remote client.
40 * write_file() - Send a file via HTTP.
41 * write_pipe() - Flag that data is available on the CGI pipe.
45 * Include necessary headers...
48 #include <cups/http-private.h>
52 # include <Security/Security.h>
53 # ifdef HAVE_SECIDENTITYSEARCHPRIV_H
54 # include <Security/SecIdentitySearchPriv.h>
55 # else /* Declare prototype for function in that header... */
56 extern OSStatus
SecIdentitySearchCreateWithPolicy(SecPolicyRef policy
,
57 CFStringRef idString
, CSSM_KEYUSE keyUsage
,
58 CFTypeRef keychainOrArray
,
59 Boolean returnOnlyValidIdentities
,
60 SecIdentitySearchRef
* searchRef
);
61 # endif /* HAVE_SECIDENTITYSEARCHPRIV_H */
62 # ifdef HAVE_SECPOLICYPRIV_H
63 # include <Security/SecPolicyPriv.h>
64 # else /* Declare prototype for function in that header... */
65 extern OSStatus
SecPolicySetValue(SecPolicyRef policyRef
,
66 const CSSM_DATA
*value
);
67 # endif /* HAVE_SECPOLICYPRIV_H */
68 # ifdef HAVE_SECBASEPRIV_H
69 # include <Security/SecBasePriv.h>
70 # else /* Declare prototype for function in that header... */
71 extern const char *cssmErrorString(int error
);
72 # endif /* HAVE_SECBASEPRIV_H */
73 #endif /* HAVE_CDSASSL */
76 # include <gnutls/x509.h>
77 #endif /* HAVE_GNUTLS */
84 static int check_if_modified(cupsd_client_t
*con
,
85 struct stat
*filestats
);
87 static int encrypt_client(cupsd_client_t
*con
);
90 static CFArrayRef
get_cdsa_certificate(cupsd_client_t
*con
);
91 #endif /* HAVE_CDSASSL */
92 static char *get_file(cupsd_client_t
*con
, struct stat
*filestats
,
93 char *filename
, int len
);
94 static http_status_t
install_conf_file(cupsd_client_t
*con
);
95 static int is_cgi(cupsd_client_t
*con
, const char *filename
,
96 struct stat
*filestats
, mime_type_t
*type
);
97 static int is_path_absolute(const char *path
);
99 static int make_certificate(cupsd_client_t
*con
);
100 #endif /* HAVE_SSL */
101 static int pipe_command(cupsd_client_t
*con
, int infile
, int *outfile
,
102 char *command
, char *options
, int root
);
103 static int write_file(cupsd_client_t
*con
, http_status_t code
,
104 char *filename
, char *type
,
105 struct stat
*filestats
);
106 static void write_pipe(cupsd_client_t
*con
);
110 * 'cupsdAcceptClient()' - Accept a new client.
114 cupsdAcceptClient(cupsd_listener_t
*lis
)/* I - Listener socket */
116 int count
; /* Count of connections on a host */
117 int val
; /* Parameter value */
118 cupsd_client_t
*con
, /* New client pointer */
119 *tempcon
; /* Temporary client pointer */
120 http_addrlist_t
*addrlist
, /* List of adddresses for host */
121 *addr
; /* Current address */
122 socklen_t addrlen
; /* Length of address */
123 char *hostname
; /* Hostname for address */
124 http_addr_t temp
; /* Temporary address variable */
125 static time_t last_dos
= 0; /* Time of last DoS attack */
128 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
129 "cupsdAcceptClient(lis=%p) %d Clients = %d",
130 lis
, lis
->fd
, cupsArrayCount(Clients
));
133 * Make sure we don't have a full set of clients already...
136 if (cupsArrayCount(Clients
) == MaxClients
)
140 * Get a pointer to the next available client...
144 Clients
= cupsArrayNew(NULL
, NULL
);
149 con
= calloc(1, sizeof(cupsd_client_t
));
151 con
->http
.activity
= time(NULL
);
153 con
->http
.hostaddr
= &(con
->clientaddr
);
156 * Accept the client and get the remote address...
159 addrlen
= sizeof(http_addr_t
);
161 if ((con
->http
.fd
= accept(lis
->fd
, (struct sockaddr
*)con
->http
.hostaddr
,
164 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to accept client connection - %s.",
171 if (lis
->address
.addr
.sa_family
== AF_INET6
)
174 * Save the connected port number...
177 con
->http
.hostaddr
->ipv6
.sin6_port
= lis
->address
.ipv6
.sin6_port
;
180 * Convert IPv4 over IPv6 addresses (::ffff:n.n.n.n) to IPv4 forms we
181 * can more easily use...
184 if (con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[0] == 0 &&
185 con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[1] == 0 &&
186 ntohl(con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[2]) == 0xffff)
187 con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[2] = 0;
190 #endif /* AF_INET6 */
191 if (lis
->address
.addr
.sa_family
== AF_INET
)
192 con
->http
.hostaddr
->ipv4
.sin_port
= lis
->address
.ipv4
.sin_port
;
195 * Check the number of clients on the same address...
198 for (count
= 0, tempcon
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
200 tempcon
= (cupsd_client_t
*)cupsArrayNext(Clients
))
201 if (httpAddrEqual(tempcon
->http
.hostaddr
, con
->http
.hostaddr
))
204 if (count
>= MaxClientsPerHost
)
208 if (count
>= MaxClientsPerHost
)
210 if ((time(NULL
) - last_dos
) >= 60)
212 last_dos
= time(NULL
);
213 cupsdLogMessage(CUPSD_LOG_WARN
,
214 "Possible DoS attack - more than %d clients connecting "
216 MaxClientsPerHost
, tempcon
->http
.hostname
);
220 closesocket(con
->http
.fd
);
230 * Get the hostname or format the IP address as needed...
233 if (httpAddrLocalhost(con
->http
.hostaddr
))
236 * Map accesses from the loopback interface to "localhost"...
239 strlcpy(con
->http
.hostname
, "localhost", sizeof(con
->http
.hostname
));
240 hostname
= con
->http
.hostname
;
245 * Map accesses from the same host to the server name.
248 for (addr
= ServerAddrs
; addr
; addr
= addr
->next
)
249 if (httpAddrEqual(con
->http
.hostaddr
, &(addr
->addr
)))
254 strlcpy(con
->http
.hostname
, ServerName
, sizeof(con
->http
.hostname
));
255 hostname
= con
->http
.hostname
;
257 else if (HostNameLookups
)
258 hostname
= httpAddrLookup(con
->http
.hostaddr
, con
->http
.hostname
,
259 sizeof(con
->http
.hostname
));
263 httpAddrString(con
->http
.hostaddr
, con
->http
.hostname
,
264 sizeof(con
->http
.hostname
));
268 if (hostname
== NULL
&& HostNameLookups
== 2)
271 * Can't have an unresolved IP address with double-lookups enabled...
274 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
275 "cupsdAcceptClient: Closing connection %d...",
279 closesocket(con
->http
.fd
);
284 cupsdLogMessage(CUPSD_LOG_WARN
,
285 "Name lookup failed - connection from %s closed!",
292 if (HostNameLookups
== 2)
295 * Do double lookups as needed...
298 if ((addrlist
= httpAddrGetList(con
->http
.hostname
, AF_UNSPEC
, NULL
)) != NULL
)
301 * See if the hostname maps to the same IP address...
304 for (addr
= addrlist
; addr
; addr
= addr
->next
)
305 if (httpAddrEqual(con
->http
.hostaddr
, &(addr
->addr
)))
311 httpAddrFreeList(addrlist
);
316 * Can't have a hostname that doesn't resolve to the same IP address
317 * with double-lookups enabled...
320 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
321 "cupsdAcceptClient: Closing connection %d...",
325 closesocket(con
->http
.fd
);
330 cupsdLogMessage(CUPSD_LOG_WARN
,
331 "IP lookup failed - connection from %s closed!",
339 if (con
->http
.hostaddr
->addr
.sa_family
== AF_INET6
)
340 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdAcceptClient: %d from %s:%d (IPv6)",
341 con
->http
.fd
, con
->http
.hostname
,
342 ntohs(con
->http
.hostaddr
->ipv6
.sin6_port
));
344 #endif /* AF_INET6 */
346 if (con
->http
.hostaddr
->addr
.sa_family
== AF_LOCAL
)
347 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdAcceptClient: %d from %s (Domain)",
348 con
->http
.fd
, con
->http
.hostname
);
350 #endif /* AF_LOCAL */
351 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdAcceptClient: %d from %s:%d (IPv4)",
352 con
->http
.fd
, con
->http
.hostname
,
353 ntohs(con
->http
.hostaddr
->ipv4
.sin_port
));
356 * Get the local address the client connected to...
359 addrlen
= sizeof(temp
);
360 if (getsockname(con
->http
.fd
, (struct sockaddr
*)&temp
, &addrlen
))
362 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to get local address - %s",
365 strcpy(con
->servername
, "localhost");
366 con
->serverport
= LocalPort
;
371 if (temp
.addr
.sa_family
== AF_INET6
)
373 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
374 con
->serverport
= ntohs(lis
->address
.ipv6
.sin6_port
);
377 #endif /* AF_INET6 */
378 if (temp
.addr
.sa_family
== AF_INET
)
380 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
381 con
->serverport
= ntohs(lis
->address
.ipv4
.sin_port
);
385 strcpy(con
->servername
, "localhost");
386 con
->serverport
= LocalPort
;
390 cupsArrayAdd(Clients
, con
);
392 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
393 "cupsdAcceptClient: %d connected to server on %s:%d",
394 con
->http
.fd
, con
->servername
, con
->serverport
);
397 * Using TCP_NODELAY improves responsiveness, especially on systems
398 * with a slow loopback interface... Since we write large buffers
399 * when sending print files and requests, there shouldn't be any
400 * performance penalty for this...
404 setsockopt(con
->http
.fd
, IPPROTO_TCP
, TCP_NODELAY
, &val
, sizeof(val
));
407 * Close this file on all execs...
410 fcntl(con
->http
.fd
, F_SETFD
, fcntl(con
->http
.fd
, F_GETFD
) | FD_CLOEXEC
);
413 * Add the socket to the select() input mask.
416 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
419 * Temporarily suspend accept()'s until we lose a client...
422 if (cupsArrayCount(Clients
) == MaxClients
)
423 cupsdPauseListening();
427 * See if we are connecting on a secure port...
430 if (lis
->encryption
== HTTP_ENCRYPT_ALWAYS
)
433 * https connection; go secure...
436 con
->http
.encryption
= HTTP_ENCRYPT_ALWAYS
;
438 if (!encrypt_client(con
))
439 cupsdCloseClient(con
);
443 #endif /* HAVE_SSL */
448 * 'cupsdCloseAllClients()' - Close all remote clients immediately.
452 cupsdCloseAllClients(void)
454 cupsd_client_t
*con
; /* Current client */
457 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
459 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
460 cupsdCloseClient(con
);
465 * 'cupsdCloseClient()' - Close a remote client.
468 int /* O - 1 if partial close, 0 if fully closed */
469 cupsdCloseClient(cupsd_client_t
*con
) /* I - Client to close */
471 int partial
; /* Do partial close for SSL? */
473 SSL_CTX
*context
; /* Context for encryption */
474 SSL
*conn
; /* Connection for encryption */
475 unsigned long error
; /* Error code */
476 #elif defined(HAVE_GNUTLS)
477 http_tls_t
*conn
; /* TLS connection information */
478 int error
; /* Error code */
479 gnutls_certificate_server_credentials
*credentials
;
480 /* TLS credentials */
481 # elif defined(HAVE_CDSASSL)
482 http_tls_t
*conn
; /* CDSA connection information */
483 #endif /* HAVE_LIBSSL */
486 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdCloseClient: %d", con
->http
.fd
);
489 * Flush pending writes before closing...
492 httpFlushWrite(HTTP(con
));
498 * Shutdown encryption as needed...
506 conn
= (SSL
*)(con
->http
.tls
);
507 context
= SSL_get_SSL_CTX(conn
);
509 switch (SSL_shutdown(conn
))
512 cupsdLogMessage(CUPSD_LOG_INFO
,
513 "cupsdCloseClient: SSL shutdown successful!");
516 cupsdLogMessage(CUPSD_LOG_ERROR
,
517 "cupsdCloseClient: Fatal error during SSL shutdown!");
519 while ((error
= ERR_get_error()) != 0)
520 cupsdLogMessage(CUPSD_LOG_ERROR
, "cupsdCloseClient: %s",
521 ERR_error_string(error
, NULL
));
525 SSL_CTX_free(context
);
528 # elif defined(HAVE_GNUTLS)
529 conn
= (http_tls_t
*)(con
->http
.tls
);
530 credentials
= (gnutls_certificate_server_credentials
*)(conn
->credentials
);
532 error
= gnutls_bye(conn
->session
, GNUTLS_SHUT_WR
);
535 case GNUTLS_E_SUCCESS
:
536 cupsdLogMessage(CUPSD_LOG_INFO
,
537 "cupsdCloseClient: SSL shutdown successful!");
540 cupsdLogMessage(CUPSD_LOG_ERROR
,
541 "cupsdCloseClient: %s", gnutls_strerror(error
));
545 gnutls_deinit(conn
->session
);
546 gnutls_certificate_free_credentials(*credentials
);
550 # elif defined(HAVE_CDSASSL)
551 conn
= (http_tls_t
*)(con
->http
.tls
);
553 while (SSLClose(conn
->session
) == errSSLWouldBlock
)
556 SSLDisposeContext(conn
->session
);
558 if (conn
->certsArray
)
559 CFRelease(conn
->certsArray
);
562 # endif /* HAVE_LIBSSL */
564 con
->http
.tls
= NULL
;
566 #endif /* HAVE_SSL */
568 if (con
->pipe_pid
!= 0)
571 * Stop any CGI process...
574 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
575 "cupsdCloseClient: %d Killing process ID %d...",
576 con
->http
.fd
, con
->pipe_pid
);
577 cupsdEndProcess(con
->pipe_pid
, 1);
583 cupsdRemoveSelect(con
->file
);
585 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
586 "cupsdCloseClient: %d Closing data file %d.",
587 con
->http
.fd
, con
->file
);
594 * Close the socket and clear the file from the input set for select()...
597 if (con
->http
.fd
> 0)
602 * Only do a partial close so that the encrypted client gets everything.
605 shutdown(con
->http
.fd
, 0);
606 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
611 * Shut the socket down fully...
614 cupsdRemoveSelect(con
->http
.fd
);
626 if (con
->http
.input_set
)
627 free(con
->http
.input_set
);
629 httpClearCookie(HTTP(con
));
631 cupsdClearString(&con
->filename
);
632 cupsdClearString(&con
->command
);
633 cupsdClearString(&con
->options
);
634 cupsdClearString(&con
->query_string
);
638 ippDelete(con
->request
);
644 ippDelete(con
->response
);
645 con
->response
= NULL
;
650 cupsLangFree(con
->language
);
651 con
->language
= NULL
;
654 #ifdef HAVE_AUTHORIZATION_H
657 AuthorizationFree(con
->authref
, kAuthorizationFlagDefaults
);
660 #endif /* HAVE_AUTHORIZATION_H */
663 * Re-enable new client connections if we are going back under the
667 if (cupsArrayCount(Clients
) == MaxClients
)
668 cupsdResumeListening();
671 * Compact the list of clients as necessary...
674 cupsArrayRemove(Clients
, con
);
684 * 'cupsdFlushHeader()' - Flush the header fields to the client.
687 int /* I - Bytes written or -1 on error */
688 cupsdFlushHeader(cupsd_client_t
*con
) /* I - Client to flush to */
690 int bytes
= httpFlushWrite(HTTP(con
));
692 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
699 * 'cupsdReadClient()' - Read data from a client.
703 cupsdReadClient(cupsd_client_t
*con
) /* I - Client to read from */
705 char line
[32768], /* Line from client... */
706 operation
[64], /* Operation code from socket */
707 version
[64], /* HTTP version number string */
708 locale
[64], /* Locale */
709 *ptr
; /* Pointer into strings */
710 int major
, minor
; /* HTTP version numbers */
711 http_status_t status
; /* Transfer status */
712 ipp_state_t ipp_state
; /* State of IPP transfer */
713 int bytes
; /* Number of bytes to POST */
714 char *filename
; /* Name of file for GET/HEAD */
715 char buf
[1024]; /* Buffer for real filename */
716 struct stat filestats
; /* File information */
717 mime_type_t
*type
; /* MIME type of file */
718 cupsd_printer_t
*p
; /* Printer */
719 static unsigned request_id
= 0; /* Request ID for temp files */
722 status
= HTTP_CONTINUE
;
724 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
725 "cupsdReadClient: %d, used=%d, file=%d state=%d",
726 con
->http
.fd
, con
->http
.used
, con
->file
, con
->http
.state
);
730 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdReadClient: http error seen...");
731 cupsdCloseClient(con
);
739 * Automatically check for a SSL/TLS handshake...
744 if (recv(con
->http
.fd
, buf
, 1, MSG_PEEK
) == 1 &&
745 (!buf
[0] || !strchr("DGHOPT", buf
[0])))
748 * Encrypt this connection...
751 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
752 "cupsdReadClient: Saw first byte %02X, auto-negotiating SSL/TLS session...",
755 if (!encrypt_client(con
))
756 cupsdCloseClient(con
);
761 #endif /* HAVE_SSL */
763 switch (con
->http
.state
)
767 * See if we've received a request line...
770 if (httpGets(line
, sizeof(line
) - 1, HTTP(con
)) == NULL
)
772 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
773 "cupsdReadClient: httpGets returned EOF...");
774 cupsdCloseClient(con
);
779 * Ignore blank request lines...
786 * Clear other state variables...
789 httpClearFields(HTTP(con
));
791 con
->http
.activity
= time(NULL
);
792 con
->http
.version
= HTTP_1_0
;
793 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
794 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
795 con
->http
.data_remaining
= 0;
796 con
->http
._data_remaining
= 0;
797 con
->operation
= HTTP_WAITING
;
802 con
->username
[0] = '\0';
803 con
->password
[0] = '\0';
806 cupsdClearString(&con
->command
);
807 cupsdClearString(&con
->options
);
808 cupsdClearString(&con
->query_string
);
812 ippDelete(con
->request
);
818 ippDelete(con
->response
);
819 con
->response
= NULL
;
824 cupsLangFree(con
->language
);
825 con
->language
= NULL
;
829 con
->gss_have_creds
= 0;
830 #endif /* HAVE_GSSAPI */
833 * Grab the request line...
836 switch (sscanf(line
, "%63s%1023s%63s", operation
, con
->uri
, version
))
839 cupsdLogMessage(CUPSD_LOG_ERROR
,
840 "Bad request line \"%s\" from %s!", line
,
842 cupsdSendError(con
, HTTP_BAD_REQUEST
, AUTH_NONE
);
843 cupsdCloseClient(con
);
846 con
->http
.version
= HTTP_0_9
;
849 if (sscanf(version
, "HTTP/%d.%d", &major
, &minor
) != 2)
851 cupsdLogMessage(CUPSD_LOG_ERROR
,
852 "Bad request line \"%s\" from %s!", line
,
854 cupsdSendError(con
, HTTP_BAD_REQUEST
, AUTH_NONE
);
855 cupsdCloseClient(con
);
861 con
->http
.version
= (http_version_t
)(major
* 100 + minor
);
862 if (con
->http
.version
== HTTP_1_1
&& KeepAlive
)
863 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
865 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
869 cupsdSendError(con
, HTTP_NOT_SUPPORTED
, AUTH_NONE
);
870 cupsdCloseClient(con
);
877 * Handle full URLs in the request line...
880 if (strcmp(con
->uri
, "*"))
882 char method
[HTTP_MAX_URI
], /* Method/scheme */
883 userpass
[HTTP_MAX_URI
], /* Username:password */
884 hostname
[HTTP_MAX_URI
], /* Hostname */
885 resource
[HTTP_MAX_URI
]; /* Resource path */
886 int port
; /* Port number */
890 * Separate the URI into its components...
893 httpSeparateURI(HTTP_URI_CODING_MOST
, con
->uri
,
894 method
, sizeof(method
),
895 userpass
, sizeof(userpass
),
896 hostname
, sizeof(hostname
), &port
,
897 resource
, sizeof(resource
));
900 * Only allow URIs with the servername, localhost, or an IP
904 if (strcmp(method
, "file") &&
905 strcasecmp(hostname
, ServerName
) &&
906 strcasecmp(hostname
, "localhost") &&
907 !isdigit(hostname
[0]))
910 * Nope, we don't do proxies...
913 cupsdLogMessage(CUPSD_LOG_ERROR
, "Bad URI \"%s\" in request!",
915 cupsdSendError(con
, HTTP_METHOD_NOT_ALLOWED
, AUTH_NONE
);
916 cupsdCloseClient(con
);
921 * Copy the resource portion back into the URI; both resource and
922 * con->uri are HTTP_MAX_URI bytes in size...
925 strcpy(con
->uri
, resource
);
929 * Process the request...
932 if (!strcmp(operation
, "GET"))
933 con
->http
.state
= HTTP_GET
;
934 else if (!strcmp(operation
, "PUT"))
935 con
->http
.state
= HTTP_PUT
;
936 else if (!strcmp(operation
, "POST"))
937 con
->http
.state
= HTTP_POST
;
938 else if (!strcmp(operation
, "DELETE"))
939 con
->http
.state
= HTTP_DELETE
;
940 else if (!strcmp(operation
, "TRACE"))
941 con
->http
.state
= HTTP_TRACE
;
942 else if (!strcmp(operation
, "OPTIONS"))
943 con
->http
.state
= HTTP_OPTIONS
;
944 else if (!strcmp(operation
, "HEAD"))
945 con
->http
.state
= HTTP_HEAD
;
948 cupsdLogMessage(CUPSD_LOG_ERROR
, "Bad operation \"%s\"!", operation
);
949 cupsdSendError(con
, HTTP_BAD_REQUEST
, AUTH_NONE
);
950 cupsdCloseClient(con
);
954 con
->start
= time(NULL
);
955 con
->operation
= con
->http
.state
;
957 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdReadClient: %d %s %s HTTP/%d.%d",
958 con
->http
.fd
, operation
, con
->uri
,
959 con
->http
.version
/ 100, con
->http
.version
% 100);
961 con
->http
.status
= HTTP_OK
;
971 * Parse incoming parameters until the status changes...
974 while ((status
= httpUpdate(HTTP(con
))) == HTTP_CONTINUE
)
975 if (con
->http
.used
== 0 ||
976 !memchr(con
->http
.buffer
, '\n', con
->http
.used
))
979 if (status
!= HTTP_OK
&& status
!= HTTP_CONTINUE
)
981 cupsdSendError(con
, HTTP_BAD_REQUEST
, AUTH_NONE
);
982 cupsdCloseClient(con
);
988 break; /* Anti-compiler-warning-code */
992 * Handle new transfers...
995 if (status
== HTTP_OK
)
997 if (con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
][0])
1000 * Figure out the locale from the Accept-Language and Content-Type
1004 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ',')) != NULL
)
1007 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ';')) != NULL
)
1010 if ((ptr
= strstr(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
], "charset=")) != NULL
)
1013 * Combine language and charset, and trim any extra params in the
1017 snprintf(locale
, sizeof(locale
), "%s.%s",
1018 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ptr
+ 8);
1020 if ((ptr
= strchr(locale
, ',')) != NULL
)
1024 snprintf(locale
, sizeof(locale
), "%s.%s",
1025 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], DefaultCharset
);
1027 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1028 "cupsdReadClient: %d Browser asked for language \"%s\"...",
1029 con
->http
.fd
, locale
);
1031 con
->language
= cupsLangGet(locale
);
1034 con
->language
= cupsLangGet(DefaultLocale
);
1036 cupsdAuthorize(con
);
1038 if (!strncmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Keep-Alive", 10) &&
1040 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
1042 if (!con
->http
.fields
[HTTP_FIELD_HOST
][0] &&
1043 con
->http
.version
>= HTTP_1_1
)
1046 * HTTP/1.1 and higher require the "Host:" field...
1049 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, AUTH_NONE
))
1051 cupsdCloseClient(con
);
1055 else if (con
->operation
== HTTP_OPTIONS
)
1058 * Do OPTIONS command...
1061 if (con
->best
&& con
->best
->type
!= AUTH_NONE
)
1063 if (!cupsdSendHeader(con
, HTTP_UNAUTHORIZED
, NULL
, AUTH_NONE
))
1065 cupsdCloseClient(con
);
1070 if (!strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") &&
1071 con
->http
.tls
== NULL
)
1075 * Do encryption stuff...
1078 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
, AUTH_NONE
))
1080 cupsdCloseClient(con
);
1084 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1085 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1086 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1087 httpPrintf(HTTP(con
), "\r\n");
1089 if (cupsdFlushHeader(con
) < 0)
1091 cupsdCloseClient(con
);
1095 if (!encrypt_client(con
))
1097 cupsdCloseClient(con
);
1101 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, AUTH_NONE
))
1103 cupsdCloseClient(con
);
1106 #endif /* HAVE_SSL */
1109 if (!cupsdSendHeader(con
, HTTP_OK
, NULL
, AUTH_NONE
))
1111 cupsdCloseClient(con
);
1115 httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n");
1116 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1117 httpPrintf(HTTP(con
), "\r\n");
1119 if (cupsdFlushHeader(con
) < 0)
1121 cupsdCloseClient(con
);
1125 else if (!is_path_absolute(con
->uri
))
1128 * Protect against malicious users!
1131 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, AUTH_NONE
))
1133 cupsdCloseClient(con
);
1139 if (!strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") &&
1140 con
->http
.tls
== NULL
)
1144 * Do encryption stuff...
1147 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
, AUTH_NONE
))
1149 cupsdCloseClient(con
);
1153 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1154 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1155 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1156 httpPrintf(HTTP(con
), "\r\n");
1158 if (cupsdFlushHeader(con
) < 0)
1160 cupsdCloseClient(con
);
1164 if (!encrypt_client(con
))
1166 cupsdCloseClient(con
);
1170 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, AUTH_NONE
))
1172 cupsdCloseClient(con
);
1175 #endif /* HAVE_SSL */
1178 if ((status
= cupsdIsAuthorized(con
, NULL
)) != HTTP_OK
)
1180 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1181 "cupsdReadClient: Unauthorized request for %s...\n",
1183 cupsdSendError(con
, status
, AUTH_NONE
);
1184 cupsdCloseClient(con
);
1188 if (con
->http
.expect
&&
1189 (con
->operation
== HTTP_POST
|| con
->operation
== HTTP_PUT
))
1191 if (con
->http
.expect
== HTTP_CONTINUE
)
1194 * Send 100-continue header...
1197 if (!cupsdSendHeader(con
, HTTP_CONTINUE
, NULL
, AUTH_NONE
))
1199 cupsdCloseClient(con
);
1206 * Send 417-expectation-failed header...
1209 if (!cupsdSendHeader(con
, HTTP_EXPECTATION_FAILED
, NULL
, AUTH_NONE
))
1211 cupsdCloseClient(con
);
1215 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1216 httpPrintf(HTTP(con
), "\r\n");
1218 if (cupsdFlushHeader(con
) < 0)
1220 cupsdCloseClient(con
);
1226 switch (con
->http
.state
)
1228 case HTTP_GET_SEND
:
1229 if (!strncmp(con
->uri
, "/printers/", 10) &&
1230 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1233 * Send PPD file - get the real printer name since printer
1234 * names are not case sensitive but filenames can be...
1237 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1239 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1240 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1243 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, AUTH_NONE
))
1245 cupsdCloseClient(con
);
1253 if ((!strncmp(con
->uri
, "/admin", 6) &&
1254 strncmp(con
->uri
, "/admin/conf/", 12) &&
1255 strncmp(con
->uri
, "/admin/log/", 11)) ||
1256 !strncmp(con
->uri
, "/printers", 9) ||
1257 !strncmp(con
->uri
, "/classes", 8) ||
1258 !strncmp(con
->uri
, "/help", 5) ||
1259 !strncmp(con
->uri
, "/jobs", 5))
1262 * Send CGI output...
1265 if (!strncmp(con
->uri
, "/admin", 6))
1267 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1270 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1272 else if (!strncmp(con
->uri
, "/printers", 9))
1274 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1277 if (con
->uri
[9] && con
->uri
[10])
1278 cupsdSetString(&con
->options
, con
->uri
+ 9);
1280 cupsdSetString(&con
->options
, NULL
);
1282 else if (!strncmp(con
->uri
, "/classes", 8))
1284 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1287 if (con
->uri
[8] && con
->uri
[9])
1288 cupsdSetString(&con
->options
, con
->uri
+ 8);
1290 cupsdSetString(&con
->options
, NULL
);
1292 else if (!strncmp(con
->uri
, "/jobs", 5))
1294 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1297 if (con
->uri
[5] && con
->uri
[6])
1298 cupsdSetString(&con
->options
, con
->uri
+ 5);
1300 cupsdSetString(&con
->options
, NULL
);
1304 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1307 if (con
->uri
[5] && con
->uri
[6])
1308 cupsdSetString(&con
->options
, con
->uri
+ 5);
1310 cupsdSetString(&con
->options
, NULL
);
1313 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1315 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, AUTH_NONE
))
1317 cupsdCloseClient(con
);
1322 cupsdLogRequest(con
, HTTP_OK
);
1324 if (con
->http
.version
<= HTTP_1_0
)
1325 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1327 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1328 (strchr(con
->uri
+ 12, '/') ||
1329 strlen(con
->uri
) == 12)) ||
1330 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1331 (strchr(con
->uri
+ 11, '/') ||
1332 strlen(con
->uri
) == 11)))
1335 * GET can only be done to configuration files under
1339 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, AUTH_NONE
))
1341 cupsdCloseClient(con
);
1353 if ((filename
= get_file(con
, &filestats
, buf
,
1354 sizeof(buf
))) == NULL
)
1356 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, AUTH_NONE
))
1358 cupsdCloseClient(con
);
1365 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1367 if (is_cgi(con
, filename
, &filestats
, type
))
1370 * Note: con->command and con->options were set by
1374 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1376 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, AUTH_NONE
))
1378 cupsdCloseClient(con
);
1383 cupsdLogRequest(con
, HTTP_OK
);
1385 if (con
->http
.version
<= HTTP_1_0
)
1386 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1390 if (!check_if_modified(con
, &filestats
))
1392 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
, AUTH_NONE
))
1394 cupsdCloseClient(con
);
1401 strcpy(line
, "text/plain");
1403 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1405 if (!write_file(con
, HTTP_OK
, filename
, line
, &filestats
))
1407 cupsdCloseClient(con
);
1414 case HTTP_POST_RECV
:
1416 * See if the POST request includes a Content-Length field, and if
1417 * so check the length against any limits that are set...
1420 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "POST %s", con
->uri
);
1421 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "CONTENT_TYPE = %s",
1422 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
1424 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1425 MaxRequestSize
> 0 &&
1426 con
->http
.data_remaining
> MaxRequestSize
)
1429 * Request too large...
1432 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, AUTH_NONE
))
1434 cupsdCloseClient(con
);
1440 else if (con
->http
.data_remaining
< 0)
1443 * Negative content lengths are invalid!
1446 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, AUTH_NONE
))
1448 cupsdCloseClient(con
);
1456 * See what kind of POST request this is; for IPP requests the
1457 * content-type field will be "application/ipp"...
1460 if (!strcmp(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
],
1462 con
->request
= ippNew();
1463 else if ((!strncmp(con
->uri
, "/admin", 6) &&
1464 strncmp(con
->uri
, "/admin/conf/", 12) &&
1465 strncmp(con
->uri
, "/admin/log/", 11)) ||
1466 !strncmp(con
->uri
, "/printers", 9) ||
1467 !strncmp(con
->uri
, "/classes", 8) ||
1468 !strncmp(con
->uri
, "/help", 5) ||
1469 !strncmp(con
->uri
, "/jobs", 5))
1475 if (!strncmp(con
->uri
, "/admin", 6))
1477 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1480 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1482 else if (!strncmp(con
->uri
, "/printers", 9))
1484 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1487 if (con
->uri
[9] && con
->uri
[10])
1488 cupsdSetString(&con
->options
, con
->uri
+ 9);
1490 cupsdSetString(&con
->options
, NULL
);
1492 else if (!strncmp(con
->uri
, "/classes", 8))
1494 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1497 if (con
->uri
[8] && con
->uri
[9])
1498 cupsdSetString(&con
->options
, con
->uri
+ 8);
1500 cupsdSetString(&con
->options
, NULL
);
1502 else if (!strncmp(con
->uri
, "/jobs", 5))
1504 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1507 if (con
->uri
[5] && con
->uri
[6])
1508 cupsdSetString(&con
->options
, con
->uri
+ 5);
1510 cupsdSetString(&con
->options
, NULL
);
1514 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1517 if (con
->uri
[5] && con
->uri
[6])
1518 cupsdSetString(&con
->options
, con
->uri
+ 5);
1520 cupsdSetString(&con
->options
, NULL
);
1523 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1524 "cupsdReadClient: %d command=\"%s\", "
1526 con
->http
.fd
, con
->command
,
1527 con
->options
? con
->options
: "(null)");
1529 if (con
->http
.version
<= HTTP_1_0
)
1530 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1538 if ((filename
= get_file(con
, &filestats
, buf
,
1539 sizeof(buf
))) == NULL
)
1541 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, AUTH_NONE
))
1543 cupsdCloseClient(con
);
1550 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1552 if (!is_cgi(con
, filename
, &filestats
, type
))
1555 * Only POST to CGI's...
1558 if (!cupsdSendError(con
, HTTP_UNAUTHORIZED
, AUTH_NONE
))
1560 cupsdCloseClient(con
);
1567 case HTTP_PUT_RECV
:
1569 * Validate the resource name...
1572 if (strncmp(con
->uri
, "/admin/conf/", 12) ||
1573 strchr(con
->uri
+ 12, '/') ||
1574 strlen(con
->uri
) == 12)
1577 * PUT can only be done to configuration files under
1581 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, AUTH_NONE
))
1583 cupsdCloseClient(con
);
1591 * See if the PUT request includes a Content-Length field, and if
1592 * so check the length against any limits that are set...
1595 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "PUT %s", con
->uri
);
1596 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "CONTENT_TYPE = %s",
1597 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
1599 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1600 MaxRequestSize
> 0 &&
1601 con
->http
.data_remaining
> MaxRequestSize
)
1604 * Request too large...
1607 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, AUTH_NONE
))
1609 cupsdCloseClient(con
);
1615 else if (con
->http
.data_remaining
< 0)
1618 * Negative content lengths are invalid!
1621 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, AUTH_NONE
))
1623 cupsdCloseClient(con
);
1631 * Open a temporary file to hold the request...
1634 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
1636 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1638 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1639 "cupsdReadClient: %d REQUEST %s=%d", con
->http
.fd
,
1640 con
->filename
, con
->file
);
1644 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, AUTH_NONE
))
1646 cupsdCloseClient(con
);
1651 fchmod(con
->file
, 0640);
1652 fchown(con
->file
, RunUser
, Group
);
1653 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1658 cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, AUTH_NONE
);
1659 cupsdCloseClient(con
);
1663 if (!strncmp(con
->uri
, "/printers/", 10) &&
1664 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1667 * Send PPD file - get the real printer name since printer
1668 * names are not case sensitive but filenames can be...
1671 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1673 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1674 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1677 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, AUTH_NONE
))
1679 cupsdCloseClient(con
);
1687 if ((!strncmp(con
->uri
, "/admin", 6) &&
1688 strncmp(con
->uri
, "/admin/conf/", 12) &&
1689 strncmp(con
->uri
, "/admin/log/", 11)) ||
1690 !strncmp(con
->uri
, "/printers", 9) ||
1691 !strncmp(con
->uri
, "/classes", 8) ||
1692 !strncmp(con
->uri
, "/help", 5) ||
1693 !strncmp(con
->uri
, "/jobs", 5))
1699 if (!cupsdSendHeader(con
, HTTP_OK
, "text/html", AUTH_NONE
))
1701 cupsdCloseClient(con
);
1705 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1707 cupsdCloseClient(con
);
1711 if (cupsdFlushHeader(con
) < 0)
1713 cupsdCloseClient(con
);
1717 cupsdLogRequest(con
, HTTP_OK
);
1719 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1720 (strchr(con
->uri
+ 12, '/') ||
1721 strlen(con
->uri
) == 12)) ||
1722 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1723 (strchr(con
->uri
+ 11, '/') ||
1724 strlen(con
->uri
) == 11)))
1727 * HEAD can only be done to configuration files under
1731 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, AUTH_NONE
))
1733 cupsdCloseClient(con
);
1739 else if ((filename
= get_file(con
, &filestats
, buf
,
1740 sizeof(buf
))) == NULL
)
1742 if (!cupsdSendHeader(con
, HTTP_NOT_FOUND
, "text/html", AUTH_NONE
))
1744 cupsdCloseClient(con
);
1748 cupsdLogRequest(con
, HTTP_NOT_FOUND
);
1750 else if (!check_if_modified(con
, &filestats
))
1752 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
, AUTH_NONE
))
1754 cupsdCloseClient(con
);
1758 cupsdLogRequest(con
, HTTP_NOT_MODIFIED
);
1766 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1768 strcpy(line
, "text/plain");
1770 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1772 if (!cupsdSendHeader(con
, HTTP_OK
, line
, AUTH_NONE
))
1774 cupsdCloseClient(con
);
1778 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
1779 httpGetDateString(filestats
.st_mtime
)) < 0)
1781 cupsdCloseClient(con
);
1785 if (httpPrintf(HTTP(con
), "Content-Length: %lu\r\n",
1786 (unsigned long)filestats
.st_size
) < 0)
1788 cupsdCloseClient(con
);
1792 cupsdLogRequest(con
, HTTP_OK
);
1795 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1797 cupsdCloseClient(con
);
1801 if (cupsdFlushHeader(con
) < 0)
1803 cupsdCloseClient(con
);
1807 con
->http
.state
= HTTP_WAITING
;
1811 break; /* Anti-compiler-warning-code */
1817 * Handle any incoming data...
1820 switch (con
->http
.state
)
1822 case HTTP_PUT_RECV
:
1823 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1824 "cupsdReadClient: %d con->data_encoding=HTTP_ENCODE_%s, "
1825 "con->data_remaining=" CUPS_LLFMT
", con->file=%d",
1827 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
?
1828 "CHUNKED" : "LENGTH",
1829 CUPS_LLCAST con
->http
.data_remaining
, con
->file
);
1833 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
1835 cupsdCloseClient(con
);
1840 con
->bytes
+= bytes
;
1842 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1843 "cupsdReadClient: %d writing %d bytes to %d",
1844 con
->http
.fd
, bytes
, con
->file
);
1846 if (write(con
->file
, line
, bytes
) < bytes
)
1848 cupsdLogMessage(CUPSD_LOG_ERROR
,
1849 "cupsdReadClient: Unable to write %d bytes to %s: %s",
1850 bytes
, con
->filename
, strerror(errno
));
1852 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1853 "cupsdReadClient: Closing data file %d...",
1858 unlink(con
->filename
);
1859 cupsdClearString(&con
->filename
);
1861 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, AUTH_NONE
))
1863 cupsdCloseClient(con
);
1869 while (con
->http
.state
== HTTP_PUT_RECV
&& con
->http
.used
> 0);
1871 if (con
->http
.state
== HTTP_WAITING
)
1874 * End of file, see how big it is...
1877 fstat(con
->file
, &filestats
);
1879 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1880 "cupsdReadClient: %d Closing data file %d, size="
1882 con
->http
.fd
, con
->file
,
1883 CUPS_LLCAST filestats
.st_size
);
1888 if (filestats
.st_size
> MaxRequestSize
&&
1892 * Request is too big; remove it and send an error...
1895 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1896 "cupsdReadClient: %d Removing temp file %s",
1897 con
->http
.fd
, con
->filename
);
1898 unlink(con
->filename
);
1899 cupsdClearString(&con
->filename
);
1901 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, AUTH_NONE
))
1903 cupsdCloseClient(con
);
1909 * Install the configuration file...
1912 status
= install_conf_file(con
);
1915 * Return the status to the client...
1918 if (!cupsdSendError(con
, status
, AUTH_NONE
))
1920 cupsdCloseClient(con
);
1926 case HTTP_POST_RECV
:
1927 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1928 "cupsdReadClient: %d con->data_encoding=HTTP_ENCODE_"
1929 "%s, con->data_remaining=" CUPS_LLFMT
", con->file=%d",
1931 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
?
1932 "CHUNKED" : "LENGTH",
1933 CUPS_LLCAST con
->http
.data_remaining
, con
->file
);
1940 * Grab any request data from the connection...
1943 if ((ipp_state
= ippRead(&(con
->http
), con
->request
)) == IPP_ERROR
)
1945 cupsdLogMessage(CUPSD_LOG_ERROR
,
1946 "cupsdReadClient: %d IPP Read Error!",
1949 cupsdSendError(con
, HTTP_BAD_REQUEST
, AUTH_NONE
);
1950 cupsdCloseClient(con
);
1953 else if (ipp_state
!= IPP_DATA
)
1955 if (con
->http
.state
== HTTP_POST_SEND
)
1957 cupsdSendError(con
, HTTP_BAD_REQUEST
, AUTH_NONE
);
1958 cupsdCloseClient(con
);
1965 con
->bytes
+= ippLength(con
->request
);
1968 if (con
->file
< 0 && con
->http
.state
!= HTTP_POST_SEND
)
1971 * Create a file as needed for the request data...
1974 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
, request_id
++);
1975 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1977 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdReadClient: %d REQUEST %s=%d", con
->http
.fd
,
1978 con
->filename
, con
->file
);
1982 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, AUTH_NONE
))
1984 cupsdCloseClient(con
);
1989 fchmod(con
->file
, 0640);
1990 fchown(con
->file
, RunUser
, Group
);
1991 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1994 if (con
->http
.state
!= HTTP_POST_SEND
)
1996 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
1998 cupsdCloseClient(con
);
2003 con
->bytes
+= bytes
;
2005 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2006 "cupsdReadClient: %d writing %d bytes to %d",
2007 con
->http
.fd
, bytes
, con
->file
);
2009 if (write(con
->file
, line
, bytes
) < bytes
)
2011 cupsdLogMessage(CUPSD_LOG_ERROR
,
2012 "cupsdReadClient: Unable to write %d bytes to %s: %s",
2013 bytes
, con
->filename
, strerror(errno
));
2015 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2016 "cupsdReadClient: Closing file %d...",
2021 unlink(con
->filename
);
2022 cupsdClearString(&con
->filename
);
2024 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, AUTH_NONE
))
2026 cupsdCloseClient(con
);
2031 else if (con
->http
.state
== HTTP_POST_RECV
)
2033 else if (con
->http
.state
!= HTTP_POST_SEND
)
2035 cupsdCloseClient(con
);
2040 while (con
->http
.state
== HTTP_POST_RECV
&& con
->http
.used
> 0);
2042 if (con
->http
.state
== HTTP_POST_SEND
)
2046 fstat(con
->file
, &filestats
);
2048 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2049 "cupsdReadClient: %d Closing data file %d, "
2050 "size=" CUPS_LLFMT
".",
2051 con
->http
.fd
, con
->file
,
2052 CUPS_LLCAST filestats
.st_size
);
2057 if (filestats
.st_size
> MaxRequestSize
&&
2061 * Request is too big; remove it and send an error...
2064 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2065 "cupsdReadClient: %d Removing temp file %s",
2066 con
->http
.fd
, con
->filename
);
2067 unlink(con
->filename
);
2068 cupsdClearString(&con
->filename
);
2073 * Delete any IPP request data...
2076 ippDelete(con
->request
);
2077 con
->request
= NULL
;
2080 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, AUTH_NONE
))
2082 cupsdCloseClient(con
);
2089 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
2091 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, AUTH_NONE
))
2093 cupsdCloseClient(con
);
2098 cupsdLogRequest(con
, HTTP_OK
);
2104 cupsdProcessIPPRequest(con
);
2108 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2109 "cupsdReadClient: %d Removing temp file %s",
2110 con
->http
.fd
, con
->filename
);
2111 unlink(con
->filename
);
2112 cupsdClearString(&con
->filename
);
2121 break; /* Anti-compiler-warning-code */
2124 if (!con
->http
.keep_alive
&& con
->http
.state
== HTTP_WAITING
)
2125 cupsdCloseClient(con
);
2130 * 'cupsdSendCommand()' - Send output from a command via HTTP.
2133 int /* O - 1 on success, 0 on failure */
2135 cupsd_client_t
*con
, /* I - Client connection */
2136 char *command
, /* I - Command to run */
2137 char *options
, /* I - Command-line options */
2138 int root
) /* I - Run as root? */
2140 int fd
; /* Standard input file descriptor */
2145 fd
= open(con
->filename
, O_RDONLY
);
2149 cupsdLogMessage(CUPSD_LOG_ERROR
,
2150 "cupsdSendCommand: %d Unable to open \"%s\" for reading: %s",
2151 con
->http
.fd
, con
->filename
? con
->filename
: "/dev/null",
2156 fcntl(fd
, F_SETFD
, fcntl(fd
, F_GETFD
) | FD_CLOEXEC
);
2161 con
->pipe_pid
= pipe_command(con
, fd
, &(con
->file
), command
, options
, root
);
2166 cupsdLogMessage(CUPSD_LOG_INFO
, "Started \"%s\" (pid=%d)", command
,
2169 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendCommand: %d file=%d",
2170 con
->http
.fd
, con
->file
);
2172 if (con
->pipe_pid
== 0)
2175 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2177 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2179 con
->sent_header
= 0;
2180 con
->file_ready
= 0;
2181 con
->got_fields
= 0;
2189 * 'cupsdSendError()' - Send an error message via HTTP.
2192 int /* O - 1 if successful, 0 otherwise */
2193 cupsdSendError(cupsd_client_t
*con
, /* I - Connection */
2194 http_status_t code
, /* I - Error code */
2195 int auth_type
)/* I - Authentication type */
2199 * Force client to upgrade for authentication if that is how the
2200 * server is configured...
2203 if (code
== HTTP_UNAUTHORIZED
&&
2204 DefaultEncryption
== HTTP_ENCRYPT_REQUIRED
&&
2205 strcasecmp(con
->http
.hostname
, "localhost") &&
2208 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2209 "cupsdSendError: Encryption before authentication!");
2210 code
= HTTP_UPGRADE_REQUIRED
;
2212 #endif /* HAVE_SSL */
2215 * Put the request in the access_log file...
2218 cupsdLogRequest(con
, code
);
2220 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendError: %d code=%d (%s)",
2221 con
->http
.fd
, code
, httpStatus(code
));
2224 * To work around bugs in some proxies, don't use Keep-Alive for some
2227 * Kerberos authentication doesn't work without Keep-Alive, so
2228 * never disable it in that case.
2231 if (code
>= HTTP_BAD_REQUEST
&& con
->http
.auth_type
!= AUTH_NEGOTIATE
)
2232 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
2235 * Send an error message back to the client. If the error code is a
2236 * 400 or 500 series, make sure the message contains some text, too!
2239 if (!cupsdSendHeader(con
, code
, NULL
, auth_type
))
2243 if (code
== HTTP_UPGRADE_REQUIRED
)
2244 if (httpPrintf(HTTP(con
), "Connection: Upgrade\r\n") < 0)
2247 if (httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n") < 0)
2249 #endif /* HAVE_SSL */
2251 if (con
->http
.version
>= HTTP_1_1
&&
2252 con
->http
.keep_alive
== HTTP_KEEPALIVE_OFF
)
2254 if (httpPrintf(HTTP(con
), "Connection: close\r\n") < 0)
2258 if (code
>= HTTP_BAD_REQUEST
)
2261 * Send a human-readable error message.
2264 char message
[4096], /* Message for user */
2265 urltext
[1024], /* URL redirection text */
2266 redirect
[1024]; /* Redirection link */
2267 const char *text
; /* Status-specific text */
2272 if (code
== HTTP_UNAUTHORIZED
)
2273 text
= _cupsLangString(con
->language
,
2274 _("Enter your username and password or the "
2275 "root username and password to access this "
2276 "page. If you are using Kerberos authentication, "
2277 "make sure you have a valid Kerberos ticket."));
2278 else if (code
== HTTP_UPGRADE_REQUIRED
)
2282 snprintf(urltext
, sizeof(urltext
),
2283 _cupsLangString(con
->language
,
2284 _("You must access this page using the URL "
2285 "<A HREF=\"https://%s:%d%s\">"
2286 "https://%s:%d%s</A>.")),
2287 con
->servername
, con
->serverport
, con
->uri
,
2288 con
->servername
, con
->serverport
, con
->uri
);
2290 snprintf(redirect
, sizeof(redirect
),
2291 "<META HTTP-EQUIV=\"Refresh\" "
2292 "CONTENT=\"3;URL=https://%s:%d%s\">\n",
2293 con
->servername
, con
->serverport
, con
->uri
);
2298 snprintf(message
, sizeof(message
),
2299 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" "
2300 "\"http://www.w3.org/TR/REC-html40/loose.dtd\">\n"
2303 "\t<META HTTP-EQUIV=\"Content-Type\" "
2304 "CONTENT=\"text/html; charset=utf-8\">\n"
2305 "\t<TITLE>%d %s</TITLE>\n"
2306 "\t<LINK REL=\"STYLESHEET\" TYPE=\"text/css\" "
2307 "HREF=\"/cups.css\">\n"
2315 code
, httpStatus(code
), redirect
, code
, httpStatus(code
), text
);
2317 if (httpPrintf(HTTP(con
), "Content-Type: text/html; charset=utf-8\r\n") < 0)
2319 if (httpPrintf(HTTP(con
), "Content-Length: %d\r\n",
2320 (int)strlen(message
)) < 0)
2322 if (httpPrintf(HTTP(con
), "\r\n") < 0)
2324 if (httpPrintf(HTTP(con
), "%s", message
) < 0)
2327 else if (httpPrintf(HTTP(con
), "\r\n") < 0)
2330 if (cupsdFlushHeader(con
) < 0)
2333 con
->http
.state
= HTTP_WAITING
;
2340 * 'cupsdSendHeader()' - Send an HTTP request.
2343 int /* O - 1 on success, 0 on failure */
2345 cupsd_client_t
*con
, /* I - Client to send to */
2346 http_status_t code
, /* I - HTTP status code */
2347 char *type
, /* I - MIME type of document */
2348 int auth_type
) /* I - Type of authentication */
2350 char auth_str
[1024]; /* Authorization string */
2354 * Send the HTTP status header...
2357 if (code
== HTTP_CONTINUE
)
2360 * 100-continue doesn't send any headers...
2363 return (httpPrintf(HTTP(con
), "HTTP/%d.%d 100 Continue\r\n\r\n",
2364 con
->http
.version
/ 100, con
->http
.version
% 100) > 0);
2367 httpFlushWrite(HTTP(con
));
2369 con
->http
.data_encoding
= HTTP_ENCODE_FIELDS
;
2371 if (httpPrintf(HTTP(con
), "HTTP/%d.%d %d %s\r\n", con
->http
.version
/ 100,
2372 con
->http
.version
% 100, code
, httpStatus(code
)) < 0)
2374 if (httpPrintf(HTTP(con
), "Date: %s\r\n", httpGetDateString(time(NULL
))) < 0)
2377 if (httpPrintf(HTTP(con
), "Server: %s\r\n", ServerHeader
) < 0)
2379 if (con
->http
.keep_alive
&& con
->http
.version
>= HTTP_1_0
)
2381 if (httpPrintf(HTTP(con
), "Connection: Keep-Alive\r\n") < 0)
2383 if (httpPrintf(HTTP(con
), "Keep-Alive: timeout=%d\r\n",
2384 KeepAliveTimeout
) < 0)
2387 if (code
== HTTP_METHOD_NOT_ALLOWED
)
2388 if (httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST\r\n") < 0)
2391 if (code
== HTTP_UNAUTHORIZED
)
2393 if (auth_type
== AUTH_NONE
)
2395 if (!con
->best
|| con
->best
->type
== AUTH_NONE
)
2396 auth_type
= DefaultAuthType
;
2398 auth_type
= con
->best
->type
;
2403 if (auth_type
== AUTH_BASIC
|| auth_type
== AUTH_BASICDIGEST
)
2404 strlcpy(auth_str
, "Basic realm=\"CUPS\"", sizeof(auth_str
));
2405 else if (auth_type
== AUTH_DIGEST
)
2406 snprintf(auth_str
, sizeof(auth_str
), "Digest realm=\"CUPS\", nonce=\"%s\"",
2407 con
->http
.hostname
);
2409 else if (auth_type
== AUTH_NEGOTIATE
&& !con
->no_negotiate
&&
2410 con
->gss_output_token
.length
== 0)
2411 strlcpy(auth_str
, "Negotiate", sizeof(auth_str
));
2412 #endif /* HAVE_GSSAPI */
2414 #ifdef HAVE_AUTHORIZATION_H
2415 if (con
->best
&& strcmp(auth_str
, "Negotiate"))
2417 int i
; /* Looping var */
2418 char *auth_key
; /* Auth key buffer */
2419 size_t auth_size
; /* Size of remaining buffer */
2422 auth_key
= auth_str
+ strlen(auth_str
);
2423 auth_size
= sizeof(auth_str
) - (auth_key
- auth_str
);
2425 for (i
= 0; i
< con
->best
->num_names
; i
++)
2427 if (!strncasecmp(con
->best
->names
[i
], "@AUTHKEY(", 9))
2429 snprintf(auth_key
, auth_size
, ", authkey=\"%s\"",
2430 con
->best
->names
[i
] + 9);
2431 /* end parenthesis is stripped in conf.c */
2434 else if (!strcasecmp(con
->best
->names
[i
], "@SYSTEM") &&
2437 snprintf(auth_key
, auth_size
, ", authkey=\"%s\"", SystemGroupAuthKey
);
2442 #endif /* HAVE_AUTHORIZATION_H */
2446 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdSendHeader: WWW-Authenticate: %s",
2449 if (httpPrintf(HTTP(con
), "WWW-Authenticate: %s\r\n", auth_str
) < 0)
2456 * WWW-Authenticate: Negotiate can be included even for
2457 * non-401 replies...
2460 if (con
->gss_output_token
.length
> 0)
2462 char buf
[2048]; /* Output token buffer */
2463 OM_uint32 minor_status
; /* Minor status code */
2466 httpEncode64_2(buf
, sizeof(buf
),
2467 con
->gss_output_token
.value
,
2468 con
->gss_output_token
.length
);
2469 gss_release_buffer(&minor_status
, &con
->gss_output_token
);
2471 if (httpPrintf(HTTP(con
), "WWW-Authenticate: Negotiate %s\r\n", buf
) < 0)
2474 #endif /* HAVE_GSSAPI */
2476 if (con
->language
&& strcmp(con
->language
->language
, "C"))
2478 if (httpPrintf(HTTP(con
), "Content-Language: %s\r\n",
2479 con
->language
->language
) < 0)
2485 if (!strcmp(type
, "text/html"))
2487 if (httpPrintf(HTTP(con
),
2488 "Content-Type: text/html; charset=utf-8\r\n") < 0)
2491 else if (httpPrintf(HTTP(con
), "Content-Type: %s\r\n", type
) < 0)
2500 * 'cupsdUpdateCGI()' - Read status messages from CGI scripts and programs.
2504 cupsdUpdateCGI(void)
2506 char *ptr
, /* Pointer to end of line in buffer */
2507 message
[1024]; /* Pointer to message text */
2508 int loglevel
; /* Log level for message */
2511 while ((ptr
= cupsdStatBufUpdate(CGIStatusBuffer
, &loglevel
,
2512 message
, sizeof(message
))) != NULL
)
2513 if (!strchr(CGIStatusBuffer
->buffer
, '\n'))
2516 if (ptr
== NULL
&& !CGIStatusBuffer
->bufused
)
2519 * Fatal error on pipe - should never happen!
2522 cupsdLogMessage(CUPSD_LOG_CRIT
,
2523 "cupsdUpdateCGI: error reading from CGI error pipe - %s",
2530 * 'cupsdWriteClient()' - Write data to a client as needed.
2534 cupsdWriteClient(cupsd_client_t
*con
) /* I - Client connection */
2536 int bytes
; /* Number of bytes written */
2537 char buf
[16385]; /* Data buffer */
2538 char *bufptr
; /* Pointer into buffer */
2539 ipp_state_t ipp_state
; /* IPP state value */
2543 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2544 "cupsdWriteClient(con=%p) %d response=%p(%d), file=%d "
2545 "pipe_pid=%d state=%d",
2546 con
, con
->http
.fd
, con
->response
, con
->response
->state
,
2547 con
->file
, con
->pipe_pid
, con
->http
.state
);
2550 if (con
->http
.state
!= HTTP_GET_SEND
&&
2551 con
->http
.state
!= HTTP_POST_SEND
)
2557 * Make sure we select on the CGI output...
2560 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2562 if (!con
->file_ready
)
2565 * Try again later when there is CGI output available...
2568 cupsdRemoveSelect(con
->http
.fd
);
2572 con
->file_ready
= 0;
2575 if (con
->response
&& con
->response
->state
!= IPP_DATA
)
2577 ipp_state
= ippWrite(HTTP(con
), con
->response
);
2578 bytes
= ipp_state
!= IPP_ERROR
&&
2579 (con
->file
>= 0 || ipp_state
!= IPP_DATA
);
2581 else if ((bytes
= read(con
->file
, buf
, sizeof(buf
) - 1)) > 0)
2583 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2584 "cupsdWriteClient: Read %d bytes from file %d...",
2587 if (con
->pipe_pid
&& !con
->got_fields
)
2590 * Inspect the data for Content-Type and other fields.
2595 for (bufptr
= buf
; !con
->got_fields
&& *bufptr
; bufptr
++)
2596 if (*bufptr
== '\n')
2599 * Send line to client...
2602 if (bufptr
> buf
&& bufptr
[-1] == '\r')
2606 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "Script header: %s", buf
);
2608 if (!con
->sent_header
)
2611 * Handle redirection and CGI status codes...
2614 if (!strncasecmp(buf
, "Location:", 9))
2616 cupsdSendHeader(con
, HTTP_SEE_OTHER
, NULL
, AUTH_NONE
);
2617 con
->sent_header
= 2;
2619 if (httpPrintf(HTTP(con
), "Content-Length: 0\r\n") < 0)
2622 else if (!strncasecmp(buf
, "Status:", 7))
2624 cupsdSendError(con
, (http_status_t
)atoi(buf
+ 7), AUTH_NONE
);
2625 con
->sent_header
= 2;
2629 cupsdSendHeader(con
, HTTP_OK
, NULL
, AUTH_NONE
);
2630 con
->sent_header
= 1;
2632 if (con
->http
.version
== HTTP_1_1
)
2634 if (httpPrintf(HTTP(con
), "Transfer-Encoding: chunked\r\n") < 0)
2640 if (strncasecmp(buf
, "Status:", 7))
2641 httpPrintf(HTTP(con
), "%s\r\n", buf
);
2643 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdWriteClient: %d %s",
2650 bytes
-= (bufptr
- buf
);
2651 memmove(buf
, bufptr
, bytes
+ 1);
2655 * See if the line was empty...
2658 if (con
->field_col
== 0)
2660 con
->got_fields
= 1;
2662 if (cupsdFlushHeader(con
) < 0)
2664 cupsdCloseClient(con
);
2668 if (con
->http
.version
== HTTP_1_1
)
2669 con
->http
.data_encoding
= HTTP_ENCODE_CHUNKED
;
2674 else if (*bufptr
!= '\r')
2677 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2678 "cupsdWriteClient: %d bytes=%d, got_fields=%d",
2679 con
->http
.fd
, bytes
, con
->got_fields
);
2681 if (bytes
> 0 && !con
->got_fields
)
2684 * Remaining text needs to go out...
2687 httpPrintf(HTTP(con
), "%s", buf
);
2689 con
->http
.activity
= time(NULL
);
2692 else if (bytes
== 0)
2693 con
->http
.activity
= time(NULL
);
2698 if (httpWrite2(HTTP(con
), buf
, bytes
) < 0)
2700 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2701 "cupsdWriteClient: %d Write of %d bytes failed!",
2702 con
->http
.fd
, bytes
);
2704 cupsdCloseClient(con
);
2708 con
->bytes
+= bytes
;
2710 if (con
->http
.state
== HTTP_WAITING
)
2717 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdWriteClient: %d bytes < 0",
2720 cupsdLogRequest(con
, HTTP_OK
);
2722 httpFlushWrite(HTTP(con
));
2724 if (con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
&& con
->sent_header
== 1)
2726 if (httpWrite2(HTTP(con
), "", 0) < 0)
2728 cupsdCloseClient(con
);
2733 con
->http
.state
= HTTP_WAITING
;
2735 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
2739 cupsdRemoveSelect(con
->file
);
2742 cupsdEndProcess(con
->pipe_pid
, 0);
2744 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2745 "cupsdWriteClient: %d Closing data file %d.",
2746 con
->http
.fd
, con
->file
);
2755 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2756 "cupsdWriteClient: %d Removing temp file %s",
2757 con
->http
.fd
, con
->filename
);
2758 unlink(con
->filename
);
2759 cupsdClearString(&con
->filename
);
2764 ippDelete(con
->request
);
2765 con
->request
= NULL
;
2770 ippDelete(con
->response
);
2771 con
->response
= NULL
;
2774 cupsdClearString(&con
->command
);
2775 cupsdClearString(&con
->options
);
2776 cupsdClearString(&con
->query_string
);
2778 if (!con
->http
.keep_alive
)
2780 cupsdCloseClient(con
);
2785 con
->http
.activity
= time(NULL
);
2790 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
2793 static int /* O - 1 if modified since */
2795 cupsd_client_t
*con
, /* I - Client connection */
2796 struct stat
*filestats
) /* I - File information */
2798 char *ptr
; /* Pointer into field */
2799 time_t date
; /* Time/date value */
2800 off_t size
; /* Size/length value */
2805 ptr
= con
->http
.fields
[HTTP_FIELD_IF_MODIFIED_SINCE
];
2810 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2811 "check_if_modified: %d If-Modified-Since=\"%s\"",
2814 while (*ptr
!= '\0')
2816 while (isspace(*ptr
) || *ptr
== ';')
2819 if (strncasecmp(ptr
, "length=", 7) == 0)
2822 size
= strtoll(ptr
, NULL
, 10);
2824 while (isdigit(*ptr
))
2827 else if (isalpha(*ptr
))
2829 date
= httpGetDateTime(ptr
);
2830 while (*ptr
!= '\0' && *ptr
!= ';')
2837 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2838 "check_if_modified: %d sizes=" CUPS_LLFMT
","
2839 CUPS_LLFMT
" dates=%d,%d",
2840 con
->http
.fd
, CUPS_LLCAST size
,
2841 CUPS_LLCAST filestats
->st_size
, (int)date
,
2842 (int)filestats
->st_mtime
);
2844 return ((size
!= filestats
->st_size
&& size
!= 0) ||
2845 (date
< filestats
->st_mtime
&& date
!= 0) ||
2846 (size
== 0 && date
== 0));
2852 * 'encrypt_client()' - Enable encryption for the client...
2855 static int /* O - 1 on success, 0 on error */
2856 encrypt_client(cupsd_client_t
*con
) /* I - Client to encrypt */
2859 SSL_CTX
*context
; /* Context for encryption */
2860 SSL
*conn
; /* Connection for encryption */
2861 BIO
*bio
; /* BIO data */
2862 unsigned long error
; /* Error code */
2866 * Verify that we have a certificate...
2869 if (access(ServerKey
, 0) || access(ServerCertificate
, 0))
2872 * Nope, make a self-signed certificate...
2875 if (!make_certificate(con
))
2880 * Create the SSL context and accept the connection...
2883 context
= SSL_CTX_new(SSLv23_server_method());
2885 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
2886 SSL_CTX_use_PrivateKey_file(context
, ServerKey
, SSL_FILETYPE_PEM
);
2887 SSL_CTX_use_certificate_file(context
, ServerCertificate
, SSL_FILETYPE_PEM
);
2889 bio
= BIO_new(_httpBIOMethods());
2890 BIO_ctrl(bio
, BIO_C_SET_FILE_PTR
, 0, (char *)HTTP(con
));
2892 conn
= SSL_new(context
);
2893 SSL_set_bio(conn
, bio
, bio
);
2895 if (SSL_accept(conn
) != 1)
2897 cupsdLogMessage(CUPSD_LOG_ERROR
,
2898 "encrypt_client: Unable to encrypt connection from %s!",
2899 con
->http
.hostname
);
2901 while ((error
= ERR_get_error()) != 0)
2902 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s",
2903 ERR_error_string(error
, NULL
));
2905 SSL_CTX_free(context
);
2910 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2911 "encrypt_client: %d Connection from %s now encrypted.",
2912 con
->http
.fd
, con
->http
.hostname
);
2914 con
->http
.tls
= conn
;
2917 # elif defined(HAVE_GNUTLS)
2918 http_tls_t
*conn
; /* TLS session object */
2919 int error
; /* Error code */
2920 gnutls_certificate_server_credentials
*credentials
;
2921 /* TLS credentials */
2925 * Verify that we have a certificate...
2928 if (access(ServerKey
, 0) || access(ServerCertificate
, 0))
2931 * Nope, make a self-signed certificate...
2934 if (!make_certificate(con
))
2939 * Create the SSL object and perform the SSL handshake...
2942 conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
));
2947 credentials
= (gnutls_certificate_server_credentials
*)
2948 malloc(sizeof(gnutls_certificate_server_credentials
));
2949 if (credentials
== NULL
)
2951 cupsdLogMessage(CUPSD_LOG_ERROR
,
2952 "encrypt_client: Unable to encrypt connection from %s!",
2953 con
->http
.hostname
);
2954 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s", strerror(errno
));
2960 gnutls_certificate_allocate_credentials(credentials
);
2961 gnutls_certificate_set_x509_key_file(*credentials
, ServerCertificate
,
2962 ServerKey
, GNUTLS_X509_FMT_PEM
);
2964 gnutls_init(&(conn
->session
), GNUTLS_SERVER
);
2965 gnutls_set_default_priority(conn
->session
);
2966 gnutls_credentials_set(conn
->session
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
2967 gnutls_transport_set_ptr(conn
->session
, (gnutls_transport_ptr
)HTTP(con
));
2968 gnutls_transport_set_pull_function(conn
->session
, _httpReadGNUTLS
);
2969 gnutls_transport_set_push_function(conn
->session
, _httpWriteGNUTLS
);
2971 error
= gnutls_handshake(conn
->session
);
2973 if (error
!= GNUTLS_E_SUCCESS
)
2975 cupsdLogMessage(CUPSD_LOG_ERROR
,
2976 "encrypt_client: Unable to encrypt connection from %s!",
2977 con
->http
.hostname
);
2978 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s",
2979 gnutls_strerror(error
));
2981 gnutls_deinit(conn
->session
);
2982 gnutls_certificate_free_credentials(*credentials
);
2988 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2989 "encrypt_client: %d Connection from %s now encrypted.",
2990 con
->http
.fd
, con
->http
.hostname
);
2992 conn
->credentials
= credentials
;
2993 con
->http
.tls
= conn
;
2996 # elif defined(HAVE_CDSASSL)
2997 OSStatus error
; /* Error code */
2998 http_tls_t
*conn
; /* CDSA connection information */
3001 if ((conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
))) == NULL
)
3005 conn
->session
= NULL
;
3006 conn
->certsArray
= get_cdsa_certificate(con
);
3008 if (!conn
->certsArray
)
3011 * No keychain (yet), make a self-signed certificate...
3014 if (make_certificate(con
))
3015 conn
->certsArray
= get_cdsa_certificate(con
);
3018 if (!conn
->certsArray
)
3020 cupsdLogMessage(CUPSD_LOG_ERROR
,
3021 "encrypt_client: Could not find signing key in keychain "
3022 "\"%s\"", ServerCertificate
);
3023 error
= errSSLBadCert
; /* errSSLBadConfiguration is a better choice, but not available on 10.2.x */
3027 error
= SSLNewContext(true, &conn
->session
);
3030 error
= SSLSetIOFuncs(conn
->session
, _httpReadCDSA
, _httpWriteCDSA
);
3033 error
= SSLSetProtocolVersionEnabled(conn
->session
, kSSLProtocol2
, false);
3036 error
= SSLSetConnection(conn
->session
, HTTP(con
));
3039 error
= SSLSetAllowsExpiredCerts(conn
->session
, true);
3042 error
= SSLSetAllowsAnyRoot(conn
->session
, true);
3045 error
= SSLSetCertificate(conn
->session
, conn
->certsArray
);
3050 * Perform SSL/TLS handshake
3053 while ((error
= SSLHandshake(conn
->session
)) == errSSLWouldBlock
)
3059 cupsdLogMessage(CUPSD_LOG_ERROR
,
3060 "encrypt_client: Unable to encrypt connection from %s!",
3061 con
->http
.hostname
);
3063 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s (%d)",
3064 cssmErrorString(error
), (int)error
);
3066 con
->http
.error
= error
;
3067 con
->http
.status
= HTTP_ERROR
;
3070 SSLDisposeContext(conn
->session
);
3072 if (conn
->certsArray
)
3073 CFRelease(conn
->certsArray
);
3080 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3081 "encrypt_client: %d Connection from %s now encrypted.",
3082 con
->http
.fd
, con
->http
.hostname
);
3084 con
->http
.tls
= conn
;
3087 # endif /* HAVE_LIBSSL */
3089 #endif /* HAVE_SSL */
3094 * 'get_cdsa_certificate()' - Get a SSL/TLS certificate from the System keychain.
3097 static CFArrayRef
/* O - Array of certificates */
3098 get_cdsa_certificate(cupsd_client_t
*con
) /* I - Client connection */
3100 OSStatus err
; /* Error info */
3101 SecKeychainRef keychain
; /* Keychain reference */
3102 SecIdentitySearchRef search
; /* Search reference */
3103 SecIdentityRef identity
; /* Identity */
3104 CFArrayRef certificates
= NULL
;
3105 /* Certificate array */
3108 if ((err
= SecKeychainOpen(ServerCertificate
, &keychain
)))
3110 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot open keychain \"%s\", %s",
3111 ServerCertificate
, cssmErrorString(err
));
3115 # if HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY
3117 * Use a policy to search for valid certificates who's common name matches the
3121 SecPolicySearchRef policy_search
; /* Policy search ref */
3122 SecPolicyRef policy
; /* Policy ref */
3123 CSSM_DATA options
; /* Policy options */
3124 CSSM_APPLE_TP_SSL_OPTIONS
3125 ssl_options
; /* SSL Option for hostname */
3128 if ((err
= SecPolicySearchCreate(CSSM_CERT_X_509v3
, &CSSMOID_APPLE_TP_SSL
,
3129 NULL
, &policy_search
)))
3131 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot create a policy search reference");
3132 CFRelease(keychain
);
3136 if ((err
= SecPolicySearchCopyNext(policy_search
, &policy
)))
3138 cupsdLogMessage(CUPSD_LOG_ERROR
,
3139 "Cannot find a policy to use for searching");
3140 CFRelease(keychain
);
3141 CFRelease(policy_search
);
3145 memset(&ssl_options
, 0, sizeof(ssl_options
));
3146 ssl_options
.Version
= CSSM_APPLE_TP_SSL_OPTS_VERSION
;
3147 ssl_options
.ServerName
= con
->servername
;
3148 ssl_options
.ServerNameLen
= strlen(con
->servername
);
3150 options
.Data
= (uint8
*)&ssl_options
;
3151 options
.Length
= sizeof(ssl_options
);
3153 if ((err
= SecPolicySetValue(policy
, &options
)))
3155 cupsdLogMessage(CUPSD_LOG_ERROR
,
3156 "Cannot set policy value to use for searching");
3157 CFRelease(keychain
);
3158 CFRelease(policy_search
);
3162 err
= SecIdentitySearchCreateWithPolicy(policy
, NULL
, CSSM_KEYUSE_SIGN
,
3163 keychain
, FALSE
, &search
);
3166 * Assume there is exactly one SecIdentity in the keychain...
3169 err
= SecIdentitySearchCreate(keychain
, CSSM_KEYUSE_SIGN
, &search
);
3170 # endif /* HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY */
3173 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3174 "Cannot create keychain search reference: %s",
3175 cssmErrorString(err
));
3178 if ((err
= SecIdentitySearchCopyNext(search
, &identity
)))
3180 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3181 "Cannot find signing key in keychain \"%s\", error %d",
3182 ServerCertificate
, (int)err
);
3186 if (CFGetTypeID(identity
) != SecIdentityGetTypeID())
3187 cupsdLogMessage(CUPSD_LOG_ERROR
,
3188 "SecIdentitySearchCopyNext CFTypeID failure!");
3191 if ((certificates
= CFArrayCreate(NULL
, (const void **)&identity
,
3192 1, &kCFTypeArrayCallBacks
)) == NULL
)
3193 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot create certificate array");
3196 CFRelease(identity
);
3202 # if HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY
3204 CFRelease(policy_search
);
3205 # endif /* HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY */
3207 return (certificates
);
3209 #endif /* HAVE_CDSASSL */
3213 * 'get_file()' - Get a filename and state info.
3216 static char * /* O - Real filename */
3217 get_file(cupsd_client_t
*con
, /* I - Client connection */
3218 struct stat
*filestats
, /* O - File information */
3219 char *filename
, /* IO - Filename buffer */
3220 int len
) /* I - Buffer length */
3222 int status
; /* Status of filesystem calls */
3223 char *ptr
; /* Pointer info filename */
3224 int plen
; /* Remaining length after pointer */
3228 * Figure out the real filename...
3231 if (!strncmp(con
->uri
, "/ppd/", 5))
3232 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
);
3233 else if (!strncmp(con
->uri
, "/rss/", 5) && !strchr(con
->uri
+ 5, '/'))
3234 snprintf(filename
, len
, "%s/rss/%s", CacheDir
, con
->uri
+ 5);
3235 else if (!strncmp(con
->uri
, "/admin/conf/", 12))
3236 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
+ 11);
3237 else if (!strncmp(con
->uri
, "/admin/log/", 11))
3239 if (!strcmp(con
->uri
+ 11, "access_log") && AccessLog
[0] == '/')
3240 strlcpy(filename
, AccessLog
, len
);
3241 else if (!strcmp(con
->uri
+ 11, "error_log") && ErrorLog
[0] == '/')
3242 strlcpy(filename
, ErrorLog
, len
);
3243 else if (!strcmp(con
->uri
+ 11, "page_log") && PageLog
[0] == '/')
3244 strlcpy(filename
, PageLog
, len
);
3248 else if (con
->language
)
3249 snprintf(filename
, len
, "%s/%s%s", DocumentRoot
, con
->language
->language
,
3252 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3254 if ((ptr
= strchr(filename
, '?')) != NULL
)
3258 * Grab the status for this language; if there isn't a language-specific file
3259 * then fallback to the default one...
3262 if ((status
= stat(filename
, filestats
)) != 0 && con
->language
&&
3263 strncmp(con
->uri
, "/ppd/", 5) &&
3264 strncmp(con
->uri
, "/admin/conf/", 12) &&
3265 strncmp(con
->uri
, "/admin/log/", 11))
3268 * Drop the country code...
3271 char ll
[3]; /* Short language name */
3274 strlcpy(ll
, con
->language
->language
, sizeof(ll
));
3275 snprintf(filename
, len
, "%s/%s%s", DocumentRoot
, ll
, con
->uri
);
3277 if ((ptr
= strchr(filename
, '?')) != NULL
)
3280 if ((status
= stat(filename
, filestats
)) != 0)
3283 * Drop the language prefix and try the root directory...
3286 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3288 if ((ptr
= strchr(filename
, '?')) != NULL
)
3291 status
= stat(filename
, filestats
);
3296 * If we're found a directory, get the index.html file instead...
3299 if (!status
&& S_ISDIR(filestats
->st_mode
))
3301 if (filename
[strlen(filename
) - 1] != '/')
3302 strlcat(filename
, "/", len
);
3304 ptr
= filename
+ strlen(filename
);
3305 plen
= len
- (ptr
- filename
);
3307 strlcpy(ptr
, "index.html", plen
);
3308 status
= stat(filename
, filestats
);
3313 strlcpy(ptr
, "index.class", plen
);
3314 status
= stat(filename
, filestats
);
3316 #endif /* HAVE_JAVA */
3321 strlcpy(ptr
, "index.pl", plen
);
3322 status
= stat(filename
, filestats
);
3324 #endif /* HAVE_PERL */
3329 strlcpy(ptr
, "index.php", plen
);
3330 status
= stat(filename
, filestats
);
3332 #endif /* HAVE_PHP */
3337 strlcpy(ptr
, "index.pyc", plen
);
3338 status
= stat(filename
, filestats
);
3343 strlcpy(ptr
, "index.py", plen
);
3344 status
= stat(filename
, filestats
);
3346 #endif /* HAVE_PYTHON */
3349 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "get_file: %d filename=%s size=%d",
3350 con
->http
.fd
, filename
,
3351 status
? -1 : (int)filestats
->st_size
);
3354 con
->http
.data_remaining
= (int)filestats
->st_size
;
3364 * 'install_conf_file()' - Install a configuration file.
3367 static http_status_t
/* O - Status */
3368 install_conf_file(cupsd_client_t
*con
) /* I - Connection */
3370 cups_file_t
*in
, /* Input file */
3371 *out
; /* Output file */
3372 char buffer
[1024]; /* Copy buffer */
3373 int bytes
; /* Number of bytes */
3374 char conffile
[1024], /* Configuration filename */
3375 newfile
[1024], /* New config filename */
3376 oldfile
[1024]; /* Old config filename */
3377 struct stat confinfo
; /* Config file info */
3381 * First construct the filenames...
3384 snprintf(conffile
, sizeof(conffile
), "%s%s", ServerRoot
, con
->uri
+ 11);
3385 snprintf(newfile
, sizeof(newfile
), "%s%s.N", ServerRoot
, con
->uri
+ 11);
3386 snprintf(oldfile
, sizeof(oldfile
), "%s%s.O", ServerRoot
, con
->uri
+ 11);
3388 cupsdLogMessage(CUPSD_LOG_INFO
, "Installing config file \"%s\"...", conffile
);
3391 * Get the owner, group, and permissions of the configuration file.
3392 * If it doesn't exist, assign it to the User and Group in the
3393 * cupsd.conf file with mode 0640 permissions.
3396 if (stat(conffile
, &confinfo
))
3398 confinfo
.st_uid
= User
;
3399 confinfo
.st_gid
= Group
;
3400 confinfo
.st_mode
= ConfigFilePerm
;
3404 * Open the request file and new config file...
3407 if ((in
= cupsFileOpen(con
->filename
, "rb")) == NULL
)
3409 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open request file \"%s\" - %s",
3410 con
->filename
, strerror(errno
));
3411 return (HTTP_SERVER_ERROR
);
3414 if ((out
= cupsFileOpen(newfile
, "wb")) == NULL
)
3417 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open config file \"%s\" - %s",
3418 newfile
, strerror(errno
));
3419 return (HTTP_SERVER_ERROR
);
3422 fchmod(cupsFileNumber(out
), confinfo
.st_mode
);
3423 fchown(cupsFileNumber(out
), confinfo
.st_uid
, confinfo
.st_gid
);
3426 * Copy from the request to the new config file...
3429 while ((bytes
= cupsFileRead(in
, buffer
, sizeof(buffer
))) > 0)
3430 if (cupsFileWrite(out
, buffer
, bytes
) < bytes
)
3432 cupsdLogMessage(CUPSD_LOG_ERROR
,
3433 "Unable to copy to config file \"%s\" - %s",
3434 newfile
, strerror(errno
));
3440 return (HTTP_SERVER_ERROR
);
3444 * Close the files...
3448 if (cupsFileClose(out
))
3450 cupsdLogMessage(CUPSD_LOG_ERROR
,
3451 "Error file closing config file \"%s\" - %s",
3452 newfile
, strerror(errno
));
3456 return (HTTP_SERVER_ERROR
);
3460 * Remove the request file...
3463 unlink(con
->filename
);
3464 cupsdClearString(&con
->filename
);
3467 * Unlink the old backup, rename the current config file to the backup
3468 * filename, and rename the new config file to the config file name...
3471 if (unlink(oldfile
))
3472 if (errno
!= ENOENT
)
3474 cupsdLogMessage(CUPSD_LOG_ERROR
,
3475 "Unable to remove backup config file \"%s\" - %s",
3476 oldfile
, strerror(errno
));
3480 return (HTTP_SERVER_ERROR
);
3483 if (rename(conffile
, oldfile
))
3484 if (errno
!= ENOENT
)
3486 cupsdLogMessage(CUPSD_LOG_ERROR
,
3487 "Unable to rename old config file \"%s\" - %s",
3488 conffile
, strerror(errno
));
3492 return (HTTP_SERVER_ERROR
);
3495 if (rename(newfile
, conffile
))
3497 cupsdLogMessage(CUPSD_LOG_ERROR
,
3498 "Unable to rename new config file \"%s\" - %s",
3499 newfile
, strerror(errno
));
3501 rename(oldfile
, conffile
);
3504 return (HTTP_SERVER_ERROR
);
3508 * If the cupsd.conf file was updated, set the NeedReload flag...
3511 if (!strcmp(con
->uri
, "/admin/conf/cupsd.conf"))
3512 NeedReload
= RELOAD_CUPSD
;
3514 NeedReload
= RELOAD_ALL
;
3516 ReloadTime
= time(NULL
);
3519 * Return that the file was created successfully...
3522 return (HTTP_CREATED
);
3527 * 'is_cgi()' - Is the resource a CGI script/program?
3530 static int /* O - 1 = CGI, 0 = file */
3531 is_cgi(cupsd_client_t
*con
, /* I - Client connection */
3532 const char *filename
, /* I - Real filename */
3533 struct stat
*filestats
, /* I - File information */
3534 mime_type_t
*type
) /* I - MIME type */
3536 const char *options
; /* Options on URL */
3539 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3540 "is_cgi(con=%p, filename=\"%s\", filestats=%p, type=%s/%s)\n",
3541 con
, filename
, filestats
, type
? type
->super
: "unknown",
3542 type
? type
->type
: "unknown");
3545 * Get the options, if any...
3548 if ((options
= strchr(con
->uri
, '?')) != NULL
)
3552 if (strchr(options
, '='))
3553 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", options
);
3557 * Check for known types...
3560 if (!type
|| strcasecmp(type
->super
, "application"))
3562 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "is_cgi: Returning 0...");
3566 if (!strcasecmp(type
->type
, "x-httpd-cgi") &&
3567 (filestats
->st_mode
& 0111))
3570 * "application/x-httpd-cgi" is a CGI script.
3573 cupsdSetString(&con
->command
, filename
);
3575 filename
= strrchr(filename
, '/') + 1; /* Filename always absolute */
3577 cupsdSetString(&con
->options
, options
);
3579 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3580 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3581 con
->command
, con
->options
);
3586 else if (!strcasecmp(type
->type
, "x-httpd-java"))
3589 * "application/x-httpd-java" is a Java servlet.
3592 cupsdSetString(&con
->command
, CUPS_JAVA
);
3595 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3597 cupsdSetStringf(&con
->options
, " %s", filename
);
3599 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3600 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3601 con
->command
, con
->options
);
3605 #endif /* HAVE_JAVA */
3607 else if (!strcasecmp(type
->type
, "x-httpd-perl"))
3610 * "application/x-httpd-perl" is a Perl page.
3613 cupsdSetString(&con
->command
, CUPS_PERL
);
3616 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3618 cupsdSetStringf(&con
->options
, " %s", filename
);
3620 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3621 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3622 con
->command
, con
->options
);
3626 #endif /* HAVE_PERL */
3628 else if (!strcasecmp(type
->type
, "x-httpd-php"))
3631 * "application/x-httpd-php" is a PHP page.
3634 cupsdSetString(&con
->command
, CUPS_PHP
);
3637 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3639 cupsdSetStringf(&con
->options
, " %s", filename
);
3641 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3642 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3643 con
->command
, con
->options
);
3647 #endif /* HAVE_PHP */
3649 else if (!strcasecmp(type
->type
, "x-httpd-python"))
3652 * "application/x-httpd-python" is a Python page.
3655 cupsdSetString(&con
->command
, CUPS_PYTHON
);
3658 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3660 cupsdSetStringf(&con
->options
, " %s", filename
);
3662 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3663 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3664 con
->command
, con
->options
);
3668 #endif /* HAVE_PYTHON */
3670 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "is_cgi: Returning 0...");
3677 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
3680 static int /* O - 0 if relative, 1 if absolute */
3681 is_path_absolute(const char *path
) /* I - Input path */
3684 * Check for a leading slash...
3691 * Check for "/.." in the path...
3694 while ((path
= strstr(path
, "/..")) != NULL
)
3696 if (!path
[3] || path
[3] == '/')
3703 * If we haven't found any relative paths, return 1 indicating an
3713 * 'make_certificate()' - Make a self-signed SSL/TLS certificate.
3716 static int /* O - 1 on success, 0 on failure */
3717 make_certificate(cupsd_client_t
*con
) /* I - Client connection */
3719 #if defined(HAVE_LIBSSL) && defined(HAVE_WAITPID)
3720 int pid
, /* Process ID of command */
3721 status
; /* Status of command */
3722 char command
[1024], /* Command */
3723 *argv
[12], /* Command-line arguments */
3724 *envp
[MAX_ENV
+ 1], /* Environment variables */
3725 home
[1024], /* HOME environment variable */
3726 infofile
[1024], /* Type-in information for cert */
3727 seedfile
[1024]; /* Random number seed file */
3728 int envc
, /* Number of environment variables */
3729 bytes
; /* Bytes written */
3730 cups_file_t
*fp
; /* Seed/info file */
3731 int infofd
; /* Info file descriptor */
3735 * Run the "openssl" command to seed the random number generator and
3736 * generate a self-signed certificate that is good for 10 years:
3738 * openssl rand -rand seedfile 1
3740 * openssl req -new -x509 -keyout ServerKey \
3741 * -out ServerCertificate -days 3650 -nodes
3743 * The seeding step is crucial in ensuring that the openssl command
3744 * does not block on systems without sufficient entropy...
3747 if (!cupsFileFind("openssl", getenv("PATH"), 1, command
, sizeof(command
)))
3749 cupsdLogMessage(CUPSD_LOG_ERROR
,
3750 "No SSL certificate and openssl command not found!");
3754 if (access("/dev/urandom", 0))
3757 * If the system doesn't provide /dev/urandom, then any random source
3758 * will probably be blocking-style, so generate some random data to
3759 * use as a seed for the certificate. Note that we have already
3760 * seeded the random number generator in cupsdInitCerts()...
3763 cupsdLogMessage(CUPSD_LOG_INFO
,
3764 "Seeding the random number generator...");
3766 snprintf(home
, sizeof(home
), "HOME=%s", TempDir
);
3769 * Write the seed file...
3772 if ((fp
= cupsTempFile2(seedfile
, sizeof(seedfile
))) == NULL
)
3774 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to create seed file %s - %s",
3775 seedfile
, strerror(errno
));
3779 for (bytes
= 0; bytes
< 262144; bytes
++)
3780 cupsFilePutChar(fp
, random());
3785 * Run the openssl command to seed its random number generator...
3788 argv
[0] = "openssl";
3795 envc
= cupsdLoadEnv(envp
, MAX_ENV
);
3796 envp
[envc
++] = home
;
3799 if (!cupsdStartProcess(command
, argv
, envp
, -1, -1, -1, -1, -1, 1, &pid
))
3805 while (waitpid(pid
, &status
, 0) < 0)
3812 cupsdFinishProcess(pid
, command
, sizeof(command
));
3815 * Remove the seed file, as it is no longer needed...
3822 if (WIFEXITED(status
))
3823 cupsdLogMessage(CUPSD_LOG_ERROR
,
3824 "Unable to seed random number generator - "
3825 "the openssl command stopped with status %d!",
3826 WEXITSTATUS(status
));
3828 cupsdLogMessage(CUPSD_LOG_ERROR
,
3829 "Unable to seed random number generator - "
3830 "the openssl command crashed on signal %d!",
3838 * Create a file with the certificate information fields...
3840 * Note: This assumes that the default questions are asked by the openssl
3844 if ((fp
= cupsTempFile2(infofile
, sizeof(infofile
))) == NULL
)
3846 cupsdLogMessage(CUPSD_LOG_ERROR
,
3847 "Unable to create certificate information file %s - %s",
3848 infofile
, strerror(errno
));
3852 cupsFilePrintf(fp
, ".\n.\n.\n%s\n.\n%s\n%s\n",
3853 ServerName
, ServerName
, ServerAdmin
);
3856 cupsdLogMessage(CUPSD_LOG_INFO
,
3857 "Generating SSL server key and certificate...");
3859 argv
[0] = "openssl";
3863 argv
[4] = "-keyout";
3864 argv
[5] = ServerKey
;
3866 argv
[7] = ServerCertificate
;
3869 argv
[10] = "-nodes";
3872 cupsdLoadEnv(envp
, MAX_ENV
);
3874 infofd
= open(infofile
, O_RDONLY
);
3876 if (!cupsdStartProcess(command
, argv
, envp
, infofd
, -1, -1, -1, -1, 1, &pid
))
3886 while (waitpid(pid
, &status
, 0) < 0)
3893 cupsdFinishProcess(pid
, command
, sizeof(command
));
3897 if (WIFEXITED(status
))
3898 cupsdLogMessage(CUPSD_LOG_ERROR
,
3899 "Unable to create SSL server key and certificate - "
3900 "the openssl command stopped with status %d!",
3901 WEXITSTATUS(status
));
3903 cupsdLogMessage(CUPSD_LOG_ERROR
,
3904 "Unable to create SSL server key and certificate - "
3905 "the openssl command crashed on signal %d!",
3910 cupsdLogMessage(CUPSD_LOG_INFO
, "Created SSL server key file \"%s\"...",
3912 cupsdLogMessage(CUPSD_LOG_INFO
,
3913 "Created SSL server certificate file \"%s\"...",
3919 #elif defined(HAVE_GNUTLS)
3920 gnutls_x509_crt crt
; /* Self-signed certificate */
3921 gnutls_x509_privkey key
; /* Encryption key */
3922 cups_lang_t
*language
; /* Default language info */
3923 cups_file_t
*fp
; /* Key/cert file */
3924 unsigned char buffer
[8192]; /* Buffer for x509 data */
3925 size_t bytes
; /* Number of bytes of data */
3926 unsigned char serial
[4]; /* Serial number buffer */
3927 time_t curtime
; /* Current time */
3928 int result
; /* Result of GNU TLS calls */
3932 * Create the encryption key...
3935 cupsdLogMessage(CUPSD_LOG_INFO
, "Generating SSL server key...");
3937 gnutls_x509_privkey_init(&key
);
3938 gnutls_x509_privkey_generate(key
, GNUTLS_PK_RSA
, 2048, 0);
3944 bytes
= sizeof(buffer
);
3946 if ((result
= gnutls_x509_privkey_export(key
, GNUTLS_X509_FMT_PEM
,
3947 buffer
, &bytes
)) < 0)
3949 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to export SSL server key - %s",
3950 gnutls_strerror(result
));
3951 gnutls_x509_privkey_deinit(key
);
3954 else if ((fp
= cupsFileOpen(ServerKey
, "w")) != NULL
)
3956 cupsFileWrite(fp
, (char *)buffer
, bytes
);
3959 cupsdLogMessage(CUPSD_LOG_INFO
, "Created SSL server key file \"%s\"...",
3964 cupsdLogMessage(CUPSD_LOG_ERROR
,
3965 "Unable to create SSL server key file \"%s\" - %s",
3966 ServerKey
, strerror(errno
));
3967 gnutls_x509_privkey_deinit(key
);
3972 * Create the self-signed certificate...
3975 cupsdLogMessage(CUPSD_LOG_INFO
, "Generating self-signed SSL certificate...");
3977 language
= cupsLangDefault();
3978 curtime
= time(NULL
);
3979 serial
[0] = curtime
>> 24;
3980 serial
[1] = curtime
>> 16;
3981 serial
[2] = curtime
>> 8;
3982 serial
[3] = curtime
;
3984 gnutls_x509_crt_init(&crt
);
3985 if (strlen(language
->language
) == 5)
3986 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
3987 language
->language
+ 3, 2);
3989 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
3991 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COMMON_NAME
, 0,
3992 ServerName
, strlen(ServerName
));
3993 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATION_NAME
, 0,
3994 ServerName
, strlen(ServerName
));
3995 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATIONAL_UNIT_NAME
,
3997 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_STATE_OR_PROVINCE_NAME
, 0,
3999 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_LOCALITY_NAME
, 0,
4001 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_PKCS9_EMAIL
, 0,
4002 ServerAdmin
, strlen(ServerAdmin
));
4003 gnutls_x509_crt_set_key(crt
, key
);
4004 gnutls_x509_crt_set_serial(crt
, serial
, sizeof(serial
));
4005 gnutls_x509_crt_set_activation_time(crt
, curtime
);
4006 gnutls_x509_crt_set_expiration_time(crt
, curtime
+ 10 * 365 * 86400);
4007 gnutls_x509_crt_set_ca_status(crt
, 0);
4008 gnutls_x509_crt_set_subject_alternative_name(crt
, GNUTLS_SAN_DNSNAME
,
4010 gnutls_x509_crt_set_key_purpose_oid(crt
, GNUTLS_KP_TLS_WWW_SERVER
, 0);
4011 gnutls_x509_crt_set_key_usage(crt
, GNUTLS_KEY_KEY_ENCIPHERMENT
);
4012 gnutls_x509_crt_set_version(crt
, 3);
4014 bytes
= sizeof(buffer
);
4015 if (gnutls_x509_crt_get_key_id(crt
, 0, buffer
, &bytes
) >= 0)
4016 gnutls_x509_crt_set_subject_key_id(crt
, buffer
, bytes
);
4018 gnutls_x509_crt_sign(crt
, crt
, key
);
4024 bytes
= sizeof(buffer
);
4025 if ((result
= gnutls_x509_crt_export(crt
, GNUTLS_X509_FMT_PEM
,
4026 buffer
, &bytes
)) < 0)
4027 cupsdLogMessage(CUPSD_LOG_ERROR
,
4028 "Unable to export SSL server certificate - %s",
4029 gnutls_strerror(result
));
4030 else if ((fp
= cupsFileOpen(ServerCertificate
, "w")) != NULL
)
4032 cupsFileWrite(fp
, (char *)buffer
, bytes
);
4035 cupsdLogMessage(CUPSD_LOG_INFO
,
4036 "Created SSL server certificate file \"%s\"...",
4040 cupsdLogMessage(CUPSD_LOG_ERROR
,
4041 "Unable to create SSL server certificate file \"%s\" - %s",
4042 ServerCertificate
, strerror(errno
));
4048 gnutls_x509_crt_deinit(crt
);
4049 gnutls_x509_privkey_deinit(key
);
4053 #elif defined(HAVE_CDSASSL) && defined(HAVE_WAITPID)
4054 int pid
, /* Process ID of command */
4055 status
; /* Status of command */
4056 char command
[1024], /* Command */
4057 *argv
[4], /* Command-line arguments */
4058 *envp
[MAX_ENV
+ 1], /* Environment variables */
4059 keychain
[1024], /* Keychain argument */
4060 infofile
[1024]; /* Type-in information for cert */
4061 cups_file_t
*fp
; /* Seed/info file */
4062 int infofd
; /* Info file descriptor */
4066 * Run the "certtool" command to generate a self-signed certificate...
4069 if (!cupsFileFind("certtool", getenv("PATH"), 1, command
, sizeof(command
)))
4071 cupsdLogMessage(CUPSD_LOG_ERROR
,
4072 "No SSL certificate and certtool command not found!");
4077 * Create a file with the certificate information fields...
4079 * Note: This assumes that the default questions are asked by the certtool
4083 if ((fp
= cupsTempFile2(infofile
, sizeof(infofile
))) == NULL
)
4085 cupsdLogMessage(CUPSD_LOG_ERROR
,
4086 "Unable to create certificate information file %s - %s",
4087 infofile
, strerror(errno
));
4091 cupsFilePrintf(fp
, "%s\nr\n\ny\nb\ns\ny\n%s\n\n\n\n\n%s\ny\n",
4092 con
->servername
, con
->servername
, ServerAdmin
);
4095 cupsdLogMessage(CUPSD_LOG_INFO
,
4096 "Generating SSL server key and certificate...");
4098 snprintf(keychain
, sizeof(keychain
), "k=%s", ServerCertificate
);
4100 argv
[0] = "certtool";
4105 cupsdLoadEnv(envp
, MAX_ENV
);
4107 infofd
= open(infofile
, O_RDONLY
);
4109 if (!cupsdStartProcess(command
, argv
, envp
, infofd
, -1, -1, -1, -1, 1, &pid
))
4119 while (waitpid(pid
, &status
, 0) < 0)
4126 cupsdFinishProcess(pid
, command
, sizeof(command
));
4130 if (WIFEXITED(status
))
4131 cupsdLogMessage(CUPSD_LOG_ERROR
,
4132 "Unable to create SSL server key and certificate - "
4133 "the certtool command stopped with status %d!",
4134 WEXITSTATUS(status
));
4136 cupsdLogMessage(CUPSD_LOG_ERROR
,
4137 "Unable to create SSL server key and certificate - "
4138 "the certtool command crashed on signal %d!",
4143 cupsdLogMessage(CUPSD_LOG_INFO
,
4144 "Created SSL server certificate file \"%s\"...",
4152 #endif /* HAVE_LIBSSL && HAVE_WAITPID */
4154 #endif /* HAVE_SSL */
4158 * 'pipe_command()' - Pipe the output of a command to the remote client.
4161 static int /* O - Process ID */
4162 pipe_command(cupsd_client_t
*con
, /* I - Client connection */
4163 int infile
, /* I - Standard input for command */
4164 int *outfile
, /* O - Standard output for command */
4165 char *command
, /* I - Command to run */
4166 char *options
, /* I - Options for command */
4167 int root
) /* I - Run as root? */
4169 int i
; /* Looping var */
4170 int pid
; /* Process ID */
4171 char *commptr
, /* Command string pointer */
4172 commch
; /* Command string character */
4173 char *uriptr
; /* URI string pointer */
4174 int fds
[2]; /* Pipe FDs */
4175 int argc
; /* Number of arguments */
4176 int envc
; /* Number of environment variables */
4177 char argbuf
[10240], /* Argument buffer */
4178 *argv
[100], /* Argument strings */
4179 *envp
[MAX_ENV
+ 20]; /* Environment variables */
4180 char auth_type
[256], /* AUTH_TYPE environment variable */
4181 content_length
[1024], /* CONTENT_LENGTH environment variable */
4182 content_type
[1024], /* CONTENT_TYPE environment variable */
4183 http_cookie
[32768], /* HTTP_COOKIE environment variable */
4184 http_referer
[1024], /* HTTP_REFERER environment variable */
4185 http_user_agent
[1024], /* HTTP_USER_AGENT environment variable */
4186 lang
[1024], /* LANG environment variable */
4187 path_info
[1024], /* PATH_INFO environment variable */
4188 remote_addr
[1024], /* REMOTE_ADDR environment variable */
4189 remote_host
[1024], /* REMOTE_HOST environment variable */
4190 remote_user
[1024], /* REMOTE_USER environment variable */
4191 script_filename
[1024], /* SCRIPT_FILENAME environment variable */
4192 script_name
[1024], /* SCRIPT_NAME environment variable */
4193 server_name
[1024], /* SERVER_NAME environment variable */
4194 server_port
[1024]; /* SERVER_PORT environment variable */
4198 * Parse a copy of the options string, which is of the form:
4200 * argument+argument+argument
4201 * ?argument+argument+argument
4202 * param=value¶m=value
4203 * ?param=value¶m=value
4204 * /name?argument+argument+argument
4205 * /name?param=value¶m=value
4207 * If the string contains an "=" character after the initial name,
4208 * then we treat it as a HTTP GET form request and make a copy of
4209 * the remaining string for the environment variable.
4211 * The string is always parsed out as command-line arguments, to
4212 * be consistent with Apache...
4215 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4216 "pipe_command: command=\"%s\", options=\"%s\"",
4217 command
, options
? options
: "(null)");
4222 strlcpy(argbuf
, options
, sizeof(argbuf
));
4226 if (argbuf
[0] == '/')
4229 * Found some trailing path information, set PATH_INFO...
4232 if ((commptr
= strchr(argbuf
, '?')) == NULL
)
4233 commptr
= argbuf
+ strlen(argbuf
);
4237 snprintf(path_info
, sizeof(path_info
), "PATH_INFO=%s", argbuf
);
4243 path_info
[0] = '\0';
4245 if (*commptr
== ' ')
4249 cupsdLogMessage(CUPSD_LOG_INFO
, "commptr=\"%s\"", commptr
);
4251 if (*commptr
== '?' && con
->operation
== HTTP_GET
&& !con
->query_string
)
4254 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", commptr
);
4261 argv
[argc
++] = commptr
;
4263 for (; *commptr
&& argc
< 99; commptr
++)
4266 * Break arguments whenever we see a + or space...
4269 if (*commptr
== ' ' || *commptr
== '+')
4271 while (*commptr
== ' ' || *commptr
== '+')
4275 * If we don't have a blank string, save it as another argument...
4280 argv
[argc
] = commptr
;
4286 else if (*commptr
== '%' && isxdigit(commptr
[1] & 255) &&
4287 isxdigit(commptr
[2] & 255))
4290 * Convert the %xx notation to the individual character.
4293 if (commptr
[1] >= '0' && commptr
[1] <= '9')
4294 *commptr
= (commptr
[1] - '0') << 4;
4296 *commptr
= (tolower(commptr
[1]) - 'a' + 10) << 4;
4298 if (commptr
[2] >= '0' && commptr
[2] <= '9')
4299 *commptr
|= commptr
[2] - '0';
4301 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
4303 _cups_strcpy(commptr
+ 1, commptr
+ 3);
4306 * Check for a %00 and break if that is the case...
4318 * Setup the environment variables as needed...
4321 if (con
->username
[0])
4323 snprintf(auth_type
, sizeof(auth_type
), "AUTH_TYPE=%s",
4324 httpGetField(HTTP(con
), HTTP_FIELD_AUTHORIZATION
));
4326 if ((uriptr
= strchr(auth_type
+ 10, ' ')) != NULL
)
4330 auth_type
[0] = '\0';
4333 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF-8", con
->language
->language
);
4335 strcpy(lang
, "LANG=C");
4337 strcpy(remote_addr
, "REMOTE_ADDR=");
4338 httpAddrString(con
->http
.hostaddr
, remote_addr
+ 12,
4339 sizeof(remote_addr
) - 12);
4341 snprintf(remote_host
, sizeof(remote_host
), "REMOTE_HOST=%s",
4342 con
->http
.hostname
);
4344 snprintf(script_name
, sizeof(script_name
), "SCRIPT_NAME=%s", con
->uri
);
4345 if ((uriptr
= strchr(script_name
, '?')) != NULL
)
4348 snprintf(script_filename
, sizeof(script_filename
), "SCRIPT_FILENAME=%s%s",
4349 DocumentRoot
, script_name
+ 12);
4351 sprintf(server_port
, "SERVER_PORT=%d", con
->serverport
);
4353 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
4356 envc
= cupsdLoadEnv(envp
, (int)(sizeof(envp
) / sizeof(envp
[0])));
4359 envp
[envc
++] = auth_type
;
4361 envp
[envc
++] = lang
;
4362 envp
[envc
++] = "REDIRECT_STATUS=1";
4363 envp
[envc
++] = "GATEWAY_INTERFACE=CGI/1.1";
4364 envp
[envc
++] = server_name
;
4365 envp
[envc
++] = server_port
;
4366 envp
[envc
++] = remote_addr
;
4367 envp
[envc
++] = remote_host
;
4368 envp
[envc
++] = script_name
;
4369 envp
[envc
++] = script_filename
;
4372 envp
[envc
++] = path_info
;
4374 if (con
->username
[0])
4376 snprintf(remote_user
, sizeof(remote_user
), "REMOTE_USER=%s", con
->username
);
4378 envp
[envc
++] = remote_user
;
4381 if (con
->http
.version
== HTTP_1_1
)
4382 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.1";
4383 else if (con
->http
.version
== HTTP_1_0
)
4384 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.0";
4386 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/0.9";
4388 if (con
->http
.cookie
)
4390 snprintf(http_cookie
, sizeof(http_cookie
), "HTTP_COOKIE=%s",
4392 envp
[envc
++] = http_cookie
;
4395 if (con
->http
.fields
[HTTP_FIELD_USER_AGENT
][0])
4397 snprintf(http_user_agent
, sizeof(http_user_agent
), "HTTP_USER_AGENT=%s",
4398 con
->http
.fields
[HTTP_FIELD_USER_AGENT
]);
4399 envp
[envc
++] = http_user_agent
;
4402 if (con
->http
.fields
[HTTP_FIELD_REFERER
][0])
4404 snprintf(http_referer
, sizeof(http_referer
), "HTTP_REFERER=%s",
4405 con
->http
.fields
[HTTP_FIELD_REFERER
]);
4406 envp
[envc
++] = http_referer
;
4409 if (con
->operation
== HTTP_GET
)
4411 envp
[envc
++] = "REQUEST_METHOD=GET";
4413 if (con
->query_string
)
4416 * Add GET form variables after ?...
4419 envp
[envc
++] = con
->query_string
;
4424 sprintf(content_length
, "CONTENT_LENGTH=" CUPS_LLFMT
,
4425 CUPS_LLCAST con
->bytes
);
4426 snprintf(content_type
, sizeof(content_type
), "CONTENT_TYPE=%s",
4427 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
4429 envp
[envc
++] = "REQUEST_METHOD=POST";
4430 envp
[envc
++] = content_length
;
4431 envp
[envc
++] = content_type
;
4435 * Tell the CGI if we are using encryption...
4439 envp
[envc
++] = "HTTPS=ON";
4442 * Terminate the environment array...
4447 if (LogLevel
== CUPSD_LOG_DEBUG2
)
4449 for (i
= 0; i
< argc
; i
++)
4450 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4451 "pipe_command: argv[%d] = \"%s\"", i
, argv
[i
]);
4452 for (i
= 0; i
< envc
; i
++)
4453 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4454 "pipe_command: envp[%d] = \"%s\"", i
, envp
[i
]);
4458 * Create a pipe for the output...
4461 if (cupsdOpenPipe(fds
))
4463 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to create pipes for CGI %s - %s",
4464 argv
[0], strerror(errno
));
4469 * Then execute the command...
4472 if (cupsdStartProcess(command
, argv
, envp
, infile
, fds
[1], CGIPipes
[1],
4473 -1, -1, root
, &pid
) < 0)
4476 * Error - can't fork!
4479 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to fork for CGI %s - %s", argv
[0],
4482 cupsdClosePipe(fds
);
4488 * Fork successful - return the PID...
4491 if (con
->username
[0])
4492 cupsdAddCert(pid
, con
->username
);
4494 cupsdLogMessage(CUPSD_LOG_DEBUG
, "CGI %s started - PID = %d", command
, pid
);
4505 * 'write_file()' - Send a file via HTTP.
4508 static int /* O - 0 on failure, 1 on success */
4509 write_file(cupsd_client_t
*con
, /* I - Client connection */
4510 http_status_t code
, /* I - HTTP status */
4511 char *filename
, /* I - Filename */
4512 char *type
, /* I - File type */
4513 struct stat
*filestats
) /* O - File information */
4515 con
->file
= open(filename
, O_RDONLY
);
4517 cupsdLogMessage(CUPSD_LOG_DEBUG
, "write_file: %d file=%d", con
->http
.fd
,
4523 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
4527 if (!cupsdSendHeader(con
, code
, type
, AUTH_NONE
))
4530 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
4531 httpGetDateString(filestats
->st_mtime
)) < 0)
4533 if (httpPrintf(HTTP(con
), "Content-Length: " CUPS_LLFMT
"\r\n",
4534 CUPS_LLCAST filestats
->st_size
) < 0)
4536 if (httpPrintf(HTTP(con
), "\r\n") < 0)
4539 if (cupsdFlushHeader(con
) < 0)
4542 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
4543 con
->http
.data_remaining
= filestats
->st_size
;
4545 if (con
->http
.data_remaining
<= INT_MAX
)
4546 con
->http
._data_remaining
= con
->http
.data_remaining
;
4548 con
->http
._data_remaining
= INT_MAX
;
4550 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
,
4551 (cupsd_selfunc_t
)cupsdWriteClient
, con
);
4558 * 'write_pipe()' - Flag that data is available on the CGI pipe.
4562 write_pipe(cupsd_client_t
*con
) /* I - Client connection */
4564 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "write_pipe: CGI output on fd %d...",
4567 con
->file_ready
= 1;
4569 cupsdRemoveSelect(con
->file
);
4570 cupsdAddSelect(con
->http
.fd
, NULL
, (cupsd_selfunc_t
)cupsdWriteClient
, con
);
4575 * End of "$Id: client.c 6681 2007-07-16 20:11:52Z mike $".