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 * data_ready() - Check whether data is available from a client.
34 * encrypt_client() - Enable encryption for the client...
35 * get_cdsa_certificate() - Get a SSL/TLS certificate from the System
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 client.
44 * valid_host() - Is the Host: field valid?
45 * write_file() - Send a file via HTTP.
46 * write_pipe() - Flag that data is available on the CGI pipe.
50 * Include necessary headers...
57 #endif /* HAVE_TCPD_H */
64 static int check_if_modified(cupsd_client_t
*con
,
65 struct stat
*filestats
);
66 static int compare_clients(cupsd_client_t
*a
, cupsd_client_t
*b
,
68 static int data_ready(cupsd_client_t
*con
);
70 static int encrypt_client(cupsd_client_t
*con
);
73 static CFArrayRef
get_cdsa_certificate(cupsd_client_t
*con
);
74 #endif /* HAVE_CDSASSL */
75 static char *get_file(cupsd_client_t
*con
, struct stat
*filestats
,
76 char *filename
, int len
);
77 static http_status_t
install_conf_file(cupsd_client_t
*con
);
78 static int is_cgi(cupsd_client_t
*con
, const char *filename
,
79 struct stat
*filestats
, mime_type_t
*type
);
80 static int is_path_absolute(const char *path
);
82 static int make_certificate(cupsd_client_t
*con
);
84 static int pipe_command(cupsd_client_t
*con
, int infile
, int *outfile
,
85 char *command
, char *options
, int root
);
86 static int valid_host(cupsd_client_t
*con
);
87 static int write_file(cupsd_client_t
*con
, http_status_t code
,
88 char *filename
, char *type
,
89 struct stat
*filestats
);
90 static void write_pipe(cupsd_client_t
*con
);
94 * 'cupsdAcceptClient()' - Accept a new client.
98 cupsdAcceptClient(cupsd_listener_t
*lis
)/* I - Listener socket */
100 int count
; /* Count of connections on a host */
101 int val
; /* Parameter value */
102 cupsd_client_t
*con
, /* New client pointer */
103 *tempcon
; /* Temporary client pointer */
104 http_addrlist_t
*addrlist
, /* List of adddresses for host */
105 *addr
; /* Current address */
106 socklen_t addrlen
; /* Length of address */
107 char *hostname
; /* Hostname for address */
108 http_addr_t temp
; /* Temporary address variable */
109 static time_t last_dos
= 0; /* Time of last DoS attack */
111 struct request_info wrap_req
; /* TCP wrappers request information */
112 #endif /* HAVE_TCPD_H */
115 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
116 "cupsdAcceptClient(lis=%p(%d)) Clients=%d",
117 lis
, lis
->fd
, cupsArrayCount(Clients
));
120 * Make sure we don't have a full set of clients already...
123 if (cupsArrayCount(Clients
) == MaxClients
)
127 * Get a pointer to the next available client...
131 Clients
= cupsArrayNew(NULL
, NULL
);
135 cupsdLogMessage(CUPSD_LOG_ERROR
,
136 "Unable to allocate memory for clients array!");
137 cupsdPauseListening();
142 ActiveClients
= cupsArrayNew((cups_array_func_t
)compare_clients
, NULL
);
146 cupsdLogMessage(CUPSD_LOG_ERROR
,
147 "Unable to allocate memory for active clients array!");
148 cupsdPauseListening();
152 if ((con
= calloc(1, sizeof(cupsd_client_t
))) == NULL
)
154 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to allocate memory for client!");
155 cupsdPauseListening();
159 con
->http
.activity
= time(NULL
);
161 con
->http
.hostaddr
= &(con
->clientaddr
);
164 * Accept the client and get the remote address...
167 addrlen
= sizeof(http_addr_t
);
169 if ((con
->http
.fd
= accept(lis
->fd
, (struct sockaddr
*)con
->http
.hostaddr
,
172 if (errno
== ENFILE
|| errno
== EMFILE
)
173 cupsdPauseListening();
175 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to accept client connection - %s.",
183 if (lis
->address
.addr
.sa_family
== AF_INET6
)
186 * Save the connected port number...
189 con
->http
.hostaddr
->ipv6
.sin6_port
= lis
->address
.ipv6
.sin6_port
;
192 * Convert IPv4 over IPv6 addresses (::ffff:n.n.n.n) to IPv4 forms we
193 * can more easily use...
196 if (con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[0] == 0 &&
197 con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[1] == 0 &&
198 ntohl(con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[2]) == 0xffff)
199 con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[2] = 0;
202 #endif /* AF_INET6 */
203 if (lis
->address
.addr
.sa_family
== AF_INET
)
204 con
->http
.hostaddr
->ipv4
.sin_port
= lis
->address
.ipv4
.sin_port
;
207 * Check the number of clients on the same address...
210 for (count
= 0, tempcon
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
212 tempcon
= (cupsd_client_t
*)cupsArrayNext(Clients
))
213 if (httpAddrEqual(tempcon
->http
.hostaddr
, con
->http
.hostaddr
))
216 if (count
>= MaxClientsPerHost
)
220 if (count
>= MaxClientsPerHost
)
222 if ((time(NULL
) - last_dos
) >= 60)
224 last_dos
= time(NULL
);
225 cupsdLogMessage(CUPSD_LOG_WARN
,
226 "Possible DoS attack - more than %d clients connecting "
229 httpAddrString(con
->http
.hostaddr
, con
->http
.hostname
,
230 sizeof(con
->http
.hostname
)));
234 closesocket(con
->http
.fd
);
244 * Get the hostname or format the IP address as needed...
247 if (httpAddrLocalhost(con
->http
.hostaddr
))
250 * Map accesses from the loopback interface to "localhost"...
253 strlcpy(con
->http
.hostname
, "localhost", sizeof(con
->http
.hostname
));
254 hostname
= con
->http
.hostname
;
259 * Map accesses from the same host to the server name.
263 hostname
= httpAddrLookup(con
->http
.hostaddr
, con
->http
.hostname
,
264 sizeof(con
->http
.hostname
));
268 httpAddrString(con
->http
.hostaddr
, con
->http
.hostname
,
269 sizeof(con
->http
.hostname
));
273 if (hostname
== NULL
&& HostNameLookups
== 2)
276 * Can't have an unresolved IP address with double-lookups enabled...
280 closesocket(con
->http
.fd
);
285 cupsdLogMessage(CUPSD_LOG_WARN
,
286 "Name lookup failed - connection from %s closed!",
293 if (HostNameLookups
== 2)
296 * Do double lookups as needed...
299 if ((addrlist
= httpAddrGetList(con
->http
.hostname
, AF_UNSPEC
, NULL
))
303 * See if the hostname maps to the same IP address...
306 for (addr
= addrlist
; addr
; addr
= addr
->next
)
307 if (httpAddrEqual(con
->http
.hostaddr
, &(addr
->addr
)))
313 httpAddrFreeList(addrlist
);
318 * Can't have a hostname that doesn't resolve to the same IP address
319 * with double-lookups enabled...
323 closesocket(con
->http
.fd
);
328 cupsdLogMessage(CUPSD_LOG_WARN
,
329 "IP lookup failed - connection from %s closed!",
338 * See if the connection is denied by TCP wrappers...
341 request_init(&wrap_req
, RQ_DAEMON
, "cupsd", RQ_FILE
, con
->http
.fd
, NULL
);
344 if (!hosts_access(&wrap_req
))
347 closesocket(con
->http
.fd
);
352 cupsdLogMessage(CUPSD_LOG_WARN
,
353 "Connection from %s refused by /etc/hosts.allow and "
354 "/etc/hosts.deny rules.", con
->http
.hostname
);
358 #endif /* HAVE_TCPD_H */
361 if (con
->http
.hostaddr
->addr
.sa_family
== AF_INET6
)
362 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdAcceptClient: %d from %s:%d (IPv6)",
363 con
->http
.fd
, con
->http
.hostname
,
364 ntohs(con
->http
.hostaddr
->ipv6
.sin6_port
));
366 #endif /* AF_INET6 */
368 if (con
->http
.hostaddr
->addr
.sa_family
== AF_LOCAL
)
369 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdAcceptClient: %d from %s (Domain)",
370 con
->http
.fd
, con
->http
.hostname
);
372 #endif /* AF_LOCAL */
373 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdAcceptClient: %d from %s:%d (IPv4)",
374 con
->http
.fd
, con
->http
.hostname
,
375 ntohs(con
->http
.hostaddr
->ipv4
.sin_port
));
378 * Get the local address the client connected to...
381 addrlen
= sizeof(temp
);
382 if (getsockname(con
->http
.fd
, (struct sockaddr
*)&temp
, &addrlen
))
384 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to get local address - %s",
387 strcpy(con
->servername
, "localhost");
388 con
->serverport
= LocalPort
;
393 if (temp
.addr
.sa_family
== AF_INET6
)
395 if (httpAddrLocalhost(&temp
))
396 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
397 else if (HostNameLookups
|| RemotePort
)
398 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
400 httpAddrString(&temp
, con
->servername
, sizeof(con
->servername
));
402 con
->serverport
= ntohs(lis
->address
.ipv6
.sin6_port
);
405 #endif /* AF_INET6 */
406 if (temp
.addr
.sa_family
== AF_INET
)
408 if (httpAddrLocalhost(&temp
))
409 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
410 else if (HostNameLookups
|| RemotePort
)
411 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
413 httpAddrString(&temp
, con
->servername
, sizeof(con
->servername
));
415 con
->serverport
= ntohs(lis
->address
.ipv4
.sin_port
);
419 strcpy(con
->servername
, "localhost");
420 con
->serverport
= LocalPort
;
424 cupsArrayAdd(Clients
, con
);
427 * Using TCP_NODELAY improves responsiveness, especially on systems with a slow
428 * loopback interface. Since we write large buffers when sending print files
429 * and requests there shouldn't be any performance penalty for this...
433 setsockopt(con
->http
.fd
, IPPROTO_TCP
, TCP_NODELAY
, &val
, sizeof(val
));
436 * Close this file on all execs...
439 fcntl(con
->http
.fd
, F_SETFD
, fcntl(con
->http
.fd
, F_GETFD
) | FD_CLOEXEC
);
442 * Add the socket to the server select.
445 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
448 * Temporarily suspend accept()'s until we lose a client...
451 if (cupsArrayCount(Clients
) == MaxClients
)
452 cupsdPauseListening();
456 * See if we are connecting on a secure port...
459 if (lis
->encryption
== HTTP_ENCRYPT_ALWAYS
)
462 * https connection; go secure...
465 con
->http
.encryption
= HTTP_ENCRYPT_ALWAYS
;
467 if (!encrypt_client(con
))
468 cupsdCloseClient(con
);
472 #endif /* HAVE_SSL */
477 * 'cupsdCloseAllClients()' - Close all remote clients immediately.
481 cupsdCloseAllClients(void)
483 cupsd_client_t
*con
; /* Current client */
486 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdCloseAllClients() Clients=%d",
487 cupsArrayCount(Clients
));
489 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
491 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
492 if (cupsdCloseClient(con
))
493 cupsdCloseClient(con
);
498 * 'cupsdCloseClient()' - Close a remote client.
501 int /* O - 1 if partial close, 0 if fully closed */
502 cupsdCloseClient(cupsd_client_t
*con
) /* I - Client to close */
504 int partial
; /* Do partial close for SSL? */
506 SSL_CTX
*context
; /* Context for encryption */
507 unsigned long error
; /* Error code */
508 #elif defined(HAVE_GNUTLS)
509 int error
; /* Error code */
510 gnutls_certificate_server_credentials
*credentials
;
511 /* TLS credentials */
512 # elif defined(HAVE_CDSASSL)
513 #endif /* HAVE_LIBSSL */
516 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdCloseClient: %d", con
->http
.fd
);
519 * Flush pending writes before closing...
522 httpFlushWrite(HTTP(con
));
528 * Shutdown encryption as needed...
536 context
= SSL_get_SSL_CTX(con
->http
.tls
);
538 switch (SSL_shutdown(con
->http
.tls
))
541 cupsdLogMessage(CUPSD_LOG_DEBUG
,
542 "SSL shutdown successful!");
545 cupsdLogMessage(CUPSD_LOG_ERROR
,
546 "Fatal error during SSL shutdown!");
548 while ((error
= ERR_get_error()) != 0)
549 cupsdLogMessage(CUPSD_LOG_ERROR
, "SSL shutdown failed: %s",
550 ERR_error_string(error
, NULL
));
554 SSL_CTX_free(context
);
555 SSL_free(con
->http
.tls
);
557 # elif defined(HAVE_GNUTLS)
558 credentials
= (gnutls_certificate_server_credentials
*)(con
->http
.tls_credentials
);
560 error
= gnutls_bye(con
->http
.tls
, GNUTLS_SHUT_WR
);
563 case GNUTLS_E_SUCCESS
:
564 cupsdLogMessage(CUPSD_LOG_DEBUG
,
565 "SSL shutdown successful!");
568 cupsdLogMessage(CUPSD_LOG_ERROR
,
569 "SSL shutdown failed: %s", gnutls_strerror(error
));
573 gnutls_deinit(con
->http
.tls
);
574 gnutls_certificate_free_credentials(*credentials
);
577 # elif defined(HAVE_CDSASSL)
578 while (SSLClose(con
->http
.tls
) == errSSLWouldBlock
)
581 SSLDisposeContext(con
->http
.tls
);
583 if (con
->http
.tls_credentials
)
584 CFRelease(con
->http
.tls_credentials
);
586 # endif /* HAVE_LIBSSL */
588 con
->http
.tls
= NULL
;
590 #endif /* HAVE_SSL */
592 if (con
->pipe_pid
!= 0)
595 * Stop any CGI process...
598 cupsdEndProcess(con
->pipe_pid
, 1);
604 cupsdRemoveSelect(con
->file
);
611 * Close the socket and clear the file from the input set for select()...
614 if (con
->http
.fd
>= 0)
616 cupsArrayRemove(ActiveClients
, con
);
622 * Only do a partial close so that the encrypted client gets everything.
625 shutdown(con
->http
.fd
, 0);
626 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
631 * Shut the socket down fully...
634 cupsdRemoveSelect(con
->http
.fd
);
646 if (con
->http
.input_set
)
647 free(con
->http
.input_set
);
649 httpClearCookie(HTTP(con
));
650 httpClearFields(HTTP(con
));
652 cupsdClearString(&con
->filename
);
653 cupsdClearString(&con
->command
);
654 cupsdClearString(&con
->options
);
655 cupsdClearString(&con
->query_string
);
659 ippDelete(con
->request
);
665 ippDelete(con
->response
);
666 con
->response
= NULL
;
671 cupsLangFree(con
->language
);
672 con
->language
= NULL
;
675 #ifdef HAVE_AUTHORIZATION_H
678 AuthorizationFree(con
->authref
, kAuthorizationFlagDefaults
);
681 #endif /* HAVE_AUTHORIZATION_H */
684 * Re-enable new client connections if we are going back under the
688 if (cupsArrayCount(Clients
) == MaxClients
)
689 cupsdResumeListening();
692 * Compact the list of clients as necessary...
695 cupsArrayRemove(Clients
, con
);
705 * 'cupsdFlushHeader()' - Flush the header fields to the client.
708 int /* I - Bytes written or -1 on error */
709 cupsdFlushHeader(cupsd_client_t
*con
) /* I - Client to flush to */
711 int bytes
= httpFlushWrite(HTTP(con
));
713 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
720 * 'cupsdReadClient()' - Read data from a client.
724 cupsdReadClient(cupsd_client_t
*con
) /* I - Client to read from */
726 char line
[32768], /* Line from client... */
727 operation
[64], /* Operation code from socket */
728 version
[64], /* HTTP version number string */
729 locale
[64], /* Locale */
730 *ptr
; /* Pointer into strings */
731 int major
, minor
; /* HTTP version numbers */
732 http_status_t status
; /* Transfer status */
733 ipp_state_t ipp_state
; /* State of IPP transfer */
734 int bytes
; /* Number of bytes to POST */
735 char *filename
; /* Name of file for GET/HEAD */
736 char buf
[1024]; /* Buffer for real filename */
737 struct stat filestats
; /* File information */
738 mime_type_t
*type
; /* MIME type of file */
739 cupsd_printer_t
*p
; /* Printer */
740 static unsigned request_id
= 0; /* Request ID for temp files */
743 status
= HTTP_CONTINUE
;
745 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
746 "cupsdReadClient(con=%p(%d)) "
747 "con->http.error=%d "
748 "con->http.used=%d, "
749 "con->http.state=%d "
750 "con->data_encoding=HTTP_ENCODE_%s, "
751 "con->data_remaining=" CUPS_LLFMT
", "
753 con
, con
->http
.fd
, con
->http
.error
, con
->http
.used
,
755 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
?
756 "CHUNKED" : "LENGTH",
757 CUPS_LLCAST con
->http
.data_remaining
, con
->file
);
763 * Automatically check for a SSL/TLS handshake...
768 if (recv(con
->http
.fd
, buf
, 1, MSG_PEEK
) == 1 &&
769 (!buf
[0] || !strchr("DGHOPT", buf
[0])))
772 * Encrypt this connection...
775 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
776 "cupsdReadClient: Saw first byte %02X, auto-negotiating "
777 "SSL/TLS session...", buf
[0] & 255);
779 if (!encrypt_client(con
))
780 cupsdCloseClient(con
);
785 #endif /* HAVE_SSL */
787 switch (con
->http
.state
)
791 * See if we've received a request line...
794 if (httpGets(line
, sizeof(line
) - 1, HTTP(con
)) == NULL
)
796 if (con
->http
.error
&& con
->http
.error
!= EPIPE
)
797 cupsdLogMessage(CUPSD_LOG_DEBUG
,
798 "cupsdReadClient: %d WAITING Closing for error %d "
799 "(%s)", con
->http
.fd
, con
->http
.error
,
800 strerror(con
->http
.error
));
802 cupsdLogMessage(CUPSD_LOG_DEBUG
,
803 "cupsdReadClient: %d WAITING Closing on EOF",
806 cupsdCloseClient(con
);
811 * Ignore blank request lines...
818 * Clear other state variables...
821 httpClearFields(HTTP(con
));
823 con
->http
.activity
= time(NULL
);
824 con
->http
.version
= HTTP_1_0
;
825 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
826 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
827 con
->http
.data_remaining
= 0;
828 con
->http
._data_remaining
= 0;
829 con
->operation
= HTTP_WAITING
;
834 con
->username
[0] = '\0';
835 con
->password
[0] = '\0';
838 cupsdClearString(&con
->command
);
839 cupsdClearString(&con
->options
);
840 cupsdClearString(&con
->query_string
);
844 ippDelete(con
->request
);
850 ippDelete(con
->response
);
851 con
->response
= NULL
;
856 cupsLangFree(con
->language
);
857 con
->language
= NULL
;
865 OM_uint32 minor_status
;
866 gss_release_cred(&minor_status
, &con
->gss_creds
);
868 #endif /* HAVE_GSSAPI */
871 * Grab the request line...
874 switch (sscanf(line
, "%63s%1023s%63s", operation
, con
->uri
, version
))
879 cupsdLogMessage(CUPSD_LOG_ERROR
,
880 "Bad request line \"%s\" from %s!", line
,
882 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
883 cupsdCloseClient(con
);
887 con
->http
.version
= HTTP_0_9
;
890 if (sscanf(version
, "HTTP/%d.%d", &major
, &minor
) != 2)
892 cupsdLogMessage(CUPSD_LOG_ERROR
,
893 "Bad request line \"%s\" from %s!", line
,
895 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
896 cupsdCloseClient(con
);
902 con
->http
.version
= (http_version_t
)(major
* 100 + minor
);
903 if (con
->http
.version
== HTTP_1_1
&& KeepAlive
)
904 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
906 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
910 cupsdLogMessage(CUPSD_LOG_ERROR
,
911 "Unsupported request line \"%s\" from %s!",
912 line
, con
->http
.hostname
);
913 cupsdSendError(con
, HTTP_NOT_SUPPORTED
, CUPSD_AUTH_NONE
);
914 cupsdCloseClient(con
);
921 * Handle full URLs in the request line...
924 if (strcmp(con
->uri
, "*"))
926 char scheme
[HTTP_MAX_URI
], /* Method/scheme */
927 userpass
[HTTP_MAX_URI
], /* Username:password */
928 hostname
[HTTP_MAX_URI
], /* Hostname */
929 resource
[HTTP_MAX_URI
]; /* Resource path */
930 int port
; /* Port number */
934 * Separate the URI into its components...
937 httpSeparateURI(HTTP_URI_CODING_MOST
, con
->uri
,
938 scheme
, sizeof(scheme
),
939 userpass
, sizeof(userpass
),
940 hostname
, sizeof(hostname
), &port
,
941 resource
, sizeof(resource
));
944 * Only allow URIs with the servername, localhost, or an IP
948 if (strcmp(scheme
, "file") &&
949 strcasecmp(hostname
, ServerName
) &&
950 strcasecmp(hostname
, "localhost") &&
951 !isdigit(hostname
[0]) && hostname
[0] != '[')
954 * Nope, we don't do proxies...
957 cupsdLogMessage(CUPSD_LOG_ERROR
, "Bad URI \"%s\" in request!",
959 cupsdSendError(con
, HTTP_METHOD_NOT_ALLOWED
, CUPSD_AUTH_NONE
);
960 cupsdCloseClient(con
);
965 * Copy the resource portion back into the URI; both resource and
966 * con->uri are HTTP_MAX_URI bytes in size...
969 strcpy(con
->uri
, resource
);
973 * Process the request...
976 if (!strcmp(operation
, "GET"))
977 con
->http
.state
= HTTP_GET
;
978 else if (!strcmp(operation
, "PUT"))
979 con
->http
.state
= HTTP_PUT
;
980 else if (!strcmp(operation
, "POST"))
981 con
->http
.state
= HTTP_POST
;
982 else if (!strcmp(operation
, "DELETE"))
983 con
->http
.state
= HTTP_DELETE
;
984 else if (!strcmp(operation
, "TRACE"))
985 con
->http
.state
= HTTP_TRACE
;
986 else if (!strcmp(operation
, "OPTIONS"))
987 con
->http
.state
= HTTP_OPTIONS
;
988 else if (!strcmp(operation
, "HEAD"))
989 con
->http
.state
= HTTP_HEAD
;
992 cupsdLogMessage(CUPSD_LOG_ERROR
, "Bad operation \"%s\"!", operation
);
993 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
994 cupsdCloseClient(con
);
998 gettimeofday(&(con
->start
), NULL
);
999 con
->operation
= con
->http
.state
;
1001 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdReadClient: %d %s %s HTTP/%d.%d",
1002 con
->http
.fd
, operation
, con
->uri
,
1003 con
->http
.version
/ 100, con
->http
.version
% 100);
1005 con
->http
.status
= HTTP_OK
;
1007 if (!cupsArrayFind(ActiveClients
, con
))
1009 cupsArrayAdd(ActiveClients
, con
);
1010 cupsdSetBusyState();
1021 * Parse incoming parameters until the status changes...
1024 while ((status
= httpUpdate(HTTP(con
))) == HTTP_CONTINUE
)
1025 if (!data_ready(con
))
1028 if (status
!= HTTP_OK
&& status
!= HTTP_CONTINUE
)
1030 if (con
->http
.error
&& con
->http
.error
!= EPIPE
)
1031 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1032 "cupsdReadClient: %d FIELDS Closing for error %d "
1033 "(%s)", con
->http
.fd
, con
->http
.error
,
1034 strerror(con
->http
.error
));
1036 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1037 "cupsdReadClient: %d FIELDS Closing on EOF",
1040 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
1041 cupsdCloseClient(con
);
1047 if (!data_ready(con
) && recv(con
->http
.fd
, buf
, 1, MSG_PEEK
) < 1)
1050 * Connection closed...
1053 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1054 "cupsdReadClient: %d Closing on EOF", con
->http
.fd
);
1055 cupsdCloseClient(con
);
1058 break; /* Anti-compiler-warning-code */
1062 * Handle new transfers...
1065 if (status
== HTTP_OK
)
1067 if (con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
][0])
1070 * Figure out the locale from the Accept-Language and Content-Type
1074 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
],
1078 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
],
1082 if ((ptr
= strstr(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
],
1083 "charset=")) != NULL
)
1086 * Combine language and charset, and trim any extra params in the
1090 snprintf(locale
, sizeof(locale
), "%s.%s",
1091 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ptr
+ 8);
1093 if ((ptr
= strchr(locale
, ',')) != NULL
)
1097 snprintf(locale
, sizeof(locale
), "%s.UTF-8",
1098 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
]);
1100 con
->language
= cupsLangGet(locale
);
1103 con
->language
= cupsLangGet(DefaultLocale
);
1105 cupsdAuthorize(con
);
1107 if (!strncasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Keep-Alive",
1109 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
1110 else if (!strncasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "close", 5))
1111 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1113 if (!con
->http
.fields
[HTTP_FIELD_HOST
][0] &&
1114 con
->http
.version
>= HTTP_1_1
)
1117 * HTTP/1.1 and higher require the "Host:" field...
1120 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1122 cupsdLogMessage(CUPSD_LOG_ERROR
, "Missing Host: field in request!");
1123 cupsdCloseClient(con
);
1127 else if (!valid_host(con
))
1130 * Access to localhost must use "localhost" or the corresponding IPv4
1131 * or IPv6 values in the Host: field.
1134 cupsdLogMessage(CUPSD_LOG_ERROR
,
1135 "Request from \"%s\" using invalid Host: field \"%s\"",
1136 con
->http
.hostname
, con
->http
.fields
[HTTP_FIELD_HOST
]);
1138 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1140 cupsdCloseClient(con
);
1144 else if (con
->operation
== HTTP_OPTIONS
)
1147 * Do OPTIONS command...
1150 if (con
->best
&& con
->best
->type
!= CUPSD_AUTH_NONE
)
1152 if (!cupsdSendHeader(con
, HTTP_UNAUTHORIZED
, NULL
, CUPSD_AUTH_NONE
))
1154 cupsdCloseClient(con
);
1159 if (!strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") &&
1160 con
->http
.tls
== NULL
)
1164 * Do encryption stuff...
1167 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
, CUPSD_AUTH_NONE
))
1169 cupsdCloseClient(con
);
1173 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1174 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1175 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1176 httpPrintf(HTTP(con
), "\r\n");
1178 if (cupsdFlushHeader(con
) < 0)
1180 cupsdCloseClient(con
);
1184 if (!encrypt_client(con
))
1186 cupsdCloseClient(con
);
1190 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
1192 cupsdCloseClient(con
);
1195 #endif /* HAVE_SSL */
1198 if (!cupsdSendHeader(con
, HTTP_OK
, NULL
, CUPSD_AUTH_NONE
))
1200 cupsdCloseClient(con
);
1204 httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n");
1205 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1206 httpPrintf(HTTP(con
), "\r\n");
1208 if (cupsdFlushHeader(con
) < 0)
1210 cupsdCloseClient(con
);
1214 else if (!is_path_absolute(con
->uri
))
1217 * Protect against malicious users!
1220 cupsdLogMessage(CUPSD_LOG_ERROR
,
1221 "Request for non-absolute resource \"%s\"!", con
->uri
);
1223 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1225 cupsdCloseClient(con
);
1231 if (!strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") &&
1232 con
->http
.tls
== NULL
)
1236 * Do encryption stuff...
1239 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
, CUPSD_AUTH_NONE
))
1241 cupsdCloseClient(con
);
1245 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1246 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1247 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1248 httpPrintf(HTTP(con
), "\r\n");
1250 if (cupsdFlushHeader(con
) < 0)
1252 cupsdCloseClient(con
);
1256 if (!encrypt_client(con
))
1258 cupsdCloseClient(con
);
1262 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
1264 cupsdCloseClient(con
);
1267 #endif /* HAVE_SSL */
1270 if ((status
= cupsdIsAuthorized(con
, NULL
)) != HTTP_OK
)
1272 cupsdSendError(con
, status
, CUPSD_AUTH_NONE
);
1273 cupsdCloseClient(con
);
1277 if (con
->http
.expect
&&
1278 (con
->operation
== HTTP_POST
|| con
->operation
== HTTP_PUT
))
1280 if (con
->http
.expect
== HTTP_CONTINUE
)
1283 * Send 100-continue header...
1286 if (!cupsdSendHeader(con
, HTTP_CONTINUE
, NULL
, CUPSD_AUTH_NONE
))
1288 cupsdCloseClient(con
);
1295 * Send 417-expectation-failed header...
1298 if (!cupsdSendHeader(con
, HTTP_EXPECTATION_FAILED
, NULL
,
1301 cupsdCloseClient(con
);
1305 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1306 httpPrintf(HTTP(con
), "\r\n");
1308 if (cupsdFlushHeader(con
) < 0)
1310 cupsdCloseClient(con
);
1316 switch (con
->http
.state
)
1318 case HTTP_GET_SEND
:
1319 if (!strncmp(con
->uri
, "/printers/", 10) &&
1320 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1323 * Send PPD file - get the real printer name since printer
1324 * names are not case sensitive but filenames can be...
1327 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1329 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1330 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1333 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1335 cupsdCloseClient(con
);
1342 else if ((!strncmp(con
->uri
, "/printers/", 10) ||
1343 !strncmp(con
->uri
, "/classes/", 9)) &&
1344 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".png"))
1347 * Send icon file - get the real queue name since queue names are
1348 * not case sensitive but filenames can be...
1351 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".png" */
1353 if (!strncmp(con
->uri
, "/printers/", 10))
1354 p
= cupsdFindPrinter(con
->uri
+ 10);
1356 p
= cupsdFindClass(con
->uri
+ 9);
1359 snprintf(con
->uri
, sizeof(con
->uri
), "/icons/%s.png", p
->name
);
1362 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1364 cupsdCloseClient(con
);
1371 else if (!WebInterface
)
1374 * Web interface is disabled. Show an appropriate message...
1377 if (!cupsdSendError(con
, HTTP_WEBIF_DISABLED
, CUPSD_AUTH_NONE
))
1379 cupsdCloseClient(con
);
1386 if ((!strncmp(con
->uri
, "/admin", 6) &&
1387 strncmp(con
->uri
, "/admin/conf/", 12) &&
1388 strncmp(con
->uri
, "/admin/log/", 11)) ||
1389 !strncmp(con
->uri
, "/printers", 9) ||
1390 !strncmp(con
->uri
, "/classes", 8) ||
1391 !strncmp(con
->uri
, "/help", 5) ||
1392 !strncmp(con
->uri
, "/jobs", 5))
1395 * Send CGI output...
1398 if (!strncmp(con
->uri
, "/admin", 6))
1400 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1403 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1405 else if (!strncmp(con
->uri
, "/printers", 9))
1407 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1410 if (con
->uri
[9] && con
->uri
[10])
1411 cupsdSetString(&con
->options
, con
->uri
+ 9);
1413 cupsdSetString(&con
->options
, NULL
);
1415 else if (!strncmp(con
->uri
, "/classes", 8))
1417 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1420 if (con
->uri
[8] && con
->uri
[9])
1421 cupsdSetString(&con
->options
, con
->uri
+ 8);
1423 cupsdSetString(&con
->options
, NULL
);
1425 else if (!strncmp(con
->uri
, "/jobs", 5))
1427 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1430 if (con
->uri
[5] && con
->uri
[6])
1431 cupsdSetString(&con
->options
, con
->uri
+ 5);
1433 cupsdSetString(&con
->options
, NULL
);
1437 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1440 if (con
->uri
[5] && con
->uri
[6])
1441 cupsdSetString(&con
->options
, con
->uri
+ 5);
1443 cupsdSetString(&con
->options
, NULL
);
1446 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1448 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1450 cupsdCloseClient(con
);
1455 cupsdLogRequest(con
, HTTP_OK
);
1457 if (con
->http
.version
<= HTTP_1_0
)
1458 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1460 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1461 (strchr(con
->uri
+ 12, '/') ||
1462 strlen(con
->uri
) == 12)) ||
1463 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1464 (strchr(con
->uri
+ 11, '/') ||
1465 strlen(con
->uri
) == 11)))
1468 * GET can only be done to configuration files directly under
1472 cupsdLogMessage(CUPSD_LOG_ERROR
,
1473 "Request for subdirectory \"%s\"!", con
->uri
);
1475 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1477 cupsdCloseClient(con
);
1489 if ((filename
= get_file(con
, &filestats
, buf
,
1490 sizeof(buf
))) == NULL
)
1492 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1494 cupsdCloseClient(con
);
1501 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1503 if (is_cgi(con
, filename
, &filestats
, type
))
1506 * Note: con->command and con->options were set by
1510 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1512 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1514 cupsdCloseClient(con
);
1519 cupsdLogRequest(con
, HTTP_OK
);
1521 if (con
->http
.version
<= HTTP_1_0
)
1522 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1526 if (!check_if_modified(con
, &filestats
))
1528 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1530 cupsdCloseClient(con
);
1537 strcpy(line
, "text/plain");
1539 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1541 if (!write_file(con
, HTTP_OK
, filename
, line
, &filestats
))
1543 cupsdCloseClient(con
);
1550 case HTTP_POST_RECV
:
1552 * See if the POST request includes a Content-Length field, and if
1553 * so check the length against any limits that are set...
1556 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1557 MaxRequestSize
> 0 &&
1558 con
->http
.data_remaining
> MaxRequestSize
)
1561 * Request too large...
1564 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1566 cupsdCloseClient(con
);
1572 else if (con
->http
.data_remaining
< 0 ||
1573 (!con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1574 con
->http
.data_encoding
== HTTP_ENCODE_LENGTH
))
1577 * Negative content lengths are invalid!
1580 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1582 cupsdCloseClient(con
);
1590 * See what kind of POST request this is; for IPP requests the
1591 * content-type field will be "application/ipp"...
1594 if (!strcmp(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
],
1596 con
->request
= ippNew();
1597 else if (!WebInterface
)
1600 * Web interface is disabled. Show an appropriate message...
1603 if (!cupsdSendError(con
, HTTP_WEBIF_DISABLED
, CUPSD_AUTH_NONE
))
1605 cupsdCloseClient(con
);
1611 else if ((!strncmp(con
->uri
, "/admin", 6) &&
1612 strncmp(con
->uri
, "/admin/conf/", 12) &&
1613 strncmp(con
->uri
, "/admin/log/", 11)) ||
1614 !strncmp(con
->uri
, "/printers", 9) ||
1615 !strncmp(con
->uri
, "/classes", 8) ||
1616 !strncmp(con
->uri
, "/help", 5) ||
1617 !strncmp(con
->uri
, "/jobs", 5))
1623 if (!strncmp(con
->uri
, "/admin", 6))
1625 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1628 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1630 else if (!strncmp(con
->uri
, "/printers", 9))
1632 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1635 if (con
->uri
[9] && con
->uri
[10])
1636 cupsdSetString(&con
->options
, con
->uri
+ 9);
1638 cupsdSetString(&con
->options
, NULL
);
1640 else if (!strncmp(con
->uri
, "/classes", 8))
1642 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1645 if (con
->uri
[8] && con
->uri
[9])
1646 cupsdSetString(&con
->options
, con
->uri
+ 8);
1648 cupsdSetString(&con
->options
, NULL
);
1650 else if (!strncmp(con
->uri
, "/jobs", 5))
1652 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1655 if (con
->uri
[5] && con
->uri
[6])
1656 cupsdSetString(&con
->options
, con
->uri
+ 5);
1658 cupsdSetString(&con
->options
, NULL
);
1662 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1665 if (con
->uri
[5] && con
->uri
[6])
1666 cupsdSetString(&con
->options
, con
->uri
+ 5);
1668 cupsdSetString(&con
->options
, NULL
);
1671 if (con
->http
.version
<= HTTP_1_0
)
1672 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1680 if ((filename
= get_file(con
, &filestats
, buf
,
1681 sizeof(buf
))) == NULL
)
1683 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1685 cupsdCloseClient(con
);
1692 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1694 if (!is_cgi(con
, filename
, &filestats
, type
))
1697 * Only POST to CGI's...
1700 if (!cupsdSendError(con
, HTTP_UNAUTHORIZED
, CUPSD_AUTH_NONE
))
1702 cupsdCloseClient(con
);
1709 case HTTP_PUT_RECV
:
1711 * Validate the resource name...
1714 if (strncmp(con
->uri
, "/admin/conf/", 12) ||
1715 strchr(con
->uri
+ 12, '/') ||
1716 strlen(con
->uri
) == 12)
1719 * PUT can only be done to configuration files under
1723 cupsdLogMessage(CUPSD_LOG_ERROR
,
1724 "Request for subdirectory \"%s\"!", con
->uri
);
1726 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1728 cupsdCloseClient(con
);
1736 * See if the PUT request includes a Content-Length field, and if
1737 * so check the length against any limits that are set...
1740 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1741 MaxRequestSize
> 0 &&
1742 con
->http
.data_remaining
> MaxRequestSize
)
1745 * Request too large...
1748 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1750 cupsdCloseClient(con
);
1756 else if (con
->http
.data_remaining
< 0)
1759 * Negative content lengths are invalid!
1762 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1764 cupsdCloseClient(con
);
1772 * Open a temporary file to hold the request...
1775 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
1777 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1781 cupsdLogMessage(CUPSD_LOG_ERROR
,
1782 "Unable to create request file %s: %s",
1783 con
->filename
, strerror(errno
));
1785 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1787 cupsdCloseClient(con
);
1792 fchmod(con
->file
, 0640);
1793 fchown(con
->file
, RunUser
, Group
);
1794 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1799 cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
);
1800 cupsdCloseClient(con
);
1804 if (!strncmp(con
->uri
, "/printers/", 10) &&
1805 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1808 * Send PPD file - get the real printer name since printer
1809 * names are not case sensitive but filenames can be...
1812 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1814 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1815 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1818 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1820 cupsdCloseClient(con
);
1827 else if (!strncmp(con
->uri
, "/printers/", 10) &&
1828 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".png"))
1831 * Send PNG file - get the real printer name since printer
1832 * names are not case sensitive but filenames can be...
1835 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1837 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1838 snprintf(con
->uri
, sizeof(con
->uri
), "/icons/%s.png", p
->name
);
1841 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1843 cupsdCloseClient(con
);
1850 else if (!WebInterface
)
1852 if (!cupsdSendHeader(con
, HTTP_OK
, line
, CUPSD_AUTH_NONE
))
1854 cupsdCloseClient(con
);
1858 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1860 cupsdCloseClient(con
);
1864 if (cupsdFlushHeader(con
) < 0)
1866 cupsdCloseClient(con
);
1870 con
->http
.state
= HTTP_WAITING
;
1874 if ((!strncmp(con
->uri
, "/admin", 6) &&
1875 strncmp(con
->uri
, "/admin/conf/", 12) &&
1876 strncmp(con
->uri
, "/admin/log/", 11)) ||
1877 !strncmp(con
->uri
, "/printers", 9) ||
1878 !strncmp(con
->uri
, "/classes", 8) ||
1879 !strncmp(con
->uri
, "/help", 5) ||
1880 !strncmp(con
->uri
, "/jobs", 5))
1886 if (!cupsdSendHeader(con
, HTTP_OK
, "text/html", CUPSD_AUTH_NONE
))
1888 cupsdCloseClient(con
);
1892 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1894 cupsdCloseClient(con
);
1898 if (cupsdFlushHeader(con
) < 0)
1900 cupsdCloseClient(con
);
1904 cupsdLogRequest(con
, HTTP_OK
);
1906 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1907 (strchr(con
->uri
+ 12, '/') ||
1908 strlen(con
->uri
) == 12)) ||
1909 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1910 (strchr(con
->uri
+ 11, '/') ||
1911 strlen(con
->uri
) == 11)))
1914 * HEAD can only be done to configuration files under
1918 cupsdLogMessage(CUPSD_LOG_ERROR
,
1919 "Request for subdirectory \"%s\"!", con
->uri
);
1921 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1923 cupsdCloseClient(con
);
1929 else if ((filename
= get_file(con
, &filestats
, buf
,
1930 sizeof(buf
))) == NULL
)
1932 if (!cupsdSendHeader(con
, HTTP_NOT_FOUND
, "text/html",
1935 cupsdCloseClient(con
);
1939 cupsdLogRequest(con
, HTTP_NOT_FOUND
);
1941 else if (!check_if_modified(con
, &filestats
))
1943 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1945 cupsdCloseClient(con
);
1949 cupsdLogRequest(con
, HTTP_NOT_MODIFIED
);
1957 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1959 strcpy(line
, "text/plain");
1961 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1963 if (!cupsdSendHeader(con
, HTTP_OK
, line
, CUPSD_AUTH_NONE
))
1965 cupsdCloseClient(con
);
1969 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
1970 httpGetDateString(filestats
.st_mtime
)) < 0)
1972 cupsdCloseClient(con
);
1976 if (httpPrintf(HTTP(con
), "Content-Length: %lu\r\n",
1977 (unsigned long)filestats
.st_size
) < 0)
1979 cupsdCloseClient(con
);
1983 cupsdLogRequest(con
, HTTP_OK
);
1986 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1988 cupsdCloseClient(con
);
1992 if (cupsdFlushHeader(con
) < 0)
1994 cupsdCloseClient(con
);
1998 con
->http
.state
= HTTP_WAITING
;
2002 break; /* Anti-compiler-warning-code */
2008 * Handle any incoming data...
2011 switch (con
->http
.state
)
2013 case HTTP_PUT_RECV
:
2016 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
2018 if (con
->http
.error
&& con
->http
.error
!= EPIPE
)
2019 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2020 "cupsdReadClient: %d PUT_RECV Closing for error "
2021 "%d (%s)", con
->http
.fd
, con
->http
.error
,
2022 strerror(con
->http
.error
));
2024 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2025 "cupsdReadClient: %d PUT_RECV Closing on EOF",
2028 cupsdCloseClient(con
);
2033 con
->bytes
+= bytes
;
2035 if (write(con
->file
, line
, bytes
) < bytes
)
2037 cupsdLogMessage(CUPSD_LOG_ERROR
,
2038 "cupsdReadClient: Unable to write %d bytes to %s: %s",
2039 bytes
, con
->filename
, strerror(errno
));
2043 unlink(con
->filename
);
2044 cupsdClearString(&con
->filename
);
2046 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2048 cupsdCloseClient(con
);
2054 while (con
->http
.state
== HTTP_PUT_RECV
&& data_ready(con
));
2056 if (con
->http
.state
== HTTP_WAITING
)
2059 * End of file, see how big it is...
2062 fstat(con
->file
, &filestats
);
2067 if (filestats
.st_size
> MaxRequestSize
&&
2071 * Request is too big; remove it and send an error...
2074 unlink(con
->filename
);
2075 cupsdClearString(&con
->filename
);
2077 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2079 cupsdCloseClient(con
);
2085 * Install the configuration file...
2088 status
= install_conf_file(con
);
2091 * Return the status to the client...
2094 if (!cupsdSendError(con
, status
, CUPSD_AUTH_NONE
))
2096 cupsdCloseClient(con
);
2102 case HTTP_POST_RECV
:
2105 if (con
->request
&& con
->file
< 0)
2108 * Grab any request data from the connection...
2111 if ((ipp_state
= ippRead(&(con
->http
), con
->request
)) == IPP_ERROR
)
2113 cupsdLogMessage(CUPSD_LOG_ERROR
,
2114 "cupsdReadClient: %d IPP Read Error!",
2117 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
2118 cupsdCloseClient(con
);
2121 else if (ipp_state
!= IPP_DATA
)
2123 if (con
->http
.state
== HTTP_POST_SEND
)
2125 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
2126 cupsdCloseClient(con
);
2134 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdReadClient: %d %d.%d %s %d",
2135 con
->http
.fd
, con
->request
->request
.op
.version
[0],
2136 con
->request
->request
.op
.version
[1],
2137 ippOpString(con
->request
->request
.op
.operation_id
),
2138 con
->request
->request
.op
.request_id
);
2139 con
->bytes
+= ippLength(con
->request
);
2143 if (con
->file
< 0 && con
->http
.state
!= HTTP_POST_SEND
)
2146 * Create a file as needed for the request data...
2149 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
2151 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
2155 cupsdLogMessage(CUPSD_LOG_ERROR
,
2156 "Unable to create request file %s: %s",
2157 con
->filename
, strerror(errno
));
2159 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2161 cupsdCloseClient(con
);
2166 fchmod(con
->file
, 0640);
2167 fchown(con
->file
, RunUser
, Group
);
2168 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2171 if (con
->http
.state
!= HTTP_POST_SEND
)
2173 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
2175 if (con
->http
.error
&& con
->http
.error
!= EPIPE
)
2176 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2177 "cupsdReadClient: %d POST_SEND Closing for "
2178 "error %d (%s)", con
->http
.fd
, con
->http
.error
,
2179 strerror(con
->http
.error
));
2181 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2182 "cupsdReadClient: %d POST_SEND Closing on EOF",
2185 cupsdCloseClient(con
);
2190 con
->bytes
+= bytes
;
2192 if (write(con
->file
, line
, bytes
) < bytes
)
2194 cupsdLogMessage(CUPSD_LOG_ERROR
,
2195 "cupsdReadClient: Unable to write %d bytes to "
2196 "%s: %s", bytes
, con
->filename
,
2201 unlink(con
->filename
);
2202 cupsdClearString(&con
->filename
);
2204 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
,
2207 cupsdCloseClient(con
);
2212 else if (con
->http
.state
== HTTP_POST_RECV
)
2214 else if (con
->http
.state
!= HTTP_POST_SEND
)
2216 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2217 "cupsdReadClient: %d Closing on unknown HTTP "
2218 "state %d", con
->http
.fd
, con
->http
.state
);
2219 cupsdCloseClient(con
);
2224 while (con
->http
.state
== HTTP_POST_RECV
&& data_ready(con
));
2226 if (con
->http
.state
== HTTP_POST_SEND
)
2230 fstat(con
->file
, &filestats
);
2235 if (filestats
.st_size
> MaxRequestSize
&&
2239 * Request is too big; remove it and send an error...
2242 unlink(con
->filename
);
2243 cupsdClearString(&con
->filename
);
2248 * Delete any IPP request data...
2251 ippDelete(con
->request
);
2252 con
->request
= NULL
;
2255 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2257 cupsdCloseClient(con
);
2261 else if (filestats
.st_size
== 0)
2264 * Don't allow empty file...
2267 unlink(con
->filename
);
2268 cupsdClearString(&con
->filename
);
2273 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
2275 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
2277 cupsdCloseClient(con
);
2282 cupsdLogRequest(con
, HTTP_OK
);
2288 cupsdProcessIPPRequest(con
);
2292 unlink(con
->filename
);
2293 cupsdClearString(&con
->filename
);
2302 break; /* Anti-compiler-warning-code */
2305 if (con
->http
.state
== HTTP_WAITING
)
2307 if (!con
->http
.keep_alive
)
2309 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2310 "cupsdReadClient: %d Closing because Keep-Alive disabled",
2312 cupsdCloseClient(con
);
2316 cupsArrayRemove(ActiveClients
, con
);
2317 cupsdSetBusyState();
2324 * 'cupsdSendCommand()' - Send output from a command via HTTP.
2327 int /* O - 1 on success, 0 on failure */
2329 cupsd_client_t
*con
, /* I - Client connection */
2330 char *command
, /* I - Command to run */
2331 char *options
, /* I - Command-line options */
2332 int root
) /* I - Run as root? */
2334 int fd
; /* Standard input file descriptor */
2339 fd
= open(con
->filename
, O_RDONLY
);
2343 cupsdLogMessage(CUPSD_LOG_ERROR
,
2344 "cupsdSendCommand: %d Unable to open \"%s\" for reading: %s",
2345 con
->http
.fd
, con
->filename
? con
->filename
: "/dev/null",
2350 fcntl(fd
, F_SETFD
, fcntl(fd
, F_GETFD
) | FD_CLOEXEC
);
2355 con
->pipe_pid
= pipe_command(con
, fd
, &(con
->file
), command
, options
, root
);
2360 cupsdLogMessage(CUPSD_LOG_INFO
, "Started \"%s\" (pid=%d)", command
,
2363 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendCommand: %d file=%d",
2364 con
->http
.fd
, con
->file
);
2366 if (con
->pipe_pid
== 0)
2369 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2371 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2373 con
->sent_header
= 0;
2374 con
->file_ready
= 0;
2375 con
->got_fields
= 0;
2376 con
->header_used
= 0;
2383 * 'cupsdSendError()' - Send an error message via HTTP.
2386 int /* O - 1 if successful, 0 otherwise */
2387 cupsdSendError(cupsd_client_t
*con
, /* I - Connection */
2388 http_status_t code
, /* I - Error code */
2389 int auth_type
)/* I - Authentication type */
2391 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2392 "cupsdSendError(con=%p(%d), code=%d, auth_type=%d", con
,
2393 con
->http
.fd
, code
, auth_type
);
2397 * Force client to upgrade for authentication if that is how the
2398 * server is configured...
2401 if (code
== HTTP_UNAUTHORIZED
&&
2402 DefaultEncryption
== HTTP_ENCRYPT_REQUIRED
&&
2403 strcasecmp(con
->http
.hostname
, "localhost") &&
2406 code
= HTTP_UPGRADE_REQUIRED
;
2408 #endif /* HAVE_SSL */
2411 * Put the request in the access_log file...
2414 cupsdLogRequest(con
, code
);
2417 * To work around bugs in some proxies, don't use Keep-Alive for some
2420 * Kerberos authentication doesn't work without Keep-Alive, so
2421 * never disable it in that case.
2424 if (code
>= HTTP_BAD_REQUEST
&& con
->http
.auth_type
!= CUPSD_AUTH_NEGOTIATE
)
2425 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
2428 * Send an error message back to the client. If the error code is a
2429 * 400 or 500 series, make sure the message contains some text, too!
2432 if (!cupsdSendHeader(con
, code
, NULL
, auth_type
))
2436 if (code
== HTTP_UPGRADE_REQUIRED
)
2437 if (httpPrintf(HTTP(con
), "Connection: Upgrade\r\n") < 0)
2440 if (httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n") < 0)
2442 #endif /* HAVE_SSL */
2444 if (con
->http
.version
>= HTTP_1_1
&&
2445 con
->http
.keep_alive
== HTTP_KEEPALIVE_OFF
)
2447 if (httpPrintf(HTTP(con
), "Connection: close\r\n") < 0)
2451 if (code
>= HTTP_BAD_REQUEST
)
2454 * Send a human-readable error message.
2457 char message
[4096], /* Message for user */
2458 urltext
[1024], /* URL redirection text */
2459 redirect
[1024]; /* Redirection link */
2460 const char *text
; /* Status-specific text */
2465 if (code
== HTTP_UNAUTHORIZED
)
2466 text
= _cupsLangString(con
->language
,
2467 _("Enter your username and password or the "
2468 "root username and password to access this "
2469 "page. If you are using Kerberos authentication, "
2470 "make sure you have a valid Kerberos ticket."));
2471 else if (code
== HTTP_UPGRADE_REQUIRED
)
2475 snprintf(urltext
, sizeof(urltext
),
2476 _cupsLangString(con
->language
,
2477 _("You must access this page using the URL "
2478 "<A HREF=\"https://%s:%d%s\">"
2479 "https://%s:%d%s</A>.")),
2480 con
->servername
, con
->serverport
, con
->uri
,
2481 con
->servername
, con
->serverport
, con
->uri
);
2483 snprintf(redirect
, sizeof(redirect
),
2484 "<META HTTP-EQUIV=\"Refresh\" "
2485 "CONTENT=\"3;URL=https://%s:%d%s\">\n",
2486 con
->servername
, con
->serverport
, con
->uri
);
2488 else if (code
== HTTP_WEBIF_DISABLED
)
2489 text
= _cupsLangString(con
->language
,
2490 _("The web interface is currently disabled. Run "
2491 "\"cupsctl WebInterface=yes\" to enable it."));
2495 snprintf(message
, sizeof(message
),
2496 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" "
2497 "\"http://www.w3.org/TR/html4/loose.dtd\">\n"
2500 "\t<META HTTP-EQUIV=\"Content-Type\" "
2501 "CONTENT=\"text/html; charset=utf-8\">\n"
2502 "\t<TITLE>%s - " CUPS_SVERSION
"</TITLE>\n"
2503 "\t<LINK REL=\"STYLESHEET\" TYPE=\"text/css\" "
2504 "HREF=\"/cups.css\">\n"
2512 httpStatus(code
), redirect
, httpStatus(code
), text
);
2514 if (httpPrintf(HTTP(con
), "Content-Type: text/html; charset=utf-8\r\n") < 0)
2516 if (httpPrintf(HTTP(con
), "Content-Length: %d\r\n",
2517 (int)strlen(message
)) < 0)
2519 if (httpPrintf(HTTP(con
), "\r\n") < 0)
2521 if (httpPrintf(HTTP(con
), "%s", message
) < 0)
2524 else if (httpPrintf(HTTP(con
), "\r\n") < 0)
2527 if (cupsdFlushHeader(con
) < 0)
2530 con
->http
.state
= HTTP_WAITING
;
2537 * 'cupsdSendHeader()' - Send an HTTP request.
2540 int /* O - 1 on success, 0 on failure */
2542 cupsd_client_t
*con
, /* I - Client to send to */
2543 http_status_t code
, /* I - HTTP status code */
2544 char *type
, /* I - MIME type of document */
2545 int auth_type
) /* I - Type of authentication */
2547 char auth_str
[1024]; /* Authorization string */
2549 static char *gss_buf
= NULL
; /* Kerberos auth data buffer */
2550 static int gss_bufsize
= 0; /* Size of Kerberos auth data buffer */
2551 #endif /* HAVE_GSSAPI */
2555 * Send the HTTP status header...
2558 if (code
== HTTP_CONTINUE
)
2561 * 100-continue doesn't send any headers...
2564 return (httpPrintf(HTTP(con
), "HTTP/%d.%d 100 Continue\r\n\r\n",
2565 con
->http
.version
/ 100, con
->http
.version
% 100) > 0);
2567 else if (code
== HTTP_WEBIF_DISABLED
)
2570 * Treat our special "web interface is disabled" status as "200 OK" for web
2577 httpFlushWrite(HTTP(con
));
2579 con
->http
.data_encoding
= HTTP_ENCODE_FIELDS
;
2581 if (httpPrintf(HTTP(con
), "HTTP/%d.%d %d %s\r\n", con
->http
.version
/ 100,
2582 con
->http
.version
% 100, code
, httpStatus(code
)) < 0)
2584 if (httpPrintf(HTTP(con
), "Date: %s\r\n", httpGetDateString(time(NULL
))) < 0)
2587 if (httpPrintf(HTTP(con
), "Server: %s\r\n", ServerHeader
) < 0)
2589 if (con
->http
.keep_alive
&& con
->http
.version
>= HTTP_1_0
)
2591 if (httpPrintf(HTTP(con
), "Connection: Keep-Alive\r\n") < 0)
2593 if (httpPrintf(HTTP(con
), "Keep-Alive: timeout=%d\r\n",
2594 KeepAliveTimeout
) < 0)
2597 if (code
== HTTP_METHOD_NOT_ALLOWED
)
2598 if (httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n") < 0)
2601 if (code
== HTTP_UNAUTHORIZED
)
2603 if (auth_type
== CUPSD_AUTH_NONE
)
2605 if (!con
->best
|| con
->best
->type
<= CUPSD_AUTH_NONE
)
2606 auth_type
= DefaultAuthType
;
2608 auth_type
= con
->best
->type
;
2613 if (auth_type
== CUPSD_AUTH_BASIC
|| auth_type
== CUPSD_AUTH_BASICDIGEST
)
2614 strlcpy(auth_str
, "Basic realm=\"CUPS\"", sizeof(auth_str
));
2615 else if (auth_type
== CUPSD_AUTH_DIGEST
)
2616 snprintf(auth_str
, sizeof(auth_str
), "Digest realm=\"CUPS\", nonce=\"%s\"",
2617 con
->http
.hostname
);
2619 else if (auth_type
== CUPSD_AUTH_NEGOTIATE
&& con
->gss_output_token
.length
== 0)
2620 strlcpy(auth_str
, "Negotiate", sizeof(auth_str
));
2621 #endif /* HAVE_GSSAPI */
2623 if (con
->best
&& auth_type
!= CUPSD_AUTH_NEGOTIATE
&&
2624 !strcasecmp(con
->http
.hostname
, "localhost"))
2627 * Add a "trc" (try root certification) parameter for local non-Kerberos
2628 * requests when the request requires system group membership - then the
2629 * client knows the root certificate can/should be used.
2631 * Also, for Mac OS X we also look for @AUTHKEY and add an "authkey"
2632 * parameter as needed...
2635 char *name
, /* Current user name */
2636 *auth_key
; /* Auth key buffer */
2637 size_t auth_size
; /* Size of remaining buffer */
2639 auth_key
= auth_str
+ strlen(auth_str
);
2640 auth_size
= sizeof(auth_str
) - (auth_key
- auth_str
);
2642 for (name
= (char *)cupsArrayFirst(con
->best
->names
);
2644 name
= (char *)cupsArrayNext(con
->best
->names
))
2646 #ifdef HAVE_AUTHORIZATION_H
2647 if (!strncasecmp(name
, "@AUTHKEY(", 9))
2649 snprintf(auth_key
, auth_size
, ", authkey=\"%s\"", name
+ 9);
2650 /* end parenthesis is stripped in conf.c */
2654 #endif /* HAVE_AUTHORIZATION_H */
2655 if (!strcasecmp(name
, "@SYSTEM"))
2657 #ifdef HAVE_AUTHORIZATION_H
2658 if (SystemGroupAuthKey
)
2659 snprintf(auth_key
, auth_size
,
2660 ", authkey=\"%s\", trc=\"y\"",
2661 SystemGroupAuthKey
);
2664 strlcpy(auth_key
, ", trc=\"y\"", auth_size
);
2665 #endif /* HAVE_AUTHORIZATION_H */
2673 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2674 "cupsdSendHeader: %d WWW-Authenticate: %s", con
->http
.fd
,
2677 if (httpPrintf(HTTP(con
), "WWW-Authenticate: %s\r\n", auth_str
) < 0)
2684 * WWW-Authenticate: Negotiate can be included even for
2685 * non-401 replies...
2688 if (con
->gss_output_token
.length
> 0 && con
->gss_output_token
.length
<= 65536)
2690 OM_uint32 minor_status
; /* Minor status code */
2691 int bufsize
; /* Size of output token buffer */
2694 bufsize
= con
->gss_output_token
.length
* 4 / 3 + 2;
2696 if (bufsize
> gss_bufsize
)
2698 char *buf
; /* New buffer */
2701 bufsize
= (bufsize
+ 1023) & 1023;/* Round up */
2704 buf
= realloc(gss_buf
, bufsize
);
2706 buf
= malloc(bufsize
);
2710 cupsdLogMessage(CUPSD_LOG_ERROR
,
2711 "Unable to allocate %d bytes for Kerberos credentials!",
2717 gss_bufsize
= bufsize
;
2720 httpEncode64_2(gss_buf
, gss_bufsize
,
2721 con
->gss_output_token
.value
,
2722 con
->gss_output_token
.length
);
2723 gss_release_buffer(&minor_status
, &con
->gss_output_token
);
2725 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2726 "cupsdSendHeader: WWW-Authenticate: Negotiate %s", gss_buf
);
2728 if (httpPrintf(HTTP(con
), "WWW-Authenticate: Negotiate %s\r\n",
2732 else if (con
->gss_output_token
.length
> 65536)
2734 cupsdLogMessage(CUPSD_LOG_ERROR
,
2735 "Kerberos credentials larger than 64k (%d)!",
2736 (int)con
->gss_output_token
.length
);
2739 #endif /* HAVE_GSSAPI */
2741 if (con
->language
&& strcmp(con
->language
->language
, "C"))
2743 if (httpPrintf(HTTP(con
), "Content-Language: %s\r\n",
2744 con
->language
->language
) < 0)
2750 if (!strcmp(type
, "text/html"))
2752 if (httpPrintf(HTTP(con
),
2753 "Content-Type: text/html; charset=utf-8\r\n") < 0)
2756 else if (httpPrintf(HTTP(con
), "Content-Type: %s\r\n", type
) < 0)
2765 * 'cupsdUpdateCGI()' - Read status messages from CGI scripts and programs.
2769 cupsdUpdateCGI(void)
2771 char *ptr
, /* Pointer to end of line in buffer */
2772 message
[1024]; /* Pointer to message text */
2773 int loglevel
; /* Log level for message */
2776 while ((ptr
= cupsdStatBufUpdate(CGIStatusBuffer
, &loglevel
,
2777 message
, sizeof(message
))) != NULL
)
2779 if (loglevel
== CUPSD_LOG_INFO
)
2780 cupsdLogMessage(CUPSD_LOG_INFO
, "%s", message
);
2782 if (!strchr(CGIStatusBuffer
->buffer
, '\n'))
2786 if (ptr
== NULL
&& !CGIStatusBuffer
->bufused
)
2789 * Fatal error on pipe - should never happen!
2792 cupsdLogMessage(CUPSD_LOG_CRIT
,
2793 "cupsdUpdateCGI: error reading from CGI error pipe - %s",
2800 * 'cupsdWriteClient()' - Write data to a client as needed.
2804 cupsdWriteClient(cupsd_client_t
*con
) /* I - Client connection */
2806 int bytes
, /* Number of bytes written */
2807 field_col
; /* Current column */
2808 char *bufptr
, /* Pointer into buffer */
2809 *bufend
; /* Pointer to end of buffer */
2810 ipp_state_t ipp_state
; /* IPP state value */
2813 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2814 "cupsdWriteClient(con=%p(%d)) response=%p(%d), file=%d "
2815 "pipe_pid=%d state=%d",
2816 con
, con
->http
.fd
, con
->response
,
2817 con
->response
? con
->response
->state
: -1,
2818 con
->file
, con
->pipe_pid
, con
->http
.state
);
2820 if (con
->http
.state
!= HTTP_GET_SEND
&&
2821 con
->http
.state
!= HTTP_POST_SEND
)
2824 * If we get called in the wrong state, then something went wrong with the
2825 * connection and we need to shut it down...
2828 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2829 "cupsdWriteClient: %d Closing on unknown HTTP state %d",
2830 con
->http
.fd
, con
->http
.state
);
2831 cupsdCloseClient(con
);
2838 * Make sure we select on the CGI output...
2841 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2843 if (!con
->file_ready
)
2846 * Try again later when there is CGI output available...
2849 cupsdRemoveSelect(con
->http
.fd
);
2853 con
->file_ready
= 0;
2856 if (con
->response
&& con
->response
->state
!= IPP_DATA
)
2858 ipp_state
= ippWrite(HTTP(con
), con
->response
);
2859 bytes
= ipp_state
!= IPP_ERROR
&&
2860 (con
->file
>= 0 || ipp_state
!= IPP_DATA
);
2862 else if ((bytes
= read(con
->file
, con
->header
,
2863 sizeof(con
->header
) - con
->header_used
)) > 0)
2865 con
->header_used
+= bytes
;
2867 if (con
->pipe_pid
&& !con
->got_fields
)
2870 * Inspect the data for Content-Type and other fields.
2873 for (bufptr
= con
->header
, bufend
= con
->header
+ con
->header_used
,
2875 !con
->got_fields
&& bufptr
< bufend
;
2878 if (*bufptr
== '\n')
2881 * Send line to client...
2884 if (bufptr
> con
->header
&& bufptr
[-1] == '\r')
2888 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Script header: %s", con
->header
);
2890 if (!con
->sent_header
)
2893 * Handle redirection and CGI status codes...
2896 if (!strncasecmp(con
->header
, "Location:", 9))
2898 cupsdSendHeader(con
, HTTP_SEE_OTHER
, NULL
, CUPSD_AUTH_NONE
);
2899 con
->sent_header
= 2;
2901 if (httpPrintf(HTTP(con
), "Content-Length: 0\r\n") < 0)
2904 else if (!strncasecmp(con
->header
, "Status:", 7))
2906 cupsdSendError(con
, (http_status_t
)atoi(con
->header
+ 7),
2908 con
->sent_header
= 2;
2912 cupsdSendHeader(con
, HTTP_OK
, NULL
, CUPSD_AUTH_NONE
);
2913 con
->sent_header
= 1;
2915 if (con
->http
.version
== HTTP_1_1
)
2917 if (httpPrintf(HTTP(con
), "Transfer-Encoding: chunked\r\n") < 0)
2923 if (strncasecmp(con
->header
, "Status:", 7))
2924 httpPrintf(HTTP(con
), "%s\r\n", con
->header
);
2930 con
->header_used
-= bufptr
- con
->header
;
2932 if (con
->header_used
> 0)
2933 memmove(con
->header
, bufptr
, con
->header_used
);
2935 bufptr
= con
->header
- 1;
2938 * See if the line was empty...
2943 con
->got_fields
= 1;
2945 if (cupsdFlushHeader(con
) < 0)
2947 cupsdCloseClient(con
);
2951 if (con
->http
.version
== HTTP_1_1
)
2952 con
->http
.data_encoding
= HTTP_ENCODE_CHUNKED
;
2957 else if (*bufptr
!= '\r')
2961 if (!con
->got_fields
)
2963 con
->http
.activity
= time(NULL
);
2968 if (con
->header_used
> 0)
2970 if (httpWrite2(HTTP(con
), con
->header
, con
->header_used
) < 0)
2972 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2973 "cupsdWriteClient: %d Closing for error %d (%s)",
2974 con
->http
.fd
, con
->http
.error
,
2975 strerror(con
->http
.error
));
2976 cupsdCloseClient(con
);
2980 if (con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
)
2981 httpFlushWrite(HTTP(con
));
2983 con
->bytes
+= con
->header_used
;
2985 if (con
->http
.state
== HTTP_WAITING
)
2988 bytes
= con
->header_used
;
2990 con
->header_used
= 0;
2995 (con
->http
.state
!= HTTP_GET_SEND
&& con
->http
.state
!= HTTP_POST_SEND
))
2997 if (!con
->sent_header
&& con
->pipe_pid
)
2998 cupsdSendError(con
, HTTP_SERVER_ERROR
, CUPSD_AUTH_NONE
);
3001 cupsdLogRequest(con
, HTTP_OK
);
3003 httpFlushWrite(HTTP(con
));
3005 if (con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
&& con
->sent_header
== 1)
3007 if (httpWrite2(HTTP(con
), "", 0) < 0)
3009 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3010 "cupsdWriteClient: %d Closing for error %d (%s)",
3011 con
->http
.fd
, con
->http
.error
,
3012 strerror(con
->http
.error
));
3013 cupsdCloseClient(con
);
3019 con
->http
.state
= HTTP_WAITING
;
3021 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
3025 cupsdRemoveSelect(con
->file
);
3028 cupsdEndProcess(con
->pipe_pid
, 0);
3037 unlink(con
->filename
);
3038 cupsdClearString(&con
->filename
);
3043 ippDelete(con
->request
);
3044 con
->request
= NULL
;
3049 ippDelete(con
->response
);
3050 con
->response
= NULL
;
3053 cupsdClearString(&con
->command
);
3054 cupsdClearString(&con
->options
);
3055 cupsdClearString(&con
->query_string
);
3057 if (!con
->http
.keep_alive
)
3059 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3060 "cupsdWriteClient: %d Closing because Keep-Alive disabled",
3062 cupsdCloseClient(con
);
3067 cupsArrayRemove(ActiveClients
, con
);
3068 cupsdSetBusyState();
3072 con
->http
.activity
= time(NULL
);
3077 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
3080 static int /* O - 1 if modified since */
3082 cupsd_client_t
*con
, /* I - Client connection */
3083 struct stat
*filestats
) /* I - File information */
3085 char *ptr
; /* Pointer into field */
3086 time_t date
; /* Time/date value */
3087 off_t size
; /* Size/length value */
3092 ptr
= con
->http
.fields
[HTTP_FIELD_IF_MODIFIED_SINCE
];
3097 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3098 "check_if_modified(con=%p(%d), "
3099 "filestats=%p(" CUPS_LLFMT
", %d)) If-Modified-Since=\"%s\"",
3100 con
, con
->http
.fd
, filestats
, CUPS_LLCAST filestats
->st_size
,
3101 (int)filestats
->st_mtime
, ptr
);
3103 while (*ptr
!= '\0')
3105 while (isspace(*ptr
) || *ptr
== ';')
3108 if (strncasecmp(ptr
, "length=", 7) == 0)
3111 size
= strtoll(ptr
, NULL
, 10);
3113 while (isdigit(*ptr
))
3116 else if (isalpha(*ptr
))
3118 date
= httpGetDateTime(ptr
);
3119 while (*ptr
!= '\0' && *ptr
!= ';')
3126 return ((size
!= filestats
->st_size
&& size
!= 0) ||
3127 (date
< filestats
->st_mtime
&& date
!= 0) ||
3128 (size
== 0 && date
== 0));
3133 * 'compare_clients()' - Compare two client connections.
3136 static int /* O - Result of comparison */
3137 compare_clients(cupsd_client_t
*a
, /* I - First client */
3138 cupsd_client_t
*b
, /* I - Second client */
3139 void *data
) /* I - User data (not used) */
3153 * 'data_ready()' - Check whether data is available from a client.
3156 static int /* O - 1 if data is ready, 0 otherwise */
3157 data_ready(cupsd_client_t
*con
) /* I - Client */
3159 if (con
->http
.used
> 0)
3162 else if (con
->http
.tls
)
3165 if (SSL_pending((SSL
*)(con
->http
.tls
)))
3167 # elif defined(HAVE_GNUTLS)
3168 if (gnutls_record_check_pending(con
->http
.tls
))
3170 # elif defined(HAVE_CDSASSL)
3171 size_t bytes
; /* Bytes that are available */
3173 if (!SSLGetBufferedReadSize(con
->http
.tls
, &bytes
) && bytes
> 0)
3175 # endif /* HAVE_LIBSSL */
3177 #endif /* HAVE_SSL */
3185 * 'encrypt_client()' - Enable encryption for the client...
3188 static int /* O - 1 on success, 0 on error */
3189 encrypt_client(cupsd_client_t
*con
) /* I - Client to encrypt */
3192 SSL_CTX
*context
; /* Context for encryption */
3193 BIO
*bio
; /* BIO data */
3194 unsigned long error
; /* Error code */
3197 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "encrypt_client(con=%p(%d))", con
,
3201 * Verify that we have a certificate...
3204 if (access(ServerKey
, 0) || access(ServerCertificate
, 0))
3207 * Nope, make a self-signed certificate...
3210 if (!make_certificate(con
))
3215 * Create the SSL context and accept the connection...
3218 context
= SSL_CTX_new(SSLv23_server_method());
3220 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
3221 if (SSLOptions
& CUPSD_SSL_NOEMPTY
)
3222 SSL_CTX_set_options(context
, SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
);
3223 SSL_CTX_use_PrivateKey_file(context
, ServerKey
, SSL_FILETYPE_PEM
);
3224 SSL_CTX_use_certificate_chain_file(context
, ServerCertificate
);
3226 bio
= BIO_new(_httpBIOMethods());
3227 BIO_ctrl(bio
, BIO_C_SET_FILE_PTR
, 0, (char *)HTTP(con
));
3229 con
->http
.tls
= SSL_new(context
);
3230 SSL_set_bio(con
->http
.tls
, bio
, bio
);
3232 if (SSL_accept(con
->http
.tls
) != 1)
3234 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to encrypt connection from %s!",
3235 con
->http
.hostname
);
3237 while ((error
= ERR_get_error()) != 0)
3238 cupsdLogMessage(CUPSD_LOG_ERROR
, "%s", ERR_error_string(error
, NULL
));
3240 SSL_CTX_free(context
);
3241 SSL_free(con
->http
.tls
);
3242 con
->http
.tls
= NULL
;
3246 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Connection from %s now encrypted.",
3247 con
->http
.hostname
);
3251 # elif defined(HAVE_GNUTLS)
3252 int error
; /* Error code */
3253 gnutls_certificate_server_credentials
*credentials
;
3254 /* TLS credentials */
3257 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "encrypt_client(con=%p(%d))", con
,
3261 * Verify that we have a certificate...
3264 if (access(ServerKey
, 0) || access(ServerCertificate
, 0))
3267 * Nope, make a self-signed certificate...
3270 if (!make_certificate(con
))
3275 * Create the SSL object and perform the SSL handshake...
3278 credentials
= (gnutls_certificate_server_credentials
*)
3279 malloc(sizeof(gnutls_certificate_server_credentials
));
3280 if (credentials
== NULL
)
3282 cupsdLogMessage(CUPSD_LOG_ERROR
,
3283 "Unable to encrypt connection from %s - %s",
3284 con
->http
.hostname
, strerror(errno
));
3289 gnutls_certificate_allocate_credentials(credentials
);
3290 gnutls_certificate_set_x509_key_file(*credentials
, ServerCertificate
,
3291 ServerKey
, GNUTLS_X509_FMT_PEM
);
3293 gnutls_init(&con
->http
.tls
), GNUTLS_SERVER
);
3294 gnutls_set_default_priority(con
->http
.tls
);
3295 gnutls_credentials_set(con
->http
.tls
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
3296 gnutls_transport_set_ptr(con
->http
.tls
, (gnutls_transport_ptr
)HTTP(con
));
3297 gnutls_transport_set_pull_function(con
->http
.tls
, _httpReadGNUTLS
);
3298 gnutls_transport_set_push_function(con
->http
.tls
, _httpWriteGNUTLS
);
3300 error
= gnutls_handshake(con
->http
.tls
);
3302 if (error
!= GNUTLS_E_SUCCESS
)
3304 cupsdLogMessage(CUPSD_LOG_ERROR
,
3305 "Unable to encrypt connection from %s - %s",
3306 con
->http
.hostname
, gnutls_strerror(error
));
3308 gnutls_deinit(con
->http
.tls
);
3309 gnutls_certificate_free_credentials(*credentials
);
3310 con
->http
.tls
= NULL
;
3315 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Connection from %s now encrypted.",
3316 con
->http
.hostname
);
3318 con
->http
.tls_credentials
= credentials
;
3321 # elif defined(HAVE_CDSASSL)
3322 OSStatus error
= 0; /* Error code */
3323 CFArrayRef peerCerts
; /* Peer certificates */
3326 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "encrypt_client(con=%p(%d))", con
,
3329 con
->http
.tls_credentials
= get_cdsa_certificate(con
);
3331 if (!con
->http
.tls_credentials
)
3334 * No keychain (yet), make a self-signed certificate...
3337 if (make_certificate(con
))
3338 con
->http
.tls_credentials
= get_cdsa_certificate(con
);
3341 if (!con
->http
.tls_credentials
)
3343 cupsdLogMessage(CUPSD_LOG_ERROR
,
3344 "Could not find signing key in keychain \"%s\"",
3346 error
= errSSLBadCert
; /* errSSLBadConfiguration is a better choice, but not available on 10.2.x */
3350 error
= SSLNewContext(true, &con
->http
.tls
);
3353 error
= SSLSetIOFuncs(con
->http
.tls
, _httpReadCDSA
, _httpWriteCDSA
);
3356 error
= SSLSetProtocolVersionEnabled(con
->http
.tls
, kSSLProtocol2
, false);
3359 error
= SSLSetConnection(con
->http
.tls
, HTTP(con
));
3362 error
= SSLSetAllowsExpiredCerts(con
->http
.tls
, true);
3365 error
= SSLSetAllowsAnyRoot(con
->http
.tls
, true);
3368 error
= SSLSetCertificate(con
->http
.tls
, con
->http
.tls_credentials
);
3373 * Perform SSL/TLS handshake
3376 while ((error
= SSLHandshake(con
->http
.tls
)) == errSSLWouldBlock
)
3382 cupsdLogMessage(CUPSD_LOG_ERROR
,
3383 "Unable to encrypt connection from %s - %s (%d)",
3384 con
->http
.hostname
, cssmErrorString(error
), (int)error
);
3386 con
->http
.error
= error
;
3387 con
->http
.status
= HTTP_ERROR
;
3391 SSLDisposeContext(con
->http
.tls
);
3392 con
->http
.tls
= NULL
;
3395 if (con
->http
.tls_credentials
)
3397 CFRelease(con
->http
.tls_credentials
);
3398 con
->http
.tls_credentials
= NULL
;
3404 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Connection from %s now encrypted.",
3405 con
->http
.hostname
);
3407 if (!SSLCopyPeerCertificates(con
->http
.tls
, &peerCerts
) && peerCerts
)
3409 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Received %d peer certificates!",
3410 (int)CFArrayGetCount(peerCerts
));
3413 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Received NO peer certificates!");
3417 # endif /* HAVE_LIBSSL */
3419 #endif /* HAVE_SSL */
3424 * 'get_cdsa_certificate()' - Get a SSL/TLS certificate from the System keychain.
3427 static CFArrayRef
/* O - Array of certificates */
3428 get_cdsa_certificate(
3429 cupsd_client_t
*con
) /* I - Client connection */
3431 OSStatus err
; /* Error info */
3432 SecKeychainRef keychain
= NULL
;/* Keychain reference */
3433 SecIdentitySearchRef search
= NULL
; /* Search reference */
3434 SecIdentityRef identity
= NULL
;/* Identity */
3435 CFArrayRef certificates
= NULL
;
3436 /* Certificate array */
3437 # if HAVE_SECPOLICYCREATESSL
3438 SecPolicyRef policy
= NULL
; /* Policy ref */
3439 CFStringRef servername
= NULL
;
3441 CFMutableDictionaryRef query
= NULL
; /* Query qualifiers */
3442 char localname
[1024];/* Local hostname */
3443 # elif defined(HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY)
3444 SecPolicyRef policy
= NULL
; /* Policy ref */
3445 SecPolicySearchRef policy_search
= NULL
;
3446 /* Policy search ref */
3447 CSSM_DATA options
; /* Policy options */
3448 CSSM_APPLE_TP_SSL_OPTIONS
3449 ssl_options
; /* SSL Option for hostname */
3450 char localname
[1024];/* Local hostname */
3451 # endif /* HAVE_SECPOLICYCREATESSL */
3454 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3455 "get_cdsa_certificate: Looking for certs for \"%s\"...",
3458 if ((err
= SecKeychainOpen(ServerCertificate
, &keychain
)))
3460 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot open keychain \"%s\" - %s (%d)",
3461 ServerCertificate
, cssmErrorString(err
), (int)err
);
3465 # if HAVE_SECPOLICYCREATESSL
3466 servername
= CFStringCreateWithCString(kCFAllocatorDefault
, con
->servername
,
3467 kCFStringEncodingUTF8
);
3469 policy
= SecPolicyCreateSSL(1, servername
);
3472 CFRelease(servername
);
3476 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot create ssl policy reference");
3480 if (!(query
= CFDictionaryCreateMutable(kCFAllocatorDefault
, 0,
3481 &kCFTypeDictionaryKeyCallBacks
,
3482 &kCFTypeDictionaryValueCallBacks
)))
3484 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot create query dictionary");
3488 CFDictionaryAddValue(query
, kSecClass
, kSecClassIdentity
);
3489 CFDictionaryAddValue(query
, kSecMatchPolicy
, policy
);
3490 CFDictionaryAddValue(query
, kSecReturnRef
, kCFBooleanTrue
);
3491 CFDictionaryAddValue(query
, kSecMatchLimit
, kSecMatchLimitOne
);
3493 err
= SecItemCopyMatching(query
, (CFTypeRef
*)&identity
);
3495 if (err
&& DNSSDHostName
)
3498 * Search for the connection server name failed; try the DNS-SD .local
3499 * hostname instead...
3502 snprintf(localname
, sizeof(localname
), "%s.local", DNSSDHostName
);
3504 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3505 "get_cdsa_certificate: Looking for certs for \"%s\"...",
3508 servername
= CFStringCreateWithCString(kCFAllocatorDefault
, localname
,
3509 kCFStringEncodingUTF8
);
3513 policy
= SecPolicyCreateSSL(1, servername
);
3516 CFRelease(servername
);
3520 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot create ssl policy reference");
3524 CFDictionarySetValue(query
, kSecMatchPolicy
, policy
);
3526 err
= SecItemCopyMatching(query
, (CFTypeRef
*)&identity
);
3531 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3532 "Cannot find signing key in keychain \"%s\": %s (%d)",
3533 ServerCertificate
, cssmErrorString(err
), (int)err
);
3537 # elif defined(HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY)
3539 * Use a policy to search for valid certificates whose common name matches the
3543 if (SecPolicySearchCreate(CSSM_CERT_X_509v3
, &CSSMOID_APPLE_TP_SSL
,
3544 NULL
, &policy_search
))
3546 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot create a policy search reference");
3550 if (SecPolicySearchCopyNext(policy_search
, &policy
))
3552 cupsdLogMessage(CUPSD_LOG_ERROR
,
3553 "Cannot find a policy to use for searching");
3557 memset(&ssl_options
, 0, sizeof(ssl_options
));
3558 ssl_options
.Version
= CSSM_APPLE_TP_SSL_OPTS_VERSION
;
3559 ssl_options
.ServerName
= con
->servername
;
3560 ssl_options
.ServerNameLen
= strlen(con
->servername
);
3562 options
.Data
= (uint8
*)&ssl_options
;
3563 options
.Length
= sizeof(ssl_options
);
3565 if (SecPolicySetValue(policy
, &options
))
3567 cupsdLogMessage(CUPSD_LOG_ERROR
,
3568 "Cannot set policy value to use for searching");
3572 if ((err
= SecIdentitySearchCreateWithPolicy(policy
, NULL
, CSSM_KEYUSE_SIGN
,
3573 keychain
, FALSE
, &search
)))
3575 cupsdLogMessage(CUPSD_LOG_ERROR
,
3576 "Cannot create identity search reference: %s (%d)",
3577 cssmErrorString(err
), (int)err
);
3581 err
= SecIdentitySearchCopyNext(search
, &identity
);
3583 if (err
&& DNSSDHostName
)
3586 * Search for the connection server name failed; try the DNS-SD .local
3587 * hostname instead...
3590 snprintf(localname
, sizeof(localname
), "%s.local", DNSSDHostName
);
3592 ssl_options
.ServerName
= localname
;
3593 ssl_options
.ServerNameLen
= strlen(localname
);
3595 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3596 "get_cdsa_certificate: Looking for certs for \"%s\"...",
3599 if (SecPolicySetValue(policy
, &options
))
3601 cupsdLogMessage(CUPSD_LOG_ERROR
,
3602 "Cannot set policy value to use for searching");
3608 if ((err
= SecIdentitySearchCreateWithPolicy(policy
, NULL
, CSSM_KEYUSE_SIGN
,
3609 keychain
, FALSE
, &search
)))
3611 cupsdLogMessage(CUPSD_LOG_ERROR
,
3612 "Cannot create identity search reference: %s (%d)",
3613 cssmErrorString(err
), (int)err
);
3617 err
= SecIdentitySearchCopyNext(search
, &identity
);
3623 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3624 "Cannot find signing key in keychain \"%s\": %s (%d)",
3625 ServerCertificate
, cssmErrorString(err
), (int)err
);
3631 * Assume there is exactly one SecIdentity in the keychain...
3634 if ((err
= SecIdentitySearchCreate(keychain
, CSSM_KEYUSE_SIGN
, &search
)))
3636 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3637 "Cannot create identity search reference (%d)", (int)err
);
3641 if ((err
= SecIdentitySearchCopyNext(search
, &identity
)))
3643 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3644 "Cannot find signing key in keychain \"%s\": %s (%d)",
3645 ServerCertificate
, cssmErrorString(err
), (int)err
);
3648 # endif /* HAVE_SECPOLICYCREATESSL */
3650 if (CFGetTypeID(identity
) != SecIdentityGetTypeID())
3652 cupsdLogMessage(CUPSD_LOG_ERROR
, "SecIdentity CFTypeID failure!");
3656 if ((certificates
= CFArrayCreate(NULL
, (const void **)&identity
,
3657 1, &kCFTypeArrayCallBacks
)) == NULL
)
3659 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot create certificate array");
3666 CFRelease(keychain
);
3670 CFRelease(identity
);
3672 # if HAVE_SECPOLICYCREATESSL
3677 # elif defined(HAVE_SECIDENTITYSEARCHCREATEWITHPOLICY)
3681 CFRelease(policy_search
);
3682 # endif /* HAVE_SECPOLICYCREATESSL */
3684 return (certificates
);
3686 #endif /* HAVE_CDSASSL */
3690 * 'get_file()' - Get a filename and state info.
3693 static char * /* O - Real filename */
3694 get_file(cupsd_client_t
*con
, /* I - Client connection */
3695 struct stat
*filestats
, /* O - File information */
3696 char *filename
, /* IO - Filename buffer */
3697 int len
) /* I - Buffer length */
3699 int status
; /* Status of filesystem calls */
3700 char *ptr
; /* Pointer info filename */
3701 int plen
; /* Remaining length after pointer */
3702 char language
[7]; /* Language subdirectory, if any */
3706 * Figure out the real filename...
3711 if (!strncmp(con
->uri
, "/ppd/", 5) && !strchr(con
->uri
+ 5, '/'))
3712 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
);
3713 else if (!strncmp(con
->uri
, "/icons/", 7) && !strchr(con
->uri
+ 7, '/'))
3715 snprintf(filename
, len
, "%s/%s", CacheDir
, con
->uri
+ 7);
3716 if (access(filename
, F_OK
) < 0)
3717 snprintf(filename
, len
, "%s/images/generic.png", DocumentRoot
);
3719 else if (!strncmp(con
->uri
, "/rss/", 5) && !strchr(con
->uri
+ 5, '/'))
3720 snprintf(filename
, len
, "%s/rss/%s", CacheDir
, con
->uri
+ 5);
3721 else if (!strncmp(con
->uri
, "/admin/conf/", 12))
3722 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
+ 11);
3723 else if (!strncmp(con
->uri
, "/admin/log/", 11))
3725 if (!strncmp(con
->uri
+ 11, "access_log", 10) && AccessLog
[0] == '/')
3726 strlcpy(filename
, AccessLog
, len
);
3727 else if (!strncmp(con
->uri
+ 11, "error_log", 9) && ErrorLog
[0] == '/')
3728 strlcpy(filename
, ErrorLog
, len
);
3729 else if (!strncmp(con
->uri
+ 11, "page_log", 8) && PageLog
[0] == '/')
3730 strlcpy(filename
, PageLog
, len
);
3734 else if (con
->language
)
3736 snprintf(language
, sizeof(language
), "/%s", con
->language
->language
);
3737 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3740 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3742 if ((ptr
= strchr(filename
, '?')) != NULL
)
3746 * Grab the status for this language; if there isn't a language-specific file
3747 * then fallback to the default one...
3750 if ((status
= stat(filename
, filestats
)) != 0 && language
[0] &&
3751 strncmp(con
->uri
, "/icons/", 7) &&
3752 strncmp(con
->uri
, "/ppd/", 5) &&
3753 strncmp(con
->uri
, "/rss/", 5) &&
3754 strncmp(con
->uri
, "/admin/conf/", 12) &&
3755 strncmp(con
->uri
, "/admin/log/", 11))
3758 * Drop the country code...
3762 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3764 if ((ptr
= strchr(filename
, '?')) != NULL
)
3767 if ((status
= stat(filename
, filestats
)) != 0)
3770 * Drop the language prefix and try the root directory...
3774 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3776 if ((ptr
= strchr(filename
, '?')) != NULL
)
3779 status
= stat(filename
, filestats
);
3784 * If we're found a directory, get the index.html file instead...
3787 if (!status
&& S_ISDIR(filestats
->st_mode
))
3790 * Make sure the URI ends with a slash...
3793 if (con
->uri
[strlen(con
->uri
) - 1] != '/')
3794 strlcat(con
->uri
, "/", sizeof(con
->uri
));
3797 * Find the directory index file, trying every language...
3802 if (status
&& language
[0])
3805 * Try a different language subset...
3809 language
[0] = '\0'; /* Strip country code */
3811 language
[0] = '\0'; /* Strip language */
3815 * Look for the index file...
3818 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3820 if ((ptr
= strchr(filename
, '?')) != NULL
)
3823 ptr
= filename
+ strlen(filename
);
3824 plen
= len
- (ptr
- filename
);
3826 strlcpy(ptr
, "index.html", plen
);
3827 status
= stat(filename
, filestats
);
3832 strlcpy(ptr
, "index.class", plen
);
3833 status
= stat(filename
, filestats
);
3835 #endif /* HAVE_JAVA */
3840 strlcpy(ptr
, "index.pl", plen
);
3841 status
= stat(filename
, filestats
);
3843 #endif /* HAVE_PERL */
3848 strlcpy(ptr
, "index.php", plen
);
3849 status
= stat(filename
, filestats
);
3851 #endif /* HAVE_PHP */
3856 strlcpy(ptr
, "index.pyc", plen
);
3857 status
= stat(filename
, filestats
);
3862 strlcpy(ptr
, "index.py", plen
);
3863 status
= stat(filename
, filestats
);
3865 #endif /* HAVE_PYTHON */
3868 while (status
&& language
[0]);
3871 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3872 "get_file(con=%p(%d), filestats=%p, filename=%p, len=%d) = "
3873 "%s", con
, con
->http
.fd
, filestats
, filename
, len
,
3874 status
? "(null)" : filename
);
3884 * 'install_conf_file()' - Install a configuration file.
3887 static http_status_t
/* O - Status */
3888 install_conf_file(cupsd_client_t
*con
) /* I - Connection */
3890 cups_file_t
*in
, /* Input file */
3891 *out
; /* Output file */
3892 char buffer
[1024]; /* Copy buffer */
3893 int bytes
; /* Number of bytes */
3894 char conffile
[1024], /* Configuration filename */
3895 newfile
[1024], /* New config filename */
3896 oldfile
[1024]; /* Old config filename */
3897 struct stat confinfo
; /* Config file info */
3901 * First construct the filenames...
3904 snprintf(conffile
, sizeof(conffile
), "%s%s", ServerRoot
, con
->uri
+ 11);
3905 snprintf(newfile
, sizeof(newfile
), "%s%s.N", ServerRoot
, con
->uri
+ 11);
3906 snprintf(oldfile
, sizeof(oldfile
), "%s%s.O", ServerRoot
, con
->uri
+ 11);
3908 cupsdLogMessage(CUPSD_LOG_INFO
, "Installing config file \"%s\"...", conffile
);
3911 * Get the owner, group, and permissions of the configuration file.
3912 * If it doesn't exist, assign it to the User and Group in the
3913 * cupsd.conf file with mode 0640 permissions.
3916 if (stat(conffile
, &confinfo
))
3918 confinfo
.st_uid
= User
;
3919 confinfo
.st_gid
= Group
;
3920 confinfo
.st_mode
= ConfigFilePerm
;
3924 * Open the request file and new config file...
3927 if ((in
= cupsFileOpen(con
->filename
, "rb")) == NULL
)
3929 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open request file \"%s\" - %s",
3930 con
->filename
, strerror(errno
));
3931 return (HTTP_SERVER_ERROR
);
3934 if ((out
= cupsFileOpen(newfile
, "wb")) == NULL
)
3937 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open config file \"%s\" - %s",
3938 newfile
, strerror(errno
));
3939 return (HTTP_SERVER_ERROR
);
3942 fchmod(cupsFileNumber(out
), confinfo
.st_mode
);
3943 fchown(cupsFileNumber(out
), confinfo
.st_uid
, confinfo
.st_gid
);
3946 * Copy from the request to the new config file...
3949 while ((bytes
= cupsFileRead(in
, buffer
, sizeof(buffer
))) > 0)
3950 if (cupsFileWrite(out
, buffer
, bytes
) < bytes
)
3952 cupsdLogMessage(CUPSD_LOG_ERROR
,
3953 "Unable to copy to config file \"%s\" - %s",
3954 newfile
, strerror(errno
));
3960 return (HTTP_SERVER_ERROR
);
3964 * Close the files...
3968 if (cupsFileClose(out
))
3970 cupsdLogMessage(CUPSD_LOG_ERROR
,
3971 "Error file closing config file \"%s\" - %s",
3972 newfile
, strerror(errno
));
3976 return (HTTP_SERVER_ERROR
);
3980 * Remove the request file...
3983 unlink(con
->filename
);
3984 cupsdClearString(&con
->filename
);
3987 * Unlink the old backup, rename the current config file to the backup
3988 * filename, and rename the new config file to the config file name...
3991 if (unlink(oldfile
))
3992 if (errno
!= ENOENT
)
3994 cupsdLogMessage(CUPSD_LOG_ERROR
,
3995 "Unable to remove backup config file \"%s\" - %s",
3996 oldfile
, strerror(errno
));
4000 return (HTTP_SERVER_ERROR
);
4003 if (rename(conffile
, oldfile
))
4004 if (errno
!= ENOENT
)
4006 cupsdLogMessage(CUPSD_LOG_ERROR
,
4007 "Unable to rename old config file \"%s\" - %s",
4008 conffile
, strerror(errno
));
4012 return (HTTP_SERVER_ERROR
);
4015 if (rename(newfile
, conffile
))
4017 cupsdLogMessage(CUPSD_LOG_ERROR
,
4018 "Unable to rename new config file \"%s\" - %s",
4019 newfile
, strerror(errno
));
4021 rename(oldfile
, conffile
);
4024 return (HTTP_SERVER_ERROR
);
4028 * If the cupsd.conf file was updated, set the NeedReload flag...
4031 if (!strcmp(con
->uri
, "/admin/conf/cupsd.conf"))
4032 NeedReload
= RELOAD_CUPSD
;
4034 NeedReload
= RELOAD_ALL
;
4036 ReloadTime
= time(NULL
);
4039 * Return that the file was created successfully...
4042 return (HTTP_CREATED
);
4047 * 'is_cgi()' - Is the resource a CGI script/program?
4050 static int /* O - 1 = CGI, 0 = file */
4051 is_cgi(cupsd_client_t
*con
, /* I - Client connection */
4052 const char *filename
, /* I - Real filename */
4053 struct stat
*filestats
, /* I - File information */
4054 mime_type_t
*type
) /* I - MIME type */
4056 const char *options
; /* Options on URL */
4060 * Get the options, if any...
4063 if ((options
= strchr(con
->uri
, '?')) != NULL
)
4066 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", options
);
4070 * Check for known types...
4073 if (!type
|| strcasecmp(type
->super
, "application"))
4075 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4076 "is_cgi(con=%p(%d), filename=\"%s\", filestats=%p, "
4077 "type=%s/%s) = 0", con
, con
->http
.fd
, filename
, filestats
,
4078 type
? type
->super
: "unknown",
4079 type
? type
->type
: "unknown");
4083 if (!strcasecmp(type
->type
, "x-httpd-cgi") &&
4084 (filestats
->st_mode
& 0111))
4087 * "application/x-httpd-cgi" is a CGI script.
4090 cupsdSetString(&con
->command
, filename
);
4093 cupsdSetStringf(&con
->options
, " %s", options
);
4095 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4096 "is_cgi(con=%p(%d), filename=\"%s\", filestats=%p, "
4097 "type=%s/%s) = 1", con
, con
->http
.fd
, filename
, filestats
,
4098 type
? type
->super
: "unknown",
4099 type
? type
->type
: "unknown");
4103 else if (!strcasecmp(type
->type
, "x-httpd-java"))
4106 * "application/x-httpd-java" is a Java servlet.
4109 cupsdSetString(&con
->command
, CUPS_JAVA
);
4112 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
4114 cupsdSetStringf(&con
->options
, " %s", filename
);
4116 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4117 "is_cgi(con=%p(%d), filename=\"%s\", filestats=%p, "
4118 "type=%s/%s) = 1", con
, con
->http
.fd
, filename
, filestats
,
4119 type
? type
->super
: "unknown",
4120 type
? type
->type
: "unknown");
4123 #endif /* HAVE_JAVA */
4125 else if (!strcasecmp(type
->type
, "x-httpd-perl"))
4128 * "application/x-httpd-perl" is a Perl page.
4131 cupsdSetString(&con
->command
, CUPS_PERL
);
4134 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
4136 cupsdSetStringf(&con
->options
, " %s", filename
);
4138 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4139 "is_cgi(con=%p(%d), filename=\"%s\", filestats=%p, "
4140 "type=%s/%s) = 1", con
, con
->http
.fd
, filename
, filestats
,
4141 type
? type
->super
: "unknown",
4142 type
? type
->type
: "unknown");
4145 #endif /* HAVE_PERL */
4147 else if (!strcasecmp(type
->type
, "x-httpd-php"))
4150 * "application/x-httpd-php" is a PHP page.
4153 cupsdSetString(&con
->command
, CUPS_PHP
);
4156 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
4158 cupsdSetStringf(&con
->options
, " %s", filename
);
4160 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4161 "is_cgi(con=%p(%d), filename=\"%s\", filestats=%p, "
4162 "type=%s/%s) = 1", con
, con
->http
.fd
, filename
, filestats
,
4163 type
? type
->super
: "unknown",
4164 type
? type
->type
: "unknown");
4167 #endif /* HAVE_PHP */
4169 else if (!strcasecmp(type
->type
, "x-httpd-python"))
4172 * "application/x-httpd-python" is a Python page.
4175 cupsdSetString(&con
->command
, CUPS_PYTHON
);
4178 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
4180 cupsdSetStringf(&con
->options
, " %s", filename
);
4182 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4183 "is_cgi(con=%p(%d), filename=\"%s\", filestats=%p, "
4184 "type=%s/%s) = 1", con
, con
->http
.fd
, filename
, filestats
,
4185 type
? type
->super
: "unknown",
4186 type
? type
->type
: "unknown");
4189 #endif /* HAVE_PYTHON */
4191 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4192 "is_cgi(con=%p(%d), filename=\"%s\", filestats=%p, "
4193 "type=%s/%s) = 0", con
, con
->http
.fd
, filename
, filestats
,
4194 type
? type
->super
: "unknown",
4195 type
? type
->type
: "unknown");
4201 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
4204 static int /* O - 0 if relative, 1 if absolute */
4205 is_path_absolute(const char *path
) /* I - Input path */
4208 * Check for a leading slash...
4215 * Check for "/.." in the path...
4218 while ((path
= strstr(path
, "/..")) != NULL
)
4220 if (!path
[3] || path
[3] == '/')
4227 * If we haven't found any relative paths, return 1 indicating an
4237 * 'make_certificate()' - Make a self-signed SSL/TLS certificate.
4240 static int /* O - 1 on success, 0 on failure */
4241 make_certificate(cupsd_client_t
*con
) /* I - Client connection */
4243 #if defined(HAVE_LIBSSL) && defined(HAVE_WAITPID)
4244 int pid
, /* Process ID of command */
4245 status
; /* Status of command */
4246 char command
[1024], /* Command */
4247 *argv
[12], /* Command-line arguments */
4248 *envp
[MAX_ENV
+ 1], /* Environment variables */
4249 infofile
[1024], /* Type-in information for cert */
4250 seedfile
[1024]; /* Random number seed file */
4251 int envc
, /* Number of environment variables */
4252 bytes
; /* Bytes written */
4253 cups_file_t
*fp
; /* Seed/info file */
4254 int infofd
; /* Info file descriptor */
4258 * Run the "openssl" command to seed the random number generator and
4259 * generate a self-signed certificate that is good for 10 years:
4261 * openssl rand -rand seedfile 1
4263 * openssl req -new -x509 -keyout ServerKey \
4264 * -out ServerCertificate -days 3650 -nodes
4266 * The seeding step is crucial in ensuring that the openssl command
4267 * does not block on systems without sufficient entropy...
4270 if (!cupsFileFind("openssl", getenv("PATH"), 1, command
, sizeof(command
)))
4272 cupsdLogMessage(CUPSD_LOG_ERROR
,
4273 "No SSL certificate and openssl command not found!");
4277 if (access("/dev/urandom", 0))
4280 * If the system doesn't provide /dev/urandom, then any random source
4281 * will probably be blocking-style, so generate some random data to
4282 * use as a seed for the certificate. Note that we have already
4283 * seeded the random number generator in cupsdInitCerts()...
4286 cupsdLogMessage(CUPSD_LOG_INFO
,
4287 "Seeding the random number generator...");
4290 * Write the seed file...
4293 if ((fp
= cupsTempFile2(seedfile
, sizeof(seedfile
))) == NULL
)
4295 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to create seed file %s - %s",
4296 seedfile
, strerror(errno
));
4300 for (bytes
= 0; bytes
< 262144; bytes
++)
4301 cupsFilePutChar(fp
, random());
4306 * Run the openssl command to seed its random number generator...
4309 argv
[0] = "openssl";
4316 envc
= cupsdLoadEnv(envp
, MAX_ENV
);
4319 if (!cupsdStartProcess(command
, argv
, envp
, -1, -1, -1, -1, -1, 1, NULL
,
4326 while (waitpid(pid
, &status
, 0) < 0)
4333 cupsdFinishProcess(pid
, command
, sizeof(command
), NULL
);
4336 * Remove the seed file, as it is no longer needed...
4343 if (WIFEXITED(status
))
4344 cupsdLogMessage(CUPSD_LOG_ERROR
,
4345 "Unable to seed random number generator - "
4346 "the openssl command stopped with status %d!",
4347 WEXITSTATUS(status
));
4349 cupsdLogMessage(CUPSD_LOG_ERROR
,
4350 "Unable to seed random number generator - "
4351 "the openssl command crashed on signal %d!",
4359 * Create a file with the certificate information fields...
4361 * Note: This assumes that the default questions are asked by the openssl
4365 if ((fp
= cupsTempFile2(infofile
, sizeof(infofile
))) == NULL
)
4367 cupsdLogMessage(CUPSD_LOG_ERROR
,
4368 "Unable to create certificate information file %s - %s",
4369 infofile
, strerror(errno
));
4373 cupsFilePrintf(fp
, ".\n.\n.\n%s\n.\n%s\n%s\n",
4374 ServerName
, ServerName
, ServerAdmin
);
4377 cupsdLogMessage(CUPSD_LOG_INFO
,
4378 "Generating SSL server key and certificate...");
4380 argv
[0] = "openssl";
4384 argv
[4] = "-keyout";
4385 argv
[5] = ServerKey
;
4387 argv
[7] = ServerCertificate
;
4390 argv
[10] = "-nodes";
4393 cupsdLoadEnv(envp
, MAX_ENV
);
4395 infofd
= open(infofile
, O_RDONLY
);
4397 if (!cupsdStartProcess(command
, argv
, envp
, infofd
, -1, -1, -1, -1, 1, NULL
,
4408 while (waitpid(pid
, &status
, 0) < 0)
4415 cupsdFinishProcess(pid
, command
, sizeof(command
), NULL
);
4419 if (WIFEXITED(status
))
4420 cupsdLogMessage(CUPSD_LOG_ERROR
,
4421 "Unable to create SSL server key and certificate - "
4422 "the openssl command stopped with status %d!",
4423 WEXITSTATUS(status
));
4425 cupsdLogMessage(CUPSD_LOG_ERROR
,
4426 "Unable to create SSL server key and certificate - "
4427 "the openssl command crashed on signal %d!",
4432 cupsdLogMessage(CUPSD_LOG_INFO
, "Created SSL server key file \"%s\"...",
4434 cupsdLogMessage(CUPSD_LOG_INFO
,
4435 "Created SSL server certificate file \"%s\"...",
4441 #elif defined(HAVE_GNUTLS)
4442 gnutls_x509_crt crt
; /* Self-signed certificate */
4443 gnutls_x509_privkey key
; /* Encryption key */
4444 cups_lang_t
*language
; /* Default language info */
4445 cups_file_t
*fp
; /* Key/cert file */
4446 unsigned char buffer
[8192]; /* Buffer for x509 data */
4447 size_t bytes
; /* Number of bytes of data */
4448 unsigned char serial
[4]; /* Serial number buffer */
4449 time_t curtime
; /* Current time */
4450 int result
; /* Result of GNU TLS calls */
4454 * Create the encryption key...
4457 cupsdLogMessage(CUPSD_LOG_INFO
, "Generating SSL server key...");
4459 gnutls_x509_privkey_init(&key
);
4460 gnutls_x509_privkey_generate(key
, GNUTLS_PK_RSA
, 2048, 0);
4466 bytes
= sizeof(buffer
);
4468 if ((result
= gnutls_x509_privkey_export(key
, GNUTLS_X509_FMT_PEM
,
4469 buffer
, &bytes
)) < 0)
4471 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to export SSL server key - %s",
4472 gnutls_strerror(result
));
4473 gnutls_x509_privkey_deinit(key
);
4476 else if ((fp
= cupsFileOpen(ServerKey
, "w")) != NULL
)
4478 cupsFileWrite(fp
, (char *)buffer
, bytes
);
4481 cupsdLogMessage(CUPSD_LOG_INFO
, "Created SSL server key file \"%s\"...",
4486 cupsdLogMessage(CUPSD_LOG_ERROR
,
4487 "Unable to create SSL server key file \"%s\" - %s",
4488 ServerKey
, strerror(errno
));
4489 gnutls_x509_privkey_deinit(key
);
4494 * Create the self-signed certificate...
4497 cupsdLogMessage(CUPSD_LOG_INFO
, "Generating self-signed SSL certificate...");
4499 language
= cupsLangDefault();
4500 curtime
= time(NULL
);
4501 serial
[0] = curtime
>> 24;
4502 serial
[1] = curtime
>> 16;
4503 serial
[2] = curtime
>> 8;
4504 serial
[3] = curtime
;
4506 gnutls_x509_crt_init(&crt
);
4507 if (strlen(language
->language
) == 5)
4508 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
4509 language
->language
+ 3, 2);
4511 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
4513 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COMMON_NAME
, 0,
4514 ServerName
, strlen(ServerName
));
4515 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATION_NAME
, 0,
4516 ServerName
, strlen(ServerName
));
4517 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATIONAL_UNIT_NAME
,
4519 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_STATE_OR_PROVINCE_NAME
, 0,
4521 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_LOCALITY_NAME
, 0,
4523 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_PKCS9_EMAIL
, 0,
4524 ServerAdmin
, strlen(ServerAdmin
));
4525 gnutls_x509_crt_set_key(crt
, key
);
4526 gnutls_x509_crt_set_serial(crt
, serial
, sizeof(serial
));
4527 gnutls_x509_crt_set_activation_time(crt
, curtime
);
4528 gnutls_x509_crt_set_expiration_time(crt
, curtime
+ 10 * 365 * 86400);
4529 gnutls_x509_crt_set_ca_status(crt
, 0);
4530 gnutls_x509_crt_set_subject_alternative_name(crt
, GNUTLS_SAN_DNSNAME
,
4532 gnutls_x509_crt_set_key_purpose_oid(crt
, GNUTLS_KP_TLS_WWW_SERVER
, 0);
4533 gnutls_x509_crt_set_key_usage(crt
, GNUTLS_KEY_KEY_ENCIPHERMENT
);
4534 gnutls_x509_crt_set_version(crt
, 3);
4536 bytes
= sizeof(buffer
);
4537 if (gnutls_x509_crt_get_key_id(crt
, 0, buffer
, &bytes
) >= 0)
4538 gnutls_x509_crt_set_subject_key_id(crt
, buffer
, bytes
);
4540 gnutls_x509_crt_sign(crt
, crt
, key
);
4546 bytes
= sizeof(buffer
);
4547 if ((result
= gnutls_x509_crt_export(crt
, GNUTLS_X509_FMT_PEM
,
4548 buffer
, &bytes
)) < 0)
4549 cupsdLogMessage(CUPSD_LOG_ERROR
,
4550 "Unable to export SSL server certificate - %s",
4551 gnutls_strerror(result
));
4552 else if ((fp
= cupsFileOpen(ServerCertificate
, "w")) != NULL
)
4554 cupsFileWrite(fp
, (char *)buffer
, bytes
);
4557 cupsdLogMessage(CUPSD_LOG_INFO
,
4558 "Created SSL server certificate file \"%s\"...",
4562 cupsdLogMessage(CUPSD_LOG_ERROR
,
4563 "Unable to create SSL server certificate file \"%s\" - %s",
4564 ServerCertificate
, strerror(errno
));
4570 gnutls_x509_crt_deinit(crt
);
4571 gnutls_x509_privkey_deinit(key
);
4575 #elif defined(HAVE_CDSASSL) && defined(HAVE_WAITPID)
4576 int pid
, /* Process ID of command */
4577 status
; /* Status of command */
4578 char command
[1024], /* Command */
4579 *argv
[4], /* Command-line arguments */
4580 *envp
[MAX_ENV
+ 1], /* Environment variables */
4581 keychain
[1024], /* Keychain argument */
4582 infofile
[1024], /* Type-in information for cert */
4583 localname
[1024], /* Local hostname */
4584 *servername
; /* Name of server in cert */
4585 cups_file_t
*fp
; /* Seed/info file */
4586 int infofd
; /* Info file descriptor */
4589 if (con
->servername
&& isdigit(con
->servername
[0] & 255) && DNSSDHostName
)
4591 snprintf(localname
, sizeof(localname
), "%s.local", DNSSDHostName
);
4592 servername
= localname
;
4595 servername
= con
->servername
;
4598 * Run the "certtool" command to generate a self-signed certificate...
4601 if (!cupsFileFind("certtool", getenv("PATH"), 1, command
, sizeof(command
)))
4603 cupsdLogMessage(CUPSD_LOG_ERROR
,
4604 "No SSL certificate and certtool command not found!");
4609 * Create a file with the certificate information fields...
4611 * Note: This assumes that the default questions are asked by the certtool
4615 if ((fp
= cupsTempFile2(infofile
, sizeof(infofile
))) == NULL
)
4617 cupsdLogMessage(CUPSD_LOG_ERROR
,
4618 "Unable to create certificate information file %s - %s",
4619 infofile
, strerror(errno
));
4623 cupsFilePrintf(fp
, "%s\nr\n\ny\nb\ns\ny\n%s\n\n\n\n\n%s\ny\n",
4624 servername
, servername
, ServerAdmin
);
4627 cupsdLogMessage(CUPSD_LOG_INFO
,
4628 "Generating SSL server key and certificate...");
4630 snprintf(keychain
, sizeof(keychain
), "k=%s", ServerCertificate
);
4632 argv
[0] = "certtool";
4637 cupsdLoadEnv(envp
, MAX_ENV
);
4639 infofd
= open(infofile
, O_RDONLY
);
4641 if (!cupsdStartProcess(command
, argv
, envp
, infofd
, -1, -1, -1, -1, 1, NULL
,
4652 while (waitpid(pid
, &status
, 0) < 0)
4659 cupsdFinishProcess(pid
, command
, sizeof(command
), NULL
);
4663 if (WIFEXITED(status
))
4664 cupsdLogMessage(CUPSD_LOG_ERROR
,
4665 "Unable to create SSL server key and certificate - "
4666 "the certtool command stopped with status %d!",
4667 WEXITSTATUS(status
));
4669 cupsdLogMessage(CUPSD_LOG_ERROR
,
4670 "Unable to create SSL server key and certificate - "
4671 "the certtool command crashed on signal %d!",
4676 cupsdLogMessage(CUPSD_LOG_INFO
,
4677 "Created SSL server certificate file \"%s\"...",
4685 #endif /* HAVE_LIBSSL && HAVE_WAITPID */
4687 #endif /* HAVE_SSL */
4691 * 'pipe_command()' - Pipe the output of a command to the remote client.
4694 static int /* O - Process ID */
4695 pipe_command(cupsd_client_t
*con
, /* I - Client connection */
4696 int infile
, /* I - Standard input for command */
4697 int *outfile
, /* O - Standard output for command */
4698 char *command
, /* I - Command to run */
4699 char *options
, /* I - Options for command */
4700 int root
) /* I - Run as root? */
4702 int i
; /* Looping var */
4703 int pid
; /* Process ID */
4704 char *commptr
, /* Command string pointer */
4705 commch
; /* Command string character */
4706 char *uriptr
; /* URI string pointer */
4707 int fds
[2]; /* Pipe FDs */
4708 int argc
; /* Number of arguments */
4709 int envc
; /* Number of environment variables */
4710 char argbuf
[10240], /* Argument buffer */
4711 *argv
[100], /* Argument strings */
4712 *envp
[MAX_ENV
+ 20]; /* Environment variables */
4713 char auth_type
[256], /* AUTH_TYPE environment variable */
4714 content_length
[1024], /* CONTENT_LENGTH environment variable */
4715 content_type
[1024], /* CONTENT_TYPE environment variable */
4716 http_cookie
[32768], /* HTTP_COOKIE environment variable */
4717 http_referer
[1024], /* HTTP_REFERER environment variable */
4718 http_user_agent
[1024], /* HTTP_USER_AGENT environment variable */
4719 lang
[1024], /* LANG environment variable */
4720 path_info
[1024], /* PATH_INFO environment variable */
4721 remote_addr
[1024], /* REMOTE_ADDR environment variable */
4722 remote_host
[1024], /* REMOTE_HOST environment variable */
4723 remote_user
[1024], /* REMOTE_USER environment variable */
4724 script_filename
[1024], /* SCRIPT_FILENAME environment variable */
4725 script_name
[1024], /* SCRIPT_NAME environment variable */
4726 server_name
[1024], /* SERVER_NAME environment variable */
4727 server_port
[1024]; /* SERVER_PORT environment variable */
4728 ipp_attribute_t
*attr
; /* attributes-natural-language attribute */
4729 void *ccache
= NULL
; /* Kerberos credentials */
4733 * Parse a copy of the options string, which is of the form:
4735 * argument+argument+argument
4736 * ?argument+argument+argument
4737 * param=value¶m=value
4738 * ?param=value¶m=value
4739 * /name?argument+argument+argument
4740 * /name?param=value¶m=value
4742 * If the string contains an "=" character after the initial name,
4743 * then we treat it as a HTTP GET form request and make a copy of
4744 * the remaining string for the environment variable.
4746 * The string is always parsed out as command-line arguments, to
4747 * be consistent with Apache...
4750 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4751 "pipe_command(con=%p(%d), infile=%d, outfile=%p, "
4752 "command=\"%s\", options=\"%s\", root=%d)",
4753 con
, con
->http
.fd
, infile
, outfile
, command
,
4754 options
? options
: "(null)", root
);
4761 if (*commptr
== ' ')
4763 strlcpy(argbuf
, commptr
, sizeof(argbuf
));
4768 if (argbuf
[0] == '/')
4771 * Found some trailing path information, set PATH_INFO...
4774 if ((commptr
= strchr(argbuf
, '?')) == NULL
)
4775 commptr
= argbuf
+ strlen(argbuf
);
4779 snprintf(path_info
, sizeof(path_info
), "PATH_INFO=%s", argbuf
);
4785 path_info
[0] = '\0';
4787 if (*commptr
== ' ')
4791 if (*commptr
== '?' && con
->operation
== HTTP_GET
&& !con
->query_string
)
4794 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", commptr
);
4801 argv
[argc
++] = commptr
;
4803 for (; *commptr
&& argc
< 99; commptr
++)
4806 * Break arguments whenever we see a + or space...
4809 if (*commptr
== ' ' || *commptr
== '+')
4811 while (*commptr
== ' ' || *commptr
== '+')
4815 * If we don't have a blank string, save it as another argument...
4820 argv
[argc
] = commptr
;
4826 else if (*commptr
== '%' && isxdigit(commptr
[1] & 255) &&
4827 isxdigit(commptr
[2] & 255))
4830 * Convert the %xx notation to the individual character.
4833 if (commptr
[1] >= '0' && commptr
[1] <= '9')
4834 *commptr
= (commptr
[1] - '0') << 4;
4836 *commptr
= (tolower(commptr
[1]) - 'a' + 10) << 4;
4838 if (commptr
[2] >= '0' && commptr
[2] <= '9')
4839 *commptr
|= commptr
[2] - '0';
4841 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
4843 _cups_strcpy(commptr
+ 1, commptr
+ 3);
4846 * Check for a %00 and break if that is the case...
4858 * Setup the environment variables as needed...
4861 if (con
->username
[0])
4863 snprintf(auth_type
, sizeof(auth_type
), "AUTH_TYPE=%s",
4864 httpGetField(HTTP(con
), HTTP_FIELD_AUTHORIZATION
));
4866 if ((uriptr
= strchr(auth_type
+ 10, ' ')) != NULL
)
4870 auth_type
[0] = '\0';
4873 (attr
= ippFindAttribute(con
->request
, "attributes-natural-language",
4874 IPP_TAG_LANGUAGE
)) != NULL
)
4876 switch (strlen(attr
->values
[0].string
.text
))
4880 * This is an unknown or badly formatted language code; use
4881 * the POSIX locale...
4884 strcpy(lang
, "LANG=C");
4889 * Just the language code (ll)...
4892 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8",
4893 attr
->values
[0].string
.text
);
4898 * Language and country code (ll-cc)...
4901 snprintf(lang
, sizeof(lang
), "LANG=%c%c_%c%c.UTF8",
4902 attr
->values
[0].string
.text
[0],
4903 attr
->values
[0].string
.text
[1],
4904 toupper(attr
->values
[0].string
.text
[3] & 255),
4905 toupper(attr
->values
[0].string
.text
[4] & 255));
4909 else if (con
->language
)
4910 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8", con
->language
->language
);
4912 strcpy(lang
, "LANG=C");
4914 strcpy(remote_addr
, "REMOTE_ADDR=");
4915 httpAddrString(con
->http
.hostaddr
, remote_addr
+ 12,
4916 sizeof(remote_addr
) - 12);
4918 snprintf(remote_host
, sizeof(remote_host
), "REMOTE_HOST=%s",
4919 con
->http
.hostname
);
4921 snprintf(script_name
, sizeof(script_name
), "SCRIPT_NAME=%s", con
->uri
);
4922 if ((uriptr
= strchr(script_name
, '?')) != NULL
)
4925 snprintf(script_filename
, sizeof(script_filename
), "SCRIPT_FILENAME=%s%s",
4926 DocumentRoot
, script_name
+ 12);
4928 sprintf(server_port
, "SERVER_PORT=%d", con
->serverport
);
4930 if (con
->http
.fields
[HTTP_FIELD_HOST
][0])
4932 char *nameptr
; /* Pointer to ":port" */
4934 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
4935 con
->http
.fields
[HTTP_FIELD_HOST
]);
4936 if ((nameptr
= strrchr(server_name
, ':')) != NULL
&& !strchr(nameptr
, ']'))
4937 *nameptr
= '\0'; /* Strip trailing ":port" */
4940 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
4943 envc
= cupsdLoadEnv(envp
, (int)(sizeof(envp
) / sizeof(envp
[0])));
4946 envp
[envc
++] = auth_type
;
4948 envp
[envc
++] = lang
;
4949 envp
[envc
++] = "REDIRECT_STATUS=1";
4950 envp
[envc
++] = "GATEWAY_INTERFACE=CGI/1.1";
4951 envp
[envc
++] = server_name
;
4952 envp
[envc
++] = server_port
;
4953 envp
[envc
++] = remote_addr
;
4954 envp
[envc
++] = remote_host
;
4955 envp
[envc
++] = script_name
;
4956 envp
[envc
++] = script_filename
;
4959 envp
[envc
++] = path_info
;
4961 if (con
->username
[0])
4963 snprintf(remote_user
, sizeof(remote_user
), "REMOTE_USER=%s", con
->username
);
4965 envp
[envc
++] = remote_user
;
4968 * Save Kerberos credentials, if any...
4973 ccache
= cupsdCopyKrb5Creds(con
);
4974 #endif /* HAVE_GSSAPI */
4977 if (con
->http
.version
== HTTP_1_1
)
4978 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.1";
4979 else if (con
->http
.version
== HTTP_1_0
)
4980 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.0";
4982 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/0.9";
4984 if (con
->http
.cookie
)
4986 snprintf(http_cookie
, sizeof(http_cookie
), "HTTP_COOKIE=%s",
4988 envp
[envc
++] = http_cookie
;
4991 if (con
->http
.fields
[HTTP_FIELD_USER_AGENT
][0])
4993 snprintf(http_user_agent
, sizeof(http_user_agent
), "HTTP_USER_AGENT=%s",
4994 con
->http
.fields
[HTTP_FIELD_USER_AGENT
]);
4995 envp
[envc
++] = http_user_agent
;
4998 if (con
->http
.fields
[HTTP_FIELD_REFERER
][0])
5000 snprintf(http_referer
, sizeof(http_referer
), "HTTP_REFERER=%s",
5001 con
->http
.fields
[HTTP_FIELD_REFERER
]);
5002 envp
[envc
++] = http_referer
;
5005 if (con
->operation
== HTTP_GET
)
5007 envp
[envc
++] = "REQUEST_METHOD=GET";
5009 if (con
->query_string
)
5012 * Add GET form variables after ?...
5015 envp
[envc
++] = con
->query_string
;
5018 envp
[envc
++] = "QUERY_STRING=";
5022 sprintf(content_length
, "CONTENT_LENGTH=" CUPS_LLFMT
,
5023 CUPS_LLCAST con
->bytes
);
5024 snprintf(content_type
, sizeof(content_type
), "CONTENT_TYPE=%s",
5025 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
5027 envp
[envc
++] = "REQUEST_METHOD=POST";
5028 envp
[envc
++] = content_length
;
5029 envp
[envc
++] = content_type
;
5033 * Tell the CGI if we are using encryption...
5037 envp
[envc
++] = "HTTPS=ON";
5040 * Terminate the environment array...
5045 if (LogLevel
>= CUPSD_LOG_DEBUG
)
5047 for (i
= 0; i
< argc
; i
++)
5048 cupsdLogMessage(CUPSD_LOG_DEBUG
,
5049 "[CGI] argv[%d] = \"%s\"", i
, argv
[i
]);
5050 for (i
= 0; i
< envc
; i
++)
5051 cupsdLogMessage(CUPSD_LOG_DEBUG
,
5052 "[CGI] envp[%d] = \"%s\"", i
, envp
[i
]);
5056 * Create a pipe for the output...
5059 if (cupsdOpenPipe(fds
))
5061 cupsdLogMessage(CUPSD_LOG_ERROR
, "[CGI] Unable to create pipe for %s - %s",
5062 argv
[0], strerror(errno
));
5067 * Then execute the command...
5070 if (cupsdStartProcess(command
, argv
, envp
, infile
, fds
[1], CGIPipes
[1],
5071 -1, -1, root
, DefaultProfile
, NULL
, &pid
) < 0)
5074 * Error - can't fork!
5077 cupsdLogMessage(CUPSD_LOG_ERROR
, "[CGI] Unable to start %s - %s", argv
[0],
5080 cupsdClosePipe(fds
);
5086 * Fork successful - return the PID...
5089 if (con
->username
[0])
5090 cupsdAddCert(pid
, con
->username
, ccache
);
5092 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[CGI] Started %s (PID %d)", command
, pid
);
5103 * 'valid_host()' - Is the Host: field valid?
5106 static int /* O - 1 if valid, 0 if not */
5107 valid_host(cupsd_client_t
*con
) /* I - Client connection */
5109 cupsd_alias_t
*a
; /* Current alias */
5110 cupsd_netif_t
*netif
; /* Current network interface */
5111 const char *host
, /* Host field */
5112 *end
; /* End character */
5115 host
= con
->http
.fields
[HTTP_FIELD_HOST
];
5117 if (httpAddrLocalhost(con
->http
.hostaddr
))
5120 * Only allow "localhost" or the equivalent IPv4 or IPv6 numerical
5121 * addresses when accessing CUPS via the loopback interface...
5124 return (!strcasecmp(host
, "localhost") ||
5125 !strncasecmp(host
, "localhost:", 10) ||
5126 !strcasecmp(host
, "localhost.") ||
5127 !strncasecmp(host
, "localhost.:", 11) ||
5129 !strcasecmp(host
, "localhost.localdomain") ||
5130 !strncasecmp(host
, "localhost.localdomain:", 22) ||
5131 #endif /* __linux */
5132 !strcmp(host
, "127.0.0.1") ||
5133 !strncmp(host
, "127.0.0.1:", 10) ||
5134 !strcmp(host
, "[::1]") ||
5135 !strncmp(host
, "[::1]:", 6));
5140 * Check if the hostname is something.local (Bonjour); if so, allow it.
5143 if ((end
= strrchr(host
, '.')) != NULL
&&
5144 (!strcasecmp(end
, ".local") || !strncasecmp(end
, ".local:", 7) ||
5145 !strcasecmp(end
, ".local.") || !strncasecmp(end
, ".local.:", 8)))
5147 #endif /* HAVE_DNSSD */
5150 * Check if the hostname is an IP address...
5153 if (isdigit(*host
& 255) || *host
== '[')
5156 * Possible IPv4/IPv6 address...
5159 char temp
[1024], /* Temporary string */
5160 *ptr
; /* Pointer into temporary string */
5161 http_addrlist_t
*addrlist
; /* List of addresses */
5164 strlcpy(temp
, host
, sizeof(temp
));
5165 if ((ptr
= strrchr(temp
, ':')) != NULL
&& !strchr(ptr
, ']'))
5166 *ptr
= '\0'; /* Strip :port from host value */
5168 if ((addrlist
= httpAddrGetList(temp
, AF_UNSPEC
, NULL
)) != NULL
)
5171 * Good IPv4/IPv6 address...
5174 httpAddrFreeList(addrlist
);
5180 * Check for (alias) name matches...
5183 for (a
= (cupsd_alias_t
*)cupsArrayFirst(ServerAlias
);
5185 a
= (cupsd_alias_t
*)cupsArrayNext(ServerAlias
))
5188 * "ServerAlias *" allows all host values through...
5191 if (!strcmp(a
->name
, "*"))
5194 if (!strncasecmp(host
, a
->name
, a
->namelen
))
5197 * Prefix matches; check the character at the end - it must be ":", ".",
5201 end
= host
+ a
->namelen
;
5203 if (!*end
|| *end
== ':' || (*end
== '.' && (!end
[1] || end
[1] == ':')))
5209 for (a
= (cupsd_alias_t
*)cupsArrayFirst(DNSSDAlias
);
5211 a
= (cupsd_alias_t
*)cupsArrayNext(DNSSDAlias
))
5214 * "ServerAlias *" allows all host values through...
5217 if (!strcmp(a
->name
, "*"))
5220 if (!strncasecmp(host
, a
->name
, a
->namelen
))
5223 * Prefix matches; check the character at the end - it must be ":", ".",
5227 end
= host
+ a
->namelen
;
5229 if (!*end
|| *end
== ':' || (*end
== '.' && (!end
[1] || end
[1] == ':')))
5233 #endif /* HAVE_DNSSD */
5236 * Check for interface hostname matches...
5239 for (netif
= (cupsd_netif_t
*)cupsArrayFirst(NetIFList
);
5241 netif
= (cupsd_netif_t
*)cupsArrayNext(NetIFList
))
5243 if (!strncasecmp(host
, netif
->hostname
, netif
->hostlen
))
5246 * Prefix matches; check the character at the end - it must be ":", ".",
5250 end
= host
+ netif
->hostlen
;
5252 if (!*end
|| *end
== ':' || (*end
== '.' && (!end
[1] || end
[1] == ':')))
5262 * 'write_file()' - Send a file via HTTP.
5265 static int /* O - 0 on failure, 1 on success */
5266 write_file(cupsd_client_t
*con
, /* I - Client connection */
5267 http_status_t code
, /* I - HTTP status */
5268 char *filename
, /* I - Filename */
5269 char *type
, /* I - File type */
5270 struct stat
*filestats
) /* O - File information */
5272 con
->file
= open(filename
, O_RDONLY
);
5274 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
5275 "write_file(con=%p(%d), code=%d, filename=\"%s\" (%d), "
5276 "type=\"%s\", filestats=%p)", con
, con
->http
.fd
,
5277 code
, filename
, con
->file
, type
? type
: "(null)", filestats
);
5282 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
5286 if (!cupsdSendHeader(con
, code
, type
, CUPSD_AUTH_NONE
))
5289 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
5290 httpGetDateString(filestats
->st_mtime
)) < 0)
5292 if (httpPrintf(HTTP(con
), "Content-Length: " CUPS_LLFMT
"\r\n",
5293 CUPS_LLCAST filestats
->st_size
) < 0)
5295 if (httpPrintf(HTTP(con
), "\r\n") < 0)
5298 if (cupsdFlushHeader(con
) < 0)
5301 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
5302 con
->http
.data_remaining
= filestats
->st_size
;
5304 if (con
->http
.data_remaining
<= INT_MAX
)
5305 con
->http
._data_remaining
= con
->http
.data_remaining
;
5307 con
->http
._data_remaining
= INT_MAX
;
5309 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
,
5310 (cupsd_selfunc_t
)cupsdWriteClient
, con
);
5317 * 'write_pipe()' - Flag that data is available on the CGI pipe.
5321 write_pipe(cupsd_client_t
*con
) /* I - Client connection */
5323 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
5324 "write_pipe(con=%p(%d)) CGI output on fd %d",
5325 con
, con
->http
.fd
, con
->file
);
5327 con
->file_ready
= 1;
5329 cupsdRemoveSelect(con
->file
);
5330 cupsdAddSelect(con
->http
.fd
, NULL
, (cupsd_selfunc_t
)cupsdWriteClient
, con
);
5335 * End of "$Id: client.c 7950 2008-09-17 00:21:59Z mike $".