2 * "$Id: client.c 6737 2007-07-26 19:08:40Z 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_DEBUG2
,
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
&& auth_type
!= AUTH_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_DEBUG
, "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 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2472 "cupsdSendHeader: WWW-Authenticate: Negotiate %s", buf
);
2474 if (httpPrintf(HTTP(con
), "WWW-Authenticate: Negotiate %s\r\n", buf
) < 0)
2477 #endif /* HAVE_GSSAPI */
2479 if (con
->language
&& strcmp(con
->language
->language
, "C"))
2481 if (httpPrintf(HTTP(con
), "Content-Language: %s\r\n",
2482 con
->language
->language
) < 0)
2488 if (!strcmp(type
, "text/html"))
2490 if (httpPrintf(HTTP(con
),
2491 "Content-Type: text/html; charset=utf-8\r\n") < 0)
2494 else if (httpPrintf(HTTP(con
), "Content-Type: %s\r\n", type
) < 0)
2503 * 'cupsdUpdateCGI()' - Read status messages from CGI scripts and programs.
2507 cupsdUpdateCGI(void)
2509 char *ptr
, /* Pointer to end of line in buffer */
2510 message
[1024]; /* Pointer to message text */
2511 int loglevel
; /* Log level for message */
2514 while ((ptr
= cupsdStatBufUpdate(CGIStatusBuffer
, &loglevel
,
2515 message
, sizeof(message
))) != NULL
)
2516 if (!strchr(CGIStatusBuffer
->buffer
, '\n'))
2519 if (ptr
== NULL
&& !CGIStatusBuffer
->bufused
)
2522 * Fatal error on pipe - should never happen!
2525 cupsdLogMessage(CUPSD_LOG_CRIT
,
2526 "cupsdUpdateCGI: error reading from CGI error pipe - %s",
2533 * 'cupsdWriteClient()' - Write data to a client as needed.
2537 cupsdWriteClient(cupsd_client_t
*con
) /* I - Client connection */
2539 int bytes
; /* Number of bytes written */
2540 char buf
[16385]; /* Data buffer */
2541 char *bufptr
; /* Pointer into buffer */
2542 ipp_state_t ipp_state
; /* IPP state value */
2546 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2547 "cupsdWriteClient(con=%p) %d response=%p(%d), file=%d "
2548 "pipe_pid=%d state=%d",
2549 con
, con
->http
.fd
, con
->response
, con
->response
->state
,
2550 con
->file
, con
->pipe_pid
, con
->http
.state
);
2553 if (con
->http
.state
!= HTTP_GET_SEND
&&
2554 con
->http
.state
!= HTTP_POST_SEND
)
2560 * Make sure we select on the CGI output...
2563 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2565 if (!con
->file_ready
)
2568 * Try again later when there is CGI output available...
2571 cupsdRemoveSelect(con
->http
.fd
);
2575 con
->file_ready
= 0;
2578 if (con
->response
&& con
->response
->state
!= IPP_DATA
)
2580 ipp_state
= ippWrite(HTTP(con
), con
->response
);
2581 bytes
= ipp_state
!= IPP_ERROR
&&
2582 (con
->file
>= 0 || ipp_state
!= IPP_DATA
);
2584 else if ((bytes
= read(con
->file
, buf
, sizeof(buf
) - 1)) > 0)
2586 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2587 "cupsdWriteClient: Read %d bytes from file %d...",
2590 if (con
->pipe_pid
&& !con
->got_fields
)
2593 * Inspect the data for Content-Type and other fields.
2598 for (bufptr
= buf
; !con
->got_fields
&& *bufptr
; bufptr
++)
2599 if (*bufptr
== '\n')
2602 * Send line to client...
2605 if (bufptr
> buf
&& bufptr
[-1] == '\r')
2609 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "Script header: %s", buf
);
2611 if (!con
->sent_header
)
2614 * Handle redirection and CGI status codes...
2617 if (!strncasecmp(buf
, "Location:", 9))
2619 cupsdSendHeader(con
, HTTP_SEE_OTHER
, NULL
, AUTH_NONE
);
2620 con
->sent_header
= 2;
2622 if (httpPrintf(HTTP(con
), "Content-Length: 0\r\n") < 0)
2625 else if (!strncasecmp(buf
, "Status:", 7))
2627 cupsdSendError(con
, (http_status_t
)atoi(buf
+ 7), AUTH_NONE
);
2628 con
->sent_header
= 2;
2632 cupsdSendHeader(con
, HTTP_OK
, NULL
, AUTH_NONE
);
2633 con
->sent_header
= 1;
2635 if (con
->http
.version
== HTTP_1_1
)
2637 if (httpPrintf(HTTP(con
), "Transfer-Encoding: chunked\r\n") < 0)
2643 if (strncasecmp(buf
, "Status:", 7))
2644 httpPrintf(HTTP(con
), "%s\r\n", buf
);
2646 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdWriteClient: %d %s",
2653 bytes
-= (bufptr
- buf
);
2654 memmove(buf
, bufptr
, bytes
+ 1);
2658 * See if the line was empty...
2661 if (con
->field_col
== 0)
2663 con
->got_fields
= 1;
2665 if (cupsdFlushHeader(con
) < 0)
2667 cupsdCloseClient(con
);
2671 if (con
->http
.version
== HTTP_1_1
)
2672 con
->http
.data_encoding
= HTTP_ENCODE_CHUNKED
;
2677 else if (*bufptr
!= '\r')
2680 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2681 "cupsdWriteClient: %d bytes=%d, got_fields=%d",
2682 con
->http
.fd
, bytes
, con
->got_fields
);
2684 if (bytes
> 0 && !con
->got_fields
)
2687 * Remaining text needs to go out...
2690 httpPrintf(HTTP(con
), "%s", buf
);
2692 con
->http
.activity
= time(NULL
);
2695 else if (bytes
== 0)
2696 con
->http
.activity
= time(NULL
);
2701 if (httpWrite2(HTTP(con
), buf
, bytes
) < 0)
2703 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2704 "cupsdWriteClient: %d Write of %d bytes failed!",
2705 con
->http
.fd
, bytes
);
2707 cupsdCloseClient(con
);
2711 con
->bytes
+= bytes
;
2713 if (con
->http
.state
== HTTP_WAITING
)
2720 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdWriteClient: %d bytes < 0",
2723 cupsdLogRequest(con
, HTTP_OK
);
2725 httpFlushWrite(HTTP(con
));
2727 if (con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
&& con
->sent_header
== 1)
2729 if (httpWrite2(HTTP(con
), "", 0) < 0)
2731 cupsdCloseClient(con
);
2736 con
->http
.state
= HTTP_WAITING
;
2738 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
2742 cupsdRemoveSelect(con
->file
);
2745 cupsdEndProcess(con
->pipe_pid
, 0);
2747 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2748 "cupsdWriteClient: %d Closing data file %d.",
2749 con
->http
.fd
, con
->file
);
2758 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2759 "cupsdWriteClient: %d Removing temp file %s",
2760 con
->http
.fd
, con
->filename
);
2761 unlink(con
->filename
);
2762 cupsdClearString(&con
->filename
);
2767 ippDelete(con
->request
);
2768 con
->request
= NULL
;
2773 ippDelete(con
->response
);
2774 con
->response
= NULL
;
2777 cupsdClearString(&con
->command
);
2778 cupsdClearString(&con
->options
);
2779 cupsdClearString(&con
->query_string
);
2781 if (!con
->http
.keep_alive
)
2783 cupsdCloseClient(con
);
2788 con
->http
.activity
= time(NULL
);
2793 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
2796 static int /* O - 1 if modified since */
2798 cupsd_client_t
*con
, /* I - Client connection */
2799 struct stat
*filestats
) /* I - File information */
2801 char *ptr
; /* Pointer into field */
2802 time_t date
; /* Time/date value */
2803 off_t size
; /* Size/length value */
2808 ptr
= con
->http
.fields
[HTTP_FIELD_IF_MODIFIED_SINCE
];
2813 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2814 "check_if_modified: %d If-Modified-Since=\"%s\"",
2817 while (*ptr
!= '\0')
2819 while (isspace(*ptr
) || *ptr
== ';')
2822 if (strncasecmp(ptr
, "length=", 7) == 0)
2825 size
= strtoll(ptr
, NULL
, 10);
2827 while (isdigit(*ptr
))
2830 else if (isalpha(*ptr
))
2832 date
= httpGetDateTime(ptr
);
2833 while (*ptr
!= '\0' && *ptr
!= ';')
2840 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2841 "check_if_modified: %d sizes=" CUPS_LLFMT
","
2842 CUPS_LLFMT
" dates=%d,%d",
2843 con
->http
.fd
, CUPS_LLCAST size
,
2844 CUPS_LLCAST filestats
->st_size
, (int)date
,
2845 (int)filestats
->st_mtime
);
2847 return ((size
!= filestats
->st_size
&& size
!= 0) ||
2848 (date
< filestats
->st_mtime
&& date
!= 0) ||
2849 (size
== 0 && date
== 0));
2855 * 'encrypt_client()' - Enable encryption for the client...
2858 static int /* O - 1 on success, 0 on error */
2859 encrypt_client(cupsd_client_t
*con
) /* I - Client to encrypt */
2862 SSL_CTX
*context
; /* Context for encryption */
2863 SSL
*conn
; /* Connection for encryption */
2864 BIO
*bio
; /* BIO data */
2865 unsigned long error
; /* Error code */
2869 * Verify that we have a certificate...
2872 if (access(ServerKey
, 0) || access(ServerCertificate
, 0))
2875 * Nope, make a self-signed certificate...
2878 if (!make_certificate(con
))
2883 * Create the SSL context and accept the connection...
2886 context
= SSL_CTX_new(SSLv23_server_method());
2888 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
2889 SSL_CTX_use_PrivateKey_file(context
, ServerKey
, SSL_FILETYPE_PEM
);
2890 SSL_CTX_use_certificate_file(context
, ServerCertificate
, SSL_FILETYPE_PEM
);
2892 bio
= BIO_new(_httpBIOMethods());
2893 BIO_ctrl(bio
, BIO_C_SET_FILE_PTR
, 0, (char *)HTTP(con
));
2895 conn
= SSL_new(context
);
2896 SSL_set_bio(conn
, bio
, bio
);
2898 if (SSL_accept(conn
) != 1)
2900 cupsdLogMessage(CUPSD_LOG_ERROR
,
2901 "encrypt_client: Unable to encrypt connection from %s!",
2902 con
->http
.hostname
);
2904 while ((error
= ERR_get_error()) != 0)
2905 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s",
2906 ERR_error_string(error
, NULL
));
2908 SSL_CTX_free(context
);
2913 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2914 "encrypt_client: %d Connection from %s now encrypted.",
2915 con
->http
.fd
, con
->http
.hostname
);
2917 con
->http
.tls
= conn
;
2920 # elif defined(HAVE_GNUTLS)
2921 http_tls_t
*conn
; /* TLS session object */
2922 int error
; /* Error code */
2923 gnutls_certificate_server_credentials
*credentials
;
2924 /* TLS credentials */
2928 * Verify that we have a certificate...
2931 if (access(ServerKey
, 0) || access(ServerCertificate
, 0))
2934 * Nope, make a self-signed certificate...
2937 if (!make_certificate(con
))
2942 * Create the SSL object and perform the SSL handshake...
2945 conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
));
2950 credentials
= (gnutls_certificate_server_credentials
*)
2951 malloc(sizeof(gnutls_certificate_server_credentials
));
2952 if (credentials
== NULL
)
2954 cupsdLogMessage(CUPSD_LOG_ERROR
,
2955 "encrypt_client: Unable to encrypt connection from %s!",
2956 con
->http
.hostname
);
2957 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s", strerror(errno
));
2963 gnutls_certificate_allocate_credentials(credentials
);
2964 gnutls_certificate_set_x509_key_file(*credentials
, ServerCertificate
,
2965 ServerKey
, GNUTLS_X509_FMT_PEM
);
2967 gnutls_init(&(conn
->session
), GNUTLS_SERVER
);
2968 gnutls_set_default_priority(conn
->session
);
2969 gnutls_credentials_set(conn
->session
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
2970 gnutls_transport_set_ptr(conn
->session
, (gnutls_transport_ptr
)HTTP(con
));
2971 gnutls_transport_set_pull_function(conn
->session
, _httpReadGNUTLS
);
2972 gnutls_transport_set_push_function(conn
->session
, _httpWriteGNUTLS
);
2974 error
= gnutls_handshake(conn
->session
);
2976 if (error
!= GNUTLS_E_SUCCESS
)
2978 cupsdLogMessage(CUPSD_LOG_ERROR
,
2979 "encrypt_client: Unable to encrypt connection from %s!",
2980 con
->http
.hostname
);
2981 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s",
2982 gnutls_strerror(error
));
2984 gnutls_deinit(conn
->session
);
2985 gnutls_certificate_free_credentials(*credentials
);
2991 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2992 "encrypt_client: %d Connection from %s now encrypted.",
2993 con
->http
.fd
, con
->http
.hostname
);
2995 conn
->credentials
= credentials
;
2996 con
->http
.tls
= conn
;
2999 # elif defined(HAVE_CDSASSL)
3000 OSStatus error
; /* Error code */
3001 http_tls_t
*conn
; /* CDSA connection information */
3004 if ((conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
))) == NULL
)
3008 conn
->session
= NULL
;
3009 conn
->certsArray
= get_cdsa_certificate(con
);
3011 if (!conn
->certsArray
)
3014 * No keychain (yet), make a self-signed certificate...
3017 if (make_certificate(con
))
3018 conn
->certsArray
= get_cdsa_certificate(con
);
3021 if (!conn
->certsArray
)
3023 cupsdLogMessage(CUPSD_LOG_ERROR
,
3024 "encrypt_client: Could not find signing key in keychain "
3025 "\"%s\"", ServerCertificate
);
3026 error
= errSSLBadCert
; /* errSSLBadConfiguration is a better choice, but not available on 10.2.x */
3030 error
= SSLNewContext(true, &conn
->session
);
3033 error
= SSLSetIOFuncs(conn
->session
, _httpReadCDSA
, _httpWriteCDSA
);
3036 error
= SSLSetProtocolVersionEnabled(conn
->session
, kSSLProtocol2
, false);
3039 error
= SSLSetConnection(conn
->session
, HTTP(con
));
3042 error
= SSLSetAllowsExpiredCerts(conn
->session
, true);
3045 error
= SSLSetAllowsAnyRoot(conn
->session
, true);
3048 error
= SSLSetCertificate(conn
->session
, conn
->certsArray
);
3053 * Perform SSL/TLS handshake
3056 while ((error
= SSLHandshake(conn
->session
)) == errSSLWouldBlock
)
3062 cupsdLogMessage(CUPSD_LOG_ERROR
,
3063 "encrypt_client: Unable to encrypt connection from %s!",
3064 con
->http
.hostname
);
3066 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s (%d)",
3067 cssmErrorString(error
), (int)error
);
3069 con
->http
.error
= error
;
3070 con
->http
.status
= HTTP_ERROR
;
3073 SSLDisposeContext(conn
->session
);
3075 if (conn
->certsArray
)
3076 CFRelease(conn
->certsArray
);
3083 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3084 "encrypt_client: %d Connection from %s now encrypted.",
3085 con
->http
.fd
, con
->http
.hostname
);
3087 con
->http
.tls
= conn
;
3090 # endif /* HAVE_LIBSSL */
3092 #endif /* HAVE_SSL */
3097 * 'get_cdsa_certificate()' - Get a SSL/TLS certificate from the System keychain.
3100 static CFArrayRef
/* O - Array of certificates */
3101 get_cdsa_certificate(cupsd_client_t
*con
) /* I - Client connection */
3103 OSStatus err
; /* Error info */
3104 SecKeychainRef keychain
; /* Keychain reference */
3105 SecIdentitySearchRef search
; /* Search reference */
3106 SecIdentityRef identity
; /* Identity */
3107 CFArrayRef certificates
= NULL
;
3108 /* Certificate array */
3111 if ((err
= SecKeychainOpen(ServerCertificate
, &keychain
)))
3113 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot open keychain \"%s\", %s",
3114 ServerCertificate
, cssmErrorString(err
));
3118 # if HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY
3120 * Use a policy to search for valid certificates who's common name matches the
3124 SecPolicySearchRef policy_search
; /* Policy search ref */
3125 SecPolicyRef policy
; /* Policy ref */
3126 CSSM_DATA options
; /* Policy options */
3127 CSSM_APPLE_TP_SSL_OPTIONS
3128 ssl_options
; /* SSL Option for hostname */
3131 if ((err
= SecPolicySearchCreate(CSSM_CERT_X_509v3
, &CSSMOID_APPLE_TP_SSL
,
3132 NULL
, &policy_search
)))
3134 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot create a policy search reference");
3135 CFRelease(keychain
);
3139 if ((err
= SecPolicySearchCopyNext(policy_search
, &policy
)))
3141 cupsdLogMessage(CUPSD_LOG_ERROR
,
3142 "Cannot find a policy to use for searching");
3143 CFRelease(keychain
);
3144 CFRelease(policy_search
);
3148 memset(&ssl_options
, 0, sizeof(ssl_options
));
3149 ssl_options
.Version
= CSSM_APPLE_TP_SSL_OPTS_VERSION
;
3150 ssl_options
.ServerName
= con
->servername
;
3151 ssl_options
.ServerNameLen
= strlen(con
->servername
);
3153 options
.Data
= (uint8
*)&ssl_options
;
3154 options
.Length
= sizeof(ssl_options
);
3156 if ((err
= SecPolicySetValue(policy
, &options
)))
3158 cupsdLogMessage(CUPSD_LOG_ERROR
,
3159 "Cannot set policy value to use for searching");
3160 CFRelease(keychain
);
3161 CFRelease(policy_search
);
3165 err
= SecIdentitySearchCreateWithPolicy(policy
, NULL
, CSSM_KEYUSE_SIGN
,
3166 keychain
, FALSE
, &search
);
3169 * Assume there is exactly one SecIdentity in the keychain...
3172 err
= SecIdentitySearchCreate(keychain
, CSSM_KEYUSE_SIGN
, &search
);
3173 # endif /* HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY */
3176 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3177 "Cannot create keychain search reference: %s",
3178 cssmErrorString(err
));
3181 if ((err
= SecIdentitySearchCopyNext(search
, &identity
)))
3183 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3184 "Cannot find signing key in keychain \"%s\", error %d",
3185 ServerCertificate
, (int)err
);
3189 if (CFGetTypeID(identity
) != SecIdentityGetTypeID())
3190 cupsdLogMessage(CUPSD_LOG_ERROR
,
3191 "SecIdentitySearchCopyNext CFTypeID failure!");
3194 if ((certificates
= CFArrayCreate(NULL
, (const void **)&identity
,
3195 1, &kCFTypeArrayCallBacks
)) == NULL
)
3196 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot create certificate array");
3199 CFRelease(identity
);
3205 # if HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY
3207 CFRelease(policy_search
);
3208 # endif /* HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY */
3210 return (certificates
);
3212 #endif /* HAVE_CDSASSL */
3216 * 'get_file()' - Get a filename and state info.
3219 static char * /* O - Real filename */
3220 get_file(cupsd_client_t
*con
, /* I - Client connection */
3221 struct stat
*filestats
, /* O - File information */
3222 char *filename
, /* IO - Filename buffer */
3223 int len
) /* I - Buffer length */
3225 int status
; /* Status of filesystem calls */
3226 char *ptr
; /* Pointer info filename */
3227 int plen
; /* Remaining length after pointer */
3231 * Figure out the real filename...
3234 if (!strncmp(con
->uri
, "/ppd/", 5))
3235 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
);
3236 else if (!strncmp(con
->uri
, "/rss/", 5) && !strchr(con
->uri
+ 5, '/'))
3237 snprintf(filename
, len
, "%s/rss/%s", CacheDir
, con
->uri
+ 5);
3238 else if (!strncmp(con
->uri
, "/admin/conf/", 12))
3239 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
+ 11);
3240 else if (!strncmp(con
->uri
, "/admin/log/", 11))
3242 if (!strcmp(con
->uri
+ 11, "access_log") && AccessLog
[0] == '/')
3243 strlcpy(filename
, AccessLog
, len
);
3244 else if (!strcmp(con
->uri
+ 11, "error_log") && ErrorLog
[0] == '/')
3245 strlcpy(filename
, ErrorLog
, len
);
3246 else if (!strcmp(con
->uri
+ 11, "page_log") && PageLog
[0] == '/')
3247 strlcpy(filename
, PageLog
, len
);
3251 else if (con
->language
)
3252 snprintf(filename
, len
, "%s/%s%s", DocumentRoot
, con
->language
->language
,
3255 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3257 if ((ptr
= strchr(filename
, '?')) != NULL
)
3261 * Grab the status for this language; if there isn't a language-specific file
3262 * then fallback to the default one...
3265 if ((status
= stat(filename
, filestats
)) != 0 && con
->language
&&
3266 strncmp(con
->uri
, "/ppd/", 5) &&
3267 strncmp(con
->uri
, "/admin/conf/", 12) &&
3268 strncmp(con
->uri
, "/admin/log/", 11))
3271 * Drop the country code...
3274 char ll
[3]; /* Short language name */
3277 strlcpy(ll
, con
->language
->language
, sizeof(ll
));
3278 snprintf(filename
, len
, "%s/%s%s", DocumentRoot
, ll
, con
->uri
);
3280 if ((ptr
= strchr(filename
, '?')) != NULL
)
3283 if ((status
= stat(filename
, filestats
)) != 0)
3286 * Drop the language prefix and try the root directory...
3289 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3291 if ((ptr
= strchr(filename
, '?')) != NULL
)
3294 status
= stat(filename
, filestats
);
3299 * If we're found a directory, get the index.html file instead...
3302 if (!status
&& S_ISDIR(filestats
->st_mode
))
3304 if (filename
[strlen(filename
) - 1] != '/')
3305 strlcat(filename
, "/", len
);
3307 ptr
= filename
+ strlen(filename
);
3308 plen
= len
- (ptr
- filename
);
3310 strlcpy(ptr
, "index.html", plen
);
3311 status
= stat(filename
, filestats
);
3316 strlcpy(ptr
, "index.class", plen
);
3317 status
= stat(filename
, filestats
);
3319 #endif /* HAVE_JAVA */
3324 strlcpy(ptr
, "index.pl", plen
);
3325 status
= stat(filename
, filestats
);
3327 #endif /* HAVE_PERL */
3332 strlcpy(ptr
, "index.php", plen
);
3333 status
= stat(filename
, filestats
);
3335 #endif /* HAVE_PHP */
3340 strlcpy(ptr
, "index.pyc", plen
);
3341 status
= stat(filename
, filestats
);
3346 strlcpy(ptr
, "index.py", plen
);
3347 status
= stat(filename
, filestats
);
3349 #endif /* HAVE_PYTHON */
3352 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "get_file: %d filename=%s size=%d",
3353 con
->http
.fd
, filename
,
3354 status
? -1 : (int)filestats
->st_size
);
3357 con
->http
.data_remaining
= (int)filestats
->st_size
;
3367 * 'install_conf_file()' - Install a configuration file.
3370 static http_status_t
/* O - Status */
3371 install_conf_file(cupsd_client_t
*con
) /* I - Connection */
3373 cups_file_t
*in
, /* Input file */
3374 *out
; /* Output file */
3375 char buffer
[1024]; /* Copy buffer */
3376 int bytes
; /* Number of bytes */
3377 char conffile
[1024], /* Configuration filename */
3378 newfile
[1024], /* New config filename */
3379 oldfile
[1024]; /* Old config filename */
3380 struct stat confinfo
; /* Config file info */
3384 * First construct the filenames...
3387 snprintf(conffile
, sizeof(conffile
), "%s%s", ServerRoot
, con
->uri
+ 11);
3388 snprintf(newfile
, sizeof(newfile
), "%s%s.N", ServerRoot
, con
->uri
+ 11);
3389 snprintf(oldfile
, sizeof(oldfile
), "%s%s.O", ServerRoot
, con
->uri
+ 11);
3391 cupsdLogMessage(CUPSD_LOG_INFO
, "Installing config file \"%s\"...", conffile
);
3394 * Get the owner, group, and permissions of the configuration file.
3395 * If it doesn't exist, assign it to the User and Group in the
3396 * cupsd.conf file with mode 0640 permissions.
3399 if (stat(conffile
, &confinfo
))
3401 confinfo
.st_uid
= User
;
3402 confinfo
.st_gid
= Group
;
3403 confinfo
.st_mode
= ConfigFilePerm
;
3407 * Open the request file and new config file...
3410 if ((in
= cupsFileOpen(con
->filename
, "rb")) == NULL
)
3412 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open request file \"%s\" - %s",
3413 con
->filename
, strerror(errno
));
3414 return (HTTP_SERVER_ERROR
);
3417 if ((out
= cupsFileOpen(newfile
, "wb")) == NULL
)
3420 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open config file \"%s\" - %s",
3421 newfile
, strerror(errno
));
3422 return (HTTP_SERVER_ERROR
);
3425 fchmod(cupsFileNumber(out
), confinfo
.st_mode
);
3426 fchown(cupsFileNumber(out
), confinfo
.st_uid
, confinfo
.st_gid
);
3429 * Copy from the request to the new config file...
3432 while ((bytes
= cupsFileRead(in
, buffer
, sizeof(buffer
))) > 0)
3433 if (cupsFileWrite(out
, buffer
, bytes
) < bytes
)
3435 cupsdLogMessage(CUPSD_LOG_ERROR
,
3436 "Unable to copy to config file \"%s\" - %s",
3437 newfile
, strerror(errno
));
3443 return (HTTP_SERVER_ERROR
);
3447 * Close the files...
3451 if (cupsFileClose(out
))
3453 cupsdLogMessage(CUPSD_LOG_ERROR
,
3454 "Error file closing config file \"%s\" - %s",
3455 newfile
, strerror(errno
));
3459 return (HTTP_SERVER_ERROR
);
3463 * Remove the request file...
3466 unlink(con
->filename
);
3467 cupsdClearString(&con
->filename
);
3470 * Unlink the old backup, rename the current config file to the backup
3471 * filename, and rename the new config file to the config file name...
3474 if (unlink(oldfile
))
3475 if (errno
!= ENOENT
)
3477 cupsdLogMessage(CUPSD_LOG_ERROR
,
3478 "Unable to remove backup config file \"%s\" - %s",
3479 oldfile
, strerror(errno
));
3483 return (HTTP_SERVER_ERROR
);
3486 if (rename(conffile
, oldfile
))
3487 if (errno
!= ENOENT
)
3489 cupsdLogMessage(CUPSD_LOG_ERROR
,
3490 "Unable to rename old config file \"%s\" - %s",
3491 conffile
, strerror(errno
));
3495 return (HTTP_SERVER_ERROR
);
3498 if (rename(newfile
, conffile
))
3500 cupsdLogMessage(CUPSD_LOG_ERROR
,
3501 "Unable to rename new config file \"%s\" - %s",
3502 newfile
, strerror(errno
));
3504 rename(oldfile
, conffile
);
3507 return (HTTP_SERVER_ERROR
);
3511 * If the cupsd.conf file was updated, set the NeedReload flag...
3514 if (!strcmp(con
->uri
, "/admin/conf/cupsd.conf"))
3515 NeedReload
= RELOAD_CUPSD
;
3517 NeedReload
= RELOAD_ALL
;
3519 ReloadTime
= time(NULL
);
3522 * Return that the file was created successfully...
3525 return (HTTP_CREATED
);
3530 * 'is_cgi()' - Is the resource a CGI script/program?
3533 static int /* O - 1 = CGI, 0 = file */
3534 is_cgi(cupsd_client_t
*con
, /* I - Client connection */
3535 const char *filename
, /* I - Real filename */
3536 struct stat
*filestats
, /* I - File information */
3537 mime_type_t
*type
) /* I - MIME type */
3539 const char *options
; /* Options on URL */
3542 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3543 "is_cgi(con=%p, filename=\"%s\", filestats=%p, type=%s/%s)\n",
3544 con
, filename
, filestats
, type
? type
->super
: "unknown",
3545 type
? type
->type
: "unknown");
3548 * Get the options, if any...
3551 if ((options
= strchr(con
->uri
, '?')) != NULL
)
3555 if (strchr(options
, '='))
3556 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", options
);
3560 * Check for known types...
3563 if (!type
|| strcasecmp(type
->super
, "application"))
3565 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "is_cgi: Returning 0...");
3569 if (!strcasecmp(type
->type
, "x-httpd-cgi") &&
3570 (filestats
->st_mode
& 0111))
3573 * "application/x-httpd-cgi" is a CGI script.
3576 cupsdSetString(&con
->command
, filename
);
3578 filename
= strrchr(filename
, '/') + 1; /* Filename always absolute */
3580 cupsdSetString(&con
->options
, options
);
3582 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3583 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3584 con
->command
, con
->options
);
3589 else if (!strcasecmp(type
->type
, "x-httpd-java"))
3592 * "application/x-httpd-java" is a Java servlet.
3595 cupsdSetString(&con
->command
, CUPS_JAVA
);
3598 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3600 cupsdSetStringf(&con
->options
, " %s", filename
);
3602 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3603 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3604 con
->command
, con
->options
);
3608 #endif /* HAVE_JAVA */
3610 else if (!strcasecmp(type
->type
, "x-httpd-perl"))
3613 * "application/x-httpd-perl" is a Perl page.
3616 cupsdSetString(&con
->command
, CUPS_PERL
);
3619 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3621 cupsdSetStringf(&con
->options
, " %s", filename
);
3623 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3624 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3625 con
->command
, con
->options
);
3629 #endif /* HAVE_PERL */
3631 else if (!strcasecmp(type
->type
, "x-httpd-php"))
3634 * "application/x-httpd-php" is a PHP page.
3637 cupsdSetString(&con
->command
, CUPS_PHP
);
3640 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3642 cupsdSetStringf(&con
->options
, " %s", filename
);
3644 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3645 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3646 con
->command
, con
->options
);
3650 #endif /* HAVE_PHP */
3652 else if (!strcasecmp(type
->type
, "x-httpd-python"))
3655 * "application/x-httpd-python" is a Python page.
3658 cupsdSetString(&con
->command
, CUPS_PYTHON
);
3661 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3663 cupsdSetStringf(&con
->options
, " %s", filename
);
3665 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3666 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3667 con
->command
, con
->options
);
3671 #endif /* HAVE_PYTHON */
3673 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "is_cgi: Returning 0...");
3680 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
3683 static int /* O - 0 if relative, 1 if absolute */
3684 is_path_absolute(const char *path
) /* I - Input path */
3687 * Check for a leading slash...
3694 * Check for "/.." in the path...
3697 while ((path
= strstr(path
, "/..")) != NULL
)
3699 if (!path
[3] || path
[3] == '/')
3706 * If we haven't found any relative paths, return 1 indicating an
3716 * 'make_certificate()' - Make a self-signed SSL/TLS certificate.
3719 static int /* O - 1 on success, 0 on failure */
3720 make_certificate(cupsd_client_t
*con
) /* I - Client connection */
3722 #if defined(HAVE_LIBSSL) && defined(HAVE_WAITPID)
3723 int pid
, /* Process ID of command */
3724 status
; /* Status of command */
3725 char command
[1024], /* Command */
3726 *argv
[12], /* Command-line arguments */
3727 *envp
[MAX_ENV
+ 1], /* Environment variables */
3728 home
[1024], /* HOME environment variable */
3729 infofile
[1024], /* Type-in information for cert */
3730 seedfile
[1024]; /* Random number seed file */
3731 int envc
, /* Number of environment variables */
3732 bytes
; /* Bytes written */
3733 cups_file_t
*fp
; /* Seed/info file */
3734 int infofd
; /* Info file descriptor */
3738 * Run the "openssl" command to seed the random number generator and
3739 * generate a self-signed certificate that is good for 10 years:
3741 * openssl rand -rand seedfile 1
3743 * openssl req -new -x509 -keyout ServerKey \
3744 * -out ServerCertificate -days 3650 -nodes
3746 * The seeding step is crucial in ensuring that the openssl command
3747 * does not block on systems without sufficient entropy...
3750 if (!cupsFileFind("openssl", getenv("PATH"), 1, command
, sizeof(command
)))
3752 cupsdLogMessage(CUPSD_LOG_ERROR
,
3753 "No SSL certificate and openssl command not found!");
3757 if (access("/dev/urandom", 0))
3760 * If the system doesn't provide /dev/urandom, then any random source
3761 * will probably be blocking-style, so generate some random data to
3762 * use as a seed for the certificate. Note that we have already
3763 * seeded the random number generator in cupsdInitCerts()...
3766 cupsdLogMessage(CUPSD_LOG_INFO
,
3767 "Seeding the random number generator...");
3769 snprintf(home
, sizeof(home
), "HOME=%s", TempDir
);
3772 * Write the seed file...
3775 if ((fp
= cupsTempFile2(seedfile
, sizeof(seedfile
))) == NULL
)
3777 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to create seed file %s - %s",
3778 seedfile
, strerror(errno
));
3782 for (bytes
= 0; bytes
< 262144; bytes
++)
3783 cupsFilePutChar(fp
, random());
3788 * Run the openssl command to seed its random number generator...
3791 argv
[0] = "openssl";
3798 envc
= cupsdLoadEnv(envp
, MAX_ENV
);
3799 envp
[envc
++] = home
;
3802 if (!cupsdStartProcess(command
, argv
, envp
, -1, -1, -1, -1, -1, 1, &pid
))
3808 while (waitpid(pid
, &status
, 0) < 0)
3815 cupsdFinishProcess(pid
, command
, sizeof(command
));
3818 * Remove the seed file, as it is no longer needed...
3825 if (WIFEXITED(status
))
3826 cupsdLogMessage(CUPSD_LOG_ERROR
,
3827 "Unable to seed random number generator - "
3828 "the openssl command stopped with status %d!",
3829 WEXITSTATUS(status
));
3831 cupsdLogMessage(CUPSD_LOG_ERROR
,
3832 "Unable to seed random number generator - "
3833 "the openssl command crashed on signal %d!",
3841 * Create a file with the certificate information fields...
3843 * Note: This assumes that the default questions are asked by the openssl
3847 if ((fp
= cupsTempFile2(infofile
, sizeof(infofile
))) == NULL
)
3849 cupsdLogMessage(CUPSD_LOG_ERROR
,
3850 "Unable to create certificate information file %s - %s",
3851 infofile
, strerror(errno
));
3855 cupsFilePrintf(fp
, ".\n.\n.\n%s\n.\n%s\n%s\n",
3856 ServerName
, ServerName
, ServerAdmin
);
3859 cupsdLogMessage(CUPSD_LOG_INFO
,
3860 "Generating SSL server key and certificate...");
3862 argv
[0] = "openssl";
3866 argv
[4] = "-keyout";
3867 argv
[5] = ServerKey
;
3869 argv
[7] = ServerCertificate
;
3872 argv
[10] = "-nodes";
3875 cupsdLoadEnv(envp
, MAX_ENV
);
3877 infofd
= open(infofile
, O_RDONLY
);
3879 if (!cupsdStartProcess(command
, argv
, envp
, infofd
, -1, -1, -1, -1, 1, &pid
))
3889 while (waitpid(pid
, &status
, 0) < 0)
3896 cupsdFinishProcess(pid
, command
, sizeof(command
));
3900 if (WIFEXITED(status
))
3901 cupsdLogMessage(CUPSD_LOG_ERROR
,
3902 "Unable to create SSL server key and certificate - "
3903 "the openssl command stopped with status %d!",
3904 WEXITSTATUS(status
));
3906 cupsdLogMessage(CUPSD_LOG_ERROR
,
3907 "Unable to create SSL server key and certificate - "
3908 "the openssl command crashed on signal %d!",
3913 cupsdLogMessage(CUPSD_LOG_INFO
, "Created SSL server key file \"%s\"...",
3915 cupsdLogMessage(CUPSD_LOG_INFO
,
3916 "Created SSL server certificate file \"%s\"...",
3922 #elif defined(HAVE_GNUTLS)
3923 gnutls_x509_crt crt
; /* Self-signed certificate */
3924 gnutls_x509_privkey key
; /* Encryption key */
3925 cups_lang_t
*language
; /* Default language info */
3926 cups_file_t
*fp
; /* Key/cert file */
3927 unsigned char buffer
[8192]; /* Buffer for x509 data */
3928 size_t bytes
; /* Number of bytes of data */
3929 unsigned char serial
[4]; /* Serial number buffer */
3930 time_t curtime
; /* Current time */
3931 int result
; /* Result of GNU TLS calls */
3935 * Create the encryption key...
3938 cupsdLogMessage(CUPSD_LOG_INFO
, "Generating SSL server key...");
3940 gnutls_x509_privkey_init(&key
);
3941 gnutls_x509_privkey_generate(key
, GNUTLS_PK_RSA
, 2048, 0);
3947 bytes
= sizeof(buffer
);
3949 if ((result
= gnutls_x509_privkey_export(key
, GNUTLS_X509_FMT_PEM
,
3950 buffer
, &bytes
)) < 0)
3952 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to export SSL server key - %s",
3953 gnutls_strerror(result
));
3954 gnutls_x509_privkey_deinit(key
);
3957 else if ((fp
= cupsFileOpen(ServerKey
, "w")) != NULL
)
3959 cupsFileWrite(fp
, (char *)buffer
, bytes
);
3962 cupsdLogMessage(CUPSD_LOG_INFO
, "Created SSL server key file \"%s\"...",
3967 cupsdLogMessage(CUPSD_LOG_ERROR
,
3968 "Unable to create SSL server key file \"%s\" - %s",
3969 ServerKey
, strerror(errno
));
3970 gnutls_x509_privkey_deinit(key
);
3975 * Create the self-signed certificate...
3978 cupsdLogMessage(CUPSD_LOG_INFO
, "Generating self-signed SSL certificate...");
3980 language
= cupsLangDefault();
3981 curtime
= time(NULL
);
3982 serial
[0] = curtime
>> 24;
3983 serial
[1] = curtime
>> 16;
3984 serial
[2] = curtime
>> 8;
3985 serial
[3] = curtime
;
3987 gnutls_x509_crt_init(&crt
);
3988 if (strlen(language
->language
) == 5)
3989 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
3990 language
->language
+ 3, 2);
3992 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
3994 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COMMON_NAME
, 0,
3995 ServerName
, strlen(ServerName
));
3996 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATION_NAME
, 0,
3997 ServerName
, strlen(ServerName
));
3998 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATIONAL_UNIT_NAME
,
4000 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_STATE_OR_PROVINCE_NAME
, 0,
4002 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_LOCALITY_NAME
, 0,
4004 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_PKCS9_EMAIL
, 0,
4005 ServerAdmin
, strlen(ServerAdmin
));
4006 gnutls_x509_crt_set_key(crt
, key
);
4007 gnutls_x509_crt_set_serial(crt
, serial
, sizeof(serial
));
4008 gnutls_x509_crt_set_activation_time(crt
, curtime
);
4009 gnutls_x509_crt_set_expiration_time(crt
, curtime
+ 10 * 365 * 86400);
4010 gnutls_x509_crt_set_ca_status(crt
, 0);
4011 gnutls_x509_crt_set_subject_alternative_name(crt
, GNUTLS_SAN_DNSNAME
,
4013 gnutls_x509_crt_set_key_purpose_oid(crt
, GNUTLS_KP_TLS_WWW_SERVER
, 0);
4014 gnutls_x509_crt_set_key_usage(crt
, GNUTLS_KEY_KEY_ENCIPHERMENT
);
4015 gnutls_x509_crt_set_version(crt
, 3);
4017 bytes
= sizeof(buffer
);
4018 if (gnutls_x509_crt_get_key_id(crt
, 0, buffer
, &bytes
) >= 0)
4019 gnutls_x509_crt_set_subject_key_id(crt
, buffer
, bytes
);
4021 gnutls_x509_crt_sign(crt
, crt
, key
);
4027 bytes
= sizeof(buffer
);
4028 if ((result
= gnutls_x509_crt_export(crt
, GNUTLS_X509_FMT_PEM
,
4029 buffer
, &bytes
)) < 0)
4030 cupsdLogMessage(CUPSD_LOG_ERROR
,
4031 "Unable to export SSL server certificate - %s",
4032 gnutls_strerror(result
));
4033 else if ((fp
= cupsFileOpen(ServerCertificate
, "w")) != NULL
)
4035 cupsFileWrite(fp
, (char *)buffer
, bytes
);
4038 cupsdLogMessage(CUPSD_LOG_INFO
,
4039 "Created SSL server certificate file \"%s\"...",
4043 cupsdLogMessage(CUPSD_LOG_ERROR
,
4044 "Unable to create SSL server certificate file \"%s\" - %s",
4045 ServerCertificate
, strerror(errno
));
4051 gnutls_x509_crt_deinit(crt
);
4052 gnutls_x509_privkey_deinit(key
);
4056 #elif defined(HAVE_CDSASSL) && defined(HAVE_WAITPID)
4057 int pid
, /* Process ID of command */
4058 status
; /* Status of command */
4059 char command
[1024], /* Command */
4060 *argv
[4], /* Command-line arguments */
4061 *envp
[MAX_ENV
+ 1], /* Environment variables */
4062 keychain
[1024], /* Keychain argument */
4063 infofile
[1024]; /* Type-in information for cert */
4064 cups_file_t
*fp
; /* Seed/info file */
4065 int infofd
; /* Info file descriptor */
4069 * Run the "certtool" command to generate a self-signed certificate...
4072 if (!cupsFileFind("certtool", getenv("PATH"), 1, command
, sizeof(command
)))
4074 cupsdLogMessage(CUPSD_LOG_ERROR
,
4075 "No SSL certificate and certtool command not found!");
4080 * Create a file with the certificate information fields...
4082 * Note: This assumes that the default questions are asked by the certtool
4086 if ((fp
= cupsTempFile2(infofile
, sizeof(infofile
))) == NULL
)
4088 cupsdLogMessage(CUPSD_LOG_ERROR
,
4089 "Unable to create certificate information file %s - %s",
4090 infofile
, strerror(errno
));
4094 cupsFilePrintf(fp
, "%s\nr\n\ny\nb\ns\ny\n%s\n\n\n\n\n%s\ny\n",
4095 con
->servername
, con
->servername
, ServerAdmin
);
4098 cupsdLogMessage(CUPSD_LOG_INFO
,
4099 "Generating SSL server key and certificate...");
4101 snprintf(keychain
, sizeof(keychain
), "k=%s", ServerCertificate
);
4103 argv
[0] = "certtool";
4108 cupsdLoadEnv(envp
, MAX_ENV
);
4110 infofd
= open(infofile
, O_RDONLY
);
4112 if (!cupsdStartProcess(command
, argv
, envp
, infofd
, -1, -1, -1, -1, 1, &pid
))
4122 while (waitpid(pid
, &status
, 0) < 0)
4129 cupsdFinishProcess(pid
, command
, sizeof(command
));
4133 if (WIFEXITED(status
))
4134 cupsdLogMessage(CUPSD_LOG_ERROR
,
4135 "Unable to create SSL server key and certificate - "
4136 "the certtool command stopped with status %d!",
4137 WEXITSTATUS(status
));
4139 cupsdLogMessage(CUPSD_LOG_ERROR
,
4140 "Unable to create SSL server key and certificate - "
4141 "the certtool command crashed on signal %d!",
4146 cupsdLogMessage(CUPSD_LOG_INFO
,
4147 "Created SSL server certificate file \"%s\"...",
4155 #endif /* HAVE_LIBSSL && HAVE_WAITPID */
4157 #endif /* HAVE_SSL */
4161 * 'pipe_command()' - Pipe the output of a command to the remote client.
4164 static int /* O - Process ID */
4165 pipe_command(cupsd_client_t
*con
, /* I - Client connection */
4166 int infile
, /* I - Standard input for command */
4167 int *outfile
, /* O - Standard output for command */
4168 char *command
, /* I - Command to run */
4169 char *options
, /* I - Options for command */
4170 int root
) /* I - Run as root? */
4172 int i
; /* Looping var */
4173 int pid
; /* Process ID */
4174 char *commptr
, /* Command string pointer */
4175 commch
; /* Command string character */
4176 char *uriptr
; /* URI string pointer */
4177 int fds
[2]; /* Pipe FDs */
4178 int argc
; /* Number of arguments */
4179 int envc
; /* Number of environment variables */
4180 char argbuf
[10240], /* Argument buffer */
4181 *argv
[100], /* Argument strings */
4182 *envp
[MAX_ENV
+ 20]; /* Environment variables */
4183 char auth_type
[256], /* AUTH_TYPE environment variable */
4184 content_length
[1024], /* CONTENT_LENGTH environment variable */
4185 content_type
[1024], /* CONTENT_TYPE environment variable */
4186 http_cookie
[32768], /* HTTP_COOKIE environment variable */
4187 http_referer
[1024], /* HTTP_REFERER environment variable */
4188 http_user_agent
[1024], /* HTTP_USER_AGENT environment variable */
4189 lang
[1024], /* LANG environment variable */
4190 path_info
[1024], /* PATH_INFO environment variable */
4191 remote_addr
[1024], /* REMOTE_ADDR environment variable */
4192 remote_host
[1024], /* REMOTE_HOST environment variable */
4193 remote_user
[1024], /* REMOTE_USER environment variable */
4194 script_filename
[1024], /* SCRIPT_FILENAME environment variable */
4195 script_name
[1024], /* SCRIPT_NAME environment variable */
4196 server_name
[1024], /* SERVER_NAME environment variable */
4197 server_port
[1024]; /* SERVER_PORT environment variable */
4201 * Parse a copy of the options string, which is of the form:
4203 * argument+argument+argument
4204 * ?argument+argument+argument
4205 * param=value¶m=value
4206 * ?param=value¶m=value
4207 * /name?argument+argument+argument
4208 * /name?param=value¶m=value
4210 * If the string contains an "=" character after the initial name,
4211 * then we treat it as a HTTP GET form request and make a copy of
4212 * the remaining string for the environment variable.
4214 * The string is always parsed out as command-line arguments, to
4215 * be consistent with Apache...
4218 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4219 "pipe_command: command=\"%s\", options=\"%s\"",
4220 command
, options
? options
: "(null)");
4225 strlcpy(argbuf
, options
, sizeof(argbuf
));
4229 if (argbuf
[0] == '/')
4232 * Found some trailing path information, set PATH_INFO...
4235 if ((commptr
= strchr(argbuf
, '?')) == NULL
)
4236 commptr
= argbuf
+ strlen(argbuf
);
4240 snprintf(path_info
, sizeof(path_info
), "PATH_INFO=%s", argbuf
);
4246 path_info
[0] = '\0';
4248 if (*commptr
== ' ')
4252 cupsdLogMessage(CUPSD_LOG_INFO
, "commptr=\"%s\"", commptr
);
4254 if (*commptr
== '?' && con
->operation
== HTTP_GET
&& !con
->query_string
)
4257 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", commptr
);
4264 argv
[argc
++] = commptr
;
4266 for (; *commptr
&& argc
< 99; commptr
++)
4269 * Break arguments whenever we see a + or space...
4272 if (*commptr
== ' ' || *commptr
== '+')
4274 while (*commptr
== ' ' || *commptr
== '+')
4278 * If we don't have a blank string, save it as another argument...
4283 argv
[argc
] = commptr
;
4289 else if (*commptr
== '%' && isxdigit(commptr
[1] & 255) &&
4290 isxdigit(commptr
[2] & 255))
4293 * Convert the %xx notation to the individual character.
4296 if (commptr
[1] >= '0' && commptr
[1] <= '9')
4297 *commptr
= (commptr
[1] - '0') << 4;
4299 *commptr
= (tolower(commptr
[1]) - 'a' + 10) << 4;
4301 if (commptr
[2] >= '0' && commptr
[2] <= '9')
4302 *commptr
|= commptr
[2] - '0';
4304 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
4306 _cups_strcpy(commptr
+ 1, commptr
+ 3);
4309 * Check for a %00 and break if that is the case...
4321 * Setup the environment variables as needed...
4324 if (con
->username
[0])
4326 snprintf(auth_type
, sizeof(auth_type
), "AUTH_TYPE=%s",
4327 httpGetField(HTTP(con
), HTTP_FIELD_AUTHORIZATION
));
4329 if ((uriptr
= strchr(auth_type
+ 10, ' ')) != NULL
)
4333 auth_type
[0] = '\0';
4336 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF-8", con
->language
->language
);
4338 strcpy(lang
, "LANG=C");
4340 strcpy(remote_addr
, "REMOTE_ADDR=");
4341 httpAddrString(con
->http
.hostaddr
, remote_addr
+ 12,
4342 sizeof(remote_addr
) - 12);
4344 snprintf(remote_host
, sizeof(remote_host
), "REMOTE_HOST=%s",
4345 con
->http
.hostname
);
4347 snprintf(script_name
, sizeof(script_name
), "SCRIPT_NAME=%s", con
->uri
);
4348 if ((uriptr
= strchr(script_name
, '?')) != NULL
)
4351 snprintf(script_filename
, sizeof(script_filename
), "SCRIPT_FILENAME=%s%s",
4352 DocumentRoot
, script_name
+ 12);
4354 sprintf(server_port
, "SERVER_PORT=%d", con
->serverport
);
4356 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
4359 envc
= cupsdLoadEnv(envp
, (int)(sizeof(envp
) / sizeof(envp
[0])));
4362 envp
[envc
++] = auth_type
;
4364 envp
[envc
++] = lang
;
4365 envp
[envc
++] = "REDIRECT_STATUS=1";
4366 envp
[envc
++] = "GATEWAY_INTERFACE=CGI/1.1";
4367 envp
[envc
++] = server_name
;
4368 envp
[envc
++] = server_port
;
4369 envp
[envc
++] = remote_addr
;
4370 envp
[envc
++] = remote_host
;
4371 envp
[envc
++] = script_name
;
4372 envp
[envc
++] = script_filename
;
4375 envp
[envc
++] = path_info
;
4377 if (con
->username
[0])
4379 snprintf(remote_user
, sizeof(remote_user
), "REMOTE_USER=%s", con
->username
);
4381 envp
[envc
++] = remote_user
;
4384 if (con
->http
.version
== HTTP_1_1
)
4385 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.1";
4386 else if (con
->http
.version
== HTTP_1_0
)
4387 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.0";
4389 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/0.9";
4391 if (con
->http
.cookie
)
4393 snprintf(http_cookie
, sizeof(http_cookie
), "HTTP_COOKIE=%s",
4395 envp
[envc
++] = http_cookie
;
4398 if (con
->http
.fields
[HTTP_FIELD_USER_AGENT
][0])
4400 snprintf(http_user_agent
, sizeof(http_user_agent
), "HTTP_USER_AGENT=%s",
4401 con
->http
.fields
[HTTP_FIELD_USER_AGENT
]);
4402 envp
[envc
++] = http_user_agent
;
4405 if (con
->http
.fields
[HTTP_FIELD_REFERER
][0])
4407 snprintf(http_referer
, sizeof(http_referer
), "HTTP_REFERER=%s",
4408 con
->http
.fields
[HTTP_FIELD_REFERER
]);
4409 envp
[envc
++] = http_referer
;
4412 if (con
->operation
== HTTP_GET
)
4414 envp
[envc
++] = "REQUEST_METHOD=GET";
4416 if (con
->query_string
)
4419 * Add GET form variables after ?...
4422 envp
[envc
++] = con
->query_string
;
4427 sprintf(content_length
, "CONTENT_LENGTH=" CUPS_LLFMT
,
4428 CUPS_LLCAST con
->bytes
);
4429 snprintf(content_type
, sizeof(content_type
), "CONTENT_TYPE=%s",
4430 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
4432 envp
[envc
++] = "REQUEST_METHOD=POST";
4433 envp
[envc
++] = content_length
;
4434 envp
[envc
++] = content_type
;
4438 * Tell the CGI if we are using encryption...
4442 envp
[envc
++] = "HTTPS=ON";
4445 * Terminate the environment array...
4450 if (LogLevel
== CUPSD_LOG_DEBUG2
)
4452 for (i
= 0; i
< argc
; i
++)
4453 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4454 "pipe_command: argv[%d] = \"%s\"", i
, argv
[i
]);
4455 for (i
= 0; i
< envc
; i
++)
4456 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4457 "pipe_command: envp[%d] = \"%s\"", i
, envp
[i
]);
4461 * Create a pipe for the output...
4464 if (cupsdOpenPipe(fds
))
4466 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to create pipes for CGI %s - %s",
4467 argv
[0], strerror(errno
));
4472 * Then execute the command...
4475 if (cupsdStartProcess(command
, argv
, envp
, infile
, fds
[1], CGIPipes
[1],
4476 -1, -1, root
, &pid
) < 0)
4479 * Error - can't fork!
4482 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to fork for CGI %s - %s", argv
[0],
4485 cupsdClosePipe(fds
);
4491 * Fork successful - return the PID...
4494 if (con
->username
[0])
4495 cupsdAddCert(pid
, con
->username
);
4497 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[CGI] %s started - PID = %d",
4509 * 'write_file()' - Send a file via HTTP.
4512 static int /* O - 0 on failure, 1 on success */
4513 write_file(cupsd_client_t
*con
, /* I - Client connection */
4514 http_status_t code
, /* I - HTTP status */
4515 char *filename
, /* I - Filename */
4516 char *type
, /* I - File type */
4517 struct stat
*filestats
) /* O - File information */
4519 con
->file
= open(filename
, O_RDONLY
);
4521 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "write_file: %d file=%d", con
->http
.fd
,
4527 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
4531 if (!cupsdSendHeader(con
, code
, type
, AUTH_NONE
))
4534 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
4535 httpGetDateString(filestats
->st_mtime
)) < 0)
4537 if (httpPrintf(HTTP(con
), "Content-Length: " CUPS_LLFMT
"\r\n",
4538 CUPS_LLCAST filestats
->st_size
) < 0)
4540 if (httpPrintf(HTTP(con
), "\r\n") < 0)
4543 if (cupsdFlushHeader(con
) < 0)
4546 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
4547 con
->http
.data_remaining
= filestats
->st_size
;
4549 if (con
->http
.data_remaining
<= INT_MAX
)
4550 con
->http
._data_remaining
= con
->http
.data_remaining
;
4552 con
->http
._data_remaining
= INT_MAX
;
4554 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
,
4555 (cupsd_selfunc_t
)cupsdWriteClient
, con
);
4562 * 'write_pipe()' - Flag that data is available on the CGI pipe.
4566 write_pipe(cupsd_client_t
*con
) /* I - Client connection */
4568 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "write_pipe: CGI output on fd %d...",
4571 con
->file_ready
= 1;
4573 cupsdRemoveSelect(con
->file
);
4574 cupsdAddSelect(con
->http
.fd
, NULL
, (cupsd_selfunc_t
)cupsdWriteClient
, con
);
4579 * End of "$Id: client.c 6737 2007-07-26 19:08:40Z mike $".