2 * "$Id: client.c 7950 2008-09-17 00:21:59Z mike $"
4 * Client routines for the CUPS scheduler.
6 * Copyright 2007-2011 by Apple Inc.
7 * Copyright 1997-2007 by Easy Software Products, all rights reserved.
9 * This file contains Kerberos support code, copyright 2006 by
12 * These coded instructions, statements, and computer programs are the
13 * property of Apple Inc. and are protected by Federal copyright
14 * law. Distribution and use rights are outlined in the file "LICENSE.txt"
15 * which should have been included with this file. If this file is
16 * file is missing or damaged, see the license at "http://www.cups.org/".
20 * cupsdAcceptClient() - Accept a new client.
21 * cupsdCloseAllClients() - Close all remote clients immediately.
22 * cupsdCloseClient() - Close a remote client.
23 * cupsdFlushHeader() - Flush the header fields to the client.
24 * cupsdReadClient() - Read data from a client.
25 * cupsdSendCommand() - Send output from a command via HTTP.
26 * cupsdSendError() - Send an error message via HTTP.
27 * cupsdSendHeader() - Send an HTTP request.
28 * cupsdUpdateCGI() - Read status messages from CGI scripts and
30 * cupsdWriteClient() - Write data to a client as needed.
31 * check_if_modified() - Decode an "If-Modified-Since" line.
32 * compare_clients() - Compare two client connections.
33 * copy_cdsa_certificate() - Copy a SSL/TLS certificate from the System
35 * data_ready() - Check whether data is available from a client.
36 * encrypt_client() - Enable encryption for the client...
37 * get_file() - Get a filename and state info.
38 * install_conf_file() - Install a configuration file.
39 * is_cgi() - Is the resource a CGI script/program?
40 * is_path_absolute() - Is a path absolute and free of relative elements
42 * make_certificate() - Make a self-signed SSL/TLS certificate.
43 * pipe_command() - Pipe the output of a command to the remote
45 * valid_host() - Is the Host: field valid?
46 * write_file() - Send a file via HTTP.
47 * write_pipe() - Flag that data is available on the CGI pipe.
51 * Include necessary headers...
58 #endif /* HAVE_TCPD_H */
65 static const char * const http_states
[] =
66 { /* HTTP state strings */
82 static const char * const ipp_states
[] =
83 { /* IPP state strings */
95 static int check_if_modified(cupsd_client_t
*con
,
96 struct stat
*filestats
);
97 static int compare_clients(cupsd_client_t
*a
, cupsd_client_t
*b
,
100 static CFArrayRef
copy_cdsa_certificate(cupsd_client_t
*con
);
101 #endif /* HAVE_CDSASSL */
102 static int data_ready(cupsd_client_t
*con
);
104 static int encrypt_client(cupsd_client_t
*con
);
105 #endif /* HAVE_SSL */
106 static char *get_file(cupsd_client_t
*con
, struct stat
*filestats
,
107 char *filename
, int len
);
108 static http_status_t
install_conf_file(cupsd_client_t
*con
);
109 static int is_cgi(cupsd_client_t
*con
, const char *filename
,
110 struct stat
*filestats
, mime_type_t
*type
);
111 static int is_path_absolute(const char *path
);
113 static int make_certificate(cupsd_client_t
*con
);
114 #endif /* HAVE_SSL */
115 static int pipe_command(cupsd_client_t
*con
, int infile
, int *outfile
,
116 char *command
, char *options
, int root
);
117 static int valid_host(cupsd_client_t
*con
);
118 static int write_file(cupsd_client_t
*con
, http_status_t code
,
119 char *filename
, char *type
,
120 struct stat
*filestats
);
121 static void write_pipe(cupsd_client_t
*con
);
125 * 'cupsdAcceptClient()' - Accept a new client.
129 cupsdAcceptClient(cupsd_listener_t
*lis
)/* I - Listener socket */
131 int count
; /* Count of connections on a host */
132 int val
; /* Parameter value */
133 cupsd_client_t
*con
, /* New client pointer */
134 *tempcon
; /* Temporary client pointer */
135 http_addrlist_t
*addrlist
, /* List of adddresses for host */
136 *addr
; /* Current address */
137 socklen_t addrlen
; /* Length of address */
138 char *hostname
; /* Hostname for address */
139 http_addr_t temp
; /* Temporary address variable */
140 static time_t last_dos
= 0; /* Time of last DoS attack */
142 struct request_info wrap_req
; /* TCP wrappers request information */
143 #endif /* HAVE_TCPD_H */
146 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
147 "cupsdAcceptClient(lis=%p(%d)) Clients=%d",
148 lis
, lis
->fd
, cupsArrayCount(Clients
));
151 * Make sure we don't have a full set of clients already...
154 if (cupsArrayCount(Clients
) == MaxClients
)
158 * Get a pointer to the next available client...
162 Clients
= cupsArrayNew(NULL
, NULL
);
166 cupsdLogMessage(CUPSD_LOG_ERROR
,
167 "Unable to allocate memory for clients array!");
168 cupsdPauseListening();
173 ActiveClients
= cupsArrayNew((cups_array_func_t
)compare_clients
, NULL
);
177 cupsdLogMessage(CUPSD_LOG_ERROR
,
178 "Unable to allocate memory for active clients array!");
179 cupsdPauseListening();
183 if ((con
= calloc(1, sizeof(cupsd_client_t
))) == NULL
)
185 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to allocate memory for client!");
186 cupsdPauseListening();
191 con
->http
.activity
= time(NULL
);
192 con
->http
.hostaddr
= &(con
->clientaddr
);
193 con
->http
.wait_value
= 10000;
196 * Accept the client and get the remote address...
199 addrlen
= sizeof(http_addr_t
);
201 if ((con
->http
.fd
= accept(lis
->fd
, (struct sockaddr
*)con
->http
.hostaddr
,
204 if (errno
== ENFILE
|| errno
== EMFILE
)
205 cupsdPauseListening();
207 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to accept client connection - %s.",
215 * Save the connected port number...
218 _httpAddrSetPort(con
->http
.hostaddr
, _httpAddrPort(&(lis
->address
)));
222 * Convert IPv4 over IPv6 addresses (::ffff:n.n.n.n) to IPv4 forms we
223 * can more easily use...
226 if (lis
->address
.addr
.sa_family
== AF_INET6
&&
227 con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[0] == 0 &&
228 con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[1] == 0 &&
229 ntohl(con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[2]) == 0xffff)
230 con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[2] = 0;
231 #endif /* AF_INET6 */
234 * Check the number of clients on the same address...
237 for (count
= 0, tempcon
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
239 tempcon
= (cupsd_client_t
*)cupsArrayNext(Clients
))
240 if (httpAddrEqual(tempcon
->http
.hostaddr
, con
->http
.hostaddr
))
243 if (count
>= MaxClientsPerHost
)
247 if (count
>= MaxClientsPerHost
)
249 if ((time(NULL
) - last_dos
) >= 60)
251 last_dos
= time(NULL
);
252 cupsdLogMessage(CUPSD_LOG_WARN
,
253 "Possible DoS attack - more than %d clients connecting "
256 httpAddrString(con
->http
.hostaddr
, con
->http
.hostname
,
257 sizeof(con
->http
.hostname
)));
261 closesocket(con
->http
.fd
);
271 * Get the hostname or format the IP address as needed...
274 if (httpAddrLocalhost(con
->http
.hostaddr
))
277 * Map accesses from the loopback interface to "localhost"...
280 strlcpy(con
->http
.hostname
, "localhost", sizeof(con
->http
.hostname
));
281 hostname
= con
->http
.hostname
;
286 * Map accesses from the same host to the server name.
290 hostname
= httpAddrLookup(con
->http
.hostaddr
, con
->http
.hostname
,
291 sizeof(con
->http
.hostname
));
295 httpAddrString(con
->http
.hostaddr
, con
->http
.hostname
,
296 sizeof(con
->http
.hostname
));
300 if (hostname
== NULL
&& HostNameLookups
== 2)
303 * Can't have an unresolved IP address with double-lookups enabled...
307 closesocket(con
->http
.fd
);
312 cupsdLogMessage(CUPSD_LOG_WARN
,
313 "Name lookup failed - connection from %s closed!",
320 if (HostNameLookups
== 2)
323 * Do double lookups as needed...
326 if ((addrlist
= httpAddrGetList(con
->http
.hostname
, AF_UNSPEC
, NULL
))
330 * See if the hostname maps to the same IP address...
333 for (addr
= addrlist
; addr
; addr
= addr
->next
)
334 if (httpAddrEqual(con
->http
.hostaddr
, &(addr
->addr
)))
340 httpAddrFreeList(addrlist
);
345 * Can't have a hostname that doesn't resolve to the same IP address
346 * with double-lookups enabled...
350 closesocket(con
->http
.fd
);
355 cupsdLogMessage(CUPSD_LOG_WARN
,
356 "IP lookup failed - connection from %s closed!",
365 * See if the connection is denied by TCP wrappers...
368 request_init(&wrap_req
, RQ_DAEMON
, "cupsd", RQ_FILE
, con
->http
.fd
, NULL
);
371 if (!hosts_access(&wrap_req
))
374 closesocket(con
->http
.fd
);
379 cupsdLogMessage(CUPSD_LOG_WARN
,
380 "Connection from %s refused by /etc/hosts.allow and "
381 "/etc/hosts.deny rules.", con
->http
.hostname
);
385 #endif /* HAVE_TCPD_H */
388 if (con
->http
.hostaddr
->addr
.sa_family
== AF_LOCAL
)
389 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[Client %d] Accepted from %s (Domain)",
390 con
->http
.fd
, con
->http
.hostname
);
392 #endif /* AF_LOCAL */
393 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[Client %d] Accepted from %s:%d (IPv%d)",
394 con
->http
.fd
, con
->http
.hostname
,
395 _httpAddrPort(con
->http
.hostaddr
),
396 _httpAddrFamily(con
->http
.hostaddr
) == AF_INET
? 4 : 6);
399 * Get the local address the client connected to...
402 addrlen
= sizeof(temp
);
403 if (getsockname(con
->http
.fd
, (struct sockaddr
*)&temp
, &addrlen
))
405 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to get local address - %s",
408 strcpy(con
->servername
, "localhost");
409 con
->serverport
= LocalPort
;
412 else if (_httpAddrFamily(&temp
) == AF_LOCAL
)
414 strcpy(con
->servername
, "localhost");
415 con
->serverport
= LocalPort
;
417 #endif /* AF_LOCAL */
420 if (httpAddrLocalhost(&temp
))
421 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
422 else if (HostNameLookups
|| RemotePort
)
423 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
425 httpAddrString(&temp
, con
->servername
, sizeof(con
->servername
));
427 con
->serverport
= _httpAddrPort(&(lis
->address
));
431 * Add the connection to the array of active clients...
434 cupsArrayAdd(Clients
, con
);
437 * Using TCP_NODELAY improves responsiveness, especially on systems with a slow
438 * loopback interface. Since we write large buffers when sending print files
439 * and requests there shouldn't be any performance penalty for this...
443 setsockopt(con
->http
.fd
, IPPROTO_TCP
, TCP_NODELAY
, &val
, sizeof(val
));
446 * Close this file on all execs...
449 fcntl(con
->http
.fd
, F_SETFD
, fcntl(con
->http
.fd
, F_GETFD
) | FD_CLOEXEC
);
452 * Add the socket to the server select.
455 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
458 * Temporarily suspend accept()'s until we lose a client...
461 if (cupsArrayCount(Clients
) == MaxClients
)
462 cupsdPauseListening();
466 * See if we are connecting on a secure port...
469 if (lis
->encryption
== HTTP_ENCRYPT_ALWAYS
)
472 * https connection; go secure...
475 con
->http
.encryption
= HTTP_ENCRYPT_ALWAYS
;
477 if (!encrypt_client(con
))
478 cupsdCloseClient(con
);
482 #endif /* HAVE_SSL */
487 * 'cupsdCloseAllClients()' - Close all remote clients immediately.
491 cupsdCloseAllClients(void)
493 cupsd_client_t
*con
; /* Current client */
496 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdCloseAllClients() Clients=%d",
497 cupsArrayCount(Clients
));
499 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
501 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
502 if (cupsdCloseClient(con
))
503 cupsdCloseClient(con
);
508 * 'cupsdCloseClient()' - Close a remote client.
511 int /* O - 1 if partial close, 0 if fully closed */
512 cupsdCloseClient(cupsd_client_t
*con
) /* I - Client to close */
514 int partial
; /* Do partial close for SSL? */
516 SSL_CTX
*context
; /* Context for encryption */
517 unsigned long error
; /* Error code */
518 #elif defined(HAVE_GNUTLS)
519 int error
; /* Error code */
520 gnutls_certificate_server_credentials
*credentials
;
521 /* TLS credentials */
522 # elif defined(HAVE_CDSASSL)
523 #endif /* HAVE_LIBSSL */
526 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[Client %d] Closing connection.",
530 * Flush pending writes before closing...
533 httpFlushWrite(HTTP(con
));
539 * Shutdown encryption as needed...
547 context
= SSL_get_SSL_CTX(con
->http
.tls
);
549 switch (SSL_shutdown(con
->http
.tls
))
552 cupsdLogMessage(CUPSD_LOG_DEBUG
,
553 "SSL shutdown successful!");
556 cupsdLogMessage(CUPSD_LOG_ERROR
,
557 "Fatal error during SSL shutdown!");
559 while ((error
= ERR_get_error()) != 0)
560 cupsdLogMessage(CUPSD_LOG_ERROR
, "SSL shutdown failed: %s",
561 ERR_error_string(error
, NULL
));
565 SSL_CTX_free(context
);
566 SSL_free(con
->http
.tls
);
568 # elif defined(HAVE_GNUTLS)
569 credentials
= (gnutls_certificate_server_credentials
*)(con
->http
.tls_credentials
);
571 error
= gnutls_bye(con
->http
.tls
, GNUTLS_SHUT_WR
);
574 case GNUTLS_E_SUCCESS
:
575 cupsdLogMessage(CUPSD_LOG_DEBUG
,
576 "SSL shutdown successful!");
579 cupsdLogMessage(CUPSD_LOG_ERROR
,
580 "SSL shutdown failed: %s", gnutls_strerror(error
));
584 gnutls_deinit(con
->http
.tls
);
585 gnutls_certificate_free_credentials(*credentials
);
588 # elif defined(HAVE_CDSASSL)
589 while (SSLClose(con
->http
.tls
) == errSSLWouldBlock
)
592 SSLDisposeContext(con
->http
.tls
);
594 if (con
->http
.tls_credentials
)
595 CFRelease(con
->http
.tls_credentials
);
597 # endif /* HAVE_LIBSSL */
599 con
->http
.tls
= NULL
;
601 #endif /* HAVE_SSL */
603 if (con
->pipe_pid
!= 0)
606 * Stop any CGI process...
609 cupsdEndProcess(con
->pipe_pid
, 1);
615 cupsdRemoveSelect(con
->file
);
622 * Close the socket and clear the file from the input set for select()...
625 if (con
->http
.fd
>= 0)
627 cupsArrayRemove(ActiveClients
, con
);
633 * Only do a partial close so that the encrypted client gets everything.
636 shutdown(con
->http
.fd
, 0);
637 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
642 * Shut the socket down fully...
645 cupsdRemoveSelect(con
->http
.fd
);
657 if (con
->http
.input_set
)
658 free(con
->http
.input_set
);
660 httpClearCookie(HTTP(con
));
661 httpClearFields(HTTP(con
));
663 cupsdClearString(&con
->filename
);
664 cupsdClearString(&con
->command
);
665 cupsdClearString(&con
->options
);
666 cupsdClearString(&con
->query_string
);
670 ippDelete(con
->request
);
676 ippDelete(con
->response
);
677 con
->response
= NULL
;
682 cupsLangFree(con
->language
);
683 con
->language
= NULL
;
686 #ifdef HAVE_AUTHORIZATION_H
689 AuthorizationFree(con
->authref
, kAuthorizationFlagDefaults
);
692 #endif /* HAVE_AUTHORIZATION_H */
695 * Re-enable new client connections if we are going back under the
699 if (cupsArrayCount(Clients
) == MaxClients
)
700 cupsdResumeListening();
703 * Compact the list of clients as necessary...
706 cupsArrayRemove(Clients
, con
);
716 * 'cupsdFlushHeader()' - Flush the header fields to the client.
719 int /* I - Bytes written or -1 on error */
720 cupsdFlushHeader(cupsd_client_t
*con
) /* I - Client to flush to */
722 int bytes
= httpFlushWrite(HTTP(con
));
724 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
731 * 'cupsdReadClient()' - Read data from a client.
735 cupsdReadClient(cupsd_client_t
*con
) /* I - Client to read from */
737 char line
[32768], /* Line from client... */
738 operation
[64], /* Operation code from socket */
739 version
[64], /* HTTP version number string */
740 locale
[64], /* Locale */
741 *ptr
; /* Pointer into strings */
742 int major
, minor
; /* HTTP version numbers */
743 http_status_t status
; /* Transfer status */
744 ipp_state_t ipp_state
; /* State of IPP transfer */
745 int bytes
; /* Number of bytes to POST */
746 char *filename
; /* Name of file for GET/HEAD */
747 char buf
[1024]; /* Buffer for real filename */
748 struct stat filestats
; /* File information */
749 mime_type_t
*type
; /* MIME type of file */
750 cupsd_printer_t
*p
; /* Printer */
751 static unsigned request_id
= 0; /* Request ID for temp files */
754 status
= HTTP_CONTINUE
;
756 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
757 "[Client %d] cupsdReadClient "
761 "data_encoding=HTTP_ENCODE_%s, "
762 "data_remaining=" CUPS_LLFMT
", "
765 con
->http
.fd
, con
->http
.error
, con
->http
.used
,
766 http_states
[con
->http
.state
],
767 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
?
768 "CHUNKED" : "LENGTH",
769 CUPS_LLCAST con
->http
.data_remaining
,
771 con
->request
? ipp_states
[con
->request
->state
] : "",
778 * Automatically check for a SSL/TLS handshake...
783 if (recv(con
->http
.fd
, buf
, 1, MSG_PEEK
) == 1 &&
784 (!buf
[0] || !strchr("DGHOPT", buf
[0])))
787 * Encrypt this connection...
790 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
791 "[Client %d] Saw first byte %02X, auto-negotiating "
792 "SSL/TLS session.", con
->http
.fd
, buf
[0] & 255);
794 if (!encrypt_client(con
))
795 cupsdCloseClient(con
);
800 #endif /* HAVE_SSL */
802 switch (con
->http
.state
)
806 * See if we've received a request line...
809 if (httpGets(line
, sizeof(line
) - 1, HTTP(con
)) == NULL
)
811 if (con
->http
.error
&& con
->http
.error
!= EPIPE
)
812 cupsdLogMessage(CUPSD_LOG_DEBUG
,
813 "[Client %d] HTTP_WAITING Closing for error %d "
814 "(%s)", con
->http
.fd
, con
->http
.error
,
815 strerror(con
->http
.error
));
817 cupsdLogMessage(CUPSD_LOG_DEBUG
,
818 "[Client %d] HTTP_WAITING Closing on EOF",
821 cupsdCloseClient(con
);
826 * Ignore blank request lines...
833 * Clear other state variables...
836 httpClearFields(HTTP(con
));
838 con
->http
.activity
= time(NULL
);
839 con
->http
.version
= HTTP_1_0
;
840 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
841 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
842 con
->http
.data_remaining
= 0;
843 con
->http
._data_remaining
= 0;
844 con
->operation
= HTTP_WAITING
;
849 con
->username
[0] = '\0';
850 con
->password
[0] = '\0';
853 cupsdClearString(&con
->command
);
854 cupsdClearString(&con
->options
);
855 cupsdClearString(&con
->query_string
);
859 ippDelete(con
->request
);
865 ippDelete(con
->response
);
866 con
->response
= NULL
;
871 cupsLangFree(con
->language
);
872 con
->language
= NULL
;
878 #endif /* HAVE_GSSAPI */
881 * Grab the request line...
884 switch (sscanf(line
, "%63s%1023s%63s", operation
, con
->uri
, version
))
889 cupsdLogMessage(CUPSD_LOG_ERROR
,
890 "[Client %d] Bad request line \"%s\" from %s.",
892 _httpEncodeURI(buf
, line
, sizeof(buf
)),
894 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
895 cupsdCloseClient(con
);
899 con
->http
.version
= HTTP_0_9
;
902 if (sscanf(version
, "HTTP/%d.%d", &major
, &minor
) != 2)
904 cupsdLogMessage(CUPSD_LOG_ERROR
,
905 "[Client %d] Bad request line \"%s\" from %s.",
907 _httpEncodeURI(buf
, line
, sizeof(buf
)),
909 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
910 cupsdCloseClient(con
);
916 con
->http
.version
= (http_version_t
)(major
* 100 + minor
);
917 if (con
->http
.version
== HTTP_1_1
&& KeepAlive
)
918 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
920 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
924 cupsdLogMessage(CUPSD_LOG_ERROR
,
925 "[Client %d] Unsupported request line \"%s\" "
926 "from %s.", con
->http
.fd
,
927 _httpEncodeURI(buf
, line
, sizeof(buf
)),
929 cupsdSendError(con
, HTTP_NOT_SUPPORTED
, CUPSD_AUTH_NONE
);
930 cupsdCloseClient(con
);
937 * Handle full URLs in the request line...
940 if (strcmp(con
->uri
, "*"))
942 char scheme
[HTTP_MAX_URI
], /* Method/scheme */
943 userpass
[HTTP_MAX_URI
], /* Username:password */
944 hostname
[HTTP_MAX_URI
], /* Hostname */
945 resource
[HTTP_MAX_URI
]; /* Resource path */
946 int port
; /* Port number */
950 * Separate the URI into its components...
953 httpSeparateURI(HTTP_URI_CODING_MOST
, con
->uri
,
954 scheme
, sizeof(scheme
),
955 userpass
, sizeof(userpass
),
956 hostname
, sizeof(hostname
), &port
,
957 resource
, sizeof(resource
));
960 * Only allow URIs with the servername, localhost, or an IP
964 if (strcmp(scheme
, "file") &&
965 _cups_strcasecmp(hostname
, ServerName
) &&
966 _cups_strcasecmp(hostname
, "localhost") &&
967 !isdigit(hostname
[0]) && hostname
[0] != '[')
970 * Nope, we don't do proxies...
973 cupsdLogMessage(CUPSD_LOG_ERROR
,
974 "[Client %d] Bad URI \"%s\" in request.",
975 con
->http
.fd
, con
->uri
);
976 cupsdSendError(con
, HTTP_METHOD_NOT_ALLOWED
, CUPSD_AUTH_NONE
);
977 cupsdCloseClient(con
);
982 * Copy the resource portion back into the URI; both resource and
983 * con->uri are HTTP_MAX_URI bytes in size...
986 strcpy(con
->uri
, resource
);
990 * Process the request...
993 if (!strcmp(operation
, "GET"))
994 con
->http
.state
= HTTP_GET
;
995 else if (!strcmp(operation
, "PUT"))
996 con
->http
.state
= HTTP_PUT
;
997 else if (!strcmp(operation
, "POST"))
998 con
->http
.state
= HTTP_POST
;
999 else if (!strcmp(operation
, "DELETE"))
1000 con
->http
.state
= HTTP_DELETE
;
1001 else if (!strcmp(operation
, "TRACE"))
1002 con
->http
.state
= HTTP_TRACE
;
1003 else if (!strcmp(operation
, "OPTIONS"))
1004 con
->http
.state
= HTTP_OPTIONS
;
1005 else if (!strcmp(operation
, "HEAD"))
1006 con
->http
.state
= HTTP_HEAD
;
1009 cupsdLogMessage(CUPSD_LOG_ERROR
,
1010 "[Client %d] Bad operation \"%s\".", con
->http
.fd
,
1012 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
1013 cupsdCloseClient(con
);
1017 gettimeofday(&(con
->start
), NULL
);
1018 con
->operation
= con
->http
.state
;
1020 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[Client %d] %s %s HTTP/%d.%d",
1021 con
->http
.fd
, operation
, con
->uri
,
1022 con
->http
.version
/ 100, con
->http
.version
% 100);
1024 con
->http
.status
= HTTP_OK
;
1026 if (!cupsArrayFind(ActiveClients
, con
))
1028 cupsArrayAdd(ActiveClients
, con
);
1029 cupsdSetBusyState();
1040 * Parse incoming parameters until the status changes...
1043 while ((status
= httpUpdate(HTTP(con
))) == HTTP_CONTINUE
)
1044 if (!data_ready(con
))
1047 if (status
!= HTTP_OK
&& status
!= HTTP_CONTINUE
)
1049 if (con
->http
.error
&& con
->http
.error
!= EPIPE
)
1050 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1051 "[Client %d] Closing for error %d (%s) while "
1053 con
->http
.fd
, con
->http
.error
,
1054 strerror(con
->http
.error
));
1056 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1057 "[Client %d] Closing on EOF while reading headers.",
1060 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
1061 cupsdCloseClient(con
);
1067 if (!data_ready(con
) && recv(con
->http
.fd
, buf
, 1, MSG_PEEK
) < 1)
1070 * Connection closed...
1073 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1074 "[Client %d] Closing on EOF", con
->http
.fd
);
1075 cupsdCloseClient(con
);
1078 break; /* Anti-compiler-warning-code */
1082 * Handle new transfers...
1085 if (status
== HTTP_OK
)
1087 if (con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
][0])
1090 * Figure out the locale from the Accept-Language and Content-Type
1094 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
],
1098 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
],
1102 if ((ptr
= strstr(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
],
1103 "charset=")) != NULL
)
1106 * Combine language and charset, and trim any extra params in the
1110 snprintf(locale
, sizeof(locale
), "%s.%s",
1111 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ptr
+ 8);
1113 if ((ptr
= strchr(locale
, ',')) != NULL
)
1117 snprintf(locale
, sizeof(locale
), "%s.UTF-8",
1118 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
]);
1120 con
->language
= cupsLangGet(locale
);
1123 con
->language
= cupsLangGet(DefaultLocale
);
1125 cupsdAuthorize(con
);
1127 if (!_cups_strncasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
],
1128 "Keep-Alive", 10) && KeepAlive
)
1129 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
1130 else if (!_cups_strncasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
],
1132 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1134 if (!con
->http
.fields
[HTTP_FIELD_HOST
][0] &&
1135 con
->http
.version
>= HTTP_1_1
)
1138 * HTTP/1.1 and higher require the "Host:" field...
1141 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1143 cupsdLogMessage(CUPSD_LOG_ERROR
,
1144 "[Client %d] Missing Host: field in request.",
1146 cupsdCloseClient(con
);
1150 else if (!valid_host(con
))
1153 * Access to localhost must use "localhost" or the corresponding IPv4
1154 * or IPv6 values in the Host: field.
1157 cupsdLogMessage(CUPSD_LOG_ERROR
,
1158 "[Client %d] Request from \"%s\" using invalid Host: "
1159 "field \"%s\"", con
->http
.fd
, con
->http
.hostname
,
1160 con
->http
.fields
[HTTP_FIELD_HOST
]);
1162 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1164 cupsdCloseClient(con
);
1168 else if (con
->operation
== HTTP_OPTIONS
)
1171 * Do OPTIONS command...
1174 if (con
->best
&& con
->best
->type
!= CUPSD_AUTH_NONE
)
1176 if (!cupsdSendHeader(con
, HTTP_UNAUTHORIZED
, NULL
, CUPSD_AUTH_NONE
))
1178 cupsdCloseClient(con
);
1183 if (!_cups_strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") &&
1184 con
->http
.tls
== NULL
)
1188 * Do encryption stuff...
1191 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
, CUPSD_AUTH_NONE
))
1193 cupsdCloseClient(con
);
1197 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1198 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1199 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1200 httpPrintf(HTTP(con
), "\r\n");
1202 if (cupsdFlushHeader(con
) < 0)
1204 cupsdCloseClient(con
);
1208 if (!encrypt_client(con
))
1210 cupsdCloseClient(con
);
1214 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
1216 cupsdCloseClient(con
);
1219 #endif /* HAVE_SSL */
1222 if (!cupsdSendHeader(con
, HTTP_OK
, NULL
, CUPSD_AUTH_NONE
))
1224 cupsdCloseClient(con
);
1228 httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n");
1229 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1230 httpPrintf(HTTP(con
), "\r\n");
1232 if (cupsdFlushHeader(con
) < 0)
1234 cupsdCloseClient(con
);
1238 else if (!is_path_absolute(con
->uri
))
1241 * Protect against malicious users!
1244 cupsdLogMessage(CUPSD_LOG_ERROR
,
1245 "[Client %d] Request for non-absolute resource \"%s\".",
1246 con
->http
.fd
, con
->uri
);
1248 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1250 cupsdCloseClient(con
);
1256 if (!_cups_strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
],
1257 "Upgrade") && con
->http
.tls
== NULL
)
1261 * Do encryption stuff...
1264 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
,
1267 cupsdCloseClient(con
);
1271 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1272 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1273 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1274 httpPrintf(HTTP(con
), "\r\n");
1276 if (cupsdFlushHeader(con
) < 0)
1278 cupsdCloseClient(con
);
1282 if (!encrypt_client(con
))
1284 cupsdCloseClient(con
);
1288 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
1290 cupsdCloseClient(con
);
1293 #endif /* HAVE_SSL */
1296 if ((status
= cupsdIsAuthorized(con
, NULL
)) != HTTP_OK
)
1298 cupsdSendError(con
, status
, CUPSD_AUTH_NONE
);
1299 cupsdCloseClient(con
);
1303 if (con
->http
.expect
&&
1304 (con
->operation
== HTTP_POST
|| con
->operation
== HTTP_PUT
))
1306 if (con
->http
.expect
== HTTP_CONTINUE
)
1309 * Send 100-continue header...
1312 if (!cupsdSendHeader(con
, HTTP_CONTINUE
, NULL
, CUPSD_AUTH_NONE
))
1314 cupsdCloseClient(con
);
1321 * Send 417-expectation-failed header...
1324 if (!cupsdSendHeader(con
, HTTP_EXPECTATION_FAILED
, NULL
,
1327 cupsdCloseClient(con
);
1331 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1332 httpPrintf(HTTP(con
), "\r\n");
1334 if (cupsdFlushHeader(con
) < 0)
1336 cupsdCloseClient(con
);
1342 switch (con
->http
.state
)
1344 case HTTP_GET_SEND
:
1345 if (!strncmp(con
->uri
, "/printers/", 10) &&
1346 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1349 * Send PPD file - get the real printer name since printer
1350 * names are not case sensitive but filenames can be...
1353 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1355 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1356 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1359 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1361 cupsdCloseClient(con
);
1368 else if ((!strncmp(con
->uri
, "/printers/", 10) ||
1369 !strncmp(con
->uri
, "/classes/", 9)) &&
1370 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".png"))
1373 * Send icon file - get the real queue name since queue names are
1374 * not case sensitive but filenames can be...
1377 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".png" */
1379 if (!strncmp(con
->uri
, "/printers/", 10))
1380 p
= cupsdFindPrinter(con
->uri
+ 10);
1382 p
= cupsdFindClass(con
->uri
+ 9);
1385 snprintf(con
->uri
, sizeof(con
->uri
), "/icons/%s.png", p
->name
);
1388 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1390 cupsdCloseClient(con
);
1397 else if (!WebInterface
)
1400 * Web interface is disabled. Show an appropriate message...
1403 if (!cupsdSendError(con
, HTTP_WEBIF_DISABLED
, CUPSD_AUTH_NONE
))
1405 cupsdCloseClient(con
);
1412 if ((!strncmp(con
->uri
, "/admin", 6) &&
1413 strncmp(con
->uri
, "/admin/conf/", 12) &&
1414 strncmp(con
->uri
, "/admin/log/", 11)) ||
1415 !strncmp(con
->uri
, "/printers", 9) ||
1416 !strncmp(con
->uri
, "/classes", 8) ||
1417 !strncmp(con
->uri
, "/help", 5) ||
1418 !strncmp(con
->uri
, "/jobs", 5))
1421 * Send CGI output...
1424 if (!strncmp(con
->uri
, "/admin", 6))
1426 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1429 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1431 else if (!strncmp(con
->uri
, "/printers", 9))
1433 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1436 if (con
->uri
[9] && con
->uri
[10])
1437 cupsdSetString(&con
->options
, con
->uri
+ 9);
1439 cupsdSetString(&con
->options
, NULL
);
1441 else if (!strncmp(con
->uri
, "/classes", 8))
1443 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1446 if (con
->uri
[8] && con
->uri
[9])
1447 cupsdSetString(&con
->options
, con
->uri
+ 8);
1449 cupsdSetString(&con
->options
, NULL
);
1451 else if (!strncmp(con
->uri
, "/jobs", 5))
1453 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1456 if (con
->uri
[5] && con
->uri
[6])
1457 cupsdSetString(&con
->options
, con
->uri
+ 5);
1459 cupsdSetString(&con
->options
, NULL
);
1463 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1466 if (con
->uri
[5] && con
->uri
[6])
1467 cupsdSetString(&con
->options
, con
->uri
+ 5);
1469 cupsdSetString(&con
->options
, NULL
);
1472 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1474 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1476 cupsdCloseClient(con
);
1481 cupsdLogRequest(con
, HTTP_OK
);
1483 if (con
->http
.version
<= HTTP_1_0
)
1484 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1486 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1487 (strchr(con
->uri
+ 12, '/') ||
1488 strlen(con
->uri
) == 12)) ||
1489 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1490 (strchr(con
->uri
+ 11, '/') ||
1491 strlen(con
->uri
) == 11)))
1494 * GET can only be done to configuration files directly under
1498 cupsdLogMessage(CUPSD_LOG_ERROR
,
1499 "Request for subdirectory \"%s\"!", con
->uri
);
1501 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1503 cupsdCloseClient(con
);
1515 if ((filename
= get_file(con
, &filestats
, buf
,
1516 sizeof(buf
))) == NULL
)
1518 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1520 cupsdCloseClient(con
);
1527 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1529 if (is_cgi(con
, filename
, &filestats
, type
))
1532 * Note: con->command and con->options were set by
1536 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1538 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1540 cupsdCloseClient(con
);
1545 cupsdLogRequest(con
, HTTP_OK
);
1547 if (con
->http
.version
<= HTTP_1_0
)
1548 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1552 if (!check_if_modified(con
, &filestats
))
1554 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1556 cupsdCloseClient(con
);
1563 strcpy(line
, "text/plain");
1565 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1567 if (!write_file(con
, HTTP_OK
, filename
, line
, &filestats
))
1569 cupsdCloseClient(con
);
1576 case HTTP_POST_RECV
:
1578 * See if the POST request includes a Content-Length field, and if
1579 * so check the length against any limits that are set...
1582 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1583 MaxRequestSize
> 0 &&
1584 con
->http
.data_remaining
> MaxRequestSize
)
1587 * Request too large...
1590 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1592 cupsdCloseClient(con
);
1598 else if (con
->http
.data_remaining
< 0 ||
1599 (!con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1600 con
->http
.data_encoding
== HTTP_ENCODE_LENGTH
))
1603 * Negative content lengths are invalid!
1606 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1608 cupsdCloseClient(con
);
1616 * See what kind of POST request this is; for IPP requests the
1617 * content-type field will be "application/ipp"...
1620 if (!strcmp(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
],
1622 con
->request
= ippNew();
1623 else if (!WebInterface
)
1626 * Web interface is disabled. Show an appropriate message...
1629 if (!cupsdSendError(con
, HTTP_WEBIF_DISABLED
, CUPSD_AUTH_NONE
))
1631 cupsdCloseClient(con
);
1637 else if ((!strncmp(con
->uri
, "/admin", 6) &&
1638 strncmp(con
->uri
, "/admin/conf/", 12) &&
1639 strncmp(con
->uri
, "/admin/log/", 11)) ||
1640 !strncmp(con
->uri
, "/printers", 9) ||
1641 !strncmp(con
->uri
, "/classes", 8) ||
1642 !strncmp(con
->uri
, "/help", 5) ||
1643 !strncmp(con
->uri
, "/jobs", 5))
1649 if (!strncmp(con
->uri
, "/admin", 6))
1651 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1654 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1656 else if (!strncmp(con
->uri
, "/printers", 9))
1658 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1661 if (con
->uri
[9] && con
->uri
[10])
1662 cupsdSetString(&con
->options
, con
->uri
+ 9);
1664 cupsdSetString(&con
->options
, NULL
);
1666 else if (!strncmp(con
->uri
, "/classes", 8))
1668 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1671 if (con
->uri
[8] && con
->uri
[9])
1672 cupsdSetString(&con
->options
, con
->uri
+ 8);
1674 cupsdSetString(&con
->options
, NULL
);
1676 else if (!strncmp(con
->uri
, "/jobs", 5))
1678 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1681 if (con
->uri
[5] && con
->uri
[6])
1682 cupsdSetString(&con
->options
, con
->uri
+ 5);
1684 cupsdSetString(&con
->options
, NULL
);
1688 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1691 if (con
->uri
[5] && con
->uri
[6])
1692 cupsdSetString(&con
->options
, con
->uri
+ 5);
1694 cupsdSetString(&con
->options
, NULL
);
1697 if (con
->http
.version
<= HTTP_1_0
)
1698 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1706 if ((filename
= get_file(con
, &filestats
, buf
,
1707 sizeof(buf
))) == NULL
)
1709 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1711 cupsdCloseClient(con
);
1718 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1720 if (!is_cgi(con
, filename
, &filestats
, type
))
1723 * Only POST to CGI's...
1726 if (!cupsdSendError(con
, HTTP_UNAUTHORIZED
, CUPSD_AUTH_NONE
))
1728 cupsdCloseClient(con
);
1735 case HTTP_PUT_RECV
:
1737 * Validate the resource name...
1740 if (strncmp(con
->uri
, "/admin/conf/", 12) ||
1741 strchr(con
->uri
+ 12, '/') ||
1742 strlen(con
->uri
) == 12)
1745 * PUT can only be done to configuration files under
1749 cupsdLogMessage(CUPSD_LOG_ERROR
,
1750 "[Client %d] Request for subdirectory \"%s\".",
1751 con
->http
.fd
, con
->uri
);
1753 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1755 cupsdCloseClient(con
);
1763 * See if the PUT request includes a Content-Length field, and if
1764 * so check the length against any limits that are set...
1767 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1768 MaxRequestSize
> 0 &&
1769 con
->http
.data_remaining
> MaxRequestSize
)
1772 * Request too large...
1775 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1777 cupsdCloseClient(con
);
1783 else if (con
->http
.data_remaining
< 0)
1786 * Negative content lengths are invalid!
1789 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1791 cupsdCloseClient(con
);
1799 * Open a temporary file to hold the request...
1802 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
1804 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1808 cupsdLogMessage(CUPSD_LOG_ERROR
,
1809 "[Client %d] Unable to create request file "
1810 "\"%s\": %s", con
->http
.fd
, con
->filename
,
1813 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1815 cupsdCloseClient(con
);
1820 fchmod(con
->file
, 0640);
1821 fchown(con
->file
, RunUser
, Group
);
1822 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1827 cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
);
1828 cupsdCloseClient(con
);
1832 if (!strncmp(con
->uri
, "/printers/", 10) &&
1833 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1836 * Send PPD file - get the real printer name since printer
1837 * names are not case sensitive but filenames can be...
1840 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1842 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1843 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1846 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1848 cupsdCloseClient(con
);
1855 else if (!strncmp(con
->uri
, "/printers/", 10) &&
1856 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".png"))
1859 * Send PNG file - get the real printer name since printer
1860 * names are not case sensitive but filenames can be...
1863 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1865 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1866 snprintf(con
->uri
, sizeof(con
->uri
), "/icons/%s.png", p
->name
);
1869 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1871 cupsdCloseClient(con
);
1878 else if (!WebInterface
)
1880 if (!cupsdSendHeader(con
, HTTP_OK
, line
, CUPSD_AUTH_NONE
))
1882 cupsdCloseClient(con
);
1886 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1888 cupsdCloseClient(con
);
1892 if (cupsdFlushHeader(con
) < 0)
1894 cupsdCloseClient(con
);
1898 con
->http
.state
= HTTP_WAITING
;
1902 if ((!strncmp(con
->uri
, "/admin", 6) &&
1903 strncmp(con
->uri
, "/admin/conf/", 12) &&
1904 strncmp(con
->uri
, "/admin/log/", 11)) ||
1905 !strncmp(con
->uri
, "/printers", 9) ||
1906 !strncmp(con
->uri
, "/classes", 8) ||
1907 !strncmp(con
->uri
, "/help", 5) ||
1908 !strncmp(con
->uri
, "/jobs", 5))
1914 if (!cupsdSendHeader(con
, HTTP_OK
, "text/html", CUPSD_AUTH_NONE
))
1916 cupsdCloseClient(con
);
1920 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1922 cupsdCloseClient(con
);
1926 if (cupsdFlushHeader(con
) < 0)
1928 cupsdCloseClient(con
);
1932 cupsdLogRequest(con
, HTTP_OK
);
1934 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1935 (strchr(con
->uri
+ 12, '/') ||
1936 strlen(con
->uri
) == 12)) ||
1937 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1938 (strchr(con
->uri
+ 11, '/') ||
1939 strlen(con
->uri
) == 11)))
1942 * HEAD can only be done to configuration files under
1946 cupsdLogMessage(CUPSD_LOG_ERROR
,
1947 "[Client %d] Request for subdirectory \"%s\".",
1948 con
->http
.fd
, con
->uri
);
1950 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1952 cupsdCloseClient(con
);
1958 else if ((filename
= get_file(con
, &filestats
, buf
,
1959 sizeof(buf
))) == NULL
)
1961 if (!cupsdSendHeader(con
, HTTP_NOT_FOUND
, "text/html",
1964 cupsdCloseClient(con
);
1968 cupsdLogRequest(con
, HTTP_NOT_FOUND
);
1970 else if (!check_if_modified(con
, &filestats
))
1972 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1974 cupsdCloseClient(con
);
1978 cupsdLogRequest(con
, HTTP_NOT_MODIFIED
);
1986 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1988 strcpy(line
, "text/plain");
1990 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1992 if (!cupsdSendHeader(con
, HTTP_OK
, line
, CUPSD_AUTH_NONE
))
1994 cupsdCloseClient(con
);
1998 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
1999 httpGetDateString(filestats
.st_mtime
)) < 0)
2001 cupsdCloseClient(con
);
2005 if (httpPrintf(HTTP(con
), "Content-Length: %lu\r\n",
2006 (unsigned long)filestats
.st_size
) < 0)
2008 cupsdCloseClient(con
);
2012 cupsdLogRequest(con
, HTTP_OK
);
2015 if (httpPrintf(HTTP(con
), "\r\n") < 0)
2017 cupsdCloseClient(con
);
2021 if (cupsdFlushHeader(con
) < 0)
2023 cupsdCloseClient(con
);
2027 con
->http
.state
= HTTP_WAITING
;
2031 break; /* Anti-compiler-warning-code */
2037 * Handle any incoming data...
2040 switch (con
->http
.state
)
2042 case HTTP_PUT_RECV
:
2045 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
2047 if (con
->http
.error
&& con
->http
.error
!= EPIPE
)
2048 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2049 "[Client %d] HTTP_PUT_RECV Closing for error "
2050 "%d (%s)", con
->http
.fd
, con
->http
.error
,
2051 strerror(con
->http
.error
));
2053 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2054 "[Client %d] HTTP_PUT_RECV Closing on EOF",
2057 cupsdCloseClient(con
);
2062 con
->bytes
+= bytes
;
2064 if (write(con
->file
, line
, bytes
) < bytes
)
2066 cupsdLogMessage(CUPSD_LOG_ERROR
,
2067 "[Client %d] Unable to write %d bytes to "
2068 "\"%s\": %s", con
->http
.fd
, bytes
, con
->filename
,
2073 unlink(con
->filename
);
2074 cupsdClearString(&con
->filename
);
2076 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2078 cupsdCloseClient(con
);
2084 while (con
->http
.state
== HTTP_PUT_RECV
&& data_ready(con
));
2086 if (con
->http
.state
== HTTP_WAITING
)
2089 * End of file, see how big it is...
2092 fstat(con
->file
, &filestats
);
2097 if (filestats
.st_size
> MaxRequestSize
&&
2101 * Request is too big; remove it and send an error...
2104 unlink(con
->filename
);
2105 cupsdClearString(&con
->filename
);
2107 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2109 cupsdCloseClient(con
);
2115 * Install the configuration file...
2118 status
= install_conf_file(con
);
2121 * Return the status to the client...
2124 if (!cupsdSendError(con
, status
, CUPSD_AUTH_NONE
))
2126 cupsdCloseClient(con
);
2132 case HTTP_POST_RECV
:
2135 if (con
->request
&& con
->file
< 0)
2138 * Grab any request data from the connection...
2141 if ((ipp_state
= ippRead(&(con
->http
), con
->request
)) == IPP_ERROR
)
2143 cupsdLogMessage(CUPSD_LOG_ERROR
,
2144 "[Client %d] IPP read error: %s", con
->http
.fd
,
2145 cupsLastErrorString());
2147 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
2148 cupsdCloseClient(con
);
2151 else if (ipp_state
!= IPP_DATA
)
2153 if (con
->http
.state
== HTTP_POST_SEND
)
2155 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
2156 cupsdCloseClient(con
);
2164 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[Client %d] %d.%d %s %d",
2165 con
->http
.fd
, con
->request
->request
.op
.version
[0],
2166 con
->request
->request
.op
.version
[1],
2167 ippOpString(con
->request
->request
.op
.operation_id
),
2168 con
->request
->request
.op
.request_id
);
2169 con
->bytes
+= ippLength(con
->request
);
2173 if (con
->file
< 0 && con
->http
.state
!= HTTP_POST_SEND
)
2176 * Create a file as needed for the request data...
2179 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
2181 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
2185 cupsdLogMessage(CUPSD_LOG_ERROR
,
2186 "[Client %d] Unable to create request file "
2187 "\"%s\": %s", con
->http
.fd
, con
->filename
,
2190 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2192 cupsdCloseClient(con
);
2197 fchmod(con
->file
, 0640);
2198 fchown(con
->file
, RunUser
, Group
);
2199 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2202 if (con
->http
.state
!= HTTP_POST_SEND
)
2204 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
2206 if (con
->http
.error
&& con
->http
.error
!= EPIPE
)
2207 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2208 "[Client %d] HTTP_POST_SEND Closing for "
2209 "error %d (%s)", con
->http
.fd
, con
->http
.error
,
2210 strerror(con
->http
.error
));
2212 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2213 "[Client %d] HTTP_POST_SEND Closing on EOF",
2216 cupsdCloseClient(con
);
2221 con
->bytes
+= bytes
;
2223 if (write(con
->file
, line
, bytes
) < bytes
)
2225 cupsdLogMessage(CUPSD_LOG_ERROR
,
2226 "[Client %d] Unable to write %d bytes to "
2227 "\"%s\": %s", con
->http
.fd
, bytes
,
2228 con
->filename
, strerror(errno
));
2232 unlink(con
->filename
);
2233 cupsdClearString(&con
->filename
);
2235 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
,
2238 cupsdCloseClient(con
);
2243 else if (con
->http
.state
== HTTP_POST_RECV
)
2245 else if (con
->http
.state
!= HTTP_POST_SEND
)
2247 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2248 "[Client %d] Closing on unexpected state %s.",
2249 con
->http
.fd
, http_states
[con
->http
.state
]);
2250 cupsdCloseClient(con
);
2255 while (con
->http
.state
== HTTP_POST_RECV
&& data_ready(con
));
2257 if (con
->http
.state
== HTTP_POST_SEND
)
2261 fstat(con
->file
, &filestats
);
2266 if (filestats
.st_size
> MaxRequestSize
&&
2270 * Request is too big; remove it and send an error...
2273 unlink(con
->filename
);
2274 cupsdClearString(&con
->filename
);
2279 * Delete any IPP request data...
2282 ippDelete(con
->request
);
2283 con
->request
= NULL
;
2286 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2288 cupsdCloseClient(con
);
2292 else if (filestats
.st_size
== 0)
2295 * Don't allow empty file...
2298 unlink(con
->filename
);
2299 cupsdClearString(&con
->filename
);
2304 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
2306 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
2308 cupsdCloseClient(con
);
2313 cupsdLogRequest(con
, HTTP_OK
);
2319 cupsdProcessIPPRequest(con
);
2323 unlink(con
->filename
);
2324 cupsdClearString(&con
->filename
);
2333 break; /* Anti-compiler-warning-code */
2336 if (con
->http
.state
== HTTP_WAITING
)
2338 if (!con
->http
.keep_alive
)
2340 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2341 "[Client %d] Closing because Keep-Alive disabled",
2343 cupsdCloseClient(con
);
2347 cupsArrayRemove(ActiveClients
, con
);
2348 cupsdSetBusyState();
2355 * 'cupsdSendCommand()' - Send output from a command via HTTP.
2358 int /* O - 1 on success, 0 on failure */
2360 cupsd_client_t
*con
, /* I - Client connection */
2361 char *command
, /* I - Command to run */
2362 char *options
, /* I - Command-line options */
2363 int root
) /* I - Run as root? */
2365 int fd
; /* Standard input file descriptor */
2370 fd
= open(con
->filename
, O_RDONLY
);
2374 cupsdLogMessage(CUPSD_LOG_ERROR
,
2375 "[Client %d] Unable to open \"%s\" for reading: %s",
2376 con
->http
.fd
, con
->filename
? con
->filename
: "/dev/null",
2381 fcntl(fd
, F_SETFD
, fcntl(fd
, F_GETFD
) | FD_CLOEXEC
);
2386 con
->pipe_pid
= pipe_command(con
, fd
, &(con
->file
), command
, options
, root
);
2391 cupsdLogMessage(CUPSD_LOG_INFO
, "[Client %d] Started \"%s\" (pid=%d)",
2392 con
->http
.fd
, command
, con
->pipe_pid
);
2394 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[Client %d] file=%d", con
->http
.fd
,
2397 if (con
->pipe_pid
== 0)
2400 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2402 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2404 con
->sent_header
= 0;
2405 con
->file_ready
= 0;
2406 con
->got_fields
= 0;
2407 con
->header_used
= 0;
2414 * 'cupsdSendError()' - Send an error message via HTTP.
2417 int /* O - 1 if successful, 0 otherwise */
2418 cupsdSendError(cupsd_client_t
*con
, /* I - Connection */
2419 http_status_t code
, /* I - Error code */
2420 int auth_type
)/* I - Authentication type */
2422 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2423 "[Client %d] cupsdSendError code=%d, auth_type=%d",
2424 con
->http
.fd
, code
, auth_type
);
2428 * Force client to upgrade for authentication if that is how the
2429 * server is configured...
2432 if (code
== HTTP_UNAUTHORIZED
&&
2433 DefaultEncryption
== HTTP_ENCRYPT_REQUIRED
&&
2434 _cups_strcasecmp(con
->http
.hostname
, "localhost") &&
2437 code
= HTTP_UPGRADE_REQUIRED
;
2439 #endif /* HAVE_SSL */
2442 * Put the request in the access_log file...
2445 cupsdLogRequest(con
, code
);
2448 * To work around bugs in some proxies, don't use Keep-Alive for some
2451 * Kerberos authentication doesn't work without Keep-Alive, so
2452 * never disable it in that case.
2455 if (code
>= HTTP_BAD_REQUEST
&& con
->http
.auth_type
!= CUPSD_AUTH_NEGOTIATE
)
2456 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
2459 * Send an error message back to the client. If the error code is a
2460 * 400 or 500 series, make sure the message contains some text, too!
2463 if (!cupsdSendHeader(con
, code
, NULL
, auth_type
))
2467 if (code
== HTTP_UPGRADE_REQUIRED
)
2468 if (httpPrintf(HTTP(con
), "Connection: Upgrade\r\n") < 0)
2471 if (httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n") < 0)
2473 #endif /* HAVE_SSL */
2475 if (con
->http
.version
>= HTTP_1_1
&&
2476 con
->http
.keep_alive
== HTTP_KEEPALIVE_OFF
)
2478 if (httpPrintf(HTTP(con
), "Connection: close\r\n") < 0)
2482 if (code
>= HTTP_BAD_REQUEST
)
2485 * Send a human-readable error message.
2488 char message
[4096], /* Message for user */
2489 urltext
[1024], /* URL redirection text */
2490 redirect
[1024]; /* Redirection link */
2491 const char *text
; /* Status-specific text */
2496 if (code
== HTTP_UNAUTHORIZED
)
2497 text
= _cupsLangString(con
->language
,
2498 _("Enter your username and password or the "
2499 "root username and password to access this "
2500 "page. If you are using Kerberos authentication, "
2501 "make sure you have a valid Kerberos ticket."));
2502 else if (code
== HTTP_UPGRADE_REQUIRED
)
2506 snprintf(urltext
, sizeof(urltext
),
2507 _cupsLangString(con
->language
,
2508 _("You must access this page using the URL "
2509 "<A HREF=\"https://%s:%d%s\">"
2510 "https://%s:%d%s</A>.")),
2511 con
->servername
, con
->serverport
, con
->uri
,
2512 con
->servername
, con
->serverport
, con
->uri
);
2514 snprintf(redirect
, sizeof(redirect
),
2515 "<META HTTP-EQUIV=\"Refresh\" "
2516 "CONTENT=\"3;URL=https://%s:%d%s\">\n",
2517 con
->servername
, con
->serverport
, con
->uri
);
2519 else if (code
== HTTP_WEBIF_DISABLED
)
2520 text
= _cupsLangString(con
->language
,
2521 _("The web interface is currently disabled. Run "
2522 "\"cupsctl WebInterface=yes\" to enable it."));
2526 snprintf(message
, sizeof(message
),
2527 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" "
2528 "\"http://www.w3.org/TR/html4/loose.dtd\">\n"
2531 "\t<META HTTP-EQUIV=\"Content-Type\" "
2532 "CONTENT=\"text/html; charset=utf-8\">\n"
2533 "\t<TITLE>%s - " CUPS_SVERSION
"</TITLE>\n"
2534 "\t<LINK REL=\"STYLESHEET\" TYPE=\"text/css\" "
2535 "HREF=\"/cups.css\">\n"
2543 httpStatus(code
), redirect
, httpStatus(code
), text
);
2545 if (httpPrintf(HTTP(con
), "Content-Type: text/html; charset=utf-8\r\n") < 0)
2547 if (httpPrintf(HTTP(con
), "Content-Length: %d\r\n",
2548 (int)strlen(message
)) < 0)
2550 if (httpPrintf(HTTP(con
), "\r\n") < 0)
2552 if (httpPrintf(HTTP(con
), "%s", message
) < 0)
2555 else if (httpPrintf(HTTP(con
), "\r\n") < 0)
2558 if (cupsdFlushHeader(con
) < 0)
2561 con
->http
.state
= HTTP_WAITING
;
2568 * 'cupsdSendHeader()' - Send an HTTP request.
2571 int /* O - 1 on success, 0 on failure */
2573 cupsd_client_t
*con
, /* I - Client to send to */
2574 http_status_t code
, /* I - HTTP status code */
2575 char *type
, /* I - MIME type of document */
2576 int auth_type
) /* I - Type of authentication */
2578 char auth_str
[1024]; /* Authorization string */
2582 * Send the HTTP status header...
2585 if (code
== HTTP_CONTINUE
)
2588 * 100-continue doesn't send any headers...
2591 return (httpPrintf(HTTP(con
), "HTTP/%d.%d 100 Continue\r\n\r\n",
2592 con
->http
.version
/ 100, con
->http
.version
% 100) > 0);
2594 else if (code
== HTTP_WEBIF_DISABLED
)
2597 * Treat our special "web interface is disabled" status as "200 OK" for web
2604 httpFlushWrite(HTTP(con
));
2606 con
->http
.data_encoding
= HTTP_ENCODE_FIELDS
;
2608 if (httpPrintf(HTTP(con
), "HTTP/%d.%d %d %s\r\n", con
->http
.version
/ 100,
2609 con
->http
.version
% 100, code
, httpStatus(code
)) < 0)
2611 if (httpPrintf(HTTP(con
), "Date: %s\r\n", httpGetDateString(time(NULL
))) < 0)
2614 if (httpPrintf(HTTP(con
), "Server: %s\r\n", ServerHeader
) < 0)
2616 if (con
->http
.keep_alive
&& con
->http
.version
>= HTTP_1_0
)
2618 if (httpPrintf(HTTP(con
), "Connection: Keep-Alive\r\n") < 0)
2620 if (httpPrintf(HTTP(con
), "Keep-Alive: timeout=%d\r\n",
2621 KeepAliveTimeout
) < 0)
2624 if (code
== HTTP_METHOD_NOT_ALLOWED
)
2625 if (httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n") < 0)
2628 if (code
== HTTP_UNAUTHORIZED
)
2630 if (auth_type
== CUPSD_AUTH_NONE
)
2632 if (!con
->best
|| con
->best
->type
<= CUPSD_AUTH_NONE
)
2633 auth_type
= cupsdDefaultAuthType();
2635 auth_type
= con
->best
->type
;
2640 if (auth_type
== CUPSD_AUTH_BASIC
|| auth_type
== CUPSD_AUTH_BASICDIGEST
)
2641 strlcpy(auth_str
, "Basic realm=\"CUPS\"", sizeof(auth_str
));
2642 else if (auth_type
== CUPSD_AUTH_DIGEST
)
2643 snprintf(auth_str
, sizeof(auth_str
), "Digest realm=\"CUPS\", nonce=\"%s\"",
2644 con
->http
.hostname
);
2646 else if (auth_type
== CUPSD_AUTH_NEGOTIATE
)
2649 if (_httpAddrFamily(con
->http
.hostaddr
) == AF_LOCAL
)
2650 strlcpy(auth_str
, "Basic realm=\"CUPS\"", sizeof(auth_str
));
2652 # endif /* AF_LOCAL */
2653 strlcpy(auth_str
, "Negotiate", sizeof(auth_str
));
2655 #endif /* HAVE_GSSAPI */
2657 if (con
->best
&& auth_type
!= CUPSD_AUTH_NEGOTIATE
&&
2658 !_cups_strcasecmp(con
->http
.hostname
, "localhost"))
2661 * Add a "trc" (try root certification) parameter for local non-Kerberos
2662 * requests when the request requires system group membership - then the
2663 * client knows the root certificate can/should be used.
2665 * Also, for Mac OS X we also look for @AUTHKEY and add an "authkey"
2666 * parameter as needed...
2669 char *name
, /* Current user name */
2670 *auth_key
; /* Auth key buffer */
2671 size_t auth_size
; /* Size of remaining buffer */
2673 auth_key
= auth_str
+ strlen(auth_str
);
2674 auth_size
= sizeof(auth_str
) - (auth_key
- auth_str
);
2676 for (name
= (char *)cupsArrayFirst(con
->best
->names
);
2678 name
= (char *)cupsArrayNext(con
->best
->names
))
2680 #ifdef HAVE_AUTHORIZATION_H
2681 if (!_cups_strncasecmp(name
, "@AUTHKEY(", 9))
2683 snprintf(auth_key
, auth_size
, ", authkey=\"%s\"", name
+ 9);
2684 /* end parenthesis is stripped in conf.c */
2688 #endif /* HAVE_AUTHORIZATION_H */
2689 if (!_cups_strcasecmp(name
, "@SYSTEM"))
2691 #ifdef HAVE_AUTHORIZATION_H
2692 if (SystemGroupAuthKey
)
2693 snprintf(auth_key
, auth_size
,
2695 SystemGroupAuthKey
);
2698 strlcpy(auth_key
, ", trc=\"y\"", auth_size
);
2699 #endif /* HAVE_AUTHORIZATION_H */
2707 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2708 "[Client %d] WWW-Authenticate: %s", con
->http
.fd
,
2711 if (httpPrintf(HTTP(con
), "WWW-Authenticate: %s\r\n", auth_str
) < 0)
2716 if (con
->language
&& strcmp(con
->language
->language
, "C"))
2718 if (httpPrintf(HTTP(con
), "Content-Language: %s\r\n",
2719 con
->language
->language
) < 0)
2725 if (!strcmp(type
, "text/html"))
2727 if (httpPrintf(HTTP(con
),
2728 "Content-Type: text/html; charset=utf-8\r\n") < 0)
2731 else if (httpPrintf(HTTP(con
), "Content-Type: %s\r\n", type
) < 0)
2740 * 'cupsdUpdateCGI()' - Read status messages from CGI scripts and programs.
2744 cupsdUpdateCGI(void)
2746 char *ptr
, /* Pointer to end of line in buffer */
2747 message
[1024]; /* Pointer to message text */
2748 int loglevel
; /* Log level for message */
2751 while ((ptr
= cupsdStatBufUpdate(CGIStatusBuffer
, &loglevel
,
2752 message
, sizeof(message
))) != NULL
)
2754 if (loglevel
== CUPSD_LOG_INFO
)
2755 cupsdLogMessage(CUPSD_LOG_INFO
, "%s", message
);
2757 if (!strchr(CGIStatusBuffer
->buffer
, '\n'))
2761 if (ptr
== NULL
&& !CGIStatusBuffer
->bufused
)
2764 * Fatal error on pipe - should never happen!
2767 cupsdLogMessage(CUPSD_LOG_CRIT
,
2768 "cupsdUpdateCGI: error reading from CGI error pipe - %s",
2775 * 'cupsdWriteClient()' - Write data to a client as needed.
2779 cupsdWriteClient(cupsd_client_t
*con
) /* I - Client connection */
2781 int bytes
, /* Number of bytes written */
2782 field_col
; /* Current column */
2783 char *bufptr
, /* Pointer into buffer */
2784 *bufend
; /* Pointer to end of buffer */
2785 ipp_state_t ipp_state
; /* IPP state value */
2788 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2789 "[Client %d] cupsdWriteClient "
2793 "data_encoding=HTTP_ENCODE_%s, "
2794 "data_remaining=" CUPS_LLFMT
", "
2798 con
->http
.fd
, con
->http
.error
, con
->http
.used
,
2799 http_states
[con
->http
.state
],
2800 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
?
2801 "CHUNKED" : "LENGTH",
2802 CUPS_LLCAST con
->http
.data_remaining
,
2804 con
->response
? ipp_states
[con
->response
->state
] : "",
2805 con
->pipe_pid
, con
->file
);
2807 if (con
->http
.state
!= HTTP_GET_SEND
&&
2808 con
->http
.state
!= HTTP_POST_SEND
)
2811 * If we get called in the wrong state, then something went wrong with the
2812 * connection and we need to shut it down...
2815 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2816 "[Client %d] Closing on unexpected HTTP state %s.",
2817 con
->http
.fd
, http_states
[con
->http
.state
]);
2818 cupsdCloseClient(con
);
2825 * Make sure we select on the CGI output...
2828 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2830 if (!con
->file_ready
)
2833 * Try again later when there is CGI output available...
2836 cupsdRemoveSelect(con
->http
.fd
);
2840 con
->file_ready
= 0;
2843 if (con
->response
&& con
->response
->state
!= IPP_DATA
)
2845 ipp_state
= ippWrite(HTTP(con
), con
->response
);
2846 bytes
= ipp_state
!= IPP_ERROR
&&
2847 (con
->file
>= 0 || ipp_state
!= IPP_DATA
);
2849 else if ((bytes
= read(con
->file
, con
->header
+ con
->header_used
,
2850 sizeof(con
->header
) - con
->header_used
)) > 0)
2852 con
->header_used
+= bytes
;
2854 if (con
->pipe_pid
&& !con
->got_fields
)
2857 * Inspect the data for Content-Type and other fields.
2860 for (bufptr
= con
->header
, bufend
= con
->header
+ con
->header_used
,
2862 !con
->got_fields
&& bufptr
< bufend
;
2865 if (*bufptr
== '\n')
2868 * Send line to client...
2871 if (bufptr
> con
->header
&& bufptr
[-1] == '\r')
2875 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Script header: %s", con
->header
);
2877 if (!con
->sent_header
)
2880 * Handle redirection and CGI status codes...
2883 if (!_cups_strncasecmp(con
->header
, "Location:", 9))
2885 if (!cupsdSendHeader(con
, HTTP_SEE_OTHER
, NULL
, CUPSD_AUTH_NONE
))
2887 cupsdCloseClient(con
);
2891 con
->sent_header
= 2;
2893 if (httpPrintf(HTTP(con
), "Content-Length: 0\r\n") < 0)
2896 else if (!_cups_strncasecmp(con
->header
, "Status:", 7))
2898 cupsdSendError(con
, (http_status_t
)atoi(con
->header
+ 7),
2900 con
->sent_header
= 2;
2904 if (!cupsdSendHeader(con
, HTTP_OK
, NULL
, CUPSD_AUTH_NONE
))
2906 cupsdCloseClient(con
);
2910 con
->sent_header
= 1;
2912 if (con
->http
.version
== HTTP_1_1
)
2914 if (httpPrintf(HTTP(con
), "Transfer-Encoding: chunked\r\n") < 0)
2920 if (_cups_strncasecmp(con
->header
, "Status:", 7))
2921 httpPrintf(HTTP(con
), "%s\r\n", con
->header
);
2927 con
->header_used
-= bufptr
- con
->header
;
2929 if (con
->header_used
> 0)
2930 memmove(con
->header
, bufptr
, con
->header_used
);
2932 bufptr
= con
->header
- 1;
2935 * See if the line was empty...
2940 con
->got_fields
= 1;
2942 if (cupsdFlushHeader(con
) < 0)
2944 cupsdCloseClient(con
);
2948 if (con
->http
.version
== HTTP_1_1
)
2949 con
->http
.data_encoding
= HTTP_ENCODE_CHUNKED
;
2954 else if (*bufptr
!= '\r')
2958 if (!con
->got_fields
)
2960 con
->http
.activity
= time(NULL
);
2965 if (con
->header_used
> 0)
2967 if (httpWrite2(HTTP(con
), con
->header
, con
->header_used
) < 0)
2969 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2970 "[Client %d] Closing for error %d (%s)",
2971 con
->http
.fd
, con
->http
.error
,
2972 strerror(con
->http
.error
));
2973 cupsdCloseClient(con
);
2977 if (con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
)
2978 httpFlushWrite(HTTP(con
));
2980 con
->bytes
+= con
->header_used
;
2982 if (con
->http
.state
== HTTP_WAITING
)
2985 bytes
= con
->header_used
;
2987 con
->header_used
= 0;
2992 (con
->http
.state
!= HTTP_GET_SEND
&& con
->http
.state
!= HTTP_POST_SEND
))
2994 if (!con
->sent_header
&& con
->pipe_pid
)
2995 cupsdSendError(con
, HTTP_SERVER_ERROR
, CUPSD_AUTH_NONE
);
2998 cupsdLogRequest(con
, HTTP_OK
);
3000 httpFlushWrite(HTTP(con
));
3002 if (con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
&& con
->sent_header
== 1)
3004 if (httpWrite2(HTTP(con
), "", 0) < 0)
3006 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3007 "[Client %d] Closing for error %d (%s)",
3008 con
->http
.fd
, con
->http
.error
,
3009 strerror(con
->http
.error
));
3010 cupsdCloseClient(con
);
3016 con
->http
.state
= HTTP_WAITING
;
3018 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
3022 cupsdRemoveSelect(con
->file
);
3025 cupsdEndProcess(con
->pipe_pid
, 0);
3034 unlink(con
->filename
);
3035 cupsdClearString(&con
->filename
);
3040 ippDelete(con
->request
);
3041 con
->request
= NULL
;
3046 ippDelete(con
->response
);
3047 con
->response
= NULL
;
3050 cupsdClearString(&con
->command
);
3051 cupsdClearString(&con
->options
);
3052 cupsdClearString(&con
->query_string
);
3054 if (!con
->http
.keep_alive
)
3056 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3057 "[Client %d] Closing because Keep-Alive disabled.",
3059 cupsdCloseClient(con
);
3064 cupsArrayRemove(ActiveClients
, con
);
3065 cupsdSetBusyState();
3069 con
->http
.activity
= time(NULL
);
3074 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
3077 static int /* O - 1 if modified since */
3079 cupsd_client_t
*con
, /* I - Client connection */
3080 struct stat
*filestats
) /* I - File information */
3082 char *ptr
; /* Pointer into field */
3083 time_t date
; /* Time/date value */
3084 off_t size
; /* Size/length value */
3089 ptr
= con
->http
.fields
[HTTP_FIELD_IF_MODIFIED_SINCE
];
3094 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3095 "[Client %d] check_if_modified "
3096 "filestats=%p(" CUPS_LLFMT
", %d)) If-Modified-Since=\"%s\"",
3097 con
->http
.fd
, filestats
, CUPS_LLCAST filestats
->st_size
,
3098 (int)filestats
->st_mtime
, ptr
);
3100 while (*ptr
!= '\0')
3102 while (isspace(*ptr
) || *ptr
== ';')
3105 if (_cups_strncasecmp(ptr
, "length=", 7) == 0)
3108 size
= strtoll(ptr
, NULL
, 10);
3110 while (isdigit(*ptr
))
3113 else if (isalpha(*ptr
))
3115 date
= httpGetDateTime(ptr
);
3116 while (*ptr
!= '\0' && *ptr
!= ';')
3123 return ((size
!= filestats
->st_size
&& size
!= 0) ||
3124 (date
< filestats
->st_mtime
&& date
!= 0) ||
3125 (size
== 0 && date
== 0));
3130 * 'compare_clients()' - Compare two client connections.
3133 static int /* O - Result of comparison */
3134 compare_clients(cupsd_client_t
*a
, /* I - First client */
3135 cupsd_client_t
*b
, /* I - Second client */
3136 void *data
) /* I - User data (not used) */
3151 * 'copy_cdsa_certificate()' - Copy a SSL/TLS certificate from the System
3155 static CFArrayRef
/* O - Array of certificates */
3156 copy_cdsa_certificate(
3157 cupsd_client_t
*con
) /* I - Client connection */
3159 OSStatus err
; /* Error info */
3160 SecKeychainRef keychain
= NULL
;/* Keychain reference */
3161 SecIdentitySearchRef search
= NULL
; /* Search reference */
3162 SecIdentityRef identity
= NULL
;/* Identity */
3163 CFArrayRef certificates
= NULL
;
3164 /* Certificate array */
3165 # if HAVE_SECPOLICYCREATESSL
3166 SecPolicyRef policy
= NULL
; /* Policy ref */
3167 CFStringRef servername
= NULL
;
3169 CFMutableDictionaryRef query
= NULL
; /* Query qualifiers */
3170 char localname
[1024];/* Local hostname */
3171 # elif defined(HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY)
3172 SecPolicyRef policy
= NULL
; /* Policy ref */
3173 SecPolicySearchRef policy_search
= NULL
;
3174 /* Policy search ref */
3175 CSSM_DATA options
; /* Policy options */
3176 CSSM_APPLE_TP_SSL_OPTIONS
3177 ssl_options
; /* SSL Option for hostname */
3178 char localname
[1024];/* Local hostname */
3179 # endif /* HAVE_SECPOLICYCREATESSL */
3182 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3183 "copy_cdsa_certificate: Looking for certs for \"%s\"...",
3186 if ((err
= SecKeychainOpen(ServerCertificate
, &keychain
)))
3188 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot open keychain \"%s\" - %s (%d)",
3189 ServerCertificate
, cssmErrorString(err
), (int)err
);
3193 # if HAVE_SECPOLICYCREATESSL
3194 servername
= CFStringCreateWithCString(kCFAllocatorDefault
, con
->servername
,
3195 kCFStringEncodingUTF8
);
3197 policy
= SecPolicyCreateSSL(1, servername
);
3200 CFRelease(servername
);
3204 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot create ssl policy reference");
3208 if (!(query
= CFDictionaryCreateMutable(kCFAllocatorDefault
, 0,
3209 &kCFTypeDictionaryKeyCallBacks
,
3210 &kCFTypeDictionaryValueCallBacks
)))
3212 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot create query dictionary");
3216 CFDictionaryAddValue(query
, kSecClass
, kSecClassIdentity
);
3217 CFDictionaryAddValue(query
, kSecMatchPolicy
, policy
);
3218 CFDictionaryAddValue(query
, kSecReturnRef
, kCFBooleanTrue
);
3219 CFDictionaryAddValue(query
, kSecMatchLimit
, kSecMatchLimitOne
);
3221 err
= SecItemCopyMatching(query
, (CFTypeRef
*)&identity
);
3223 if (err
&& DNSSDHostName
)
3226 * Search for the connection server name failed; try the DNS-SD .local
3227 * hostname instead...
3230 snprintf(localname
, sizeof(localname
), "%s.local", DNSSDHostName
);
3232 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3233 "copy_cdsa_certificate: Looking for certs for \"%s\"...",
3236 servername
= CFStringCreateWithCString(kCFAllocatorDefault
, localname
,
3237 kCFStringEncodingUTF8
);
3241 policy
= SecPolicyCreateSSL(1, servername
);
3244 CFRelease(servername
);
3248 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot create ssl policy reference");
3252 CFDictionarySetValue(query
, kSecMatchPolicy
, policy
);
3254 err
= SecItemCopyMatching(query
, (CFTypeRef
*)&identity
);
3259 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3260 "Cannot find signing key in keychain \"%s\": %s (%d)",
3261 ServerCertificate
, cssmErrorString(err
), (int)err
);
3265 # elif defined(HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY)
3267 * Use a policy to search for valid certificates whose common name matches the
3271 if (SecPolicySearchCreate(CSSM_CERT_X_509v3
, &CSSMOID_APPLE_TP_SSL
,
3272 NULL
, &policy_search
))
3274 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot create a policy search reference");
3278 if (SecPolicySearchCopyNext(policy_search
, &policy
))
3280 cupsdLogMessage(CUPSD_LOG_ERROR
,
3281 "Cannot find a policy to use for searching");
3285 memset(&ssl_options
, 0, sizeof(ssl_options
));
3286 ssl_options
.Version
= CSSM_APPLE_TP_SSL_OPTS_VERSION
;
3287 ssl_options
.ServerName
= con
->servername
;
3288 ssl_options
.ServerNameLen
= strlen(con
->servername
);
3290 options
.Data
= (uint8
*)&ssl_options
;
3291 options
.Length
= sizeof(ssl_options
);
3293 if (SecPolicySetValue(policy
, &options
))
3295 cupsdLogMessage(CUPSD_LOG_ERROR
,
3296 "Cannot set policy value to use for searching");
3300 if ((err
= SecIdentitySearchCreateWithPolicy(policy
, NULL
, CSSM_KEYUSE_SIGN
,
3301 keychain
, FALSE
, &search
)))
3303 cupsdLogMessage(CUPSD_LOG_ERROR
,
3304 "Cannot create identity search reference: %s (%d)",
3305 cssmErrorString(err
), (int)err
);
3309 err
= SecIdentitySearchCopyNext(search
, &identity
);
3311 if (err
&& DNSSDHostName
)
3314 * Search for the connection server name failed; try the DNS-SD .local
3315 * hostname instead...
3318 snprintf(localname
, sizeof(localname
), "%s.local", DNSSDHostName
);
3320 ssl_options
.ServerName
= localname
;
3321 ssl_options
.ServerNameLen
= strlen(localname
);
3323 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3324 "copy_cdsa_certificate: Looking for certs for \"%s\"...",
3327 if (SecPolicySetValue(policy
, &options
))
3329 cupsdLogMessage(CUPSD_LOG_ERROR
,
3330 "Cannot set policy value to use for searching");
3336 if ((err
= SecIdentitySearchCreateWithPolicy(policy
, NULL
, CSSM_KEYUSE_SIGN
,
3337 keychain
, FALSE
, &search
)))
3339 cupsdLogMessage(CUPSD_LOG_ERROR
,
3340 "Cannot create identity search reference: %s (%d)",
3341 cssmErrorString(err
), (int)err
);
3345 err
= SecIdentitySearchCopyNext(search
, &identity
);
3351 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3352 "Cannot find signing key in keychain \"%s\": %s (%d)",
3353 ServerCertificate
, cssmErrorString(err
), (int)err
);
3359 * Assume there is exactly one SecIdentity in the keychain...
3362 if ((err
= SecIdentitySearchCreate(keychain
, CSSM_KEYUSE_SIGN
, &search
)))
3364 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3365 "Cannot create identity search reference (%d)", (int)err
);
3369 if ((err
= SecIdentitySearchCopyNext(search
, &identity
)))
3371 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3372 "Cannot find signing key in keychain \"%s\": %s (%d)",
3373 ServerCertificate
, cssmErrorString(err
), (int)err
);
3376 # endif /* HAVE_SECPOLICYCREATESSL */
3378 if (CFGetTypeID(identity
) != SecIdentityGetTypeID())
3380 cupsdLogMessage(CUPSD_LOG_ERROR
, "SecIdentity CFTypeID failure!");
3384 if ((certificates
= CFArrayCreate(NULL
, (const void **)&identity
,
3385 1, &kCFTypeArrayCallBacks
)) == NULL
)
3387 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot create certificate array");
3394 CFRelease(keychain
);
3398 CFRelease(identity
);
3400 # if HAVE_SECPOLICYCREATESSL
3405 # elif defined(HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY)
3409 CFRelease(policy_search
);
3410 # endif /* HAVE_SECPOLICYCREATESSL */
3412 return (certificates
);
3414 #endif /* HAVE_CDSASSL */
3418 * 'data_ready()' - Check whether data is available from a client.
3421 static int /* O - 1 if data is ready, 0 otherwise */
3422 data_ready(cupsd_client_t
*con
) /* I - Client */
3424 if (con
->http
.used
> 0)
3427 else if (con
->http
.tls
)
3430 if (SSL_pending((SSL
*)(con
->http
.tls
)))
3432 # elif defined(HAVE_GNUTLS)
3433 if (gnutls_record_check_pending(con
->http
.tls
))
3435 # elif defined(HAVE_CDSASSL)
3436 size_t bytes
; /* Bytes that are available */
3438 if (!SSLGetBufferedReadSize(con
->http
.tls
, &bytes
) && bytes
> 0)
3440 # endif /* HAVE_LIBSSL */
3442 #endif /* HAVE_SSL */
3450 * 'encrypt_client()' - Enable encryption for the client...
3453 static int /* O - 1 on success, 0 on error */
3454 encrypt_client(cupsd_client_t
*con
) /* I - Client to encrypt */
3457 SSL_CTX
*context
; /* Context for encryption */
3458 BIO
*bio
; /* BIO data */
3459 unsigned long error
; /* Error code */
3462 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[Client %d] Encrypting connection.",
3466 * Verify that we have a certificate...
3469 if (access(ServerKey
, 0) || access(ServerCertificate
, 0))
3472 * Nope, make a self-signed certificate...
3475 if (!make_certificate(con
))
3480 * Create the SSL context and accept the connection...
3483 context
= SSL_CTX_new(SSLv23_server_method());
3485 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
3486 if (SSLOptions
& CUPSD_SSL_NOEMPTY
)
3487 SSL_CTX_set_options(context
, SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
);
3488 SSL_CTX_use_PrivateKey_file(context
, ServerKey
, SSL_FILETYPE_PEM
);
3489 SSL_CTX_use_certificate_chain_file(context
, ServerCertificate
);
3491 bio
= BIO_new(_httpBIOMethods());
3492 BIO_ctrl(bio
, BIO_C_SET_FILE_PTR
, 0, (char *)HTTP(con
));
3494 con
->http
.tls
= SSL_new(context
);
3495 SSL_set_bio(con
->http
.tls
, bio
, bio
);
3497 if (SSL_accept(con
->http
.tls
) != 1)
3499 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to encrypt connection from %s.",
3500 con
->http
.hostname
);
3502 while ((error
= ERR_get_error()) != 0)
3503 cupsdLogMessage(CUPSD_LOG_ERROR
, "%s", ERR_error_string(error
, NULL
));
3505 SSL_CTX_free(context
);
3506 SSL_free(con
->http
.tls
);
3507 con
->http
.tls
= NULL
;
3511 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Connection from %s now encrypted.",
3512 con
->http
.hostname
);
3516 # elif defined(HAVE_GNUTLS)
3517 int status
; /* Error code */
3518 gnutls_certificate_server_credentials
*credentials
;
3519 /* TLS credentials */
3522 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[Client %d] Encrypting connection.",
3526 * Verify that we have a certificate...
3529 if (access(ServerKey
, 0) || access(ServerCertificate
, 0))
3532 * Nope, make a self-signed certificate...
3535 if (!make_certificate(con
))
3540 * Create the SSL object and perform the SSL handshake...
3543 credentials
= (gnutls_certificate_server_credentials
*)
3544 malloc(sizeof(gnutls_certificate_server_credentials
));
3545 if (credentials
== NULL
)
3547 cupsdLogMessage(CUPSD_LOG_ERROR
,
3548 "Unable to encrypt connection from %s - %s",
3549 con
->http
.hostname
, strerror(errno
));
3554 gnutls_certificate_allocate_credentials(credentials
);
3555 gnutls_certificate_set_x509_key_file(*credentials
, ServerCertificate
,
3556 ServerKey
, GNUTLS_X509_FMT_PEM
);
3558 gnutls_init(&con
->http
.tls
, GNUTLS_SERVER
);
3559 gnutls_set_default_priority(con
->http
.tls
);
3561 gnutls_credentials_set(con
->http
.tls
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
3562 gnutls_transport_set_ptr(con
->http
.tls
, (gnutls_transport_ptr
)HTTP(con
));
3563 gnutls_transport_set_pull_function(con
->http
.tls
, _httpReadGNUTLS
);
3564 gnutls_transport_set_push_function(con
->http
.tls
, _httpWriteGNUTLS
);
3566 while ((status
= gnutls_handshake(con
->http
.tls
)) != GNUTLS_E_SUCCESS
)
3568 if (gnutls_error_is_fatal(status
))
3570 cupsdLogMessage(CUPSD_LOG_ERROR
,
3571 "Unable to encrypt connection from %s - %s",
3572 con
->http
.hostname
, gnutls_strerror(status
));
3574 gnutls_deinit(con
->http
.tls
);
3575 gnutls_certificate_free_credentials(*credentials
);
3576 con
->http
.tls
= NULL
;
3582 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Connection from %s now encrypted.",
3583 con
->http
.hostname
);
3585 con
->http
.tls_credentials
= credentials
;
3588 # elif defined(HAVE_CDSASSL)
3589 OSStatus error
= 0; /* Error code */
3590 CFArrayRef peerCerts
; /* Peer certificates */
3593 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[Client %d] Encrypting connection.",
3596 con
->http
.tls_credentials
= copy_cdsa_certificate(con
);
3598 if (!con
->http
.tls_credentials
)
3601 * No keychain (yet), make a self-signed certificate...
3604 if (make_certificate(con
))
3605 con
->http
.tls_credentials
= copy_cdsa_certificate(con
);
3608 if (!con
->http
.tls_credentials
)
3610 cupsdLogMessage(CUPSD_LOG_ERROR
,
3611 "Could not find signing key in keychain \"%s\"",
3613 error
= errSSLBadCert
; /* errSSLBadConfiguration is a better choice, but not available on 10.2.x */
3617 error
= SSLNewContext(true, &con
->http
.tls
);
3620 error
= SSLSetIOFuncs(con
->http
.tls
, _httpReadCDSA
, _httpWriteCDSA
);
3623 error
= SSLSetConnection(con
->http
.tls
, HTTP(con
));
3626 error
= SSLSetAllowsExpiredCerts(con
->http
.tls
, true);
3629 error
= SSLSetAllowsAnyRoot(con
->http
.tls
, true);
3632 error
= SSLSetCertificate(con
->http
.tls
, con
->http
.tls_credentials
);
3637 * Perform SSL/TLS handshake
3640 while ((error
= SSLHandshake(con
->http
.tls
)) == errSSLWouldBlock
)
3646 cupsdLogMessage(CUPSD_LOG_ERROR
,
3647 "Unable to encrypt connection from %s - %s (%d)",
3648 con
->http
.hostname
, cssmErrorString(error
), (int)error
);
3650 con
->http
.error
= error
;
3651 con
->http
.status
= HTTP_ERROR
;
3655 SSLDisposeContext(con
->http
.tls
);
3656 con
->http
.tls
= NULL
;
3659 if (con
->http
.tls_credentials
)
3661 CFRelease(con
->http
.tls_credentials
);
3662 con
->http
.tls_credentials
= NULL
;
3668 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Connection from %s now encrypted.",
3669 con
->http
.hostname
);
3671 if (!SSLCopyPeerCertificates(con
->http
.tls
, &peerCerts
) && peerCerts
)
3673 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Received %d peer certificates!",
3674 (int)CFArrayGetCount(peerCerts
));
3675 CFRelease(peerCerts
);
3678 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Received NO peer certificates!");
3682 # endif /* HAVE_LIBSSL */
3684 #endif /* HAVE_SSL */
3688 * 'get_file()' - Get a filename and state info.
3691 static char * /* O - Real filename */
3692 get_file(cupsd_client_t
*con
, /* I - Client connection */
3693 struct stat
*filestats
, /* O - File information */
3694 char *filename
, /* IO - Filename buffer */
3695 int len
) /* I - Buffer length */
3697 int status
; /* Status of filesystem calls */
3698 char *ptr
; /* Pointer info filename */
3699 int plen
; /* Remaining length after pointer */
3700 char language
[7]; /* Language subdirectory, if any */
3704 * Figure out the real filename...
3709 if (!strncmp(con
->uri
, "/ppd/", 5) && !strchr(con
->uri
+ 5, '/'))
3710 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
);
3711 else if (!strncmp(con
->uri
, "/icons/", 7) && !strchr(con
->uri
+ 7, '/'))
3713 snprintf(filename
, len
, "%s/%s", CacheDir
, con
->uri
+ 7);
3714 if (access(filename
, F_OK
) < 0)
3715 snprintf(filename
, len
, "%s/images/generic.png", DocumentRoot
);
3717 else if (!strncmp(con
->uri
, "/rss/", 5) && !strchr(con
->uri
+ 5, '/'))
3718 snprintf(filename
, len
, "%s/rss/%s", CacheDir
, con
->uri
+ 5);
3719 else if (!strncmp(con
->uri
, "/admin/conf/", 12))
3720 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
+ 11);
3721 else if (!strncmp(con
->uri
, "/admin/log/", 11))
3723 if (!strncmp(con
->uri
+ 11, "access_log", 10) && AccessLog
[0] == '/')
3724 strlcpy(filename
, AccessLog
, len
);
3725 else if (!strncmp(con
->uri
+ 11, "error_log", 9) && ErrorLog
[0] == '/')
3726 strlcpy(filename
, ErrorLog
, len
);
3727 else if (!strncmp(con
->uri
+ 11, "page_log", 8) && PageLog
[0] == '/')
3728 strlcpy(filename
, PageLog
, len
);
3732 else if (con
->language
)
3734 snprintf(language
, sizeof(language
), "/%s", con
->language
->language
);
3735 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3738 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3740 if ((ptr
= strchr(filename
, '?')) != NULL
)
3744 * Grab the status for this language; if there isn't a language-specific file
3745 * then fallback to the default one...
3748 if ((status
= stat(filename
, filestats
)) != 0 && language
[0] &&
3749 strncmp(con
->uri
, "/icons/", 7) &&
3750 strncmp(con
->uri
, "/ppd/", 5) &&
3751 strncmp(con
->uri
, "/rss/", 5) &&
3752 strncmp(con
->uri
, "/admin/conf/", 12) &&
3753 strncmp(con
->uri
, "/admin/log/", 11))
3756 * Drop the country code...
3760 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3762 if ((ptr
= strchr(filename
, '?')) != NULL
)
3765 if ((status
= stat(filename
, filestats
)) != 0)
3768 * Drop the language prefix and try the root directory...
3772 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3774 if ((ptr
= strchr(filename
, '?')) != NULL
)
3777 status
= stat(filename
, filestats
);
3782 * If we're found a directory, get the index.html file instead...
3785 if (!status
&& S_ISDIR(filestats
->st_mode
))
3788 * Make sure the URI ends with a slash...
3791 if (con
->uri
[strlen(con
->uri
) - 1] != '/')
3792 strlcat(con
->uri
, "/", sizeof(con
->uri
));
3795 * Find the directory index file, trying every language...
3800 if (status
&& language
[0])
3803 * Try a different language subset...
3807 language
[0] = '\0'; /* Strip country code */
3809 language
[0] = '\0'; /* Strip language */
3813 * Look for the index file...
3816 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3818 if ((ptr
= strchr(filename
, '?')) != NULL
)
3821 ptr
= filename
+ strlen(filename
);
3822 plen
= len
- (ptr
- filename
);
3824 strlcpy(ptr
, "index.html", plen
);
3825 status
= stat(filename
, filestats
);
3830 strlcpy(ptr
, "index.class", plen
);
3831 status
= stat(filename
, filestats
);
3833 #endif /* HAVE_JAVA */
3838 strlcpy(ptr
, "index.pl", plen
);
3839 status
= stat(filename
, filestats
);
3841 #endif /* HAVE_PERL */
3846 strlcpy(ptr
, "index.php", plen
);
3847 status
= stat(filename
, filestats
);
3849 #endif /* HAVE_PHP */
3854 strlcpy(ptr
, "index.pyc", plen
);
3855 status
= stat(filename
, filestats
);
3860 strlcpy(ptr
, "index.py", plen
);
3861 status
= stat(filename
, filestats
);
3863 #endif /* HAVE_PYTHON */
3866 while (status
&& language
[0]);
3869 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3870 "[Client %d] get_file filestats=%p, filename=%p, len=%d, "
3871 "returning \"%s\".", con
->http
.fd
, filestats
, filename
, len
,
3872 status
? "(null)" : filename
);
3882 * 'install_conf_file()' - Install a configuration file.
3885 static http_status_t
/* O - Status */
3886 install_conf_file(cupsd_client_t
*con
) /* I - Connection */
3888 char filename
[1024]; /* Configuration filename */
3889 mode_t mode
; /* Permissions */
3890 cups_file_t
*in
, /* Input file */
3891 *out
; /* Output file */
3892 char buffer
[16384]; /* Copy buffer */
3893 ssize_t bytes
; /* Number of bytes */
3897 * Open the request file...
3900 if ((in
= cupsFileOpen(con
->filename
, "rb")) == NULL
)
3902 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open request file \"%s\": %s",
3903 con
->filename
, strerror(errno
));
3904 return (HTTP_SERVER_ERROR
);
3908 * Open the new config file...
3911 snprintf(filename
, sizeof(filename
), "%s%s", ServerRoot
, con
->uri
+ 11);
3912 if (!strcmp(con
->uri
, "/admin/conf/printers.conf"))
3913 mode
= ConfigFilePerm
& 0600;
3915 mode
= ConfigFilePerm
;
3917 if ((out
= cupsdCreateConfFile(filename
, mode
)) == NULL
)
3920 return (HTTP_SERVER_ERROR
);
3923 cupsdLogMessage(CUPSD_LOG_INFO
, "Installing config file \"%s\"...", filename
);
3926 * Copy from the request to the new config file...
3929 while ((bytes
= cupsFileRead(in
, buffer
, sizeof(buffer
))) > 0)
3930 if (cupsFileWrite(out
, buffer
, bytes
) < bytes
)
3932 cupsdLogMessage(CUPSD_LOG_ERROR
,
3933 "Unable to copy to config file \"%s\": %s",
3934 filename
, strerror(errno
));
3939 snprintf(filename
, sizeof(filename
), "%s%s.N", ServerRoot
, con
->uri
+ 11);
3940 cupsdRemoveFile(filename
);
3942 return (HTTP_SERVER_ERROR
);
3946 * Close the files...
3951 if (cupsdCloseCreatedConfFile(out
, filename
))
3952 return (HTTP_SERVER_ERROR
);
3955 * Remove the request file...
3958 cupsdRemoveFile(con
->filename
);
3959 cupsdClearString(&con
->filename
);
3962 * If the cupsd.conf file was updated, set the NeedReload flag...
3965 if (!strcmp(con
->uri
, "/admin/conf/cupsd.conf"))
3966 NeedReload
= RELOAD_CUPSD
;
3968 NeedReload
= RELOAD_ALL
;
3970 ReloadTime
= time(NULL
);
3973 * Return that the file was created successfully...
3976 return (HTTP_CREATED
);
3981 * 'is_cgi()' - Is the resource a CGI script/program?
3984 static int /* O - 1 = CGI, 0 = file */
3985 is_cgi(cupsd_client_t
*con
, /* I - Client connection */
3986 const char *filename
, /* I - Real filename */
3987 struct stat
*filestats
, /* I - File information */
3988 mime_type_t
*type
) /* I - MIME type */
3990 const char *options
; /* Options on URL */
3994 * Get the options, if any...
3997 if ((options
= strchr(con
->uri
, '?')) != NULL
)
4000 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", options
);
4004 * Check for known types...
4007 if (!type
|| _cups_strcasecmp(type
->super
, "application"))
4009 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4010 "[Client %d] is_cgi filename=\"%s\", filestats=%p, "
4011 "type=%s/%s, returning 0", con
->http
.fd
, filename
,
4012 filestats
, type
? type
->super
: "unknown",
4013 type
? type
->type
: "unknown");
4017 if (!_cups_strcasecmp(type
->type
, "x-httpd-cgi") &&
4018 (filestats
->st_mode
& 0111))
4021 * "application/x-httpd-cgi" is a CGI script.
4024 cupsdSetString(&con
->command
, filename
);
4027 cupsdSetStringf(&con
->options
, " %s", options
);
4029 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4030 "[Client %d] is_cgi filename=\"%s\", filestats=%p, "
4031 "type=%s/%s, returning 1", con
->http
.fd
, filename
,
4032 filestats
, type
->super
, type
->type
);
4036 else if (!_cups_strcasecmp(type
->type
, "x-httpd-java"))
4039 * "application/x-httpd-java" is a Java servlet.
4042 cupsdSetString(&con
->command
, CUPS_JAVA
);
4045 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
4047 cupsdSetStringf(&con
->options
, " %s", filename
);
4049 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4050 "[Client %d] is_cgi filename=\"%s\", filestats=%p, "
4051 "type=%s/%s, returning 1", con
->http
.fd
, filename
,
4052 filestats
, type
->super
, type
->type
);
4055 #endif /* HAVE_JAVA */
4057 else if (!_cups_strcasecmp(type
->type
, "x-httpd-perl"))
4060 * "application/x-httpd-perl" is a Perl page.
4063 cupsdSetString(&con
->command
, CUPS_PERL
);
4066 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
4068 cupsdSetStringf(&con
->options
, " %s", filename
);
4070 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4071 "[Client %d] is_cgi filename=\"%s\", filestats=%p, "
4072 "type=%s/%s, returning 1", con
->http
.fd
, filename
,
4073 filestats
, type
->super
, type
->type
);
4076 #endif /* HAVE_PERL */
4078 else if (!_cups_strcasecmp(type
->type
, "x-httpd-php"))
4081 * "application/x-httpd-php" is a PHP page.
4084 cupsdSetString(&con
->command
, CUPS_PHP
);
4087 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
4089 cupsdSetStringf(&con
->options
, " %s", filename
);
4091 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4092 "[Client %d] is_cgi filename=\"%s\", filestats=%p, "
4093 "type=%s/%s, returning 1", con
->http
.fd
, filename
,
4094 filestats
, type
->super
, type
->type
);
4097 #endif /* HAVE_PHP */
4099 else if (!_cups_strcasecmp(type
->type
, "x-httpd-python"))
4102 * "application/x-httpd-python" is a Python page.
4105 cupsdSetString(&con
->command
, CUPS_PYTHON
);
4108 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
4110 cupsdSetStringf(&con
->options
, " %s", filename
);
4112 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4113 "[Client %d] is_cgi filename=\"%s\", filestats=%p, "
4114 "type=%s/%s, returning 1", con
->http
.fd
, filename
,
4115 filestats
, type
->super
, type
->type
);
4118 #endif /* HAVE_PYTHON */
4120 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4121 "[Client %d] is_cgi filename=\"%s\", filestats=%p, "
4122 "type=%s/%s, returning 0", con
->http
.fd
, filename
,
4123 filestats
, type
->super
, type
->type
);
4129 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
4132 static int /* O - 0 if relative, 1 if absolute */
4133 is_path_absolute(const char *path
) /* I - Input path */
4136 * Check for a leading slash...
4143 * Check for "/.." in the path...
4146 while ((path
= strstr(path
, "/..")) != NULL
)
4148 if (!path
[3] || path
[3] == '/')
4155 * If we haven't found any relative paths, return 1 indicating an
4165 * 'make_certificate()' - Make a self-signed SSL/TLS certificate.
4168 static int /* O - 1 on success, 0 on failure */
4169 make_certificate(cupsd_client_t
*con
) /* I - Client connection */
4171 #if defined(HAVE_LIBSSL) && defined(HAVE_WAITPID)
4172 int pid
, /* Process ID of command */
4173 status
; /* Status of command */
4174 char command
[1024], /* Command */
4175 *argv
[12], /* Command-line arguments */
4176 *envp
[MAX_ENV
+ 1], /* Environment variables */
4177 infofile
[1024], /* Type-in information for cert */
4178 seedfile
[1024]; /* Random number seed file */
4179 int envc
, /* Number of environment variables */
4180 bytes
; /* Bytes written */
4181 cups_file_t
*fp
; /* Seed/info file */
4182 int infofd
; /* Info file descriptor */
4186 * Run the "openssl" command to seed the random number generator and
4187 * generate a self-signed certificate that is good for 10 years:
4189 * openssl rand -rand seedfile 1
4191 * openssl req -new -x509 -keyout ServerKey \
4192 * -out ServerCertificate -days 3650 -nodes
4194 * The seeding step is crucial in ensuring that the openssl command
4195 * does not block on systems without sufficient entropy...
4198 if (!cupsFileFind("openssl", getenv("PATH"), 1, command
, sizeof(command
)))
4200 cupsdLogMessage(CUPSD_LOG_ERROR
,
4201 "No SSL certificate and openssl command not found!");
4205 if (access("/dev/urandom", 0))
4208 * If the system doesn't provide /dev/urandom, then any random source
4209 * will probably be blocking-style, so generate some random data to
4210 * use as a seed for the certificate. Note that we have already
4211 * seeded the random number generator in cupsdInitCerts()...
4214 cupsdLogMessage(CUPSD_LOG_INFO
,
4215 "Seeding the random number generator...");
4218 * Write the seed file...
4221 if ((fp
= cupsTempFile2(seedfile
, sizeof(seedfile
))) == NULL
)
4223 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to create seed file %s - %s",
4224 seedfile
, strerror(errno
));
4228 for (bytes
= 0; bytes
< 262144; bytes
++)
4229 cupsFilePutChar(fp
, random());
4234 * Run the openssl command to seed its random number generator...
4237 argv
[0] = "openssl";
4244 envc
= cupsdLoadEnv(envp
, MAX_ENV
);
4247 if (!cupsdStartProcess(command
, argv
, envp
, -1, -1, -1, -1, -1, 1, NULL
,
4254 while (waitpid(pid
, &status
, 0) < 0)
4261 cupsdFinishProcess(pid
, command
, sizeof(command
), NULL
);
4264 * Remove the seed file, as it is no longer needed...
4271 if (WIFEXITED(status
))
4272 cupsdLogMessage(CUPSD_LOG_ERROR
,
4273 "Unable to seed random number generator - "
4274 "the openssl command stopped with status %d!",
4275 WEXITSTATUS(status
));
4277 cupsdLogMessage(CUPSD_LOG_ERROR
,
4278 "Unable to seed random number generator - "
4279 "the openssl command crashed on signal %d!",
4287 * Create a file with the certificate information fields...
4289 * Note: This assumes that the default questions are asked by the openssl
4293 if ((fp
= cupsTempFile2(infofile
, sizeof(infofile
))) == NULL
)
4295 cupsdLogMessage(CUPSD_LOG_ERROR
,
4296 "Unable to create certificate information file %s - %s",
4297 infofile
, strerror(errno
));
4301 cupsFilePrintf(fp
, ".\n.\n.\n%s\n.\n%s\n%s\n",
4302 ServerName
, ServerName
, ServerAdmin
);
4305 cupsdLogMessage(CUPSD_LOG_INFO
,
4306 "Generating SSL server key and certificate...");
4308 argv
[0] = "openssl";
4312 argv
[4] = "-keyout";
4313 argv
[5] = ServerKey
;
4315 argv
[7] = ServerCertificate
;
4318 argv
[10] = "-nodes";
4321 cupsdLoadEnv(envp
, MAX_ENV
);
4323 infofd
= open(infofile
, O_RDONLY
);
4325 if (!cupsdStartProcess(command
, argv
, envp
, infofd
, -1, -1, -1, -1, 1, NULL
,
4336 while (waitpid(pid
, &status
, 0) < 0)
4343 cupsdFinishProcess(pid
, command
, sizeof(command
), NULL
);
4347 if (WIFEXITED(status
))
4348 cupsdLogMessage(CUPSD_LOG_ERROR
,
4349 "Unable to create SSL server key and certificate - "
4350 "the openssl command stopped with status %d!",
4351 WEXITSTATUS(status
));
4353 cupsdLogMessage(CUPSD_LOG_ERROR
,
4354 "Unable to create SSL server key and certificate - "
4355 "the openssl command crashed on signal %d!",
4360 cupsdLogMessage(CUPSD_LOG_INFO
, "Created SSL server key file \"%s\"...",
4362 cupsdLogMessage(CUPSD_LOG_INFO
,
4363 "Created SSL server certificate file \"%s\"...",
4369 #elif defined(HAVE_GNUTLS)
4370 gnutls_x509_crt crt
; /* Self-signed certificate */
4371 gnutls_x509_privkey key
; /* Encryption key */
4372 cups_lang_t
*language
; /* Default language info */
4373 cups_file_t
*fp
; /* Key/cert file */
4374 unsigned char buffer
[8192]; /* Buffer for x509 data */
4375 size_t bytes
; /* Number of bytes of data */
4376 unsigned char serial
[4]; /* Serial number buffer */
4377 time_t curtime
; /* Current time */
4378 int result
; /* Result of GNU TLS calls */
4382 * Create the encryption key...
4385 cupsdLogMessage(CUPSD_LOG_INFO
, "Generating SSL server key...");
4387 gnutls_x509_privkey_init(&key
);
4388 gnutls_x509_privkey_generate(key
, GNUTLS_PK_RSA
, 2048, 0);
4394 bytes
= sizeof(buffer
);
4396 if ((result
= gnutls_x509_privkey_export(key
, GNUTLS_X509_FMT_PEM
,
4397 buffer
, &bytes
)) < 0)
4399 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to export SSL server key - %s",
4400 gnutls_strerror(result
));
4401 gnutls_x509_privkey_deinit(key
);
4404 else if ((fp
= cupsFileOpen(ServerKey
, "w")) != NULL
)
4406 cupsFileWrite(fp
, (char *)buffer
, bytes
);
4409 cupsdLogMessage(CUPSD_LOG_INFO
, "Created SSL server key file \"%s\"...",
4414 cupsdLogMessage(CUPSD_LOG_ERROR
,
4415 "Unable to create SSL server key file \"%s\" - %s",
4416 ServerKey
, strerror(errno
));
4417 gnutls_x509_privkey_deinit(key
);
4422 * Create the self-signed certificate...
4425 cupsdLogMessage(CUPSD_LOG_INFO
, "Generating self-signed SSL certificate...");
4427 language
= cupsLangDefault();
4428 curtime
= time(NULL
);
4429 serial
[0] = curtime
>> 24;
4430 serial
[1] = curtime
>> 16;
4431 serial
[2] = curtime
>> 8;
4432 serial
[3] = curtime
;
4434 gnutls_x509_crt_init(&crt
);
4435 if (strlen(language
->language
) == 5)
4436 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
4437 language
->language
+ 3, 2);
4439 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
4441 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COMMON_NAME
, 0,
4442 ServerName
, strlen(ServerName
));
4443 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATION_NAME
, 0,
4444 ServerName
, strlen(ServerName
));
4445 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATIONAL_UNIT_NAME
,
4447 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_STATE_OR_PROVINCE_NAME
, 0,
4449 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_LOCALITY_NAME
, 0,
4451 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_PKCS9_EMAIL
, 0,
4452 ServerAdmin
, strlen(ServerAdmin
));
4453 gnutls_x509_crt_set_key(crt
, key
);
4454 gnutls_x509_crt_set_serial(crt
, serial
, sizeof(serial
));
4455 gnutls_x509_crt_set_activation_time(crt
, curtime
);
4456 gnutls_x509_crt_set_expiration_time(crt
, curtime
+ 10 * 365 * 86400);
4457 gnutls_x509_crt_set_ca_status(crt
, 0);
4458 gnutls_x509_crt_set_subject_alternative_name(crt
, GNUTLS_SAN_DNSNAME
,
4460 gnutls_x509_crt_set_key_purpose_oid(crt
, GNUTLS_KP_TLS_WWW_SERVER
, 0);
4461 gnutls_x509_crt_set_key_usage(crt
, GNUTLS_KEY_KEY_ENCIPHERMENT
);
4462 gnutls_x509_crt_set_version(crt
, 3);
4464 bytes
= sizeof(buffer
);
4465 if (gnutls_x509_crt_get_key_id(crt
, 0, buffer
, &bytes
) >= 0)
4466 gnutls_x509_crt_set_subject_key_id(crt
, buffer
, bytes
);
4468 gnutls_x509_crt_sign(crt
, crt
, key
);
4474 bytes
= sizeof(buffer
);
4475 if ((result
= gnutls_x509_crt_export(crt
, GNUTLS_X509_FMT_PEM
,
4476 buffer
, &bytes
)) < 0)
4477 cupsdLogMessage(CUPSD_LOG_ERROR
,
4478 "Unable to export SSL server certificate - %s",
4479 gnutls_strerror(result
));
4480 else if ((fp
= cupsFileOpen(ServerCertificate
, "w")) != NULL
)
4482 cupsFileWrite(fp
, (char *)buffer
, bytes
);
4485 cupsdLogMessage(CUPSD_LOG_INFO
,
4486 "Created SSL server certificate file \"%s\"...",
4490 cupsdLogMessage(CUPSD_LOG_ERROR
,
4491 "Unable to create SSL server certificate file \"%s\" - %s",
4492 ServerCertificate
, strerror(errno
));
4498 gnutls_x509_crt_deinit(crt
);
4499 gnutls_x509_privkey_deinit(key
);
4503 #elif defined(HAVE_CDSASSL) && defined(HAVE_WAITPID)
4504 int pid
, /* Process ID of command */
4505 status
; /* Status of command */
4506 char command
[1024], /* Command */
4507 *argv
[4], /* Command-line arguments */
4508 *envp
[MAX_ENV
+ 1], /* Environment variables */
4509 keychain
[1024], /* Keychain argument */
4510 infofile
[1024], /* Type-in information for cert */
4511 localname
[1024], /* Local hostname */
4512 *servername
; /* Name of server in cert */
4513 cups_file_t
*fp
; /* Seed/info file */
4514 int infofd
; /* Info file descriptor */
4517 if (con
->servername
&& isdigit(con
->servername
[0] & 255) && DNSSDHostName
)
4519 snprintf(localname
, sizeof(localname
), "%s.local", DNSSDHostName
);
4520 servername
= localname
;
4523 servername
= con
->servername
;
4526 * Run the "certtool" command to generate a self-signed certificate...
4529 if (!cupsFileFind("certtool", getenv("PATH"), 1, command
, sizeof(command
)))
4531 cupsdLogMessage(CUPSD_LOG_ERROR
,
4532 "No SSL certificate and certtool command not found!");
4537 * Create a file with the certificate information fields...
4539 * Note: This assumes that the default questions are asked by the certtool
4543 if ((fp
= cupsTempFile2(infofile
, sizeof(infofile
))) == NULL
)
4545 cupsdLogMessage(CUPSD_LOG_ERROR
,
4546 "Unable to create certificate information file %s - %s",
4547 infofile
, strerror(errno
));
4551 cupsFilePrintf(fp
, "%s\nr\n\ny\nb\ns\ny\n%s\n\n\n\n\n%s\ny\n",
4552 servername
, servername
, ServerAdmin
);
4555 cupsdLogMessage(CUPSD_LOG_INFO
,
4556 "Generating SSL server key and certificate...");
4558 snprintf(keychain
, sizeof(keychain
), "k=%s", ServerCertificate
);
4560 argv
[0] = "certtool";
4565 cupsdLoadEnv(envp
, MAX_ENV
);
4567 infofd
= open(infofile
, O_RDONLY
);
4569 if (!cupsdStartProcess(command
, argv
, envp
, infofd
, -1, -1, -1, -1, 1, NULL
,
4580 while (waitpid(pid
, &status
, 0) < 0)
4587 cupsdFinishProcess(pid
, command
, sizeof(command
), NULL
);
4591 if (WIFEXITED(status
))
4592 cupsdLogMessage(CUPSD_LOG_ERROR
,
4593 "Unable to create SSL server key and certificate - "
4594 "the certtool command stopped with status %d!",
4595 WEXITSTATUS(status
));
4597 cupsdLogMessage(CUPSD_LOG_ERROR
,
4598 "Unable to create SSL server key and certificate - "
4599 "the certtool command crashed on signal %d!",
4604 cupsdLogMessage(CUPSD_LOG_INFO
,
4605 "Created SSL server certificate file \"%s\"...",
4613 #endif /* HAVE_LIBSSL && HAVE_WAITPID */
4615 #endif /* HAVE_SSL */
4619 * 'pipe_command()' - Pipe the output of a command to the remote client.
4622 static int /* O - Process ID */
4623 pipe_command(cupsd_client_t
*con
, /* I - Client connection */
4624 int infile
, /* I - Standard input for command */
4625 int *outfile
, /* O - Standard output for command */
4626 char *command
, /* I - Command to run */
4627 char *options
, /* I - Options for command */
4628 int root
) /* I - Run as root? */
4630 int i
; /* Looping var */
4631 int pid
; /* Process ID */
4632 char *commptr
, /* Command string pointer */
4633 commch
; /* Command string character */
4634 char *uriptr
; /* URI string pointer */
4635 int fds
[2]; /* Pipe FDs */
4636 int argc
; /* Number of arguments */
4637 int envc
; /* Number of environment variables */
4638 char argbuf
[10240], /* Argument buffer */
4639 *argv
[100], /* Argument strings */
4640 *envp
[MAX_ENV
+ 20]; /* Environment variables */
4641 char auth_type
[256], /* AUTH_TYPE environment variable */
4642 content_length
[1024], /* CONTENT_LENGTH environment variable */
4643 content_type
[1024], /* CONTENT_TYPE environment variable */
4644 http_cookie
[32768], /* HTTP_COOKIE environment variable */
4645 http_referer
[1024], /* HTTP_REFERER environment variable */
4646 http_user_agent
[1024], /* HTTP_USER_AGENT environment variable */
4647 lang
[1024], /* LANG environment variable */
4648 path_info
[1024], /* PATH_INFO environment variable */
4649 remote_addr
[1024], /* REMOTE_ADDR environment variable */
4650 remote_host
[1024], /* REMOTE_HOST environment variable */
4651 remote_user
[1024], /* REMOTE_USER environment variable */
4652 script_filename
[1024], /* SCRIPT_FILENAME environment variable */
4653 script_name
[1024], /* SCRIPT_NAME environment variable */
4654 server_name
[1024], /* SERVER_NAME environment variable */
4655 server_port
[1024]; /* SERVER_PORT environment variable */
4656 ipp_attribute_t
*attr
; /* attributes-natural-language attribute */
4657 void *ccache
= NULL
; /* Kerberos credentials */
4661 * Parse a copy of the options string, which is of the form:
4663 * argument+argument+argument
4664 * ?argument+argument+argument
4665 * param=value¶m=value
4666 * ?param=value¶m=value
4667 * /name?argument+argument+argument
4668 * /name?param=value¶m=value
4670 * If the string contains an "=" character after the initial name,
4671 * then we treat it as a HTTP GET form request and make a copy of
4672 * the remaining string for the environment variable.
4674 * The string is always parsed out as command-line arguments, to
4675 * be consistent with Apache...
4678 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4679 "[Client %d] pipe_command infile=%d, outfile=%p, "
4680 "command=\"%s\", options=\"%s\", root=%d",
4681 con
->http
.fd
, infile
, outfile
, command
,
4682 options
? options
: "(null)", root
);
4689 if (*commptr
== ' ')
4691 strlcpy(argbuf
, commptr
, sizeof(argbuf
));
4696 if (argbuf
[0] == '/')
4699 * Found some trailing path information, set PATH_INFO...
4702 if ((commptr
= strchr(argbuf
, '?')) == NULL
)
4703 commptr
= argbuf
+ strlen(argbuf
);
4707 snprintf(path_info
, sizeof(path_info
), "PATH_INFO=%s", argbuf
);
4713 path_info
[0] = '\0';
4715 if (*commptr
== ' ')
4719 if (*commptr
== '?' && con
->operation
== HTTP_GET
&& !con
->query_string
)
4722 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", commptr
);
4729 argv
[argc
++] = commptr
;
4731 for (; *commptr
&& argc
< 99; commptr
++)
4734 * Break arguments whenever we see a + or space...
4737 if (*commptr
== ' ' || *commptr
== '+')
4739 while (*commptr
== ' ' || *commptr
== '+')
4743 * If we don't have a blank string, save it as another argument...
4748 argv
[argc
] = commptr
;
4754 else if (*commptr
== '%' && isxdigit(commptr
[1] & 255) &&
4755 isxdigit(commptr
[2] & 255))
4758 * Convert the %xx notation to the individual character.
4761 if (commptr
[1] >= '0' && commptr
[1] <= '9')
4762 *commptr
= (commptr
[1] - '0') << 4;
4764 *commptr
= (tolower(commptr
[1]) - 'a' + 10) << 4;
4766 if (commptr
[2] >= '0' && commptr
[2] <= '9')
4767 *commptr
|= commptr
[2] - '0';
4769 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
4771 _cups_strcpy(commptr
+ 1, commptr
+ 3);
4774 * Check for a %00 and break if that is the case...
4786 * Setup the environment variables as needed...
4789 if (con
->username
[0])
4791 snprintf(auth_type
, sizeof(auth_type
), "AUTH_TYPE=%s",
4792 httpGetField(HTTP(con
), HTTP_FIELD_AUTHORIZATION
));
4794 if ((uriptr
= strchr(auth_type
+ 10, ' ')) != NULL
)
4798 auth_type
[0] = '\0';
4801 (attr
= ippFindAttribute(con
->request
, "attributes-natural-language",
4802 IPP_TAG_LANGUAGE
)) != NULL
)
4804 switch (strlen(attr
->values
[0].string
.text
))
4808 * This is an unknown or badly formatted language code; use
4809 * the POSIX locale...
4812 strcpy(lang
, "LANG=C");
4817 * Just the language code (ll)...
4820 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8",
4821 attr
->values
[0].string
.text
);
4826 * Language and country code (ll-cc)...
4829 snprintf(lang
, sizeof(lang
), "LANG=%c%c_%c%c.UTF8",
4830 attr
->values
[0].string
.text
[0],
4831 attr
->values
[0].string
.text
[1],
4832 toupper(attr
->values
[0].string
.text
[3] & 255),
4833 toupper(attr
->values
[0].string
.text
[4] & 255));
4837 else if (con
->language
)
4838 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8", con
->language
->language
);
4840 strcpy(lang
, "LANG=C");
4842 strcpy(remote_addr
, "REMOTE_ADDR=");
4843 httpAddrString(con
->http
.hostaddr
, remote_addr
+ 12,
4844 sizeof(remote_addr
) - 12);
4846 snprintf(remote_host
, sizeof(remote_host
), "REMOTE_HOST=%s",
4847 con
->http
.hostname
);
4849 snprintf(script_name
, sizeof(script_name
), "SCRIPT_NAME=%s", con
->uri
);
4850 if ((uriptr
= strchr(script_name
, '?')) != NULL
)
4853 snprintf(script_filename
, sizeof(script_filename
), "SCRIPT_FILENAME=%s%s",
4854 DocumentRoot
, script_name
+ 12);
4856 sprintf(server_port
, "SERVER_PORT=%d", con
->serverport
);
4858 if (con
->http
.fields
[HTTP_FIELD_HOST
][0])
4860 char *nameptr
; /* Pointer to ":port" */
4862 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
4863 con
->http
.fields
[HTTP_FIELD_HOST
]);
4864 if ((nameptr
= strrchr(server_name
, ':')) != NULL
&& !strchr(nameptr
, ']'))
4865 *nameptr
= '\0'; /* Strip trailing ":port" */
4868 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
4871 envc
= cupsdLoadEnv(envp
, (int)(sizeof(envp
) / sizeof(envp
[0])));
4874 envp
[envc
++] = auth_type
;
4876 envp
[envc
++] = lang
;
4877 envp
[envc
++] = "REDIRECT_STATUS=1";
4878 envp
[envc
++] = "GATEWAY_INTERFACE=CGI/1.1";
4879 envp
[envc
++] = server_name
;
4880 envp
[envc
++] = server_port
;
4881 envp
[envc
++] = remote_addr
;
4882 envp
[envc
++] = remote_host
;
4883 envp
[envc
++] = script_name
;
4884 envp
[envc
++] = script_filename
;
4887 envp
[envc
++] = path_info
;
4889 if (con
->username
[0])
4891 snprintf(remote_user
, sizeof(remote_user
), "REMOTE_USER=%s", con
->username
);
4893 envp
[envc
++] = remote_user
;
4896 if (con
->http
.version
== HTTP_1_1
)
4897 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.1";
4898 else if (con
->http
.version
== HTTP_1_0
)
4899 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.0";
4901 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/0.9";
4903 if (con
->http
.cookie
)
4905 snprintf(http_cookie
, sizeof(http_cookie
), "HTTP_COOKIE=%s",
4907 envp
[envc
++] = http_cookie
;
4910 if (con
->http
.fields
[HTTP_FIELD_USER_AGENT
][0])
4912 snprintf(http_user_agent
, sizeof(http_user_agent
), "HTTP_USER_AGENT=%s",
4913 con
->http
.fields
[HTTP_FIELD_USER_AGENT
]);
4914 envp
[envc
++] = http_user_agent
;
4917 if (con
->http
.fields
[HTTP_FIELD_REFERER
][0])
4919 snprintf(http_referer
, sizeof(http_referer
), "HTTP_REFERER=%s",
4920 con
->http
.fields
[HTTP_FIELD_REFERER
]);
4921 envp
[envc
++] = http_referer
;
4924 if (con
->operation
== HTTP_GET
)
4926 envp
[envc
++] = "REQUEST_METHOD=GET";
4928 if (con
->query_string
)
4931 * Add GET form variables after ?...
4934 envp
[envc
++] = con
->query_string
;
4937 envp
[envc
++] = "QUERY_STRING=";
4941 sprintf(content_length
, "CONTENT_LENGTH=" CUPS_LLFMT
,
4942 CUPS_LLCAST con
->bytes
);
4943 snprintf(content_type
, sizeof(content_type
), "CONTENT_TYPE=%s",
4944 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
4946 envp
[envc
++] = "REQUEST_METHOD=POST";
4947 envp
[envc
++] = content_length
;
4948 envp
[envc
++] = content_type
;
4952 * Tell the CGI if we are using encryption...
4956 envp
[envc
++] = "HTTPS=ON";
4959 * Terminate the environment array...
4964 if (LogLevel
>= CUPSD_LOG_DEBUG
)
4966 for (i
= 0; i
< argc
; i
++)
4967 cupsdLogMessage(CUPSD_LOG_DEBUG
,
4968 "[CGI] argv[%d] = \"%s\"", i
, argv
[i
]);
4969 for (i
= 0; i
< envc
; i
++)
4970 cupsdLogMessage(CUPSD_LOG_DEBUG
,
4971 "[CGI] envp[%d] = \"%s\"", i
, envp
[i
]);
4975 * Create a pipe for the output...
4978 if (cupsdOpenPipe(fds
))
4980 cupsdLogMessage(CUPSD_LOG_ERROR
, "[CGI] Unable to create pipe for %s - %s",
4981 argv
[0], strerror(errno
));
4986 * Then execute the command...
4989 if (cupsdStartProcess(command
, argv
, envp
, infile
, fds
[1], CGIPipes
[1],
4990 -1, -1, root
, DefaultProfile
, NULL
, &pid
) < 0)
4993 * Error - can't fork!
4996 cupsdLogMessage(CUPSD_LOG_ERROR
, "[CGI] Unable to start %s - %s", argv
[0],
4999 cupsdClosePipe(fds
);
5005 * Fork successful - return the PID...
5008 if (con
->username
[0])
5009 cupsdAddCert(pid
, con
->username
, ccache
);
5011 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[CGI] Started %s (PID %d)", command
, pid
);
5022 * 'valid_host()' - Is the Host: field valid?
5025 static int /* O - 1 if valid, 0 if not */
5026 valid_host(cupsd_client_t
*con
) /* I - Client connection */
5028 cupsd_alias_t
*a
; /* Current alias */
5029 cupsd_netif_t
*netif
; /* Current network interface */
5030 const char *host
, /* Host field */
5031 *end
; /* End character */
5034 host
= con
->http
.fields
[HTTP_FIELD_HOST
];
5036 if (httpAddrLocalhost(con
->http
.hostaddr
))
5039 * Only allow "localhost" or the equivalent IPv4 or IPv6 numerical
5040 * addresses when accessing CUPS via the loopback interface...
5043 return (!_cups_strcasecmp(host
, "localhost") ||
5044 !_cups_strncasecmp(host
, "localhost:", 10) ||
5045 !_cups_strcasecmp(host
, "localhost.") ||
5046 !_cups_strncasecmp(host
, "localhost.:", 11) ||
5048 !_cups_strcasecmp(host
, "localhost.localdomain") ||
5049 !_cups_strncasecmp(host
, "localhost.localdomain:", 22) ||
5050 #endif /* __linux */
5051 !strcmp(host
, "127.0.0.1") ||
5052 !strncmp(host
, "127.0.0.1:", 10) ||
5053 !strcmp(host
, "[::1]") ||
5054 !strncmp(host
, "[::1]:", 6));
5059 * Check if the hostname is something.local (Bonjour); if so, allow it.
5062 if ((end
= strrchr(host
, '.')) != NULL
&&
5063 (!_cups_strcasecmp(end
, ".local") || !_cups_strncasecmp(end
, ".local:", 7) ||
5064 !_cups_strcasecmp(end
, ".local.") || !_cups_strncasecmp(end
, ".local.:", 8)))
5066 #endif /* HAVE_DNSSD */
5069 * Check if the hostname is an IP address...
5072 if (isdigit(*host
& 255) || *host
== '[')
5075 * Possible IPv4/IPv6 address...
5078 char temp
[1024], /* Temporary string */
5079 *ptr
; /* Pointer into temporary string */
5080 http_addrlist_t
*addrlist
; /* List of addresses */
5083 strlcpy(temp
, host
, sizeof(temp
));
5084 if ((ptr
= strrchr(temp
, ':')) != NULL
&& !strchr(ptr
, ']'))
5085 *ptr
= '\0'; /* Strip :port from host value */
5087 if ((addrlist
= httpAddrGetList(temp
, AF_UNSPEC
, NULL
)) != NULL
)
5090 * Good IPv4/IPv6 address...
5093 httpAddrFreeList(addrlist
);
5099 * Check for (alias) name matches...
5102 for (a
= (cupsd_alias_t
*)cupsArrayFirst(ServerAlias
);
5104 a
= (cupsd_alias_t
*)cupsArrayNext(ServerAlias
))
5107 * "ServerAlias *" allows all host values through...
5110 if (!strcmp(a
->name
, "*"))
5113 if (!_cups_strncasecmp(host
, a
->name
, a
->namelen
))
5116 * Prefix matches; check the character at the end - it must be ":", ".",
5120 end
= host
+ a
->namelen
;
5122 if (!*end
|| *end
== ':' || (*end
== '.' && (!end
[1] || end
[1] == ':')))
5128 for (a
= (cupsd_alias_t
*)cupsArrayFirst(DNSSDAlias
);
5130 a
= (cupsd_alias_t
*)cupsArrayNext(DNSSDAlias
))
5133 * "ServerAlias *" allows all host values through...
5136 if (!strcmp(a
->name
, "*"))
5139 if (!_cups_strncasecmp(host
, a
->name
, a
->namelen
))
5142 * Prefix matches; check the character at the end - it must be ":", ".",
5146 end
= host
+ a
->namelen
;
5148 if (!*end
|| *end
== ':' || (*end
== '.' && (!end
[1] || end
[1] == ':')))
5152 #endif /* HAVE_DNSSD */
5155 * Check for interface hostname matches...
5158 for (netif
= (cupsd_netif_t
*)cupsArrayFirst(NetIFList
);
5160 netif
= (cupsd_netif_t
*)cupsArrayNext(NetIFList
))
5162 if (!_cups_strncasecmp(host
, netif
->hostname
, netif
->hostlen
))
5165 * Prefix matches; check the character at the end - it must be ":", ".",
5169 end
= host
+ netif
->hostlen
;
5171 if (!*end
|| *end
== ':' || (*end
== '.' && (!end
[1] || end
[1] == ':')))
5181 * 'write_file()' - Send a file via HTTP.
5184 static int /* O - 0 on failure, 1 on success */
5185 write_file(cupsd_client_t
*con
, /* I - Client connection */
5186 http_status_t code
, /* I - HTTP status */
5187 char *filename
, /* I - Filename */
5188 char *type
, /* I - File type */
5189 struct stat
*filestats
) /* O - File information */
5191 con
->file
= open(filename
, O_RDONLY
);
5193 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
5194 "[Client %d] write_file code=%d, filename=\"%s\" (%d), "
5195 "type=\"%s\", filestats=%p", con
->http
.fd
,
5196 code
, filename
, con
->file
, type
? type
: "(null)", filestats
);
5201 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
5205 if (!cupsdSendHeader(con
, code
, type
, CUPSD_AUTH_NONE
))
5208 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
5209 httpGetDateString(filestats
->st_mtime
)) < 0)
5211 if (httpPrintf(HTTP(con
), "Content-Length: " CUPS_LLFMT
"\r\n",
5212 CUPS_LLCAST filestats
->st_size
) < 0)
5214 if (httpPrintf(HTTP(con
), "\r\n") < 0)
5217 if (cupsdFlushHeader(con
) < 0)
5220 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
5221 con
->http
.data_remaining
= filestats
->st_size
;
5223 if (con
->http
.data_remaining
<= INT_MAX
)
5224 con
->http
._data_remaining
= con
->http
.data_remaining
;
5226 con
->http
._data_remaining
= INT_MAX
;
5228 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
,
5229 (cupsd_selfunc_t
)cupsdWriteClient
, con
);
5236 * 'write_pipe()' - Flag that data is available on the CGI pipe.
5240 write_pipe(cupsd_client_t
*con
) /* I - Client connection */
5242 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
5243 "[Client %d] write_pipe CGI output on fd %d",
5244 con
->http
.fd
, con
->file
);
5246 con
->file_ready
= 1;
5248 cupsdRemoveSelect(con
->file
);
5249 cupsdAddSelect(con
->http
.fd
, NULL
, (cupsd_selfunc_t
)cupsdWriteClient
, con
);
5254 * End of "$Id: client.c 7950 2008-09-17 00:21:59Z mike $".