2 * "$Id: client.c 6111 2006-11-15 20:28:39Z mike $"
4 * Client routines for the Common UNIX Printing System (CUPS) scheduler.
6 * Copyright 1997-2006 by Easy Software Products, all rights reserved.
8 * These coded instructions, statements, and computer programs are the
9 * property of Easy Software Products and are protected by Federal
10 * copyright law. Distribution and use rights are outlined in the file
11 * "LICENSE.txt" which should have been included with this file. If this
12 * file is missing or damaged please contact Easy Software Products
15 * Attn: CUPS Licensing Information
16 * Easy Software Products
17 * 44141 Airport View Drive, Suite 204
18 * Hollywood, Maryland 20636 USA
20 * Voice: (301) 373-9600
21 * EMail: cups-info@cups.org
22 * WWW: http://www.cups.org
26 * cupsdAcceptClient() - Accept a new client.
27 * cupsdCloseAllClients() - Close all remote clients immediately.
28 * cupsdCloseClient() - Close a remote client.
29 * cupsdFlushHeader() - Flush the header fields to the client.
30 * cupsdReadClient() - Read data from a client.
31 * cupsdSendCommand() - Send output from a command via HTTP.
32 * cupsdSendError() - Send an error message via HTTP.
33 * cupsdSendHeader() - Send an HTTP request.
34 * cupsdUpdateCGI() - Read status messages from CGI scripts and programs.
35 * cupsdWriteClient() - Write data to a client as needed.
36 * check_if_modified() - Decode an "If-Modified-Since" line.
37 * encrypt_client() - Enable encryption for the client...
38 * get_cdsa_server_certs() - Convert a keychain name into the CFArrayRef
39 * required by SSLSetCertificate.
40 * get_file() - Get a filename and state info.
41 * install_conf_file() - Install a configuration file.
42 * is_cgi() - Is the resource a CGI script/program?
43 * is_path_absolute() - Is a path absolute and free of relative elements.
44 * make_certificate() - Make a self-signed SSL/TLS certificate.
45 * pipe_command() - Pipe the output of a command to the remote client.
46 * write_file() - Send a file via HTTP.
50 * Include necessary headers...
53 #include <cups/http-private.h>
57 # include <Security/Security.h>
58 # ifdef HAVE_SECBASEPRIV_H
59 # include <Security/SecBasePriv.h>
61 extern const char *cssmErrorString(int error
);
62 # endif /* HAVE_SECBASEPRIV_H */
63 #endif /* HAVE_CDSASSL */
65 # include <gnutls/x509.h>
66 #endif /* HAVE_GNUTLS */
73 static int check_if_modified(cupsd_client_t
*con
,
74 struct stat
*filestats
);
76 static int encrypt_client(cupsd_client_t
*con
);
79 static CFArrayRef
get_cdsa_server_certs(void);
80 #endif /* HAVE_CDSASSL */
81 static char *get_file(cupsd_client_t
*con
, struct stat
*filestats
,
82 char *filename
, int len
);
83 static http_status_t
install_conf_file(cupsd_client_t
*con
);
84 static int is_cgi(cupsd_client_t
*con
, const char *filename
,
85 struct stat
*filestats
, mime_type_t
*type
);
86 static int is_path_absolute(const char *path
);
88 static int make_certificate(void);
90 static int pipe_command(cupsd_client_t
*con
, int infile
, int *outfile
,
91 char *command
, char *options
, int root
);
92 static int write_file(cupsd_client_t
*con
, http_status_t code
,
93 char *filename
, char *type
,
94 struct stat
*filestats
);
98 * 'cupsdAcceptClient()' - Accept a new client.
102 cupsdAcceptClient(cupsd_listener_t
*lis
)/* I - Listener socket */
104 int count
; /* Count of connections on a host */
105 int val
; /* Parameter value */
106 cupsd_client_t
*con
, /* New client pointer */
107 *tempcon
; /* Temporary client pointer */
108 http_addrlist_t
*addrlist
, /* List of adddresses for host */
109 *addr
; /* Current address */
110 socklen_t addrlen
; /* Length of address */
111 char *hostname
; /* Hostname for address */
112 http_addr_t temp
; /* Temporary address variable */
113 static time_t last_dos
= 0; /* Time of last DoS attack */
116 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
117 "cupsdAcceptClient(lis=%p) %d Clients = %d",
118 lis
, lis
->fd
, cupsArrayCount(Clients
));
121 * Make sure we don't have a full set of clients already...
124 if (cupsArrayCount(Clients
) == MaxClients
)
128 * Get a pointer to the next available client...
132 Clients
= cupsArrayNew(NULL
, NULL
);
137 con
= calloc(1, sizeof(cupsd_client_t
));
139 con
->http
.activity
= time(NULL
);
141 con
->http
.hostaddr
= &(con
->clientaddr
);
144 * Accept the client and get the remote address...
147 addrlen
= sizeof(http_addr_t
);
149 if ((con
->http
.fd
= accept(lis
->fd
, (struct sockaddr
*)con
->http
.hostaddr
,
152 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to accept client connection - %s.",
159 if (lis
->address
.addr
.sa_family
== AF_INET6
)
162 * Save the connected port number...
165 con
->http
.hostaddr
->ipv6
.sin6_port
= lis
->address
.ipv6
.sin6_port
;
168 * Convert IPv4 over IPv6 addresses (::ffff:n.n.n.n) to IPv4 forms we
169 * can more easily use...
172 if (con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[0] == 0 &&
173 con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[1] == 0 &&
174 ntohl(con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[2]) == 0xffff)
175 con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[2] = 0;
178 #endif /* AF_INET6 */
179 if (lis
->address
.addr
.sa_family
== AF_INET
)
180 con
->http
.hostaddr
->ipv4
.sin_port
= lis
->address
.ipv4
.sin_port
;
183 * Check the number of clients on the same address...
186 for (count
= 0, tempcon
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
188 tempcon
= (cupsd_client_t
*)cupsArrayNext(Clients
))
189 if (httpAddrEqual(tempcon
->http
.hostaddr
, con
->http
.hostaddr
))
192 if (count
>= MaxClientsPerHost
)
196 if (count
>= MaxClientsPerHost
)
198 if ((time(NULL
) - last_dos
) >= 60)
200 last_dos
= time(NULL
);
201 cupsdLogMessage(CUPSD_LOG_WARN
,
202 "Possible DoS attack - more than %d clients connecting "
204 MaxClientsPerHost
, tempcon
->http
.hostname
);
208 closesocket(con
->http
.fd
);
218 * Get the hostname or format the IP address as needed...
221 if (httpAddrLocalhost(con
->http
.hostaddr
))
224 * Map accesses from the loopback interface to "localhost"...
227 strlcpy(con
->http
.hostname
, "localhost", sizeof(con
->http
.hostname
));
228 hostname
= con
->http
.hostname
;
233 * Map accesses from the same host to the server name.
236 for (addr
= ServerAddrs
; addr
; addr
= addr
->next
)
237 if (httpAddrEqual(con
->http
.hostaddr
, &(addr
->addr
)))
242 strlcpy(con
->http
.hostname
, ServerName
, sizeof(con
->http
.hostname
));
243 hostname
= con
->http
.hostname
;
245 else if (HostNameLookups
)
246 hostname
= httpAddrLookup(con
->http
.hostaddr
, con
->http
.hostname
,
247 sizeof(con
->http
.hostname
));
251 httpAddrString(con
->http
.hostaddr
, con
->http
.hostname
,
252 sizeof(con
->http
.hostname
));
256 if (hostname
== NULL
&& HostNameLookups
== 2)
259 * Can't have an unresolved IP address with double-lookups enabled...
262 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
263 "cupsdAcceptClient: Closing connection %d...",
267 closesocket(con
->http
.fd
);
272 cupsdLogMessage(CUPSD_LOG_WARN
,
273 "Name lookup failed - connection from %s closed!",
280 if (HostNameLookups
== 2)
283 * Do double lookups as needed...
286 if ((addrlist
= httpAddrGetList(con
->http
.hostname
, AF_UNSPEC
, NULL
)) != NULL
)
289 * See if the hostname maps to the same IP address...
292 for (addr
= addrlist
; addr
; addr
= addr
->next
)
293 if (httpAddrEqual(con
->http
.hostaddr
, &(addr
->addr
)))
299 httpAddrFreeList(addrlist
);
304 * Can't have a hostname that doesn't resolve to the same IP address
305 * with double-lookups enabled...
308 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
309 "cupsdAcceptClient: Closing connection %d...",
313 closesocket(con
->http
.fd
);
318 cupsdLogMessage(CUPSD_LOG_WARN
,
319 "IP lookup failed - connection from %s closed!",
327 if (con
->http
.hostaddr
->addr
.sa_family
== AF_INET6
)
328 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdAcceptClient: %d from %s:%d (IPv6)",
329 con
->http
.fd
, con
->http
.hostname
,
330 ntohs(con
->http
.hostaddr
->ipv6
.sin6_port
));
332 #endif /* AF_INET6 */
334 if (con
->http
.hostaddr
->addr
.sa_family
== AF_LOCAL
)
335 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdAcceptClient: %d from %s (Domain)",
336 con
->http
.fd
, con
->http
.hostname
);
338 #endif /* AF_LOCAL */
339 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdAcceptClient: %d from %s:%d (IPv4)",
340 con
->http
.fd
, con
->http
.hostname
,
341 ntohs(con
->http
.hostaddr
->ipv4
.sin_port
));
344 * Get the local address the client connected to...
347 addrlen
= sizeof(temp
);
348 if (getsockname(con
->http
.fd
, (struct sockaddr
*)&temp
, &addrlen
))
350 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to get local address - %s",
353 strcpy(con
->servername
, "localhost");
354 con
->serverport
= LocalPort
;
359 if (temp
.addr
.sa_family
== AF_INET6
)
361 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
362 con
->serverport
= ntohs(lis
->address
.ipv6
.sin6_port
);
365 #endif /* AF_INET6 */
366 if (temp
.addr
.sa_family
== AF_INET
)
368 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
369 con
->serverport
= ntohs(lis
->address
.ipv4
.sin_port
);
373 strcpy(con
->servername
, "localhost");
374 con
->serverport
= LocalPort
;
378 cupsArrayAdd(Clients
, con
);
380 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
381 "cupsdAcceptClient: %d connected to server on %s:%d",
382 con
->http
.fd
, con
->servername
, con
->serverport
);
385 * Using TCP_NODELAY improves responsiveness, especially on systems
386 * with a slow loopback interface... Since we write large buffers
387 * when sending print files and requests, there shouldn't be any
388 * performance penalty for this...
392 setsockopt(con
->http
.fd
, IPPROTO_TCP
, TCP_NODELAY
, &val
, sizeof(val
));
395 * Close this file on all execs...
398 fcntl(con
->http
.fd
, F_SETFD
, fcntl(con
->http
.fd
, F_GETFD
) | FD_CLOEXEC
);
401 * Add the socket to the select() input mask.
404 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
405 "cupsdAcceptClient: Adding fd %d to InputSet...",
407 FD_SET(con
->http
.fd
, InputSet
);
410 * Temporarily suspend accept()'s until we lose a client...
413 if (cupsArrayCount(Clients
) == MaxClients
)
414 cupsdPauseListening();
418 * See if we are connecting on a secure port...
421 if (lis
->encryption
== HTTP_ENCRYPT_ALWAYS
)
424 * https connection; go secure...
427 con
->http
.encryption
= HTTP_ENCRYPT_ALWAYS
;
429 if (!encrypt_client(con
))
430 cupsdCloseClient(con
);
434 #endif /* HAVE_SSL */
439 * 'cupsdCloseAllClients()' - Close all remote clients immediately.
443 cupsdCloseAllClients(void)
445 cupsd_client_t
*con
; /* Current client */
448 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
450 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
451 cupsdCloseClient(con
);
456 * 'cupsdCloseClient()' - Close a remote client.
459 int /* O - 1 if partial close, 0 if fully closed */
460 cupsdCloseClient(cupsd_client_t
*con
) /* I - Client to close */
462 int partial
; /* Do partial close for SSL? */
464 SSL_CTX
*context
; /* Context for encryption */
465 SSL
*conn
; /* Connection for encryption */
466 unsigned long error
; /* Error code */
467 #elif defined(HAVE_GNUTLS)
468 http_tls_t
*conn
; /* TLS connection information */
469 int error
; /* Error code */
470 gnutls_certificate_server_credentials
*credentials
;
471 /* TLS credentials */
472 # elif defined(HAVE_CDSASSL)
473 http_tls_t
*conn
; /* CDSA connection information */
474 #endif /* HAVE_LIBSSL */
477 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdCloseClient: %d", con
->http
.fd
);
480 * Flush pending writes before closing...
483 httpFlushWrite(HTTP(con
));
489 * Shutdown encryption as needed...
497 conn
= (SSL
*)(con
->http
.tls
);
498 context
= SSL_get_SSL_CTX(conn
);
500 switch (SSL_shutdown(conn
))
503 cupsdLogMessage(CUPSD_LOG_INFO
,
504 "cupsdCloseClient: SSL shutdown successful!");
507 cupsdLogMessage(CUPSD_LOG_ERROR
,
508 "cupsdCloseClient: Fatal error during SSL shutdown!");
510 while ((error
= ERR_get_error()) != 0)
511 cupsdLogMessage(CUPSD_LOG_ERROR
, "cupsdCloseClient: %s",
512 ERR_error_string(error
, NULL
));
516 SSL_CTX_free(context
);
519 # elif defined(HAVE_GNUTLS)
520 conn
= (http_tls_t
*)(con
->http
.tls
);
521 credentials
= (gnutls_certificate_server_credentials
*)(conn
->credentials
);
523 error
= gnutls_bye(conn
->session
, GNUTLS_SHUT_WR
);
526 case GNUTLS_E_SUCCESS
:
527 cupsdLogMessage(CUPSD_LOG_INFO
,
528 "cupsdCloseClient: SSL shutdown successful!");
531 cupsdLogMessage(CUPSD_LOG_ERROR
,
532 "cupsdCloseClient: %s", gnutls_strerror(error
));
536 gnutls_deinit(conn
->session
);
537 gnutls_certificate_free_credentials(*credentials
);
541 # elif defined(HAVE_CDSASSL)
542 conn
= (http_tls_t
*)(con
->http
.tls
);
544 while (SSLClose(conn
->session
) == errSSLWouldBlock
)
547 SSLDisposeContext(conn
->session
);
549 if (conn
->certsArray
)
550 CFRelease(conn
->certsArray
);
553 # endif /* HAVE_LIBSSL */
555 con
->http
.tls
= NULL
;
557 #endif /* HAVE_SSL */
559 if (con
->pipe_pid
!= 0)
562 * Stop any CGI process...
565 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
566 "cupsdCloseClient: %d Killing process ID %d...",
567 con
->http
.fd
, con
->pipe_pid
);
568 cupsdEndProcess(con
->pipe_pid
, 1);
574 if (FD_ISSET(con
->file
, InputSet
))
576 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
577 "cupsdCloseClient: %d Removing fd %d from InputSet...",
578 con
->http
.fd
, con
->file
);
579 FD_CLR(con
->file
, InputSet
);
582 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
583 "cupsdCloseClient: %d Closing data file %d.",
584 con
->http
.fd
, con
->file
);
591 * Close the socket and clear the file from the input set for select()...
594 if (con
->http
.fd
> 0)
599 * Only do a partial close so that the encrypted client gets everything.
602 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
603 "cupsdCloseClient: Removing fd %d from OutputSet...",
605 shutdown(con
->http
.fd
, 0);
606 FD_CLR(con
->http
.fd
, OutputSet
);
611 * Shut the socket down fully...
614 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
615 "cupsdCloseClient: Removing fd %d from InputSet and OutputSet...",
618 FD_CLR(con
->http
.fd
, InputSet
);
619 FD_CLR(con
->http
.fd
, OutputSet
);
630 if (con
->http
.input_set
)
631 free(con
->http
.input_set
);
633 httpClearCookie(HTTP(con
));
635 cupsdClearString(&con
->filename
);
636 cupsdClearString(&con
->command
);
637 cupsdClearString(&con
->options
);
641 ippDelete(con
->request
);
647 ippDelete(con
->response
);
648 con
->response
= NULL
;
653 cupsLangFree(con
->language
);
654 con
->language
= NULL
;
658 * Re-enable new client connections if we are going back under the
662 if (cupsArrayCount(Clients
) == MaxClients
)
663 cupsdResumeListening();
666 * Compact the list of clients as necessary...
669 cupsArrayRemove(Clients
, con
);
679 * 'cupsdFlushHeader()' - Flush the header fields to the client.
682 int /* I - Bytes written or -1 on error */
683 cupsdFlushHeader(cupsd_client_t
*con
) /* I - Client to flush to */
685 int bytes
= httpFlushWrite(HTTP(con
));
687 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
694 * 'cupsdReadClient()' - Read data from a client.
697 int /* O - 1 on success, 0 on error */
698 cupsdReadClient(cupsd_client_t
*con
) /* I - Client to read from */
700 char line
[32768], /* Line from client... */
701 operation
[64], /* Operation code from socket */
702 version
[64], /* HTTP version number string */
703 locale
[64], /* Locale */
704 *ptr
; /* Pointer into strings */
705 int major
, minor
; /* HTTP version numbers */
706 http_status_t status
; /* Transfer status */
707 ipp_state_t ipp_state
; /* State of IPP transfer */
708 int bytes
; /* Number of bytes to POST */
709 char *filename
; /* Name of file for GET/HEAD */
710 char buf
[1024]; /* Buffer for real filename */
711 struct stat filestats
; /* File information */
712 mime_type_t
*type
; /* MIME type of file */
713 cupsd_printer_t
*p
; /* Printer */
714 static unsigned request_id
= 0; /* Request ID for temp files */
717 status
= HTTP_CONTINUE
;
719 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
720 "cupsdReadClient: %d, used=%d, file=%d state=%d",
721 con
->http
.fd
, con
->http
.used
, con
->file
, con
->http
.state
);
725 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdReadClient: http error seen...");
726 return (cupsdCloseClient(con
));
733 * Automatically check for a SSL/TLS handshake...
738 if (recv(con
->http
.fd
, buf
, 1, MSG_PEEK
) == 1 &&
739 (!buf
[0] || !strchr("DGHOPT", buf
[0])))
742 * Encrypt this connection...
745 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
746 "cupsdReadClient: Saw first byte %02X, auto-negotiating SSL/TLS session...",
749 if (!encrypt_client(con
))
750 return (cupsdCloseClient(con
));
755 #endif /* HAVE_SSL */
757 switch (con
->http
.state
)
761 * See if we've received a request line...
764 if (httpGets(line
, sizeof(line
) - 1, HTTP(con
)) == NULL
)
766 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
767 "cupsdReadClient: httpGets returned EOF...");
768 return (cupsdCloseClient(con
));
772 * Ignore blank request lines...
779 * Clear other state variables...
782 httpClearFields(HTTP(con
));
784 con
->http
.activity
= time(NULL
);
785 con
->http
.version
= HTTP_1_0
;
786 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
787 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
788 con
->http
.data_remaining
= 0;
789 con
->http
._data_remaining
= 0;
790 con
->operation
= HTTP_WAITING
;
795 con
->username
[0] = '\0';
796 con
->password
[0] = '\0';
799 cupsdClearString(&con
->command
);
800 cupsdClearString(&con
->options
);
804 ippDelete(con
->request
);
810 ippDelete(con
->response
);
811 con
->response
= NULL
;
816 cupsLangFree(con
->language
);
817 con
->language
= NULL
;
821 * Grab the request line...
824 switch (sscanf(line
, "%63s%1023s%63s", operation
, con
->uri
, version
))
827 cupsdLogMessage(CUPSD_LOG_ERROR
,
828 "Bad request line \"%s\" from %s!", line
,
830 cupsdSendError(con
, HTTP_BAD_REQUEST
);
831 return (cupsdCloseClient(con
));
833 con
->http
.version
= HTTP_0_9
;
836 if (sscanf(version
, "HTTP/%d.%d", &major
, &minor
) != 2)
838 cupsdLogMessage(CUPSD_LOG_ERROR
,
839 "Bad request line \"%s\" from %s!", line
,
841 cupsdSendError(con
, HTTP_BAD_REQUEST
);
842 return (cupsdCloseClient(con
));
847 con
->http
.version
= (http_version_t
)(major
* 100 + minor
);
848 if (con
->http
.version
== HTTP_1_1
&& KeepAlive
)
849 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
851 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
855 cupsdSendError(con
, HTTP_NOT_SUPPORTED
);
856 return (cupsdCloseClient(con
));
862 * Handle full URLs in the request line...
865 if (strcmp(con
->uri
, "*"))
867 char method
[HTTP_MAX_URI
], /* Method/scheme */
868 userpass
[HTTP_MAX_URI
], /* Username:password */
869 hostname
[HTTP_MAX_URI
], /* Hostname */
870 resource
[HTTP_MAX_URI
]; /* Resource path */
871 int port
; /* Port number */
875 * Separate the URI into its components...
878 httpSeparateURI(HTTP_URI_CODING_MOST
, con
->uri
,
879 method
, sizeof(method
),
880 userpass
, sizeof(userpass
),
881 hostname
, sizeof(hostname
), &port
,
882 resource
, sizeof(resource
));
885 * Only allow URIs with the servername, localhost, or an IP
889 if (strcmp(method
, "file") &&
890 strcasecmp(hostname
, ServerName
) &&
891 strcasecmp(hostname
, "localhost") &&
892 !isdigit(hostname
[0]))
895 * Nope, we don't do proxies...
898 cupsdLogMessage(CUPSD_LOG_ERROR
, "Bad URI \"%s\" in request!",
900 cupsdSendError(con
, HTTP_METHOD_NOT_ALLOWED
);
901 return (cupsdCloseClient(con
));
905 * Copy the resource portion back into the URI; both resource and
906 * con->uri are HTTP_MAX_URI bytes in size...
909 strcpy(con
->uri
, resource
);
913 * Process the request...
916 if (!strcmp(operation
, "GET"))
917 con
->http
.state
= HTTP_GET
;
918 else if (!strcmp(operation
, "PUT"))
919 con
->http
.state
= HTTP_PUT
;
920 else if (!strcmp(operation
, "POST"))
921 con
->http
.state
= HTTP_POST
;
922 else if (!strcmp(operation
, "DELETE"))
923 con
->http
.state
= HTTP_DELETE
;
924 else if (!strcmp(operation
, "TRACE"))
925 con
->http
.state
= HTTP_TRACE
;
926 else if (!strcmp(operation
, "OPTIONS"))
927 con
->http
.state
= HTTP_OPTIONS
;
928 else if (!strcmp(operation
, "HEAD"))
929 con
->http
.state
= HTTP_HEAD
;
932 cupsdLogMessage(CUPSD_LOG_ERROR
, "Bad operation \"%s\"!", operation
);
933 cupsdSendError(con
, HTTP_BAD_REQUEST
);
934 return (cupsdCloseClient(con
));
937 con
->start
= time(NULL
);
938 con
->operation
= con
->http
.state
;
940 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdReadClient: %d %s %s HTTP/%d.%d",
941 con
->http
.fd
, operation
, con
->uri
,
942 con
->http
.version
/ 100, con
->http
.version
% 100);
944 con
->http
.status
= HTTP_OK
;
954 * Parse incoming parameters until the status changes...
957 status
= httpUpdate(HTTP(con
));
959 if (status
!= HTTP_OK
&& status
!= HTTP_CONTINUE
)
961 cupsdSendError(con
, HTTP_BAD_REQUEST
);
962 return (cupsdCloseClient(con
));
967 break; /* Anti-compiler-warning-code */
971 * Handle new transfers...
974 if (status
== HTTP_OK
)
976 if (con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
][0])
979 * Figure out the locale from the Accept-Language and Content-Type
983 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ',')) != NULL
)
986 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ';')) != NULL
)
989 if ((ptr
= strstr(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
], "charset=")) != NULL
)
992 * Combine language and charset, and trim any extra params in the
996 snprintf(locale
, sizeof(locale
), "%s.%s",
997 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ptr
+ 8);
999 if ((ptr
= strchr(locale
, ',')) != NULL
)
1003 snprintf(locale
, sizeof(locale
), "%s.%s",
1004 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], DefaultCharset
);
1006 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1007 "cupsdReadClient: %d Browser asked for language \"%s\"...",
1008 con
->http
.fd
, locale
);
1010 con
->language
= cupsLangGet(locale
);
1013 con
->language
= cupsLangGet(DefaultLocale
);
1015 cupsdAuthorize(con
);
1017 if (!strncmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Keep-Alive", 10) &&
1019 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
1021 if (!con
->http
.fields
[HTTP_FIELD_HOST
][0] &&
1022 con
->http
.version
>= HTTP_1_1
)
1025 * HTTP/1.1 and higher require the "Host:" field...
1028 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
))
1029 return (cupsdCloseClient(con
));
1031 else if (con
->operation
== HTTP_OPTIONS
)
1034 * Do OPTIONS command...
1037 if (con
->best
&& con
->best
->type
!= AUTH_NONE
)
1039 if (!cupsdSendHeader(con
, HTTP_UNAUTHORIZED
, NULL
))
1040 return (cupsdCloseClient(con
));
1043 if (!strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") &&
1044 con
->http
.tls
== NULL
)
1048 * Do encryption stuff...
1051 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
))
1052 return (cupsdCloseClient(con
));
1054 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1055 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1056 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1057 httpPrintf(HTTP(con
), "\r\n");
1059 if (cupsdFlushHeader(con
) < 0)
1060 return (cupsdCloseClient(con
));
1062 if (!encrypt_client(con
))
1063 return (cupsdCloseClient(con
));
1065 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
))
1066 return (cupsdCloseClient(con
));
1067 #endif /* HAVE_SSL */
1070 if (!cupsdSendHeader(con
, HTTP_OK
, NULL
))
1071 return (cupsdCloseClient(con
));
1073 httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n");
1074 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1075 httpPrintf(HTTP(con
), "\r\n");
1077 if (cupsdFlushHeader(con
) < 0)
1078 return (cupsdCloseClient(con
));
1080 else if (!is_path_absolute(con
->uri
))
1083 * Protect against malicious users!
1086 if (!cupsdSendError(con
, HTTP_FORBIDDEN
))
1087 return (cupsdCloseClient(con
));
1091 if (!strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") &&
1092 con
->http
.tls
== NULL
)
1096 * Do encryption stuff...
1099 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
))
1100 return (cupsdCloseClient(con
));
1102 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1103 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1104 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1105 httpPrintf(HTTP(con
), "\r\n");
1107 if (cupsdFlushHeader(con
) < 0)
1108 return (cupsdCloseClient(con
));
1110 if (!encrypt_client(con
))
1111 return (cupsdCloseClient(con
));
1113 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
))
1114 return (cupsdCloseClient(con
));
1115 #endif /* HAVE_SSL */
1118 if ((status
= cupsdIsAuthorized(con
, NULL
)) != HTTP_OK
)
1120 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1121 "cupsdReadClient: Unauthorized request for %s...\n",
1123 cupsdSendError(con
, status
);
1124 return (cupsdCloseClient(con
));
1127 if (con
->http
.expect
&&
1128 (con
->operation
== HTTP_POST
|| con
->operation
== HTTP_PUT
))
1130 if (con
->http
.expect
== HTTP_CONTINUE
)
1133 * Send 100-continue header...
1136 if (!cupsdSendHeader(con
, HTTP_CONTINUE
, NULL
))
1137 return (cupsdCloseClient(con
));
1142 * Send 417-expectation-failed header...
1145 if (!cupsdSendHeader(con
, HTTP_EXPECTATION_FAILED
, NULL
))
1146 return (cupsdCloseClient(con
));
1148 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1149 httpPrintf(HTTP(con
), "\r\n");
1151 if (cupsdFlushHeader(con
) < 0)
1152 return (cupsdCloseClient(con
));
1156 switch (con
->http
.state
)
1158 case HTTP_GET_SEND
:
1159 if (!strncmp(con
->uri
, "/printers/", 10) &&
1160 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1163 * Send PPD file - get the real printer name since printer
1164 * names are not case sensitive but filenames can be...
1167 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1169 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1170 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1173 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
1174 return (cupsdCloseClient(con
));
1180 if ((!strncmp(con
->uri
, "/admin", 6) &&
1181 strncmp(con
->uri
, "/admin/conf/", 12) &&
1182 strncmp(con
->uri
, "/admin/log/", 11)) ||
1183 !strncmp(con
->uri
, "/printers", 9) ||
1184 !strncmp(con
->uri
, "/classes", 8) ||
1185 !strncmp(con
->uri
, "/help", 5) ||
1186 !strncmp(con
->uri
, "/jobs", 5))
1189 * Send CGI output...
1192 if (!strncmp(con
->uri
, "/admin", 6))
1194 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1197 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1199 else if (!strncmp(con
->uri
, "/printers", 9))
1201 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1204 if (con
->uri
[9] && con
->uri
[10])
1205 cupsdSetString(&con
->options
, con
->uri
+ 9);
1207 cupsdSetString(&con
->options
, NULL
);
1209 else if (!strncmp(con
->uri
, "/classes", 8))
1211 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1214 if (con
->uri
[8] && con
->uri
[9])
1215 cupsdSetString(&con
->options
, con
->uri
+ 8);
1217 cupsdSetString(&con
->options
, NULL
);
1219 else if (!strncmp(con
->uri
, "/jobs", 5))
1221 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1224 if (con
->uri
[5] && con
->uri
[6])
1225 cupsdSetString(&con
->options
, con
->uri
+ 5);
1227 cupsdSetString(&con
->options
, NULL
);
1231 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1234 if (con
->uri
[5] && con
->uri
[6])
1235 cupsdSetString(&con
->options
, con
->uri
+ 5);
1237 cupsdSetString(&con
->options
, NULL
);
1240 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1242 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
1243 return (cupsdCloseClient(con
));
1246 cupsdLogRequest(con
, HTTP_OK
);
1248 if (con
->http
.version
<= HTTP_1_0
)
1249 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1251 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1252 (strchr(con
->uri
+ 12, '/') ||
1253 strlen(con
->uri
) == 12)) ||
1254 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1255 (strchr(con
->uri
+ 11, '/') ||
1256 strlen(con
->uri
) == 11)))
1259 * GET can only be done to configuration files under
1263 if (!cupsdSendError(con
, HTTP_FORBIDDEN
))
1264 return (cupsdCloseClient(con
));
1274 if ((filename
= get_file(con
, &filestats
, buf
,
1275 sizeof(buf
))) == NULL
)
1277 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
1278 return (cupsdCloseClient(con
));
1283 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1285 if (is_cgi(con
, filename
, &filestats
, type
))
1288 * Note: con->command and con->options were set by
1292 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1294 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
1295 return (cupsdCloseClient(con
));
1298 cupsdLogRequest(con
, HTTP_OK
);
1300 if (con
->http
.version
<= HTTP_1_0
)
1301 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1305 if (!check_if_modified(con
, &filestats
))
1307 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
))
1308 return (cupsdCloseClient(con
));
1313 strcpy(line
, "text/plain");
1315 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1317 if (!write_file(con
, HTTP_OK
, filename
, line
, &filestats
))
1318 return (cupsdCloseClient(con
));
1323 case HTTP_POST_RECV
:
1325 * See if the POST request includes a Content-Length field, and if
1326 * so check the length against any limits that are set...
1329 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "POST %s", con
->uri
);
1330 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "CONTENT_TYPE = %s",
1331 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
1333 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1334 MaxRequestSize
> 0 &&
1335 con
->http
.data_remaining
> MaxRequestSize
)
1338 * Request too large...
1341 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1342 return (cupsdCloseClient(con
));
1346 else if (con
->http
.data_remaining
< 0)
1349 * Negative content lengths are invalid!
1352 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
))
1353 return (cupsdCloseClient(con
));
1359 * See what kind of POST request this is; for IPP requests the
1360 * content-type field will be "application/ipp"...
1363 if (!strcmp(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
],
1365 con
->request
= ippNew();
1366 else if ((!strncmp(con
->uri
, "/admin", 6) &&
1367 strncmp(con
->uri
, "/admin/conf/", 12) &&
1368 strncmp(con
->uri
, "/admin/log/", 11)) ||
1369 !strncmp(con
->uri
, "/printers", 9) ||
1370 !strncmp(con
->uri
, "/classes", 8) ||
1371 !strncmp(con
->uri
, "/help", 5) ||
1372 !strncmp(con
->uri
, "/jobs", 5))
1378 if (!strncmp(con
->uri
, "/admin", 6))
1380 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1383 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1385 else if (!strncmp(con
->uri
, "/printers", 9))
1387 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1390 if (con
->uri
[9] && con
->uri
[10])
1391 cupsdSetString(&con
->options
, con
->uri
+ 9);
1393 cupsdSetString(&con
->options
, NULL
);
1395 else if (!strncmp(con
->uri
, "/classes", 8))
1397 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1400 if (con
->uri
[8] && con
->uri
[9])
1401 cupsdSetString(&con
->options
, con
->uri
+ 8);
1403 cupsdSetString(&con
->options
, NULL
);
1405 else if (!strncmp(con
->uri
, "/jobs", 5))
1407 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1410 if (con
->uri
[5] && con
->uri
[6])
1411 cupsdSetString(&con
->options
, con
->uri
+ 5);
1413 cupsdSetString(&con
->options
, NULL
);
1417 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1420 if (con
->uri
[5] && con
->uri
[6])
1421 cupsdSetString(&con
->options
, con
->uri
+ 5);
1423 cupsdSetString(&con
->options
, NULL
);
1426 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1427 "cupsdReadClient: %d command=\"%s\", "
1429 con
->http
.fd
, con
->command
,
1430 con
->options
? con
->options
: "(null)");
1432 if (con
->http
.version
<= HTTP_1_0
)
1433 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1441 if ((filename
= get_file(con
, &filestats
, buf
,
1442 sizeof(buf
))) == NULL
)
1444 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
1445 return (cupsdCloseClient(con
));
1450 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1452 if (!is_cgi(con
, filename
, &filestats
, type
))
1455 * Only POST to CGI's...
1458 if (!cupsdSendError(con
, HTTP_UNAUTHORIZED
))
1459 return (cupsdCloseClient(con
));
1464 case HTTP_PUT_RECV
:
1466 * Validate the resource name...
1469 if (strncmp(con
->uri
, "/admin/conf/", 12) ||
1470 strchr(con
->uri
+ 12, '/') ||
1471 strlen(con
->uri
) == 12)
1474 * PUT can only be done to configuration files under
1478 if (!cupsdSendError(con
, HTTP_FORBIDDEN
))
1479 return (cupsdCloseClient(con
));
1485 * See if the PUT request includes a Content-Length field, and if
1486 * so check the length against any limits that are set...
1489 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "PUT %s", con
->uri
);
1490 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "CONTENT_TYPE = %s",
1491 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
1493 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1494 MaxRequestSize
> 0 &&
1495 con
->http
.data_remaining
> MaxRequestSize
)
1498 * Request too large...
1501 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1502 return (cupsdCloseClient(con
));
1506 else if (con
->http
.data_remaining
< 0)
1509 * Negative content lengths are invalid!
1512 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
))
1513 return (cupsdCloseClient(con
));
1519 * Open a temporary file to hold the request...
1522 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
1524 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1526 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1527 "cupsdReadClient: %d REQUEST %s=%d", con
->http
.fd
,
1528 con
->filename
, con
->file
);
1532 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1533 return (cupsdCloseClient(con
));
1536 fchmod(con
->file
, 0640);
1537 fchown(con
->file
, RunUser
, Group
);
1538 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1543 cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
);
1544 return (cupsdCloseClient(con
));
1547 if (!strncmp(con
->uri
, "/printers/", 10) &&
1548 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1551 * Send PPD file - get the real printer name since printer
1552 * names are not case sensitive but filenames can be...
1555 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1557 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1558 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1561 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
1562 return (cupsdCloseClient(con
));
1568 if ((!strncmp(con
->uri
, "/admin", 6) &&
1569 strncmp(con
->uri
, "/admin/conf/", 12) &&
1570 strncmp(con
->uri
, "/admin/log/", 11)) ||
1571 !strncmp(con
->uri
, "/printers", 9) ||
1572 !strncmp(con
->uri
, "/classes", 8) ||
1573 !strncmp(con
->uri
, "/help", 5) ||
1574 !strncmp(con
->uri
, "/jobs", 5))
1580 if (!cupsdSendHeader(con
, HTTP_OK
, "text/html"))
1581 return (cupsdCloseClient(con
));
1583 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1584 return (cupsdCloseClient(con
));
1586 if (cupsdFlushHeader(con
) < 0)
1587 return (cupsdCloseClient(con
));
1589 cupsdLogRequest(con
, HTTP_OK
);
1591 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1592 (strchr(con
->uri
+ 12, '/') ||
1593 strlen(con
->uri
) == 12)) ||
1594 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1595 (strchr(con
->uri
+ 11, '/') ||
1596 strlen(con
->uri
) == 11)))
1599 * HEAD can only be done to configuration files under
1603 if (!cupsdSendError(con
, HTTP_FORBIDDEN
))
1604 return (cupsdCloseClient(con
));
1608 else if ((filename
= get_file(con
, &filestats
, buf
,
1609 sizeof(buf
))) == NULL
)
1611 if (!cupsdSendHeader(con
, HTTP_NOT_FOUND
, "text/html"))
1612 return (cupsdCloseClient(con
));
1614 cupsdLogRequest(con
, HTTP_NOT_FOUND
);
1616 else if (!check_if_modified(con
, &filestats
))
1618 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
))
1619 return (cupsdCloseClient(con
));
1621 cupsdLogRequest(con
, HTTP_NOT_MODIFIED
);
1629 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1631 strcpy(line
, "text/plain");
1633 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1635 if (!cupsdSendHeader(con
, HTTP_OK
, line
))
1636 return (cupsdCloseClient(con
));
1638 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
1639 httpGetDateString(filestats
.st_mtime
)) < 0)
1640 return (cupsdCloseClient(con
));
1642 if (httpPrintf(HTTP(con
), "Content-Length: %lu\r\n",
1643 (unsigned long)filestats
.st_size
) < 0)
1644 return (cupsdCloseClient(con
));
1646 cupsdLogRequest(con
, HTTP_OK
);
1649 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1650 return (cupsdCloseClient(con
));
1652 if (cupsdFlushHeader(con
) < 0)
1653 return (cupsdCloseClient(con
));
1655 con
->http
.state
= HTTP_WAITING
;
1659 break; /* Anti-compiler-warning-code */
1665 * Handle any incoming data...
1668 switch (con
->http
.state
)
1670 case HTTP_PUT_RECV
:
1671 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1672 "cupsdReadClient: %d con->data_encoding=HTTP_ENCODE_%s, "
1673 "con->data_remaining=" CUPS_LLFMT
", con->file=%d",
1675 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
?
1676 "CHUNKED" : "LENGTH",
1677 CUPS_LLCAST con
->http
.data_remaining
, con
->file
);
1679 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
1680 return (cupsdCloseClient(con
));
1683 con
->bytes
+= bytes
;
1685 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1686 "cupsdReadClient: %d writing %d bytes to %d",
1687 con
->http
.fd
, bytes
, con
->file
);
1689 if (write(con
->file
, line
, bytes
) < bytes
)
1691 cupsdLogMessage(CUPSD_LOG_ERROR
,
1692 "cupsdReadClient: Unable to write %d bytes to %s: %s",
1693 bytes
, con
->filename
, strerror(errno
));
1695 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1696 "cupsdReadClient: Closing data file %d...",
1701 unlink(con
->filename
);
1702 cupsdClearString(&con
->filename
);
1704 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1705 return (cupsdCloseClient(con
));
1709 if (con
->http
.state
== HTTP_WAITING
)
1712 * End of file, see how big it is...
1715 fstat(con
->file
, &filestats
);
1717 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1718 "cupsdReadClient: %d Closing data file %d, size="
1720 con
->http
.fd
, con
->file
,
1721 CUPS_LLCAST filestats
.st_size
);
1726 if (filestats
.st_size
> MaxRequestSize
&&
1730 * Request is too big; remove it and send an error...
1733 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1734 "cupsdReadClient: %d Removing temp file %s",
1735 con
->http
.fd
, con
->filename
);
1736 unlink(con
->filename
);
1737 cupsdClearString(&con
->filename
);
1739 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1740 return (cupsdCloseClient(con
));
1744 * Install the configuration file...
1747 status
= install_conf_file(con
);
1750 * Return the status to the client...
1753 if (!cupsdSendError(con
, status
))
1754 return (cupsdCloseClient(con
));
1758 case HTTP_POST_RECV
:
1759 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1760 "cupsdReadClient: %d con->data_encoding=HTTP_ENCODE_"
1761 "%s, con->data_remaining=" CUPS_LLFMT
", con->file=%d",
1763 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
?
1764 "CHUNKED" : "LENGTH",
1765 CUPS_LLCAST con
->http
.data_remaining
, con
->file
);
1770 * Grab any request data from the connection...
1773 if ((ipp_state
= ippRead(&(con
->http
), con
->request
)) == IPP_ERROR
)
1775 cupsdLogMessage(CUPSD_LOG_ERROR
,
1776 "cupsdReadClient: %d IPP Read Error!",
1779 cupsdSendError(con
, HTTP_BAD_REQUEST
);
1780 return (cupsdCloseClient(con
));
1782 else if (ipp_state
!= IPP_DATA
)
1784 if (con
->http
.state
== HTTP_POST_SEND
)
1786 cupsdSendError(con
, HTTP_BAD_REQUEST
);
1787 return (cupsdCloseClient(con
));
1793 con
->bytes
+= ippLength(con
->request
);
1796 if (con
->file
< 0 && con
->http
.state
!= HTTP_POST_SEND
)
1799 * Create a file as needed for the request data...
1802 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
, request_id
++);
1803 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1805 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdReadClient: %d REQUEST %s=%d", con
->http
.fd
,
1806 con
->filename
, con
->file
);
1810 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1811 return (cupsdCloseClient(con
));
1814 fchmod(con
->file
, 0640);
1815 fchown(con
->file
, RunUser
, Group
);
1816 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1819 if (con
->http
.state
!= HTTP_POST_SEND
)
1821 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
1822 return (cupsdCloseClient(con
));
1825 con
->bytes
+= bytes
;
1827 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1828 "cupsdReadClient: %d writing %d bytes to %d",
1829 con
->http
.fd
, bytes
, con
->file
);
1831 if (write(con
->file
, line
, bytes
) < bytes
)
1833 cupsdLogMessage(CUPSD_LOG_ERROR
,
1834 "cupsdReadClient: Unable to write %d bytes to %s: %s",
1835 bytes
, con
->filename
, strerror(errno
));
1837 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1838 "cupsdReadClient: Closing file %d...",
1843 unlink(con
->filename
);
1844 cupsdClearString(&con
->filename
);
1846 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1847 return (cupsdCloseClient(con
));
1850 else if (con
->http
.state
== HTTP_POST_RECV
)
1851 return (1); /* ??? */
1852 else if (con
->http
.state
!= HTTP_POST_SEND
)
1853 return (cupsdCloseClient(con
));
1856 if (con
->http
.state
== HTTP_POST_SEND
)
1860 fstat(con
->file
, &filestats
);
1862 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1863 "cupsdReadClient: %d Closing data file %d, "
1864 "size=" CUPS_LLFMT
".",
1865 con
->http
.fd
, con
->file
,
1866 CUPS_LLCAST filestats
.st_size
);
1871 if (filestats
.st_size
> MaxRequestSize
&&
1875 * Request is too big; remove it and send an error...
1878 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1879 "cupsdReadClient: %d Removing temp file %s",
1880 con
->http
.fd
, con
->filename
);
1881 unlink(con
->filename
);
1882 cupsdClearString(&con
->filename
);
1887 * Delete any IPP request data...
1890 ippDelete(con
->request
);
1891 con
->request
= NULL
;
1894 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1895 return (cupsdCloseClient(con
));
1900 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1902 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
1903 return (cupsdCloseClient(con
));
1906 cupsdLogRequest(con
, HTTP_OK
);
1911 return (cupsdProcessIPPRequest(con
));
1916 break; /* Anti-compiler-warning-code */
1919 if (!con
->http
.keep_alive
&& con
->http
.state
== HTTP_WAITING
)
1920 return (cupsdCloseClient(con
));
1927 * 'cupsdSendCommand()' - Send output from a command via HTTP.
1930 int /* O - 1 on success, 0 on failure */
1932 cupsd_client_t
*con
, /* I - Client connection */
1933 char *command
, /* I - Command to run */
1934 char *options
, /* I - Command-line options */
1935 int root
) /* I - Run as root? */
1937 int fd
; /* Standard input file descriptor */
1942 fd
= open(con
->filename
, O_RDONLY
);
1946 cupsdLogMessage(CUPSD_LOG_ERROR
,
1947 "cupsdSendCommand: %d Unable to open \"%s\" for reading: %s",
1948 con
->http
.fd
, con
->filename
? con
->filename
: "/dev/null",
1953 fcntl(fd
, F_SETFD
, fcntl(fd
, F_GETFD
) | FD_CLOEXEC
);
1958 con
->pipe_pid
= pipe_command(con
, fd
, &(con
->file
), command
, options
, root
);
1963 cupsdLogMessage(CUPSD_LOG_INFO
, "Started \"%s\" (pid=%d)", command
,
1966 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendCommand: %d file=%d",
1967 con
->http
.fd
, con
->file
);
1969 if (con
->pipe_pid
== 0)
1972 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1974 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1975 "cupsdSendCommand: Adding fd %d to InputSet...", con
->file
);
1976 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1977 "cupsdSendCommand: Adding fd %d to OutputSet...",
1980 FD_SET(con
->file
, InputSet
);
1981 FD_SET(con
->http
.fd
, OutputSet
);
1983 con
->sent_header
= 0;
1984 con
->file_ready
= 0;
1985 con
->got_fields
= 0;
1993 * 'cupsdSendError()' - Send an error message via HTTP.
1996 int /* O - 1 if successful, 0 otherwise */
1997 cupsdSendError(cupsd_client_t
*con
, /* I - Connection */
1998 http_status_t code
) /* I - Error code */
2002 * Force client to upgrade for authentication if that is how the
2003 * server is configured...
2006 if (code
== HTTP_UNAUTHORIZED
&&
2007 DefaultEncryption
== HTTP_ENCRYPT_REQUIRED
&&
2008 strcasecmp(con
->http
.hostname
, "localhost") &&
2011 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2012 "cupsdSendError: Encryption before authentication!");
2013 code
= HTTP_UPGRADE_REQUIRED
;
2015 #endif /* HAVE_SSL */
2018 * Put the request in the access_log file...
2021 cupsdLogRequest(con
, code
);
2023 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendError: %d code=%d (%s)",
2024 con
->http
.fd
, code
, httpStatus(code
));
2027 * To work around bugs in some proxies, don't use Keep-Alive for some
2031 if (code
>= HTTP_BAD_REQUEST
)
2032 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
2035 * Send an error message back to the client. If the error code is a
2036 * 400 or 500 series, make sure the message contains some text, too!
2039 if (!cupsdSendHeader(con
, code
, NULL
))
2043 if (code
== HTTP_UPGRADE_REQUIRED
)
2044 if (httpPrintf(HTTP(con
), "Connection: Upgrade\r\n") < 0)
2047 if (httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n") < 0)
2049 #endif /* HAVE_SSL */
2051 if ((con
->http
.version
>= HTTP_1_1
&& !con
->http
.keep_alive
) ||
2052 (code
>= HTTP_BAD_REQUEST
&& code
!= HTTP_UPGRADE_REQUIRED
))
2054 if (httpPrintf(HTTP(con
), "Connection: close\r\n") < 0)
2058 if (code
>= HTTP_BAD_REQUEST
)
2061 * Send a human-readable error message.
2064 char message
[4096], /* Message for user */
2065 urltext
[1024], /* URL redirection text */
2066 redirect
[1024]; /* Redirection link */
2067 const char *text
; /* Status-specific text */
2072 if (code
== HTTP_UNAUTHORIZED
)
2073 text
= _cupsLangString(con
->language
,
2074 _("Enter your username and password or the "
2075 "root username and password to access this "
2077 else if (code
== HTTP_UPGRADE_REQUIRED
)
2081 snprintf(urltext
, sizeof(urltext
),
2082 _cupsLangString(con
->language
,
2083 _("You must access this page using the URL "
2084 "<A HREF=\"https://%s:%d%s\">"
2085 "https://%s:%d%s</A>.")),
2086 con
->servername
, con
->serverport
, con
->uri
,
2087 con
->servername
, con
->serverport
, con
->uri
);
2089 snprintf(redirect
, sizeof(redirect
),
2090 "<META HTTP-EQUIV=\"Refresh\" CONTENT=\"3;https://%s:%d%s\">\n",
2091 con
->servername
, con
->serverport
, con
->uri
);
2096 snprintf(message
, sizeof(message
),
2097 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" "
2098 "\"http://www.w3.org/TR/REC-html40/loose.dtd\">\n"
2101 "\t<META HTTP-EQUIV=\"Content-Type\" "
2102 "CONTENT=\"text/html; charset=utf-8\">\n"
2103 "\t<TITLE>%d %s</TITLE>\n"
2104 "\t<LINK REL=\"STYLESHEET\" TYPE=\"text/css\" "
2105 "HREF=\"/cups.css\">\n"
2113 code
, httpStatus(code
), redirect
, code
, httpStatus(code
), text
);
2115 if (httpPrintf(HTTP(con
), "Content-Type: text/html; charset=utf-8\r\n") < 0)
2117 if (httpPrintf(HTTP(con
), "Content-Length: %d\r\n",
2118 (int)strlen(message
)) < 0)
2120 if (httpPrintf(HTTP(con
), "\r\n") < 0)
2122 if (httpPrintf(HTTP(con
), "%s", message
) < 0)
2125 else if (httpPrintf(HTTP(con
), "\r\n") < 0)
2128 if (cupsdFlushHeader(con
) < 0)
2131 con
->http
.state
= HTTP_WAITING
;
2138 * 'cupsdSendHeader()' - Send an HTTP request.
2141 int /* O - 1 on success, 0 on failure */
2142 cupsdSendHeader(cupsd_client_t
*con
, /* I - Client to send to */
2143 http_status_t code
, /* I - HTTP status code */
2144 char *type
) /* I - MIME type of document */
2147 * Send the HTTP status header...
2150 if (code
== HTTP_CONTINUE
)
2153 * 100-continue doesn't send any headers...
2156 return (httpPrintf(HTTP(con
), "HTTP/%d.%d 100 Continue\r\n\r\n",
2157 con
->http
.version
/ 100, con
->http
.version
% 100) > 0);
2160 httpFlushWrite(HTTP(con
));
2162 con
->http
.data_encoding
= HTTP_ENCODE_FIELDS
;
2164 if (httpPrintf(HTTP(con
), "HTTP/%d.%d %d %s\r\n", con
->http
.version
/ 100,
2165 con
->http
.version
% 100, code
, httpStatus(code
)) < 0)
2167 if (httpPrintf(HTTP(con
), "Date: %s\r\n", httpGetDateString(time(NULL
))) < 0)
2170 if (httpPrintf(HTTP(con
), "Server: %s\r\n", ServerHeader
) < 0)
2172 if (con
->http
.keep_alive
&& con
->http
.version
>= HTTP_1_0
)
2174 if (httpPrintf(HTTP(con
), "Connection: Keep-Alive\r\n") < 0)
2176 if (httpPrintf(HTTP(con
), "Keep-Alive: timeout=%d\r\n",
2177 KeepAliveTimeout
) < 0)
2180 if (code
== HTTP_METHOD_NOT_ALLOWED
)
2181 if (httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST\r\n") < 0)
2184 if (code
== HTTP_UNAUTHORIZED
)
2186 int auth_type
; /* Authentication type */
2189 if (!con
->best
|| con
->best
->type
== AUTH_NONE
)
2190 auth_type
= DefaultAuthType
;
2192 auth_type
= con
->best
->type
;
2194 if (auth_type
!= AUTH_DIGEST
)
2196 if (httpPrintf(HTTP(con
),
2197 "WWW-Authenticate: Basic realm=\"CUPS\"\r\n") < 0)
2202 if (httpPrintf(HTTP(con
),
2203 "WWW-Authenticate: Digest realm=\"CUPS\", nonce=\"%s\"\r\n",
2204 con
->http
.hostname
) < 0)
2209 if (con
->language
&& strcmp(con
->language
->language
, "C"))
2211 if (httpPrintf(HTTP(con
), "Content-Language: %s\r\n",
2212 con
->language
->language
) < 0)
2218 if (!strcmp(type
, "text/html"))
2220 if (httpPrintf(HTTP(con
),
2221 "Content-Type: text/html; charset=utf-8\r\n") < 0)
2224 else if (httpPrintf(HTTP(con
), "Content-Type: %s\r\n", type
) < 0)
2233 * 'cupsdUpdateCGI()' - Read status messages from CGI scripts and programs.
2237 cupsdUpdateCGI(void)
2239 char *ptr
, /* Pointer to end of line in buffer */
2240 message
[1024]; /* Pointer to message text */
2241 int loglevel
; /* Log level for message */
2244 while ((ptr
= cupsdStatBufUpdate(CGIStatusBuffer
, &loglevel
,
2245 message
, sizeof(message
))) != NULL
)
2246 if (!strchr(CGIStatusBuffer
->buffer
, '\n'))
2249 if (ptr
== NULL
&& !CGIStatusBuffer
->bufused
)
2252 * Fatal error on pipe - should never happen!
2255 cupsdLogMessage(CUPSD_LOG_CRIT
,
2256 "cupsdUpdateCGI: error reading from CGI error pipe - %s",
2263 * 'cupsdWriteClient()' - Write data to a client as needed.
2266 int /* O - 1 if success, 0 if fail */
2267 cupsdWriteClient(cupsd_client_t
*con
) /* I - Client connection */
2269 int bytes
; /* Number of bytes written */
2270 char buf
[16385]; /* Data buffer */
2271 char *bufptr
; /* Pointer into buffer */
2272 ipp_state_t ipp_state
; /* IPP state value */
2276 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2277 "cupsdWriteClient(con=%p) %d response=%p, file=%d "
2278 "pipe_pid=%d state=%d",
2279 con
, con
->http
.fd
, con
->response
, con
->file
, con
->pipe_pid
,
2283 if (con
->http
.state
!= HTTP_GET_SEND
&&
2284 con
->http
.state
!= HTTP_POST_SEND
)
2289 ipp_state
= ippWrite(HTTP(con
), con
->response
);
2290 bytes
= ipp_state
!= IPP_ERROR
&& ipp_state
!= IPP_DATA
;
2292 else if ((bytes
= read(con
->file
, buf
, sizeof(buf
) - 1)) > 0)
2294 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2295 "cupsdWriteClient: Read %d bytes from file %d...",
2298 if (con
->pipe_pid
&& !con
->got_fields
)
2301 * Inspect the data for Content-Type and other fields.
2306 for (bufptr
= buf
; !con
->got_fields
&& *bufptr
; bufptr
++)
2307 if (*bufptr
== '\n')
2310 * Send line to client...
2313 if (bufptr
> buf
&& bufptr
[-1] == '\r')
2317 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "Script header: %s", buf
);
2319 if (!con
->sent_header
)
2322 * Handle redirection and CGI status codes...
2325 if (!strncasecmp(buf
, "Location:", 9))
2327 cupsdSendHeader(con
, HTTP_SEE_OTHER
, NULL
);
2328 con
->sent_header
= 2;
2330 if (httpPrintf(HTTP(con
), "Content-Length: 0\r\n") < 0)
2333 else if (!strncasecmp(buf
, "Status:", 7))
2335 cupsdSendError(con
, (http_status_t
)atoi(buf
+ 7));
2336 con
->sent_header
= 2;
2340 cupsdSendHeader(con
, HTTP_OK
, NULL
);
2341 con
->sent_header
= 1;
2343 if (con
->http
.version
== HTTP_1_1
)
2345 if (httpPrintf(HTTP(con
), "Transfer-Encoding: chunked\r\n") < 0)
2351 if (strncasecmp(buf
, "Status:", 7))
2352 httpPrintf(HTTP(con
), "%s\r\n", buf
);
2354 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdWriteClient: %d %s",
2361 bytes
-= (bufptr
- buf
);
2362 memmove(buf
, bufptr
, bytes
+ 1);
2366 * See if the line was empty...
2369 if (con
->field_col
== 0)
2371 con
->got_fields
= 1;
2373 if (cupsdFlushHeader(con
) < 0)
2375 cupsdCloseClient(con
);
2379 if (con
->http
.version
== HTTP_1_1
)
2380 con
->http
.data_encoding
= HTTP_ENCODE_CHUNKED
;
2385 else if (*bufptr
!= '\r')
2388 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2389 "cupsdWriteClient: %d bytes=%d, got_fields=%d",
2390 con
->http
.fd
, bytes
, con
->got_fields
);
2392 if (bytes
> 0 && !con
->got_fields
)
2395 * Remaining text needs to go out...
2398 httpPrintf(HTTP(con
), "%s", buf
);
2400 con
->http
.activity
= time(NULL
);
2403 else if (bytes
== 0)
2404 con
->http
.activity
= time(NULL
);
2409 if (httpWrite2(HTTP(con
), buf
, bytes
) < 0)
2411 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2412 "cupsdWriteClient: %d Write of %d bytes failed!",
2413 con
->http
.fd
, bytes
);
2415 cupsdCloseClient(con
);
2419 con
->bytes
+= bytes
;
2421 if (con
->http
.state
== HTTP_WAITING
)
2428 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdWriteClient: %d bytes < 0",
2431 cupsdLogRequest(con
, HTTP_OK
);
2433 httpFlushWrite(HTTP(con
));
2435 if (con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
&& con
->sent_header
== 1)
2437 if (httpWrite2(HTTP(con
), "", 0) < 0)
2439 cupsdCloseClient(con
);
2444 con
->http
.state
= HTTP_WAITING
;
2446 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2447 "cupsdWriteClient: Removing fd %d from OutputSet...",
2450 FD_CLR(con
->http
.fd
, OutputSet
);
2454 if (FD_ISSET(con
->file
, InputSet
))
2456 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2457 "cupsdWriteClient: Removing fd %d from InputSet...",
2459 FD_CLR(con
->file
, InputSet
);
2463 cupsdEndProcess(con
->pipe_pid
, 0);
2465 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2466 "cupsdWriteClient: %d Closing data file %d.",
2467 con
->http
.fd
, con
->file
);
2476 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2477 "cupsdWriteClient: %d Removing temp file %s",
2478 con
->http
.fd
, con
->filename
);
2479 unlink(con
->filename
);
2480 cupsdClearString(&con
->filename
);
2485 ippDelete(con
->request
);
2486 con
->request
= NULL
;
2491 ippDelete(con
->response
);
2492 con
->response
= NULL
;
2495 cupsdClearString(&con
->command
);
2496 cupsdClearString(&con
->options
);
2498 if (!con
->http
.keep_alive
)
2500 cupsdCloseClient(con
);
2506 con
->file_ready
= 0;
2508 if (con
->pipe_pid
&& !FD_ISSET(con
->file
, InputSet
))
2510 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2511 "cupsdWriteClient: Adding fd %d to InputSet...",
2513 FD_SET(con
->file
, InputSet
);
2517 con
->http
.activity
= time(NULL
);
2524 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
2527 static int /* O - 1 if modified since */
2529 cupsd_client_t
*con
, /* I - Client connection */
2530 struct stat
*filestats
) /* I - File information */
2532 char *ptr
; /* Pointer into field */
2533 time_t date
; /* Time/date value */
2534 off_t size
; /* Size/length value */
2539 ptr
= con
->http
.fields
[HTTP_FIELD_IF_MODIFIED_SINCE
];
2544 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2545 "check_if_modified: %d If-Modified-Since=\"%s\"",
2548 while (*ptr
!= '\0')
2550 while (isspace(*ptr
) || *ptr
== ';')
2553 if (strncasecmp(ptr
, "length=", 7) == 0)
2556 size
= strtoll(ptr
, NULL
, 10);
2558 while (isdigit(*ptr
))
2561 else if (isalpha(*ptr
))
2563 date
= httpGetDateTime(ptr
);
2564 while (*ptr
!= '\0' && *ptr
!= ';')
2571 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2572 "check_if_modified: %d sizes=" CUPS_LLFMT
","
2573 CUPS_LLFMT
" dates=%d,%d",
2574 con
->http
.fd
, CUPS_LLCAST size
,
2575 CUPS_LLCAST filestats
->st_size
, (int)date
,
2576 (int)filestats
->st_mtime
);
2578 return ((size
!= filestats
->st_size
&& size
!= 0) ||
2579 (date
< filestats
->st_mtime
&& date
!= 0) ||
2580 (size
== 0 && date
== 0));
2586 * 'encrypt_client()' - Enable encryption for the client...
2589 static int /* O - 1 on success, 0 on error */
2590 encrypt_client(cupsd_client_t
*con
) /* I - Client to encrypt */
2593 SSL_CTX
*context
; /* Context for encryption */
2594 SSL
*conn
; /* Connection for encryption */
2595 BIO
*bio
; /* BIO data */
2596 unsigned long error
; /* Error code */
2600 * Verify that we have a certificate...
2603 if (access(ServerKey
, 0) || access(ServerCertificate
, 0))
2606 * Nope, make a self-signed certificate...
2609 if (!make_certificate())
2614 * Create the SSL context and accept the connection...
2617 context
= SSL_CTX_new(SSLv23_server_method());
2619 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
2620 SSL_CTX_use_PrivateKey_file(context
, ServerKey
, SSL_FILETYPE_PEM
);
2621 SSL_CTX_use_certificate_file(context
, ServerCertificate
, SSL_FILETYPE_PEM
);
2623 bio
= BIO_new(_httpBIOMethods());
2624 BIO_ctrl(bio
, BIO_C_SET_FILE_PTR
, 0, (char *)HTTP(con
));
2626 conn
= SSL_new(context
);
2627 SSL_set_bio(conn
, bio
, bio
);
2629 if (SSL_accept(conn
) != 1)
2631 cupsdLogMessage(CUPSD_LOG_ERROR
,
2632 "encrypt_client: Unable to encrypt connection from %s!",
2633 con
->http
.hostname
);
2635 while ((error
= ERR_get_error()) != 0)
2636 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s",
2637 ERR_error_string(error
, NULL
));
2639 SSL_CTX_free(context
);
2644 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2645 "encrypt_client: %d Connection from %s now encrypted.",
2646 con
->http
.fd
, con
->http
.hostname
);
2648 con
->http
.tls
= conn
;
2651 # elif defined(HAVE_GNUTLS)
2652 http_tls_t
*conn
; /* TLS session object */
2653 int error
; /* Error code */
2654 gnutls_certificate_server_credentials
*credentials
;
2655 /* TLS credentials */
2659 * Verify that we have a certificate...
2662 if (access(ServerKey
, 0) || access(ServerCertificate
, 0))
2665 * Nope, make a self-signed certificate...
2668 if (!make_certificate())
2673 * Create the SSL object and perform the SSL handshake...
2676 conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
));
2681 credentials
= (gnutls_certificate_server_credentials
*)
2682 malloc(sizeof(gnutls_certificate_server_credentials
));
2683 if (credentials
== NULL
)
2685 cupsdLogMessage(CUPSD_LOG_ERROR
,
2686 "encrypt_client: Unable to encrypt connection from %s!",
2687 con
->http
.hostname
);
2688 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s", strerror(errno
));
2694 gnutls_certificate_allocate_credentials(credentials
);
2695 gnutls_certificate_set_x509_key_file(*credentials
, ServerCertificate
,
2696 ServerKey
, GNUTLS_X509_FMT_PEM
);
2698 gnutls_init(&(conn
->session
), GNUTLS_SERVER
);
2699 gnutls_set_default_priority(conn
->session
);
2700 gnutls_credentials_set(conn
->session
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
2701 gnutls_transport_set_ptr(conn
->session
, (gnutls_transport_ptr
)HTTP(con
));
2702 gnutls_transport_set_pull_function(conn
->session
, _httpReadGNUTLS
);
2703 gnutls_transport_set_push_function(conn
->session
, _httpWriteGNUTLS
);
2705 error
= gnutls_handshake(conn
->session
);
2707 if (error
!= GNUTLS_E_SUCCESS
)
2709 cupsdLogMessage(CUPSD_LOG_ERROR
,
2710 "encrypt_client: Unable to encrypt connection from %s!",
2711 con
->http
.hostname
);
2712 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s",
2713 gnutls_strerror(error
));
2715 gnutls_deinit(conn
->session
);
2716 gnutls_certificate_free_credentials(*credentials
);
2722 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2723 "encrypt_client: %d Connection from %s now encrypted.",
2724 con
->http
.fd
, con
->http
.hostname
);
2726 conn
->credentials
= credentials
;
2727 con
->http
.tls
= conn
;
2730 # elif defined(HAVE_CDSASSL)
2731 OSStatus error
; /* Error code */
2732 http_tls_t
*conn
; /* CDSA connection information */
2735 if ((conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
))) == NULL
)
2739 conn
->session
= NULL
;
2740 conn
->certsArray
= get_cdsa_server_certs();
2742 if (!conn
->certsArray
)
2745 * No keychain (yet), make a self-signed certificate...
2748 if (make_certificate())
2749 conn
->certsArray
= get_cdsa_server_certs();
2752 if (!conn
->certsArray
)
2754 cupsdLogMessage(CUPSD_LOG_ERROR
,
2755 "encrypt_client: Could not find signing key in keychain "
2756 "\"%s\"", ServerCertificate
);
2757 error
= errSSLBadCert
; /* errSSLBadConfiguration is a better choice, but not available on 10.2.x */
2761 error
= SSLNewContext(true, &conn
->session
);
2764 error
= SSLSetIOFuncs(conn
->session
, _httpReadCDSA
, _httpWriteCDSA
);
2767 error
= SSLSetProtocolVersionEnabled(conn
->session
, kSSLProtocol2
, false);
2770 error
= SSLSetConnection(conn
->session
, HTTP(con
));
2773 error
= SSLSetAllowsExpiredCerts(conn
->session
, true);
2776 error
= SSLSetAllowsAnyRoot(conn
->session
, true);
2779 error
= SSLSetCertificate(conn
->session
, conn
->certsArray
);
2784 * Perform SSL/TLS handshake
2787 while ((error
= SSLHandshake(conn
->session
)) == errSSLWouldBlock
)
2793 cupsdLogMessage(CUPSD_LOG_ERROR
,
2794 "encrypt_client: Unable to encrypt connection from %s!",
2795 con
->http
.hostname
);
2797 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s (%d)",
2798 cssmErrorString(error
), (int)error
);
2800 con
->http
.error
= error
;
2801 con
->http
.status
= HTTP_ERROR
;
2804 SSLDisposeContext(conn
->session
);
2806 if (conn
->certsArray
)
2807 CFRelease(conn
->certsArray
);
2814 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2815 "encrypt_client: %d Connection from %s now encrypted.",
2816 con
->http
.fd
, con
->http
.hostname
);
2818 con
->http
.tls
= conn
;
2821 # endif /* HAVE_LIBSSL */
2823 #endif /* HAVE_SSL */
2828 * 'get_cdsa_server_certs()' - Convert a keychain name into the CFArrayRef
2829 * required by SSLSetCertificate.
2831 * For now we assumes that there is exactly one SecIdentity in the
2832 * keychain - i.e. there is exactly one matching cert/private key pair.
2833 * In the future we will search a keychain for a SecIdentity matching a
2834 * specific criteria. We also skip the operation of adding additional
2835 * non-signing certs from the keychain to the CFArrayRef.
2837 * To create a self-signed certificate for testing use the certtool.
2838 * Executing the following as root will do it:
2840 * certtool c k=/Library/Keychains/System.keychain
2843 static CFArrayRef
/* O - Array of certificates */
2844 get_cdsa_server_certs(void)
2846 OSStatus err
; /* Error info */
2847 SecKeychainRef kcRef
; /* Keychain reference */
2848 SecIdentitySearchRef srchRef
; /* Search reference */
2849 SecIdentityRef identity
; /* Identity */
2850 CFArrayRef ca
; /* Certificate array */
2857 err
= SecKeychainOpen(ServerCertificate
, &kcRef
);
2860 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot open keychain \"%s\", error %d.",
2861 ServerCertificate
, (int)err
);
2865 * Search for "any" identity matching specified key use;
2866 * in this app, we expect there to be exactly one.
2869 err
= SecIdentitySearchCreate(kcRef
, CSSM_KEYUSE_SIGN
, &srchRef
);
2872 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2873 "Cannot find signing key in keychain \"%s\", error %d",
2874 ServerCertificate
, (int)err
);
2877 err
= SecIdentitySearchCopyNext(srchRef
, &identity
);
2880 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2881 "Cannot find signing key in keychain \"%s\", error %d",
2882 ServerCertificate
, (int)err
);
2885 if (CFGetTypeID(identity
) != SecIdentityGetTypeID())
2886 cupsdLogMessage(CUPSD_LOG_ERROR
,
2887 "SecIdentitySearchCopyNext CFTypeID failure!");
2891 * Found one. Place it in a CFArray.
2892 * TBD: snag other (non-identity) certs from keychain and add them
2896 ca
= CFArrayCreate(NULL
, (const void **)&identity
, 1, &kCFTypeArrayCallBacks
);
2899 cupsdLogMessage(CUPSD_LOG_ERROR
, "CFArrayCreate error");
2902 CFRelease(identity
);
2913 #endif /* HAVE_CDSASSL */
2917 * 'get_file()' - Get a filename and state info.
2920 static char * /* O - Real filename */
2921 get_file(cupsd_client_t
*con
, /* I - Client connection */
2922 struct stat
*filestats
, /* O - File information */
2923 char *filename
, /* IO - Filename buffer */
2924 int len
) /* I - Buffer length */
2926 int status
; /* Status of filesystem calls */
2927 char *ptr
; /* Pointer info filename */
2928 int plen
; /* Remaining length after pointer */
2932 * Need to add DocumentRoot global...
2935 if (!strncmp(con
->uri
, "/ppd/", 5))
2936 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
);
2937 else if (!strncmp(con
->uri
, "/admin/conf/", 12))
2938 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
+ 11);
2939 else if (!strncmp(con
->uri
, "/admin/log/", 11))
2941 if (!strcmp(con
->uri
+ 11, "access_log") && AccessLog
[0] == '/')
2942 strlcpy(filename
, AccessLog
, len
);
2943 else if (!strcmp(con
->uri
+ 11, "error_log") && ErrorLog
[0] == '/')
2944 strlcpy(filename
, ErrorLog
, len
);
2945 else if (!strcmp(con
->uri
+ 11, "page_log") && PageLog
[0] == '/')
2946 strlcpy(filename
, PageLog
, len
);
2950 else if (con
->language
)
2951 snprintf(filename
, len
, "%s/%s%s", DocumentRoot
, con
->language
->language
,
2954 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
2956 if ((ptr
= strchr(filename
, '?')) != NULL
)
2960 * Grab the status for this language; if there isn't a language-specific file
2961 * then fallback to the default one...
2964 if ((status
= stat(filename
, filestats
)) != 0 && con
->language
&&
2965 strncmp(con
->uri
, "/ppd/", 5) &&
2966 strncmp(con
->uri
, "/admin/conf/", 12) &&
2967 strncmp(con
->uri
, "/admin/log/", 11))
2970 * Drop the country code...
2973 char ll
[3]; /* Short language name */
2976 strlcpy(ll
, con
->language
->language
, sizeof(ll
));
2977 snprintf(filename
, len
, "%s/%s%s", DocumentRoot
, ll
, con
->uri
);
2979 if ((ptr
= strchr(filename
, '?')) != NULL
)
2982 if ((status
= stat(filename
, filestats
)) != 0)
2985 * Drop the language prefix and try the root directory...
2988 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
2990 if ((ptr
= strchr(filename
, '?')) != NULL
)
2993 status
= stat(filename
, filestats
);
2998 * If we're found a directory, get the index.html file instead...
3001 if (!status
&& S_ISDIR(filestats
->st_mode
))
3003 if (filename
[strlen(filename
) - 1] != '/')
3004 strlcat(filename
, "/", len
);
3006 ptr
= filename
+ strlen(filename
);
3007 plen
= len
- (ptr
- filename
);
3009 strlcpy(ptr
, "index.html", plen
);
3010 status
= stat(filename
, filestats
);
3015 strlcpy(ptr
, "index.class", plen
);
3016 status
= stat(filename
, filestats
);
3018 #endif /* HAVE_JAVA */
3023 strlcpy(ptr
, "index.pl", plen
);
3024 status
= stat(filename
, filestats
);
3026 #endif /* HAVE_PERL */
3031 strlcpy(ptr
, "index.php", plen
);
3032 status
= stat(filename
, filestats
);
3034 #endif /* HAVE_PHP */
3039 strlcpy(ptr
, "index.pyc", plen
);
3040 status
= stat(filename
, filestats
);
3045 strlcpy(ptr
, "index.py", plen
);
3046 status
= stat(filename
, filestats
);
3048 #endif /* HAVE_PYTHON */
3051 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "get_file: %d filename=%s size=%d",
3052 con
->http
.fd
, filename
,
3053 status
? -1 : (int)filestats
->st_size
);
3056 con
->http
.data_remaining
= (int)filestats
->st_size
;
3066 * 'install_conf_file()' - Install a configuration file.
3069 static http_status_t
/* O - Status */
3070 install_conf_file(cupsd_client_t
*con
) /* I - Connection */
3072 cups_file_t
*in
, /* Input file */
3073 *out
; /* Output file */
3074 char buffer
[1024]; /* Copy buffer */
3075 int bytes
; /* Number of bytes */
3076 char conffile
[1024], /* Configuration filename */
3077 newfile
[1024], /* New config filename */
3078 oldfile
[1024]; /* Old config filename */
3079 struct stat confinfo
; /* Config file info */
3083 * First construct the filenames...
3086 snprintf(conffile
, sizeof(conffile
), "%s%s", ServerRoot
, con
->uri
+ 11);
3087 snprintf(newfile
, sizeof(newfile
), "%s%s.N", ServerRoot
, con
->uri
+ 11);
3088 snprintf(oldfile
, sizeof(oldfile
), "%s%s.O", ServerRoot
, con
->uri
+ 11);
3090 cupsdLogMessage(CUPSD_LOG_INFO
, "Installing config file \"%s\"...", conffile
);
3093 * Get the owner, group, and permissions of the configuration file.
3094 * If it doesn't exist, assign it to the User and Group in the
3095 * cupsd.conf file with mode 0640 permissions.
3098 if (stat(conffile
, &confinfo
))
3100 confinfo
.st_uid
= User
;
3101 confinfo
.st_gid
= Group
;
3102 confinfo
.st_mode
= ConfigFilePerm
;
3106 * Open the request file and new config file...
3109 if ((in
= cupsFileOpen(con
->filename
, "rb")) == NULL
)
3111 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open request file \"%s\" - %s",
3112 con
->filename
, strerror(errno
));
3113 return (HTTP_SERVER_ERROR
);
3116 if ((out
= cupsFileOpen(newfile
, "wb")) == NULL
)
3119 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open config file \"%s\" - %s",
3120 newfile
, strerror(errno
));
3121 return (HTTP_SERVER_ERROR
);
3124 fchmod(cupsFileNumber(out
), confinfo
.st_mode
);
3125 fchown(cupsFileNumber(out
), confinfo
.st_uid
, confinfo
.st_gid
);
3128 * Copy from the request to the new config file...
3131 while ((bytes
= cupsFileRead(in
, buffer
, sizeof(buffer
))) > 0)
3132 if (cupsFileWrite(out
, buffer
, bytes
) < bytes
)
3134 cupsdLogMessage(CUPSD_LOG_ERROR
,
3135 "Unable to copy to config file \"%s\" - %s",
3136 newfile
, strerror(errno
));
3142 return (HTTP_SERVER_ERROR
);
3146 * Close the files...
3150 if (cupsFileClose(out
))
3152 cupsdLogMessage(CUPSD_LOG_ERROR
,
3153 "Error file closing config file \"%s\" - %s",
3154 newfile
, strerror(errno
));
3158 return (HTTP_SERVER_ERROR
);
3162 * Remove the request file...
3165 unlink(con
->filename
);
3166 cupsdClearString(&con
->filename
);
3169 * Unlink the old backup, rename the current config file to the backup
3170 * filename, and rename the new config file to the config file name...
3173 if (unlink(oldfile
))
3174 if (errno
!= ENOENT
)
3176 cupsdLogMessage(CUPSD_LOG_ERROR
,
3177 "Unable to remove backup config file \"%s\" - %s",
3178 oldfile
, strerror(errno
));
3182 return (HTTP_SERVER_ERROR
);
3185 if (rename(conffile
, oldfile
))
3186 if (errno
!= ENOENT
)
3188 cupsdLogMessage(CUPSD_LOG_ERROR
,
3189 "Unable to rename old config file \"%s\" - %s",
3190 conffile
, strerror(errno
));
3194 return (HTTP_SERVER_ERROR
);
3197 if (rename(newfile
, conffile
))
3199 cupsdLogMessage(CUPSD_LOG_ERROR
,
3200 "Unable to rename new config file \"%s\" - %s",
3201 newfile
, strerror(errno
));
3203 rename(oldfile
, conffile
);
3206 return (HTTP_SERVER_ERROR
);
3210 * If the cupsd.conf file was updated, set the NeedReload flag...
3213 if (!strcmp(con
->uri
, "/admin/conf/cupsd.conf"))
3214 NeedReload
= RELOAD_CUPSD
;
3216 NeedReload
= RELOAD_ALL
;
3218 ReloadTime
= time(NULL
);
3221 * Return that the file was created successfully...
3224 return (HTTP_CREATED
);
3229 * 'is_cgi()' - Is the resource a CGI script/program?
3232 static int /* O - 1 = CGI, 0 = file */
3233 is_cgi(cupsd_client_t
*con
, /* I - Client connection */
3234 const char *filename
, /* I - Real filename */
3235 struct stat
*filestats
, /* I - File information */
3236 mime_type_t
*type
) /* I - MIME type */
3238 const char *options
; /* Options on URL */
3241 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3242 "is_cgi(con=%p, filename=\"%s\", filestats=%p, type=%s/%s)\n",
3243 con
, filename
, filestats
, type
? type
->super
: "unknown",
3244 type
? type
->type
: "unknown");
3247 * Get the options, if any...
3250 if ((options
= strchr(con
->uri
, '?')) != NULL
)
3254 * Check for known types...
3257 if (!type
|| strcasecmp(type
->super
, "application"))
3259 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "is_cgi: Returning 0...");
3263 if (!strcasecmp(type
->type
, "x-httpd-cgi") &&
3264 (filestats
->st_mode
& 0111))
3267 * "application/x-httpd-cgi" is a CGI script.
3270 cupsdSetString(&con
->command
, filename
);
3272 filename
= strrchr(filename
, '/') + 1; /* Filename always absolute */
3274 cupsdSetString(&con
->options
, options
);
3276 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3277 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3278 con
->command
, con
->options
);
3283 else if (!strcasecmp(type
->type
, "x-httpd-java"))
3286 * "application/x-httpd-java" is a Java servlet.
3289 cupsdSetString(&con
->command
, CUPS_JAVA
);
3292 cupsdSetStringf(&con
->options
, "%s %s", filename
, options
);
3294 cupsdSetString(&con
->options
, filename
);
3296 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3297 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3298 con
->command
, con
->options
);
3302 #endif /* HAVE_JAVA */
3304 else if (!strcasecmp(type
->type
, "x-httpd-perl"))
3307 * "application/x-httpd-perl" is a Perl page.
3310 cupsdSetString(&con
->command
, CUPS_PERL
);
3313 cupsdSetStringf(&con
->options
, "%s %s", filename
, options
);
3315 cupsdSetString(&con
->options
, filename
);
3317 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3318 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3319 con
->command
, con
->options
);
3323 #endif /* HAVE_PERL */
3325 else if (!strcasecmp(type
->type
, "x-httpd-php"))
3328 * "application/x-httpd-php" is a PHP page.
3331 cupsdSetString(&con
->command
, CUPS_PHP
);
3334 cupsdSetStringf(&con
->options
, "%s %s", filename
, options
);
3336 cupsdSetString(&con
->options
, filename
);
3338 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3339 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3340 con
->command
, con
->options
);
3344 #endif /* HAVE_PHP */
3346 else if (!strcasecmp(type
->type
, "x-httpd-python"))
3349 * "application/x-httpd-python" is a Python page.
3352 cupsdSetString(&con
->command
, CUPS_PYTHON
);
3355 cupsdSetStringf(&con
->options
, "%s %s", filename
, options
);
3357 cupsdSetString(&con
->options
, filename
);
3359 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3360 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3361 con
->command
, con
->options
);
3365 #endif /* HAVE_PYTHON */
3367 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "is_cgi: Returning 0...");
3374 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
3377 static int /* O - 0 if relative, 1 if absolute */
3378 is_path_absolute(const char *path
) /* I - Input path */
3381 * Check for a leading slash...
3388 * Check for "/.." in the path...
3391 while ((path
= strstr(path
, "/..")) != NULL
)
3393 if (!path
[3] || path
[3] == '/')
3400 * If we haven't found any relative paths, return 1 indicating an
3410 * 'make_certificate()' - Make a self-signed SSL/TLS certificate.
3413 static int /* O - 1 on success, 0 on failure */
3414 make_certificate(void)
3416 #if defined(HAVE_LIBSSL) && defined(HAVE_WAITPID)
3417 int pid
, /* Process ID of command */
3418 status
; /* Status of command */
3419 char command
[1024], /* Command */
3420 *argv
[11], /* Command-line arguments */
3421 *envp
[MAX_ENV
+ 1], /* Environment variables */
3422 home
[1024], /* HOME environment variable */
3423 infofile
[1024], /* Type-in information for cert */
3424 seedfile
[1024]; /* Random number seed file */
3425 int envc
, /* Number of environment variables */
3426 bytes
; /* Bytes written */
3427 cups_file_t
*fp
; /* Seed/info file */
3428 int infofd
; /* Info file descriptor */
3432 * Run the "openssl" command to seed the random number generator and
3433 * generate a self-signed certificate that is good for 10 years:
3435 * openssl rand -rand seedfile 1
3437 * openssl req -new -x509 -keyout ServerKey \
3438 * -out ServerCertificate -days 3650 -nodes
3440 * The seeding step is crucial in ensuring that the openssl command
3441 * does not block on systems without sufficient entropy...
3444 if (!cupsFileFind("openssl", getenv("PATH"), 1, command
, sizeof(command
)))
3446 cupsdLogMessage(CUPSD_LOG_ERROR
,
3447 "No SSL certificate and openssl command not found!");
3451 if (access("/dev/urandom", 0))
3454 * If the system doesn't provide /dev/urandom, then any random source
3455 * will probably be blocking-style, so generate some random data to
3456 * use as a seed for the certificate. Note that we have already
3457 * seeded the random number generator in cupsdInitCerts()...
3460 cupsdLogMessage(CUPSD_LOG_INFO
,
3461 "Seeding the random number generator...");
3463 snprintf(home
, sizeof(home
), "HOME=%s", TempDir
);
3466 * Write the seed file...
3469 if ((fp
= cupsTempFile2(seedfile
, sizeof(seedfile
))) == NULL
)
3471 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to create seed file %s - %s",
3472 seedfile
, strerror(errno
));
3476 for (bytes
= 0; bytes
< 262144; bytes
++)
3477 cupsFilePutChar(fp
, random());
3482 * Run the openssl command to seed its random number generator...
3485 argv
[0] = "openssl";
3492 envc
= cupsdLoadEnv(envp
, MAX_ENV
);
3493 envp
[envc
++] = home
;
3496 if (!cupsdStartProcess(command
, argv
, envp
, -1, -1, -1, -1, 1, &pid
))
3502 while (waitpid(pid
, &status
, 0) < 0)
3509 cupsdFinishProcess(pid
, command
, sizeof(command
));
3512 * Remove the seed file, as it is no longer needed...
3519 if (WIFEXITED(status
))
3520 cupsdLogMessage(CUPSD_LOG_ERROR
,
3521 "Unable to seed random number generator - "
3522 "the openssl command stopped with status %d!",
3523 WEXITSTATUS(status
));
3525 cupsdLogMessage(CUPSD_LOG_ERROR
,
3526 "Unable to seed random number generator - "
3527 "the openssl command crashed on signal %d!",
3535 * Create a file with the certificate information fields...
3537 * Note: This assumes that the default questions are asked by the openssl
3541 if ((fp
= cupsTempFile2(infofile
, sizeof(infofile
))) == NULL
)
3543 cupsdLogMessage(CUPSD_LOG_ERROR
,
3544 "Unable to create certificate information file %s - %s",
3545 infofile
, strerror(errno
));
3549 cupsFilePrintf(fp
, ".\n.\n.\n%s\n.\n%s\n%s\n",
3550 ServerName
, ServerName
, ServerAdmin
);
3553 cupsdLogMessage(CUPSD_LOG_INFO
,
3554 "Generating SSL server key and certificate...");
3556 argv
[0] = "openssl";
3560 argv
[4] = "-keyout";
3561 argv
[5] = ServerKey
;
3563 argv
[7] = ServerCertificate
;
3566 argv
[10] = "-nodes";
3569 cupsdLoadEnv(envp
, MAX_ENV
);
3571 infofd
= open(infofile
, O_RDONLY
);
3573 if (!cupsdStartProcess(command
, argv
, envp
, infofd
, -1, -1, -1, 1, &pid
))
3583 while (waitpid(pid
, &status
, 0) < 0)
3590 cupsdFinishProcess(pid
, command
, sizeof(command
));
3594 if (WIFEXITED(status
))
3595 cupsdLogMessage(CUPSD_LOG_ERROR
,
3596 "Unable to create SSL server key and certificate - "
3597 "the openssl command stopped with status %d!",
3598 WEXITSTATUS(status
));
3600 cupsdLogMessage(CUPSD_LOG_ERROR
,
3601 "Unable to create SSL server key and certificate - "
3602 "the openssl command crashed on signal %d!",
3607 cupsdLogMessage(CUPSD_LOG_INFO
, "Created SSL server key file \"%s\"...",
3609 cupsdLogMessage(CUPSD_LOG_INFO
,
3610 "Created SSL server certificate file \"%s\"...",
3616 #elif defined(HAVE_GNUTLS)
3617 gnutls_x509_crt crt
; /* Self-signed certificate */
3618 gnutls_x509_privkey key
; /* Encryption key */
3619 cups_lang_t
*language
; /* Default language info */
3620 cups_file_t
*fp
; /* Key/cert file */
3621 unsigned char buffer
[8192]; /* Buffer for x509 data */
3622 size_t bytes
; /* Number of bytes of data */
3623 unsigned char serial
[4]; /* Serial number buffer */
3624 time_t curtime
; /* Current time */
3625 int result
; /* Result of GNU TLS calls */
3629 * Create the encryption key...
3632 cupsdLogMessage(CUPSD_LOG_INFO
, "Generating SSL server key...");
3634 gnutls_x509_privkey_init(&key
);
3635 gnutls_x509_privkey_generate(key
, GNUTLS_PK_RSA
, 2048, 0);
3641 bytes
= sizeof(buffer
);
3643 if ((result
= gnutls_x509_privkey_export(key
, GNUTLS_X509_FMT_PEM
,
3644 buffer
, &bytes
)) < 0)
3646 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to export SSL server key - %s",
3647 gnutls_strerror(result
));
3648 gnutls_x509_privkey_deinit(key
);
3651 else if ((fp
= cupsFileOpen(ServerKey
, "w")) != NULL
)
3653 cupsFileWrite(fp
, (char *)buffer
, bytes
);
3656 cupsdLogMessage(CUPSD_LOG_INFO
, "Created SSL server key file \"%s\"...",
3661 cupsdLogMessage(CUPSD_LOG_ERROR
,
3662 "Unable to create SSL server key file \"%s\" - %s",
3663 ServerKey
, strerror(errno
));
3664 gnutls_x509_privkey_deinit(key
);
3669 * Create the self-signed certificate...
3672 cupsdLogMessage(CUPSD_LOG_INFO
, "Generating self-signed SSL certificate...");
3674 language
= cupsLangDefault();
3675 curtime
= time(NULL
);
3676 serial
[0] = curtime
>> 24;
3677 serial
[1] = curtime
>> 16;
3678 serial
[2] = curtime
>> 8;
3679 serial
[3] = curtime
;
3681 gnutls_x509_crt_init(&crt
);
3682 if (strlen(language
->language
) == 5)
3683 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
3684 language
->language
+ 3, 2);
3686 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
3688 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COMMON_NAME
, 0,
3689 ServerName
, strlen(ServerName
));
3690 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATION_NAME
, 0,
3691 ServerName
, strlen(ServerName
));
3692 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATIONAL_UNIT_NAME
,
3694 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_STATE_OR_PROVINCE_NAME
, 0,
3696 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_LOCALITY_NAME
, 0,
3698 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_PKCS9_EMAIL
, 0,
3699 ServerAdmin
, strlen(ServerAdmin
));
3700 gnutls_x509_crt_set_key(crt
, key
);
3701 gnutls_x509_crt_set_serial(crt
, serial
, sizeof(serial
));
3702 gnutls_x509_crt_set_activation_time(crt
, curtime
);
3703 gnutls_x509_crt_set_expiration_time(crt
, curtime
+ 10 * 365 * 86400);
3704 gnutls_x509_crt_set_ca_status(crt
, 0);
3705 gnutls_x509_crt_set_subject_alternative_name(crt
, GNUTLS_SAN_DNSNAME
,
3707 gnutls_x509_crt_set_key_purpose_oid(crt
, GNUTLS_KP_TLS_WWW_SERVER
, 0);
3708 gnutls_x509_crt_set_key_usage(crt
, GNUTLS_KEY_KEY_ENCIPHERMENT
);
3709 gnutls_x509_crt_set_version(crt
, 3);
3711 bytes
= sizeof(buffer
);
3712 if (gnutls_x509_crt_get_key_id(crt
, 0, buffer
, &bytes
) >= 0)
3713 gnutls_x509_crt_set_subject_key_id(crt
, buffer
, bytes
);
3715 gnutls_x509_crt_sign(crt
, crt
, key
);
3721 bytes
= sizeof(buffer
);
3722 if ((result
= gnutls_x509_crt_export(crt
, GNUTLS_X509_FMT_PEM
,
3723 buffer
, &bytes
)) < 0)
3724 cupsdLogMessage(CUPSD_LOG_ERROR
,
3725 "Unable to export SSL server certificate - %s",
3726 gnutls_strerror(result
));
3727 else if ((fp
= cupsFileOpen(ServerCertificate
, "w")) != NULL
)
3729 cupsFileWrite(fp
, (char *)buffer
, bytes
);
3732 cupsdLogMessage(CUPSD_LOG_INFO
,
3733 "Created SSL server certificate file \"%s\"...",
3737 cupsdLogMessage(CUPSD_LOG_ERROR
,
3738 "Unable to create SSL server certificate file \"%s\" - %s",
3739 ServerCertificate
, strerror(errno
));
3745 gnutls_x509_crt_deinit(crt
);
3746 gnutls_x509_privkey_deinit(key
);
3750 #elif defined(HAVE_CDSASSL) && defined(HAVE_WAITPID)
3751 int pid
, /* Process ID of command */
3752 status
; /* Status of command */
3753 char command
[1024], /* Command */
3754 keychain
[1024], /* Keychain argument */
3755 *argv
[5], /* Command-line arguments */
3756 *envp
[MAX_ENV
]; /* Environment variables */
3760 * Run the "certtool" command to generate a self-signed certificate:
3762 * certtool c Z k=ServerCertificate
3765 if (!cupsFileFind("certtool", getenv("PATH"), 1, command
, sizeof(command
)))
3767 cupsdLogMessage(CUPSD_LOG_ERROR
,
3768 "No SSL certificate and certtool command not found!");
3772 cupsdLogMessage(CUPSD_LOG_INFO
,
3773 "Generating SSL server key and certificate...");
3775 snprintf(keychain
, sizeof(keychain
), "k=%s", ServerCertificate
);
3777 argv
[0] = "certtool";
3783 cupsdLoadEnv(envp
, MAX_ENV
);
3785 if (!cupsdStartProcess(command
, argv
, envp
, -1, -1, -1, -1, 1, &pid
))
3788 while (waitpid(pid
, &status
, 0) < 0)
3795 cupsdFinishProcess(pid
, command
, sizeof(command
));
3799 if (WIFEXITED(status
))
3800 cupsdLogMessage(CUPSD_LOG_ERROR
,
3801 "Unable to create SSL server key and certificate - "
3802 "the certtool command stopped with status %d!",
3803 WEXITSTATUS(status
));
3805 cupsdLogMessage(CUPSD_LOG_ERROR
,
3806 "Unable to create SSL server key and certificate - "
3807 "the certtool command crashed on signal %d!",
3812 cupsdLogMessage(CUPSD_LOG_INFO
,
3813 "Created SSL server certificate file \"%s\"...",
3821 #endif /* HAVE_LIBSSL && HAVE_WAITPID */
3823 #endif /* HAVE_SSL */
3827 * 'pipe_command()' - Pipe the output of a command to the remote client.
3830 static int /* O - Process ID */
3831 pipe_command(cupsd_client_t
*con
, /* I - Client connection */
3832 int infile
, /* I - Standard input for command */
3833 int *outfile
, /* O - Standard output for command */
3834 char *command
, /* I - Command to run */
3835 char *options
, /* I - Options for command */
3836 int root
) /* I - Run as root? */
3838 int i
; /* Looping var */
3839 int pid
; /* Process ID */
3840 char *commptr
, /* Command string pointer */
3841 commch
; /* Command string character */
3842 char *uriptr
; /* URI string pointer */
3843 int fds
[2]; /* Pipe FDs */
3844 int argc
; /* Number of arguments */
3845 int envc
; /* Number of environment variables */
3846 char argbuf
[10240], /* Argument buffer */
3847 *argv
[100], /* Argument strings */
3848 *envp
[MAX_ENV
+ 17]; /* Environment variables */
3849 char content_length
[1024], /* CONTENT_LENGTH environment variable */
3850 content_type
[1024], /* CONTENT_TYPE environment variable */
3851 http_cookie
[32768], /* HTTP_COOKIE environment variable */
3852 http_user_agent
[1024], /* HTTP_USER_AGENT environment variable */
3853 lang
[1024], /* LANG environment variable */
3854 path_info
[1024], /* PATH_INFO environment variable */
3855 *query_string
, /* QUERY_STRING env variable */
3856 remote_addr
[1024], /* REMOTE_ADDR environment variable */
3857 remote_host
[1024], /* REMOTE_HOST environment variable */
3858 remote_user
[1024], /* REMOTE_USER environment variable */
3859 script_name
[1024], /* SCRIPT_NAME environment variable */
3860 server_name
[1024], /* SERVER_NAME environment variable */
3861 server_port
[1024]; /* SERVER_PORT environment variable */
3865 * Parse a copy of the options string, which is of the form:
3867 * argument+argument+argument
3868 * ?argument+argument+argument
3869 * param=value¶m=value
3870 * ?param=value¶m=value
3871 * /name?argument+argument+argument
3872 * /name?param=value¶m=value
3874 * If the string contains an "=" character after the initial name,
3875 * then we treat it as a HTTP GET form request and make a copy of
3876 * the remaining string for the environment variable.
3878 * The string is always parsed out as command-line arguments, to
3879 * be consistent with Apache...
3882 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3883 "pipe_command: command=\"%s\", options=\"%s\"",
3884 command
, options
? options
: "(null)");
3887 query_string
= NULL
;
3890 strlcpy(argbuf
, options
, sizeof(argbuf
));
3894 if (argbuf
[0] == '/')
3897 * Found some trailing path information, set PATH_INFO...
3900 if ((commptr
= strchr(argbuf
, '?')) == NULL
)
3901 commptr
= argbuf
+ strlen(argbuf
);
3905 snprintf(path_info
, sizeof(path_info
), "PATH_INFO=%s", argbuf
);
3911 path_info
[0] = '\0';
3914 if (*commptr
== '?' && con
->operation
== HTTP_GET
)
3917 cupsdSetStringf(&query_string
, "QUERY_STRING=%s", commptr
);
3924 argv
[argc
++] = commptr
;
3926 for (; *commptr
&& argc
< 99; commptr
++)
3929 * Break arguments whenever we see a + or space...
3932 if (*commptr
== ' ' || *commptr
== '+')
3934 while (*commptr
== ' ' || *commptr
== '+')
3938 * If we don't have a blank string, save it as another argument...
3943 argv
[argc
] = commptr
;
3949 else if (*commptr
== '%' && isxdigit(commptr
[1] & 255) &&
3950 isxdigit(commptr
[2] & 255))
3953 * Convert the %xx notation to the individual character.
3956 if (commptr
[1] >= '0' && commptr
[1] <= '9')
3957 *commptr
= (commptr
[1] - '0') << 4;
3959 *commptr
= (tolower(commptr
[1]) - 'a' + 10) << 4;
3961 if (commptr
[2] >= '0' && commptr
[2] <= '9')
3962 *commptr
|= commptr
[2] - '0';
3964 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
3966 _cups_strcpy(commptr
+ 1, commptr
+ 3);
3969 * Check for a %00 and break if that is the case...
3981 * Setup the environment variables as needed...
3985 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF-8", con
->language
->language
);
3987 strcpy(lang
, "LANG=C");
3989 strcpy(remote_addr
, "REMOTE_ADDR=");
3990 httpAddrString(con
->http
.hostaddr
, remote_addr
+ 12,
3991 sizeof(remote_addr
) - 12);
3993 snprintf(remote_host
, sizeof(remote_host
), "REMOTE_HOST=%s",
3994 con
->http
.hostname
);
3996 snprintf(script_name
, sizeof(script_name
), "SCRIPT_NAME=%s", con
->uri
);
3997 if ((uriptr
= strchr(script_name
, '?')) != NULL
)
4000 sprintf(server_port
, "SERVER_PORT=%d", con
->serverport
);
4002 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
4005 envc
= cupsdLoadEnv(envp
, (int)(sizeof(envp
) / sizeof(envp
[0])));
4007 envp
[envc
++] = lang
;
4008 envp
[envc
++] = "REDIRECT_STATUS=1";
4009 envp
[envc
++] = server_name
;
4010 envp
[envc
++] = server_port
;
4011 envp
[envc
++] = remote_addr
;
4012 envp
[envc
++] = remote_host
;
4013 envp
[envc
++] = script_name
;
4016 envp
[envc
++] = path_info
;
4018 if (con
->username
[0])
4020 snprintf(remote_user
, sizeof(remote_user
), "REMOTE_USER=%s", con
->username
);
4022 envp
[envc
++] = remote_user
;
4025 if (con
->http
.version
== HTTP_1_1
)
4026 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.1";
4027 else if (con
->http
.version
== HTTP_1_0
)
4028 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.0";
4030 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/0.9";
4032 if (con
->http
.cookie
)
4034 snprintf(http_cookie
, sizeof(http_cookie
), "HTTP_COOKIE=%s",
4036 envp
[envc
++] = http_cookie
;
4039 if (con
->http
.fields
[HTTP_FIELD_USER_AGENT
][0])
4041 snprintf(http_user_agent
, sizeof(http_user_agent
), "HTTP_USER_AGENT=%s",
4042 con
->http
.fields
[HTTP_FIELD_USER_AGENT
]);
4043 envp
[envc
++] = http_user_agent
;
4046 if (con
->operation
== HTTP_GET
)
4048 for (i
= 0; i
< argc
; i
++)
4049 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "argv[%d] = \"%s\"", i
, argv
[i
]);
4051 envp
[envc
++] = "REQUEST_METHOD=GET";
4056 * Add GET form variables after ?...
4059 envp
[envc
++] = query_string
;
4064 sprintf(content_length
, "CONTENT_LENGTH=" CUPS_LLFMT
,
4065 CUPS_LLCAST con
->bytes
);
4066 snprintf(content_type
, sizeof(content_type
), "CONTENT_TYPE=%s",
4067 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
4069 envp
[envc
++] = "REQUEST_METHOD=POST";
4070 envp
[envc
++] = content_length
;
4071 envp
[envc
++] = content_type
;
4075 * Tell the CGI if we are using encryption...
4079 envp
[envc
++] = "HTTPS=ON";
4082 * Terminate the environment array...
4087 if (LogLevel
== CUPSD_LOG_DEBUG2
)
4089 for (i
= 0; i
< argc
; i
++)
4090 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4091 "pipe_command: argv[%d] = \"%s\"", i
, argv
[i
]);
4092 for (i
= 0; i
< envc
; i
++)
4093 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4094 "pipe_command: envp[%d] = \"%s\"", i
, envp
[i
]);
4098 * Create a pipe for the output...
4101 if (cupsdOpenPipe(fds
))
4103 cupsdClearString(&query_string
);
4105 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to create pipes for CGI %s - %s",
4106 argv
[0], strerror(errno
));
4111 * Then execute the command...
4114 if (cupsdStartProcess(command
, argv
, envp
, infile
, fds
[1], CGIPipes
[1],
4115 -1, root
, &pid
) < 0)
4118 * Error - can't fork!
4121 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to fork for CGI %s - %s", argv
[0],
4124 cupsdClosePipe(fds
);
4130 * Fork successful - return the PID...
4133 if (con
->username
[0])
4134 cupsdAddCert(pid
, con
->username
);
4136 cupsdLogMessage(CUPSD_LOG_DEBUG
, "CGI %s started - PID = %d", command
, pid
);
4142 cupsdClearString(&query_string
);
4149 * 'write_file()' - Send a file via HTTP.
4152 static int /* O - 0 on failure, 1 on success */
4153 write_file(cupsd_client_t
*con
, /* I - Client connection */
4154 http_status_t code
, /* I - HTTP status */
4155 char *filename
, /* I - Filename */
4156 char *type
, /* I - File type */
4157 struct stat
*filestats
) /* O - File information */
4159 con
->file
= open(filename
, O_RDONLY
);
4161 cupsdLogMessage(CUPSD_LOG_DEBUG
, "write_file: %d file=%d", con
->http
.fd
,
4167 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
4171 if (!cupsdSendHeader(con
, code
, type
))
4174 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
4175 httpGetDateString(filestats
->st_mtime
)) < 0)
4177 if (httpPrintf(HTTP(con
), "Content-Length: " CUPS_LLFMT
"\r\n",
4178 CUPS_LLCAST filestats
->st_size
) < 0)
4180 if (httpPrintf(HTTP(con
), "\r\n") < 0)
4183 if (cupsdFlushHeader(con
) < 0)
4186 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
4187 con
->http
.data_remaining
= filestats
->st_size
;
4189 if (con
->http
.data_remaining
<= INT_MAX
)
4190 con
->http
._data_remaining
= con
->http
.data_remaining
;
4192 con
->http
._data_remaining
= INT_MAX
;
4194 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4195 "write_file: Adding fd %d to OutputSet...", con
->http
.fd
);
4197 FD_SET(con
->http
.fd
, OutputSet
);
4204 * End of "$Id: client.c 6111 2006-11-15 20:28:39Z mike $".