2 * "$Id: client.c 5898 2006-08-28 18:54:10Z mike $"
4 * Client routines for the Common UNIX Printing System (CUPS) scheduler.
6 * Copyright 1997-2006 by Easy Software Products, all rights reserved.
8 * These coded instructions, statements, and computer programs are the
9 * property of Easy Software Products and are protected by Federal
10 * copyright law. Distribution and use rights are outlined in the file
11 * "LICENSE.txt" which should have been included with this file. If this
12 * file is missing or damaged please contact Easy Software Products
15 * Attn: CUPS Licensing Information
16 * Easy Software Products
17 * 44141 Airport View Drive, Suite 204
18 * Hollywood, Maryland 20636 USA
20 * Voice: (301) 373-9600
21 * EMail: cups-info@cups.org
22 * WWW: http://www.cups.org
26 * cupsdAcceptClient() - Accept a new client.
27 * cupsdCloseAllClients() - Close all remote clients immediately.
28 * cupsdCloseClient() - Close a remote client.
29 * cupsdFlushHeader() - Flush the header fields to the client.
30 * cupsdReadClient() - Read data from a client.
31 * cupsdSendCommand() - Send output from a command via HTTP.
32 * cupsdSendError() - Send an error message via HTTP.
33 * cupsdSendHeader() - Send an HTTP request.
34 * cupsdUpdateCGI() - Read status messages from CGI scripts and programs.
35 * cupsdWriteClient() - Write data to a client as needed.
36 * check_if_modified() - Decode an "If-Modified-Since" line.
37 * encrypt_client() - Enable encryption for the client...
38 * get_cdsa_server_certs() - Convert a keychain name into the CFArrayRef
39 * required by SSLSetCertificate.
40 * get_file() - Get a filename and state info.
41 * install_conf_file() - Install a configuration file.
42 * is_cgi() - Is the resource a CGI script/program?
43 * is_path_absolute() - Is a path absolute and free of relative elements.
44 * make_certificate() - Make a self-signed SSL/TLS certificate.
45 * pipe_command() - Pipe the output of a command to the remote client.
46 * write_file() - Send a file via HTTP.
50 * Include necessary headers...
53 #include <cups/http-private.h>
57 # include <Security/Security.h>
58 # ifdef HAVE_SECBASEPRIV_H
59 # include <Security/SecBasePriv.h>
61 extern const char *cssmErrorString(int error
);
62 # endif /* HAVE_SECBASEPRIV_H */
63 #endif /* HAVE_CDSASSL */
65 # include <gnutls/x509.h>
66 #endif /* HAVE_GNUTLS */
73 static int check_if_modified(cupsd_client_t
*con
,
74 struct stat
*filestats
);
76 static int encrypt_client(cupsd_client_t
*con
);
79 static CFArrayRef
get_cdsa_server_certs(void);
80 #endif /* HAVE_CDSASSL */
81 static char *get_file(cupsd_client_t
*con
, struct stat
*filestats
,
82 char *filename
, int len
);
83 static http_status_t
install_conf_file(cupsd_client_t
*con
);
84 static int is_cgi(cupsd_client_t
*con
, const char *filename
,
85 struct stat
*filestats
, mime_type_t
*type
);
86 static int is_path_absolute(const char *path
);
88 static int make_certificate(void);
90 static int pipe_command(cupsd_client_t
*con
, int infile
, int *outfile
,
91 char *command
, char *options
, int root
);
92 static int write_file(cupsd_client_t
*con
, http_status_t code
,
93 char *filename
, char *type
,
94 struct stat
*filestats
);
98 * 'cupsdAcceptClient()' - Accept a new client.
102 cupsdAcceptClient(cupsd_listener_t
*lis
)/* I - Listener socket */
104 int count
; /* Count of connections on a host */
105 int val
; /* Parameter value */
106 cupsd_client_t
*con
, /* New client pointer */
107 *tempcon
; /* Temporary client pointer */
108 http_addrlist_t
*addrlist
, /* List of adddresses for host */
109 *addr
; /* Current address */
110 socklen_t addrlen
; /* Length of address */
111 char *hostname
; /* Hostname for address */
112 http_addr_t temp
; /* Temporary address variable */
113 static time_t last_dos
= 0; /* Time of last DoS attack */
116 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
117 "cupsdAcceptClient(lis=%p) %d Clients = %d",
118 lis
, lis
->fd
, cupsArrayCount(Clients
));
121 * Make sure we don't have a full set of clients already...
124 if (cupsArrayCount(Clients
) == MaxClients
)
128 * Get a pointer to the next available client...
132 Clients
= cupsArrayNew(NULL
, NULL
);
137 con
= calloc(1, sizeof(cupsd_client_t
));
139 con
->http
.activity
= time(NULL
);
141 con
->http
.hostaddr
= &(con
->clientaddr
);
144 * Accept the client and get the remote address...
147 addrlen
= sizeof(http_addr_t
);
149 if ((con
->http
.fd
= accept(lis
->fd
, (struct sockaddr
*)con
->http
.hostaddr
,
152 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to accept client connection - %s.",
159 if (lis
->address
.addr
.sa_family
== AF_INET6
)
162 * Save the connected port number...
165 con
->http
.hostaddr
->ipv6
.sin6_port
= lis
->address
.ipv6
.sin6_port
;
168 * Convert IPv4 over IPv6 addresses (::ffff:n.n.n.n) to IPv4 forms we
169 * can more easily use...
172 if (con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[0] == 0 &&
173 con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[1] == 0 &&
174 ntohl(con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[2]) == 0xffff)
175 con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[2] = 0;
178 #endif /* AF_INET6 */
179 if (lis
->address
.addr
.sa_family
== AF_INET
)
180 con
->http
.hostaddr
->ipv4
.sin_port
= lis
->address
.ipv4
.sin_port
;
183 * Check the number of clients on the same address...
186 for (count
= 0, tempcon
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
188 tempcon
= (cupsd_client_t
*)cupsArrayNext(Clients
))
189 if (httpAddrEqual(tempcon
->http
.hostaddr
, con
->http
.hostaddr
))
192 if (count
>= MaxClientsPerHost
)
196 if (count
>= MaxClientsPerHost
)
198 if ((time(NULL
) - last_dos
) >= 60)
200 last_dos
= time(NULL
);
201 cupsdLogMessage(CUPSD_LOG_WARN
,
202 "Possible DoS attack - more than %d clients connecting "
204 MaxClientsPerHost
, tempcon
->http
.hostname
);
208 closesocket(con
->http
.fd
);
218 * Get the hostname or format the IP address as needed...
221 if (httpAddrLocalhost(con
->http
.hostaddr
))
224 * Map accesses from the loopback interface to "localhost"...
227 strlcpy(con
->http
.hostname
, "localhost", sizeof(con
->http
.hostname
));
228 hostname
= con
->http
.hostname
;
233 * Map accesses from the same host to the server name.
236 for (addr
= ServerAddrs
; addr
; addr
= addr
->next
)
237 if (httpAddrEqual(con
->http
.hostaddr
, &(addr
->addr
)))
242 strlcpy(con
->http
.hostname
, ServerName
, sizeof(con
->http
.hostname
));
243 hostname
= con
->http
.hostname
;
245 else if (HostNameLookups
)
246 hostname
= httpAddrLookup(con
->http
.hostaddr
, con
->http
.hostname
,
247 sizeof(con
->http
.hostname
));
251 httpAddrString(con
->http
.hostaddr
, con
->http
.hostname
,
252 sizeof(con
->http
.hostname
));
256 if (hostname
== NULL
&& HostNameLookups
== 2)
259 * Can't have an unresolved IP address with double-lookups enabled...
262 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
263 "cupsdAcceptClient: Closing connection %d...",
267 closesocket(con
->http
.fd
);
272 cupsdLogMessage(CUPSD_LOG_WARN
,
273 "Name lookup failed - connection from %s closed!",
280 if (HostNameLookups
== 2)
283 * Do double lookups as needed...
286 if ((addrlist
= httpAddrGetList(con
->http
.hostname
, AF_UNSPEC
, NULL
)) != NULL
)
289 * See if the hostname maps to the same IP address...
292 for (addr
= addrlist
; addr
; addr
= addr
->next
)
293 if (httpAddrEqual(con
->http
.hostaddr
, &(addr
->addr
)))
299 httpAddrFreeList(addrlist
);
304 * Can't have a hostname that doesn't resolve to the same IP address
305 * with double-lookups enabled...
308 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
309 "cupsdAcceptClient: Closing connection %d...",
313 closesocket(con
->http
.fd
);
318 cupsdLogMessage(CUPSD_LOG_WARN
,
319 "IP lookup failed - connection from %s closed!",
327 if (con
->http
.hostaddr
->addr
.sa_family
== AF_INET6
)
328 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdAcceptClient: %d from %s:%d (IPv6)",
329 con
->http
.fd
, con
->http
.hostname
,
330 ntohs(con
->http
.hostaddr
->ipv6
.sin6_port
));
332 #endif /* AF_INET6 */
334 if (con
->http
.hostaddr
->addr
.sa_family
== AF_LOCAL
)
335 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdAcceptClient: %d from %s (Domain)",
336 con
->http
.fd
, con
->http
.hostname
);
338 #endif /* AF_LOCAL */
339 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdAcceptClient: %d from %s:%d (IPv4)",
340 con
->http
.fd
, con
->http
.hostname
,
341 ntohs(con
->http
.hostaddr
->ipv4
.sin_port
));
344 * Get the local address the client connected to...
347 addrlen
= sizeof(temp
);
348 if (getsockname(con
->http
.fd
, (struct sockaddr
*)&temp
, &addrlen
))
350 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to get local address - %s",
353 strcpy(con
->servername
, "localhost");
354 con
->serverport
= LocalPort
;
359 if (temp
.addr
.sa_family
== AF_INET6
)
361 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
362 con
->serverport
= ntohs(lis
->address
.ipv6
.sin6_port
);
365 #endif /* AF_INET6 */
366 if (temp
.addr
.sa_family
== AF_INET
)
368 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
369 con
->serverport
= ntohs(lis
->address
.ipv4
.sin_port
);
373 strcpy(con
->servername
, "localhost");
374 con
->serverport
= LocalPort
;
378 cupsArrayAdd(Clients
, con
);
380 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
381 "cupsdAcceptClient: %d connected to server on %s:%d",
382 con
->http
.fd
, con
->servername
, con
->serverport
);
385 * Using TCP_NODELAY improves responsiveness, especially on systems
386 * with a slow loopback interface... Since we write large buffers
387 * when sending print files and requests, there shouldn't be any
388 * performance penalty for this...
392 setsockopt(con
->http
.fd
, IPPROTO_TCP
, TCP_NODELAY
, &val
, sizeof(val
));
395 * Close this file on all execs...
398 fcntl(con
->http
.fd
, F_SETFD
, fcntl(con
->http
.fd
, F_GETFD
) | FD_CLOEXEC
);
401 * Add the socket to the select() input mask.
404 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
405 "cupsdAcceptClient: Adding fd %d to InputSet...",
407 FD_SET(con
->http
.fd
, InputSet
);
410 * Temporarily suspend accept()'s until we lose a client...
413 if (cupsArrayCount(Clients
) == MaxClients
)
414 cupsdPauseListening();
418 * See if we are connecting on a secure port...
421 if (lis
->encryption
== HTTP_ENCRYPT_ALWAYS
)
424 * https connection; go secure...
427 con
->http
.encryption
= HTTP_ENCRYPT_ALWAYS
;
433 #endif /* HAVE_SSL */
438 * 'cupsdCloseAllClients()' - Close all remote clients immediately.
442 cupsdCloseAllClients(void)
444 cupsd_client_t
*con
; /* Current client */
447 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
449 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
450 cupsdCloseClient(con
);
455 * 'cupsdCloseClient()' - Close a remote client.
458 int /* O - 1 if partial close, 0 if fully closed */
459 cupsdCloseClient(cupsd_client_t
*con
) /* I - Client to close */
461 int partial
; /* Do partial close for SSL? */
463 SSL_CTX
*context
; /* Context for encryption */
464 SSL
*conn
; /* Connection for encryption */
465 unsigned long error
; /* Error code */
466 #elif defined(HAVE_GNUTLS)
467 http_tls_t
*conn
; /* TLS connection information */
468 int error
; /* Error code */
469 gnutls_certificate_server_credentials
*credentials
;
470 /* TLS credentials */
471 # elif defined(HAVE_CDSASSL)
472 http_tls_t
*conn
; /* CDSA connection information */
473 #endif /* HAVE_LIBSSL */
476 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdCloseClient: %d", con
->http
.fd
);
479 * Flush pending writes before closing...
482 httpFlushWrite(HTTP(con
));
488 * Shutdown encryption as needed...
496 conn
= (SSL
*)(con
->http
.tls
);
497 context
= SSL_get_SSL_CTX(conn
);
499 switch (SSL_shutdown(conn
))
502 cupsdLogMessage(CUPSD_LOG_INFO
,
503 "cupsdCloseClient: SSL shutdown successful!");
506 cupsdLogMessage(CUPSD_LOG_ERROR
,
507 "cupsdCloseClient: Fatal error during SSL shutdown!");
509 while ((error
= ERR_get_error()) != 0)
510 cupsdLogMessage(CUPSD_LOG_ERROR
, "cupsdCloseClient: %s",
511 ERR_error_string(error
, NULL
));
515 SSL_CTX_free(context
);
518 # elif defined(HAVE_GNUTLS)
519 conn
= (http_tls_t
*)(con
->http
.tls
);
520 credentials
= (gnutls_certificate_server_credentials
*)(conn
->credentials
);
522 error
= gnutls_bye(conn
->session
, GNUTLS_SHUT_WR
);
525 case GNUTLS_E_SUCCESS
:
526 cupsdLogMessage(CUPSD_LOG_INFO
,
527 "cupsdCloseClient: SSL shutdown successful!");
530 cupsdLogMessage(CUPSD_LOG_ERROR
,
531 "cupsdCloseClient: %s", gnutls_strerror(error
));
535 gnutls_deinit(conn
->session
);
536 gnutls_certificate_free_credentials(*credentials
);
540 # elif defined(HAVE_CDSASSL)
541 conn
= (http_tls_t
*)(con
->http
.tls
);
543 while (SSLClose(conn
->session
) == errSSLWouldBlock
)
546 SSLDisposeContext(conn
->session
);
548 if (conn
->certsArray
)
549 CFRelease(conn
->certsArray
);
552 # endif /* HAVE_LIBSSL */
554 con
->http
.tls
= NULL
;
556 #endif /* HAVE_SSL */
558 if (con
->pipe_pid
!= 0)
561 * Stop any CGI process...
564 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
565 "cupsdCloseClient: %d Killing process ID %d...",
566 con
->http
.fd
, con
->pipe_pid
);
567 cupsdEndProcess(con
->pipe_pid
, 1);
573 if (FD_ISSET(con
->file
, InputSet
))
575 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
576 "cupsdCloseClient: %d Removing fd %d from InputSet...",
577 con
->http
.fd
, con
->file
);
578 FD_CLR(con
->file
, InputSet
);
581 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
582 "cupsdCloseClient: %d Closing data file %d.",
583 con
->http
.fd
, con
->file
);
590 * Close the socket and clear the file from the input set for select()...
593 if (con
->http
.fd
> 0)
598 * Only do a partial close so that the encrypted client gets everything.
601 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
602 "cupsdCloseClient: Removing fd %d from OutputSet...",
604 shutdown(con
->http
.fd
, 0);
605 FD_CLR(con
->http
.fd
, OutputSet
);
610 * Shut the socket down fully...
613 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
614 "cupsdCloseClient: Removing fd %d from InputSet and OutputSet...",
617 FD_CLR(con
->http
.fd
, InputSet
);
618 FD_CLR(con
->http
.fd
, OutputSet
);
629 if (con
->http
.input_set
)
630 free(con
->http
.input_set
);
632 httpClearCookie(HTTP(con
));
634 cupsdClearString(&con
->filename
);
635 cupsdClearString(&con
->command
);
636 cupsdClearString(&con
->options
);
640 ippDelete(con
->request
);
646 ippDelete(con
->response
);
647 con
->response
= NULL
;
652 cupsLangFree(con
->language
);
653 con
->language
= NULL
;
657 * Re-enable new client connections if we are going back under the
661 if (cupsArrayCount(Clients
) == MaxClients
)
662 cupsdResumeListening();
665 * Compact the list of clients as necessary...
668 cupsArrayRemove(Clients
, con
);
678 * 'cupsdFlushHeader()' - Flush the header fields to the client.
682 cupsdFlushHeader(cupsd_client_t
*con
) /* I - Client to flush to */
684 httpFlushWrite(HTTP(con
));
686 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
691 * 'cupsdReadClient()' - Read data from a client.
694 int /* O - 1 on success, 0 on error */
695 cupsdReadClient(cupsd_client_t
*con
) /* I - Client to read from */
697 char line
[32768], /* Line from client... */
698 operation
[64], /* Operation code from socket */
699 version
[64], /* HTTP version number string */
700 locale
[64], /* Locale */
701 *ptr
; /* Pointer into strings */
702 int major
, minor
; /* HTTP version numbers */
703 http_status_t status
; /* Transfer status */
704 ipp_state_t ipp_state
; /* State of IPP transfer */
705 int bytes
; /* Number of bytes to POST */
706 char *filename
; /* Name of file for GET/HEAD */
707 char buf
[1024]; /* Buffer for real filename */
708 struct stat filestats
; /* File information */
709 mime_type_t
*type
; /* MIME type of file */
710 cupsd_printer_t
*p
; /* Printer */
711 static unsigned request_id
= 0; /* Request ID for temp files */
714 status
= HTTP_CONTINUE
;
716 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
717 "cupsdReadClient: %d, used=%d, file=%d state=%d",
718 con
->http
.fd
, con
->http
.used
, con
->file
, con
->http
.state
);
722 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdReadClient: http error seen...");
723 return (cupsdCloseClient(con
));
730 * Automatically check for a SSL/TLS handshake...
735 if (recv(con
->http
.fd
, buf
, 1, MSG_PEEK
) == 1 &&
736 (!buf
[0] || !strchr("DGHOPT", buf
[0])))
739 * Encrypt this connection...
742 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
743 "cupsdReadClient: Saw first byte %02X, auto-negotiating SSL/TLS session...",
750 #endif /* HAVE_SSL */
752 switch (con
->http
.state
)
756 * See if we've received a request line...
759 if (httpGets(line
, sizeof(line
) - 1, HTTP(con
)) == NULL
)
761 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
762 "cupsdReadClient: httpGets returned EOF...");
763 return (cupsdCloseClient(con
));
767 * Ignore blank request lines...
774 * Clear other state variables...
777 httpClearFields(HTTP(con
));
779 con
->http
.activity
= time(NULL
);
780 con
->http
.version
= HTTP_1_0
;
781 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
782 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
783 con
->http
.data_remaining
= 0;
784 con
->http
._data_remaining
= 0;
785 con
->operation
= HTTP_WAITING
;
790 con
->username
[0] = '\0';
791 con
->password
[0] = '\0';
794 cupsdClearString(&con
->command
);
795 cupsdClearString(&con
->options
);
797 if (con
->language
!= NULL
)
799 cupsLangFree(con
->language
);
800 con
->language
= NULL
;
804 * Grab the request line...
807 switch (sscanf(line
, "%63s%1023s%63s", operation
, con
->uri
, version
))
810 cupsdLogMessage(CUPSD_LOG_ERROR
,
811 "Bad request line \"%s\" from %s!", line
,
813 cupsdSendError(con
, HTTP_BAD_REQUEST
);
814 return (cupsdCloseClient(con
));
816 con
->http
.version
= HTTP_0_9
;
819 if (sscanf(version
, "HTTP/%d.%d", &major
, &minor
) != 2)
821 cupsdLogMessage(CUPSD_LOG_ERROR
,
822 "Bad request line \"%s\" from %s!", line
,
824 cupsdSendError(con
, HTTP_BAD_REQUEST
);
825 return (cupsdCloseClient(con
));
830 con
->http
.version
= (http_version_t
)(major
* 100 + minor
);
831 if (con
->http
.version
== HTTP_1_1
&& KeepAlive
)
832 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
834 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
838 cupsdSendError(con
, HTTP_NOT_SUPPORTED
);
839 return (cupsdCloseClient(con
));
845 * Handle full URLs in the request line...
848 if (strcmp(con
->uri
, "*"))
850 char method
[HTTP_MAX_URI
], /* Method/scheme */
851 userpass
[HTTP_MAX_URI
], /* Username:password */
852 hostname
[HTTP_MAX_URI
], /* Hostname */
853 resource
[HTTP_MAX_URI
]; /* Resource path */
854 int port
; /* Port number */
858 * Separate the URI into its components...
861 httpSeparateURI(HTTP_URI_CODING_MOST
, con
->uri
,
862 method
, sizeof(method
),
863 userpass
, sizeof(userpass
),
864 hostname
, sizeof(hostname
), &port
,
865 resource
, sizeof(resource
));
868 * Only allow URIs with the servername, localhost, or an IP
872 if (strcmp(method
, "file") &&
873 strcasecmp(hostname
, ServerName
) &&
874 strcasecmp(hostname
, "localhost") &&
875 !isdigit(hostname
[0]))
878 * Nope, we don't do proxies...
881 cupsdLogMessage(CUPSD_LOG_ERROR
, "Bad URI \"%s\" in request!",
883 cupsdSendError(con
, HTTP_METHOD_NOT_ALLOWED
);
884 return (cupsdCloseClient(con
));
888 * Copy the resource portion back into the URI; both resource and
889 * con->uri are HTTP_MAX_URI bytes in size...
892 strcpy(con
->uri
, resource
);
896 * Process the request...
899 if (!strcmp(operation
, "GET"))
900 con
->http
.state
= HTTP_GET
;
901 else if (!strcmp(operation
, "PUT"))
902 con
->http
.state
= HTTP_PUT
;
903 else if (!strcmp(operation
, "POST"))
904 con
->http
.state
= HTTP_POST
;
905 else if (!strcmp(operation
, "DELETE"))
906 con
->http
.state
= HTTP_DELETE
;
907 else if (!strcmp(operation
, "TRACE"))
908 con
->http
.state
= HTTP_TRACE
;
909 else if (!strcmp(operation
, "OPTIONS"))
910 con
->http
.state
= HTTP_OPTIONS
;
911 else if (!strcmp(operation
, "HEAD"))
912 con
->http
.state
= HTTP_HEAD
;
915 cupsdLogMessage(CUPSD_LOG_ERROR
, "Bad operation \"%s\"!", operation
);
916 cupsdSendError(con
, HTTP_BAD_REQUEST
);
917 return (cupsdCloseClient(con
));
920 con
->start
= time(NULL
);
921 con
->operation
= con
->http
.state
;
923 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdReadClient: %d %s %s HTTP/%d.%d",
924 con
->http
.fd
, operation
, con
->uri
,
925 con
->http
.version
/ 100, con
->http
.version
% 100);
927 con
->http
.status
= HTTP_OK
;
937 * Parse incoming parameters until the status changes...
940 status
= httpUpdate(HTTP(con
));
942 if (status
!= HTTP_OK
&& status
!= HTTP_CONTINUE
)
944 cupsdSendError(con
, HTTP_BAD_REQUEST
);
945 return (cupsdCloseClient(con
));
950 break; /* Anti-compiler-warning-code */
954 * Handle new transfers...
957 if (status
== HTTP_OK
)
959 if (con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
][0])
962 * Figure out the locale from the Accept-Language and Content-Type
966 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ',')) != NULL
)
969 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ';')) != NULL
)
972 if ((ptr
= strstr(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
], "charset=")) != NULL
)
975 * Combine language and charset, and trim any extra params in the
979 snprintf(locale
, sizeof(locale
), "%s.%s",
980 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ptr
+ 8);
982 if ((ptr
= strchr(locale
, ',')) != NULL
)
986 snprintf(locale
, sizeof(locale
), "%s.%s",
987 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], DefaultCharset
);
989 cupsdLogMessage(CUPSD_LOG_DEBUG
,
990 "cupsdReadClient: %d Browser asked for language \"%s\"...",
991 con
->http
.fd
, locale
);
993 con
->language
= cupsLangGet(locale
);
996 con
->language
= cupsLangGet(DefaultLocale
);
1000 if (!strncmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Keep-Alive", 10) &&
1002 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
1004 if (!con
->http
.fields
[HTTP_FIELD_HOST
][0] &&
1005 con
->http
.version
>= HTTP_1_1
)
1008 * HTTP/1.1 and higher require the "Host:" field...
1011 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
))
1012 return (cupsdCloseClient(con
));
1014 else if (con
->operation
== HTTP_OPTIONS
)
1017 * Do OPTIONS command...
1020 if (con
->best
&& con
->best
->type
!= AUTH_NONE
)
1022 if (!cupsdSendHeader(con
, HTTP_UNAUTHORIZED
, NULL
))
1023 return (cupsdCloseClient(con
));
1026 if (!strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") &&
1027 con
->http
.tls
== NULL
)
1031 * Do encryption stuff...
1034 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
))
1035 return (cupsdCloseClient(con
));
1037 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1038 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1039 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1040 httpPrintf(HTTP(con
), "\r\n");
1041 cupsdFlushHeader(con
);
1043 encrypt_client(con
);
1045 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
))
1046 return (cupsdCloseClient(con
));
1047 #endif /* HAVE_SSL */
1050 if (!cupsdSendHeader(con
, HTTP_OK
, NULL
))
1051 return (cupsdCloseClient(con
));
1053 httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n");
1054 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1055 httpPrintf(HTTP(con
), "\r\n");
1056 cupsdFlushHeader(con
);
1058 else if (!is_path_absolute(con
->uri
))
1061 * Protect against malicious users!
1064 if (!cupsdSendError(con
, HTTP_FORBIDDEN
))
1065 return (cupsdCloseClient(con
));
1069 if (!strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") &&
1070 con
->http
.tls
== NULL
)
1074 * Do encryption stuff...
1077 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
))
1078 return (cupsdCloseClient(con
));
1080 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1081 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1082 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1083 httpPrintf(HTTP(con
), "\r\n");
1084 cupsdFlushHeader(con
);
1086 encrypt_client(con
);
1088 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
))
1089 return (cupsdCloseClient(con
));
1090 #endif /* HAVE_SSL */
1093 if ((status
= cupsdIsAuthorized(con
, NULL
)) != HTTP_OK
)
1095 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1096 "cupsdReadClient: Unauthorized request for %s...\n",
1098 cupsdSendError(con
, status
);
1099 return (cupsdCloseClient(con
));
1102 if (con
->http
.expect
&&
1103 (con
->operation
== HTTP_POST
|| con
->operation
== HTTP_PUT
))
1105 if (con
->http
.expect
== HTTP_CONTINUE
)
1108 * Send 100-continue header...
1111 if (!cupsdSendHeader(con
, HTTP_CONTINUE
, NULL
))
1112 return (cupsdCloseClient(con
));
1117 * Send 417-expectation-failed header...
1120 if (!cupsdSendHeader(con
, HTTP_EXPECTATION_FAILED
, NULL
))
1121 return (cupsdCloseClient(con
));
1123 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1124 httpPrintf(HTTP(con
), "\r\n");
1125 cupsdFlushHeader(con
);
1129 switch (con
->http
.state
)
1131 case HTTP_GET_SEND
:
1132 if (!strncmp(con
->uri
, "/printers/", 10) &&
1133 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1136 * Send PPD file - get the real printer name since printer
1137 * names are not case sensitive but filenames can be...
1140 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1142 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1143 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1146 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
1147 return (cupsdCloseClient(con
));
1153 if ((!strncmp(con
->uri
, "/admin", 6) &&
1154 strncmp(con
->uri
, "/admin/conf/", 12) &&
1155 strncmp(con
->uri
, "/admin/log/", 11)) ||
1156 !strncmp(con
->uri
, "/printers", 9) ||
1157 !strncmp(con
->uri
, "/classes", 8) ||
1158 !strncmp(con
->uri
, "/help", 5) ||
1159 !strncmp(con
->uri
, "/jobs", 5))
1162 * Send CGI output...
1165 if (!strncmp(con
->uri
, "/admin", 6))
1167 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1170 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1172 else if (!strncmp(con
->uri
, "/printers", 9))
1174 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1177 if (con
->uri
[9] && con
->uri
[10])
1178 cupsdSetString(&con
->options
, con
->uri
+ 9);
1180 cupsdSetString(&con
->options
, NULL
);
1182 else if (!strncmp(con
->uri
, "/classes", 8))
1184 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1187 if (con
->uri
[8] && con
->uri
[9])
1188 cupsdSetString(&con
->options
, con
->uri
+ 8);
1190 cupsdSetString(&con
->options
, NULL
);
1192 else if (!strncmp(con
->uri
, "/jobs", 5))
1194 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1197 if (con
->uri
[5] && con
->uri
[6])
1198 cupsdSetString(&con
->options
, con
->uri
+ 5);
1200 cupsdSetString(&con
->options
, NULL
);
1204 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1207 if (con
->uri
[5] && con
->uri
[6])
1208 cupsdSetString(&con
->options
, con
->uri
+ 5);
1210 cupsdSetString(&con
->options
, NULL
);
1213 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1215 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
1216 return (cupsdCloseClient(con
));
1219 cupsdLogRequest(con
, HTTP_OK
);
1221 if (con
->http
.version
<= HTTP_1_0
)
1222 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1224 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1225 (strchr(con
->uri
+ 12, '/') ||
1226 strlen(con
->uri
) == 12)) ||
1227 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1228 (strchr(con
->uri
+ 11, '/') ||
1229 strlen(con
->uri
) == 11)))
1232 * GET can only be done to configuration files under
1236 if (!cupsdSendError(con
, HTTP_FORBIDDEN
))
1237 return (cupsdCloseClient(con
));
1247 if ((filename
= get_file(con
, &filestats
, buf
,
1248 sizeof(buf
))) == NULL
)
1250 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
1251 return (cupsdCloseClient(con
));
1256 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1258 if (is_cgi(con
, filename
, &filestats
, type
))
1261 * Note: con->command and con->options were set by
1265 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1267 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
1268 return (cupsdCloseClient(con
));
1271 cupsdLogRequest(con
, HTTP_OK
);
1273 if (con
->http
.version
<= HTTP_1_0
)
1274 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1278 if (!check_if_modified(con
, &filestats
))
1280 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
))
1281 return (cupsdCloseClient(con
));
1286 strcpy(line
, "text/plain");
1288 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1290 if (!write_file(con
, HTTP_OK
, filename
, line
, &filestats
))
1291 return (cupsdCloseClient(con
));
1296 case HTTP_POST_RECV
:
1298 * See if the POST request includes a Content-Length field, and if
1299 * so check the length against any limits that are set...
1302 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "POST %s", con
->uri
);
1303 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "CONTENT_TYPE = %s",
1304 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
1306 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1307 MaxRequestSize
> 0 &&
1308 con
->http
.data_remaining
> MaxRequestSize
)
1311 * Request too large...
1314 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1315 return (cupsdCloseClient(con
));
1319 else if (con
->http
.data_remaining
< 0)
1322 * Negative content lengths are invalid!
1325 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
))
1326 return (cupsdCloseClient(con
));
1332 * See what kind of POST request this is; for IPP requests the
1333 * content-type field will be "application/ipp"...
1336 if (!strcmp(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
],
1338 con
->request
= ippNew();
1339 else if ((!strncmp(con
->uri
, "/admin", 6) &&
1340 strncmp(con
->uri
, "/admin/conf/", 12) &&
1341 strncmp(con
->uri
, "/admin/log/", 11)) ||
1342 !strncmp(con
->uri
, "/printers", 9) ||
1343 !strncmp(con
->uri
, "/classes", 8) ||
1344 !strncmp(con
->uri
, "/help", 5) ||
1345 !strncmp(con
->uri
, "/jobs", 5))
1351 if (!strncmp(con
->uri
, "/admin", 6))
1353 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1356 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1358 else if (!strncmp(con
->uri
, "/printers", 9))
1360 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1363 if (con
->uri
[9] && con
->uri
[10])
1364 cupsdSetString(&con
->options
, con
->uri
+ 9);
1366 cupsdSetString(&con
->options
, NULL
);
1368 else if (!strncmp(con
->uri
, "/classes", 8))
1370 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1373 if (con
->uri
[8] && con
->uri
[9])
1374 cupsdSetString(&con
->options
, con
->uri
+ 8);
1376 cupsdSetString(&con
->options
, NULL
);
1378 else if (!strncmp(con
->uri
, "/jobs", 5))
1380 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1383 if (con
->uri
[5] && con
->uri
[6])
1384 cupsdSetString(&con
->options
, con
->uri
+ 5);
1386 cupsdSetString(&con
->options
, NULL
);
1390 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1393 if (con
->uri
[5] && con
->uri
[6])
1394 cupsdSetString(&con
->options
, con
->uri
+ 5);
1396 cupsdSetString(&con
->options
, NULL
);
1399 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1400 "cupsdReadClient: %d command=\"%s\", "
1402 con
->http
.fd
, con
->command
,
1403 con
->options
? con
->options
: "(null)");
1405 if (con
->http
.version
<= HTTP_1_0
)
1406 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1414 if ((filename
= get_file(con
, &filestats
, buf
,
1415 sizeof(buf
))) == NULL
)
1417 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
1418 return (cupsdCloseClient(con
));
1423 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1425 if (!is_cgi(con
, filename
, &filestats
, type
))
1428 * Only POST to CGI's...
1431 if (!cupsdSendError(con
, HTTP_UNAUTHORIZED
))
1432 return (cupsdCloseClient(con
));
1437 case HTTP_PUT_RECV
:
1439 * Validate the resource name...
1442 if (strncmp(con
->uri
, "/admin/conf/", 12) ||
1443 strchr(con
->uri
+ 12, '/') ||
1444 strlen(con
->uri
) == 12)
1447 * PUT can only be done to configuration files under
1451 if (!cupsdSendError(con
, HTTP_FORBIDDEN
))
1452 return (cupsdCloseClient(con
));
1458 * See if the PUT request includes a Content-Length field, and if
1459 * so check the length against any limits that are set...
1462 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "PUT %s", con
->uri
);
1463 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "CONTENT_TYPE = %s",
1464 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
1466 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1467 MaxRequestSize
> 0 &&
1468 con
->http
.data_remaining
> MaxRequestSize
)
1471 * Request too large...
1474 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1475 return (cupsdCloseClient(con
));
1479 else if (con
->http
.data_remaining
< 0)
1482 * Negative content lengths are invalid!
1485 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
))
1486 return (cupsdCloseClient(con
));
1492 * Open a temporary file to hold the request...
1495 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
1497 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1499 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1500 "cupsdReadClient: %d REQUEST %s=%d", con
->http
.fd
,
1501 con
->filename
, con
->file
);
1505 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1506 return (cupsdCloseClient(con
));
1509 fchmod(con
->file
, 0640);
1510 fchown(con
->file
, RunUser
, Group
);
1511 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1516 cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
);
1517 return (cupsdCloseClient(con
));
1520 if (!strncmp(con
->uri
, "/printers/", 10) &&
1521 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1524 * Send PPD file - get the real printer name since printer
1525 * names are not case sensitive but filenames can be...
1528 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1530 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1531 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1534 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
1535 return (cupsdCloseClient(con
));
1541 if ((!strncmp(con
->uri
, "/admin", 6) &&
1542 strncmp(con
->uri
, "/admin/conf/", 12) &&
1543 strncmp(con
->uri
, "/admin/log/", 11)) ||
1544 !strncmp(con
->uri
, "/printers", 9) ||
1545 !strncmp(con
->uri
, "/classes", 8) ||
1546 !strncmp(con
->uri
, "/help", 5) ||
1547 !strncmp(con
->uri
, "/jobs", 5))
1553 if (!cupsdSendHeader(con
, HTTP_OK
, "text/html"))
1554 return (cupsdCloseClient(con
));
1556 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1557 return (cupsdCloseClient(con
));
1559 cupsdFlushHeader(con
);
1561 cupsdLogRequest(con
, HTTP_OK
);
1563 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1564 (strchr(con
->uri
+ 12, '/') ||
1565 strlen(con
->uri
) == 12)) ||
1566 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1567 (strchr(con
->uri
+ 11, '/') ||
1568 strlen(con
->uri
) == 11)))
1571 * HEAD can only be done to configuration files under
1575 if (!cupsdSendError(con
, HTTP_FORBIDDEN
))
1576 return (cupsdCloseClient(con
));
1580 else if ((filename
= get_file(con
, &filestats
, buf
,
1581 sizeof(buf
))) == NULL
)
1583 if (!cupsdSendHeader(con
, HTTP_NOT_FOUND
, "text/html"))
1584 return (cupsdCloseClient(con
));
1586 cupsdLogRequest(con
, HTTP_NOT_FOUND
);
1588 else if (!check_if_modified(con
, &filestats
))
1590 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
))
1591 return (cupsdCloseClient(con
));
1593 cupsdLogRequest(con
, HTTP_NOT_MODIFIED
);
1601 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1603 strcpy(line
, "text/plain");
1605 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1607 if (!cupsdSendHeader(con
, HTTP_OK
, line
))
1608 return (cupsdCloseClient(con
));
1610 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
1611 httpGetDateString(filestats
.st_mtime
)) < 0)
1612 return (cupsdCloseClient(con
));
1614 if (httpPrintf(HTTP(con
), "Content-Length: %lu\r\n",
1615 (unsigned long)filestats
.st_size
) < 0)
1616 return (cupsdCloseClient(con
));
1618 cupsdLogRequest(con
, HTTP_OK
);
1621 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1622 return (cupsdCloseClient(con
));
1624 cupsdFlushHeader(con
);
1626 con
->http
.state
= HTTP_WAITING
;
1630 break; /* Anti-compiler-warning-code */
1636 * Handle any incoming data...
1639 switch (con
->http
.state
)
1641 case HTTP_PUT_RECV
:
1642 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1643 "cupsdReadClient: %d con->data_encoding=HTTP_ENCODE_%s, "
1644 "con->data_remaining=" CUPS_LLFMT
", con->file=%d",
1646 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
?
1647 "CHUNKED" : "LENGTH",
1648 CUPS_LLCAST con
->http
.data_remaining
, con
->file
);
1650 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
1651 return (cupsdCloseClient(con
));
1654 con
->bytes
+= bytes
;
1656 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1657 "cupsdReadClient: %d writing %d bytes to %d",
1658 con
->http
.fd
, bytes
, con
->file
);
1660 if (write(con
->file
, line
, bytes
) < bytes
)
1662 cupsdLogMessage(CUPSD_LOG_ERROR
,
1663 "cupsdReadClient: Unable to write %d bytes to %s: %s",
1664 bytes
, con
->filename
, strerror(errno
));
1666 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1667 "cupsdReadClient: Closing data file %d...",
1672 unlink(con
->filename
);
1673 cupsdClearString(&con
->filename
);
1675 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1676 return (cupsdCloseClient(con
));
1680 if (con
->http
.state
== HTTP_WAITING
)
1683 * End of file, see how big it is...
1686 fstat(con
->file
, &filestats
);
1688 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1689 "cupsdReadClient: %d Closing data file %d, size="
1691 con
->http
.fd
, con
->file
,
1692 CUPS_LLCAST filestats
.st_size
);
1697 if (filestats
.st_size
> MaxRequestSize
&&
1701 * Request is too big; remove it and send an error...
1704 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1705 "cupsdReadClient: %d Removing temp file %s",
1706 con
->http
.fd
, con
->filename
);
1707 unlink(con
->filename
);
1708 cupsdClearString(&con
->filename
);
1710 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1711 return (cupsdCloseClient(con
));
1715 * Install the configuration file...
1718 status
= install_conf_file(con
);
1721 * Return the status to the client...
1724 if (!cupsdSendError(con
, status
))
1725 return (cupsdCloseClient(con
));
1729 case HTTP_POST_RECV
:
1730 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1731 "cupsdReadClient: %d con->data_encoding=HTTP_ENCODE_"
1732 "%s, con->data_remaining=" CUPS_LLFMT
", con->file=%d",
1734 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
?
1735 "CHUNKED" : "LENGTH",
1736 CUPS_LLCAST con
->http
.data_remaining
, con
->file
);
1738 if (con
->request
!= NULL
)
1741 * Grab any request data from the connection...
1744 if ((ipp_state
= ippRead(&(con
->http
), con
->request
)) == IPP_ERROR
)
1746 cupsdLogMessage(CUPSD_LOG_ERROR
,
1747 "cupsdReadClient: %d IPP Read Error!",
1750 cupsdSendError(con
, HTTP_BAD_REQUEST
);
1751 return (cupsdCloseClient(con
));
1753 else if (ipp_state
!= IPP_DATA
)
1755 if (con
->http
.state
== HTTP_POST_SEND
)
1757 cupsdSendError(con
, HTTP_BAD_REQUEST
);
1758 return (cupsdCloseClient(con
));
1764 con
->bytes
+= ippLength(con
->request
);
1767 if (con
->file
< 0 && con
->http
.state
!= HTTP_POST_SEND
)
1770 * Create a file as needed for the request data...
1773 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
, request_id
++);
1774 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1776 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdReadClient: %d REQUEST %s=%d", con
->http
.fd
,
1777 con
->filename
, con
->file
);
1781 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1782 return (cupsdCloseClient(con
));
1785 fchmod(con
->file
, 0640);
1786 fchown(con
->file
, RunUser
, Group
);
1787 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1790 if (con
->http
.state
!= HTTP_POST_SEND
)
1792 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
1793 return (cupsdCloseClient(con
));
1796 con
->bytes
+= bytes
;
1798 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1799 "cupsdReadClient: %d writing %d bytes to %d",
1800 con
->http
.fd
, bytes
, con
->file
);
1802 if (write(con
->file
, line
, bytes
) < bytes
)
1804 cupsdLogMessage(CUPSD_LOG_ERROR
,
1805 "cupsdReadClient: Unable to write %d bytes to %s: %s",
1806 bytes
, con
->filename
, strerror(errno
));
1808 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1809 "cupsdReadClient: Closing file %d...",
1814 unlink(con
->filename
);
1815 cupsdClearString(&con
->filename
);
1817 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1818 return (cupsdCloseClient(con
));
1821 else if (con
->http
.state
== HTTP_POST_RECV
)
1822 return (1); /* ??? */
1823 else if (con
->http
.state
!= HTTP_POST_SEND
)
1824 return (cupsdCloseClient(con
));
1827 if (con
->http
.state
== HTTP_POST_SEND
)
1831 fstat(con
->file
, &filestats
);
1833 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1834 "cupsdReadClient: %d Closing data file %d, "
1835 "size=" CUPS_LLFMT
".",
1836 con
->http
.fd
, con
->file
,
1837 CUPS_LLCAST filestats
.st_size
);
1842 if (filestats
.st_size
> MaxRequestSize
&&
1846 * Request is too big; remove it and send an error...
1849 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1850 "cupsdReadClient: %d Removing temp file %s",
1851 con
->http
.fd
, con
->filename
);
1852 unlink(con
->filename
);
1853 cupsdClearString(&con
->filename
);
1858 * Delete any IPP request data...
1861 ippDelete(con
->request
);
1862 con
->request
= NULL
;
1865 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1866 return (cupsdCloseClient(con
));
1871 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1873 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
1874 return (cupsdCloseClient(con
));
1877 cupsdLogRequest(con
, HTTP_OK
);
1882 return (cupsdProcessIPPRequest(con
));
1887 break; /* Anti-compiler-warning-code */
1890 if (!con
->http
.keep_alive
&& con
->http
.state
== HTTP_WAITING
)
1891 return (cupsdCloseClient(con
));
1898 * 'cupsdSendCommand()' - Send output from a command via HTTP.
1901 int /* O - 1 on success, 0 on failure */
1903 cupsd_client_t
*con
, /* I - Client connection */
1904 char *command
, /* I - Command to run */
1905 char *options
, /* I - Command-line options */
1906 int root
) /* I - Run as root? */
1908 int fd
; /* Standard input file descriptor */
1913 fd
= open(con
->filename
, O_RDONLY
);
1917 cupsdLogMessage(CUPSD_LOG_ERROR
,
1918 "cupsdSendCommand: %d Unable to open \"%s\" for reading: %s",
1919 con
->http
.fd
, con
->filename
? con
->filename
: "/dev/null",
1924 fcntl(fd
, F_SETFD
, fcntl(fd
, F_GETFD
) | FD_CLOEXEC
);
1929 con
->pipe_pid
= pipe_command(con
, fd
, &(con
->file
), command
, options
, root
);
1934 cupsdLogMessage(CUPSD_LOG_INFO
, "Started \"%s\" (pid=%d)", command
,
1937 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendCommand: %d file=%d",
1938 con
->http
.fd
, con
->file
);
1940 if (con
->pipe_pid
== 0)
1943 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1945 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1946 "cupsdSendCommand: Adding fd %d to InputSet...", con
->file
);
1947 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1948 "cupsdSendCommand: Adding fd %d to OutputSet...",
1951 FD_SET(con
->file
, InputSet
);
1952 FD_SET(con
->http
.fd
, OutputSet
);
1954 con
->sent_header
= 0;
1955 con
->file_ready
= 0;
1956 con
->got_fields
= 0;
1964 * 'cupsdSendError()' - Send an error message via HTTP.
1967 int /* O - 1 if successful, 0 otherwise */
1968 cupsdSendError(cupsd_client_t
*con
, /* I - Connection */
1969 http_status_t code
) /* I - Error code */
1973 * Force client to upgrade for authentication if that is how the
1974 * server is configured...
1977 if (code
== HTTP_UNAUTHORIZED
&&
1978 DefaultEncryption
== HTTP_ENCRYPT_REQUIRED
&&
1979 strcasecmp(con
->http
.hostname
, "localhost") &&
1982 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1983 "cupsdSendError: Encryption before authentication!");
1984 code
= HTTP_UPGRADE_REQUIRED
;
1986 #endif /* HAVE_SSL */
1989 * Put the request in the access_log file...
1992 cupsdLogRequest(con
, code
);
1994 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendError: %d code=%d (%s)",
1995 con
->http
.fd
, code
, httpStatus(code
));
1998 * To work around bugs in some proxies, don't use Keep-Alive for some
2002 if (code
>= HTTP_BAD_REQUEST
)
2003 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
2006 * Send an error message back to the client. If the error code is a
2007 * 400 or 500 series, make sure the message contains some text, too!
2010 if (!cupsdSendHeader(con
, code
, NULL
))
2014 if (code
== HTTP_UPGRADE_REQUIRED
)
2015 if (httpPrintf(HTTP(con
), "Connection: Upgrade\r\n") < 0)
2018 if (httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n") < 0)
2020 #endif /* HAVE_SSL */
2022 if ((con
->http
.version
>= HTTP_1_1
&& !con
->http
.keep_alive
) ||
2023 (code
>= HTTP_BAD_REQUEST
&& code
!= HTTP_UPGRADE_REQUIRED
))
2025 if (httpPrintf(HTTP(con
), "Connection: close\r\n") < 0)
2029 if (code
>= HTTP_BAD_REQUEST
)
2032 * Send a human-readable error message.
2035 char message
[4096], /* Message for user */
2036 urltext
[1024], /* URL redirection text */
2037 redirect
[1024]; /* Redirection link */
2038 const char *text
; /* Status-specific text */
2043 if (code
== HTTP_UNAUTHORIZED
)
2044 text
= _cupsLangString(con
->language
,
2045 _("Enter your username and password or the "
2046 "root username and password to access this "
2048 else if (code
== HTTP_UPGRADE_REQUIRED
)
2052 snprintf(urltext
, sizeof(urltext
),
2053 _cupsLangString(con
->language
,
2054 _("You must access this page using the URL "
2055 "<A HREF=\"https://%s:%d%s\">"
2056 "https://%s:%d%s</A>.")),
2057 con
->servername
, con
->serverport
, con
->uri
,
2058 con
->servername
, con
->serverport
, con
->uri
);
2060 snprintf(redirect
, sizeof(redirect
),
2061 "<META HTTP-EQUIV=\"Refresh\" CONTENT=\"3;https://%s:%d%s\">\n",
2062 con
->servername
, con
->serverport
, con
->uri
);
2067 snprintf(message
, sizeof(message
),
2068 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" "
2069 "\"http://www.w3.org/TR/REC-html40/loose.dtd\">\n"
2072 "\t<META HTTP-EQUIV=\"Content-Type\" "
2073 "CONTENT=\"text/html; charset=utf-8\">\n"
2074 "\t<TITLE>%d %s</TITLE>\n"
2075 "\t<LINK REL=\"STYLESHEET\" TYPE=\"text/css\" "
2076 "HREF=\"/cups.css\">\n"
2084 code
, httpStatus(code
), redirect
, code
, httpStatus(code
), text
);
2086 if (httpPrintf(HTTP(con
), "Content-Type: text/html; charset=utf-8\r\n") < 0)
2088 if (httpPrintf(HTTP(con
), "Content-Length: %d\r\n",
2089 (int)strlen(message
)) < 0)
2091 if (httpPrintf(HTTP(con
), "\r\n") < 0)
2093 if (httpPrintf(HTTP(con
), "%s", message
) < 0)
2096 else if (httpPrintf(HTTP(con
), "\r\n") < 0)
2099 cupsdFlushHeader(con
);
2101 con
->http
.state
= HTTP_WAITING
;
2108 * 'cupsdSendHeader()' - Send an HTTP request.
2111 int /* O - 1 on success, 0 on failure */
2112 cupsdSendHeader(cupsd_client_t
*con
, /* I - Client to send to */
2113 http_status_t code
, /* I - HTTP status code */
2114 char *type
) /* I - MIME type of document */
2117 * Send the HTTP status header...
2120 httpFlushWrite(HTTP(con
));
2122 con
->http
.data_encoding
= HTTP_ENCODE_FIELDS
;
2124 if (httpPrintf(HTTP(con
), "HTTP/%d.%d %d %s\r\n", con
->http
.version
/ 100,
2125 con
->http
.version
% 100, code
, httpStatus(code
)) < 0)
2128 if (code
== HTTP_CONTINUE
)
2131 * 100-continue doesn't send any headers...
2134 if (httpPrintf(HTTP(con
), "\r\n") < 0)
2138 cupsdFlushHeader(con
);
2143 if (httpPrintf(HTTP(con
), "Date: %s\r\n", httpGetDateString(time(NULL
))) < 0)
2146 if (httpPrintf(HTTP(con
), "Server: %s\r\n", ServerHeader
) < 0)
2148 if (con
->http
.keep_alive
&& con
->http
.version
>= HTTP_1_0
)
2150 if (httpPrintf(HTTP(con
), "Connection: Keep-Alive\r\n") < 0)
2152 if (httpPrintf(HTTP(con
), "Keep-Alive: timeout=%d\r\n",
2153 KeepAliveTimeout
) < 0)
2156 if (code
== HTTP_METHOD_NOT_ALLOWED
)
2157 if (httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST\r\n") < 0)
2160 if (code
== HTTP_UNAUTHORIZED
)
2162 int auth_type
; /* Authentication type */
2165 if (!con
->best
|| con
->best
->type
== AUTH_NONE
)
2166 auth_type
= DefaultAuthType
;
2168 auth_type
= con
->best
->type
;
2170 if (auth_type
!= AUTH_DIGEST
)
2172 if (httpPrintf(HTTP(con
),
2173 "WWW-Authenticate: Basic realm=\"CUPS\"\r\n") < 0)
2178 if (httpPrintf(HTTP(con
),
2179 "WWW-Authenticate: Digest realm=\"CUPS\", nonce=\"%s\"\r\n",
2180 con
->http
.hostname
) < 0)
2185 if (con
->language
&& strcmp(con
->language
->language
, "C"))
2187 if (httpPrintf(HTTP(con
), "Content-Language: %s\r\n",
2188 con
->language
->language
) < 0)
2194 if (!strcmp(type
, "text/html"))
2196 if (httpPrintf(HTTP(con
),
2197 "Content-Type: text/html; charset=utf-8\r\n") < 0)
2200 else if (httpPrintf(HTTP(con
), "Content-Type: %s\r\n", type
) < 0)
2209 * 'cupsdUpdateCGI()' - Read status messages from CGI scripts and programs.
2213 cupsdUpdateCGI(void)
2215 char *ptr
, /* Pointer to end of line in buffer */
2216 message
[1024]; /* Pointer to message text */
2217 int loglevel
; /* Log level for message */
2220 while ((ptr
= cupsdStatBufUpdate(CGIStatusBuffer
, &loglevel
,
2221 message
, sizeof(message
))) != NULL
)
2222 if (!strchr(CGIStatusBuffer
->buffer
, '\n'))
2225 if (ptr
== NULL
&& !CGIStatusBuffer
->bufused
)
2228 * Fatal error on pipe - should never happen!
2231 cupsdLogMessage(CUPSD_LOG_CRIT
,
2232 "cupsdUpdateCGI: error reading from CGI error pipe - %s",
2239 * 'cupsdWriteClient()' - Write data to a client as needed.
2242 int /* O - 1 if success, 0 if fail */
2243 cupsdWriteClient(cupsd_client_t
*con
) /* I - Client connection */
2245 int bytes
; /* Number of bytes written */
2246 char buf
[16385]; /* Data buffer */
2247 char *bufptr
; /* Pointer into buffer */
2248 ipp_state_t ipp_state
; /* IPP state value */
2252 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2253 "cupsdWriteClient(con=%p) %d response=%p, file=%d "
2254 "pipe_pid=%d state=%d",
2255 con
, con
->http
.fd
, con
->response
, con
->file
, con
->pipe_pid
,
2259 if (con
->http
.state
!= HTTP_GET_SEND
&&
2260 con
->http
.state
!= HTTP_POST_SEND
)
2263 if (con
->response
!= NULL
)
2265 ipp_state
= ippWrite(&(con
->http
), con
->response
);
2266 bytes
= ipp_state
!= IPP_ERROR
&& ipp_state
!= IPP_DATA
;
2268 else if ((bytes
= read(con
->file
, buf
, sizeof(buf
) - 1)) > 0)
2270 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2271 "cupsdWriteClient: Read %d bytes from file %d...",
2274 if (con
->pipe_pid
&& !con
->got_fields
)
2277 * Inspect the data for Content-Type and other fields.
2282 for (bufptr
= buf
; !con
->got_fields
&& *bufptr
; bufptr
++)
2283 if (*bufptr
== '\n')
2286 * Send line to client...
2289 if (bufptr
> buf
&& bufptr
[-1] == '\r')
2293 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "Script header: %s", buf
);
2295 if (!con
->sent_header
)
2298 * Handle redirection and CGI status codes...
2301 if (!strncasecmp(buf
, "Location:", 9))
2303 cupsdSendHeader(con
, HTTP_SEE_OTHER
, NULL
);
2304 if (httpPrintf(HTTP(con
), "Content-Length: 0\r\n") < 0)
2307 else if (!strncasecmp(buf
, "Status:", 7))
2308 cupsdSendError(con
, (http_status_t
)atoi(buf
+ 7));
2311 cupsdSendHeader(con
, HTTP_OK
, NULL
);
2313 if (con
->http
.version
== HTTP_1_1
)
2315 if (httpPrintf(HTTP(con
), "Transfer-Encoding: chunked\r\n") < 0)
2320 con
->sent_header
= 1;
2323 if (strncasecmp(buf
, "Status:", 7))
2324 httpPrintf(HTTP(con
), "%s\r\n", buf
);
2326 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdWriteClient: %d %s",
2333 bytes
-= (bufptr
- buf
);
2334 memmove(buf
, bufptr
, bytes
+ 1);
2338 * See if the line was empty...
2341 if (con
->field_col
== 0)
2343 con
->got_fields
= 1;
2345 cupsdFlushHeader(con
);
2347 if (con
->http
.version
== HTTP_1_1
)
2348 con
->http
.data_encoding
= HTTP_ENCODE_CHUNKED
;
2353 else if (*bufptr
!= '\r')
2356 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2357 "cupsdWriteClient: %d bytes=%d, got_fields=%d",
2358 con
->http
.fd
, bytes
, con
->got_fields
);
2360 if (bytes
> 0 && !con
->got_fields
)
2363 * Remaining text needs to go out...
2366 httpPrintf(HTTP(con
), "%s", buf
);
2368 con
->http
.activity
= time(NULL
);
2371 else if (bytes
== 0)
2372 con
->http
.activity
= time(NULL
);
2377 if (httpWrite2(HTTP(con
), buf
, bytes
) < 0)
2379 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2380 "cupsdWriteClient: %d Write of %d bytes failed!",
2381 con
->http
.fd
, bytes
);
2383 cupsdCloseClient(con
);
2387 con
->bytes
+= bytes
;
2389 if (con
->http
.state
== HTTP_WAITING
)
2396 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdWriteClient: %d bytes < 0",
2399 cupsdLogRequest(con
, HTTP_OK
);
2401 httpFlushWrite(HTTP(con
));
2403 if (con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
)
2405 if (httpPrintf(HTTP(con
), "0\r\n\r\n") < 0)
2407 cupsdCloseClient(con
);
2412 con
->http
.state
= HTTP_WAITING
;
2414 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2415 "cupsdWriteClient: Removing fd %d from OutputSet...",
2418 FD_CLR(con
->http
.fd
, OutputSet
);
2422 if (FD_ISSET(con
->file
, InputSet
))
2424 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2425 "cupsdWriteClient: Removing fd %d from InputSet...",
2427 FD_CLR(con
->file
, InputSet
);
2431 cupsdEndProcess(con
->pipe_pid
, 0);
2433 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2434 "cupsdWriteClient: %d Closing data file %d.",
2435 con
->http
.fd
, con
->file
);
2444 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2445 "cupsdWriteClient: %d Removing temp file %s",
2446 con
->http
.fd
, con
->filename
);
2447 unlink(con
->filename
);
2448 cupsdClearString(&con
->filename
);
2451 if (con
->request
!= NULL
)
2453 ippDelete(con
->request
);
2454 con
->request
= NULL
;
2457 if (con
->response
!= NULL
)
2459 ippDelete(con
->response
);
2460 con
->response
= NULL
;
2463 cupsdClearString(&con
->command
);
2464 cupsdClearString(&con
->options
);
2466 if (!con
->http
.keep_alive
)
2468 cupsdCloseClient(con
);
2474 con
->file_ready
= 0;
2476 if (con
->pipe_pid
&& !FD_ISSET(con
->file
, InputSet
))
2478 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2479 "cupsdWriteClient: Adding fd %d to InputSet...",
2481 FD_SET(con
->file
, InputSet
);
2485 con
->http
.activity
= time(NULL
);
2492 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
2495 static int /* O - 1 if modified since */
2497 cupsd_client_t
*con
, /* I - Client connection */
2498 struct stat
*filestats
) /* I - File information */
2500 char *ptr
; /* Pointer into field */
2501 time_t date
; /* Time/date value */
2502 off_t size
; /* Size/length value */
2507 ptr
= con
->http
.fields
[HTTP_FIELD_IF_MODIFIED_SINCE
];
2512 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2513 "check_if_modified: %d If-Modified-Since=\"%s\"",
2516 while (*ptr
!= '\0')
2518 while (isspace(*ptr
) || *ptr
== ';')
2521 if (strncasecmp(ptr
, "length=", 7) == 0)
2524 size
= strtoll(ptr
, NULL
, 10);
2526 while (isdigit(*ptr
))
2529 else if (isalpha(*ptr
))
2531 date
= httpGetDateTime(ptr
);
2532 while (*ptr
!= '\0' && *ptr
!= ';')
2539 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2540 "check_if_modified: %d sizes=" CUPS_LLFMT
","
2541 CUPS_LLFMT
" dates=%d,%d",
2542 con
->http
.fd
, CUPS_LLCAST size
,
2543 CUPS_LLCAST filestats
->st_size
, (int)date
,
2544 (int)filestats
->st_mtime
);
2546 return ((size
!= filestats
->st_size
&& size
!= 0) ||
2547 (date
< filestats
->st_mtime
&& date
!= 0) ||
2548 (size
== 0 && date
== 0));
2554 * 'encrypt_client()' - Enable encryption for the client...
2557 static int /* O - 1 on success, 0 on error */
2558 encrypt_client(cupsd_client_t
*con
) /* I - Client to encrypt */
2561 SSL_CTX
*context
; /* Context for encryption */
2562 SSL
*conn
; /* Connection for encryption */
2563 unsigned long error
; /* Error code */
2567 * Verify that we have a certificate...
2570 if (access(ServerKey
, 0) || access(ServerCertificate
, 0))
2573 * Nope, make a self-signed certificate...
2576 if (!make_certificate())
2581 * Create the SSL context and accept the connection...
2584 context
= SSL_CTX_new(SSLv23_server_method());
2586 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
2587 SSL_CTX_use_PrivateKey_file(context
, ServerKey
, SSL_FILETYPE_PEM
);
2588 SSL_CTX_use_certificate_file(context
, ServerCertificate
, SSL_FILETYPE_PEM
);
2590 conn
= SSL_new(context
);
2592 SSL_set_fd(conn
, con
->http
.fd
);
2593 if (SSL_accept(conn
) != 1)
2595 cupsdLogMessage(CUPSD_LOG_ERROR
,
2596 "encrypt_client: Unable to encrypt connection from %s!",
2597 con
->http
.hostname
);
2599 while ((error
= ERR_get_error()) != 0)
2600 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s",
2601 ERR_error_string(error
, NULL
));
2603 SSL_CTX_free(context
);
2608 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2609 "encrypt_client: %d Connection from %s now encrypted.",
2610 con
->http
.fd
, con
->http
.hostname
);
2612 con
->http
.tls
= conn
;
2615 # elif defined(HAVE_GNUTLS)
2616 http_tls_t
*conn
; /* TLS session object */
2617 int error
; /* Error code */
2618 gnutls_certificate_server_credentials
*credentials
;
2619 /* TLS credentials */
2623 * Verify that we have a certificate...
2626 if (access(ServerKey
, 0) || access(ServerCertificate
, 0))
2629 * Nope, make a self-signed certificate...
2632 if (!make_certificate())
2637 * Create the SSL object and perform the SSL handshake...
2640 conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
));
2645 credentials
= (gnutls_certificate_server_credentials
*)
2646 malloc(sizeof(gnutls_certificate_server_credentials
));
2647 if (credentials
== NULL
)
2649 cupsdLogMessage(CUPSD_LOG_ERROR
,
2650 "encrypt_client: Unable to encrypt connection from %s!",
2651 con
->http
.hostname
);
2652 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s", strerror(errno
));
2658 gnutls_certificate_allocate_credentials(credentials
);
2659 gnutls_certificate_set_x509_key_file(*credentials
, ServerCertificate
,
2660 ServerKey
, GNUTLS_X509_FMT_PEM
);
2662 gnutls_init(&(conn
->session
), GNUTLS_SERVER
);
2663 gnutls_set_default_priority(conn
->session
);
2664 gnutls_credentials_set(conn
->session
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
2665 gnutls_transport_set_ptr(conn
->session
,
2666 (gnutls_transport_ptr
)((long)con
->http
.fd
));
2668 error
= gnutls_handshake(conn
->session
);
2670 if (error
!= GNUTLS_E_SUCCESS
)
2672 cupsdLogMessage(CUPSD_LOG_ERROR
,
2673 "encrypt_client: Unable to encrypt connection from %s!",
2674 con
->http
.hostname
);
2675 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s",
2676 gnutls_strerror(error
));
2678 gnutls_deinit(conn
->session
);
2679 gnutls_certificate_free_credentials(*credentials
);
2685 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2686 "encrypt_client: %d Connection from %s now encrypted.",
2687 con
->http
.fd
, con
->http
.hostname
);
2689 conn
->credentials
= credentials
;
2690 con
->http
.tls
= conn
;
2693 # elif defined(HAVE_CDSASSL)
2694 OSStatus error
; /* Error code */
2695 http_tls_t
*conn
; /* CDSA connection information */
2696 cdsa_conn_ref_t u
; /* Connection reference union */
2699 if ((conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
))) == NULL
)
2703 conn
->session
= NULL
;
2704 conn
->certsArray
= get_cdsa_server_certs();
2706 if (!conn
->certsArray
)
2709 * No keychain (yet), make a self-signed certificate...
2712 if (make_certificate())
2713 conn
->certsArray
= get_cdsa_server_certs();
2716 if (!conn
->certsArray
)
2718 cupsdLogMessage(CUPSD_LOG_ERROR
,
2719 "EncryptClient: Could not find signing key in keychain "
2720 "\"%s\"", ServerCertificate
);
2721 error
= errSSLBadCert
; /* errSSLBadConfiguration is a better choice, but not available on 10.2.x */
2725 error
= SSLNewContext(true, &conn
->session
);
2728 error
= SSLSetIOFuncs(conn
->session
, _httpReadCDSA
, _httpWriteCDSA
);
2731 error
= SSLSetProtocolVersionEnabled(conn
->session
, kSSLProtocol2
, false);
2736 * Use a union to resolve warnings about int/pointer size mismatches...
2739 u
.connection
= NULL
;
2740 u
.sock
= con
->http
.fd
;
2741 error
= SSLSetConnection(conn
->session
, u
.connection
);
2745 error
= SSLSetAllowsExpiredCerts(conn
->session
, true);
2748 error
= SSLSetAllowsAnyRoot(conn
->session
, true);
2751 error
= SSLSetCertificate(conn
->session
, conn
->certsArray
);
2756 * Perform SSL/TLS handshake
2759 while ((error
= SSLHandshake(conn
->session
)) == errSSLWouldBlock
)
2765 cupsdLogMessage(CUPSD_LOG_ERROR
,
2766 "encrypt_client: Unable to encrypt connection from %s!",
2767 con
->http
.hostname
);
2769 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s (%d)",
2770 cssmErrorString(error
), (int)error
);
2772 con
->http
.error
= error
;
2773 con
->http
.status
= HTTP_ERROR
;
2776 SSLDisposeContext(conn
->session
);
2778 if (conn
->certsArray
)
2779 CFRelease(conn
->certsArray
);
2786 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2787 "encrypt_client: %d Connection from %s now encrypted.",
2788 con
->http
.fd
, con
->http
.hostname
);
2790 con
->http
.tls
= conn
;
2793 # endif /* HAVE_LIBSSL */
2795 #endif /* HAVE_SSL */
2800 * 'get_cdsa_server_certs()' - Convert a keychain name into the CFArrayRef
2801 * required by SSLSetCertificate.
2803 * For now we assumes that there is exactly one SecIdentity in the
2804 * keychain - i.e. there is exactly one matching cert/private key pair.
2805 * In the future we will search a keychain for a SecIdentity matching a
2806 * specific criteria. We also skip the operation of adding additional
2807 * non-signing certs from the keychain to the CFArrayRef.
2809 * To create a self-signed certificate for testing use the certtool.
2810 * Executing the following as root will do it:
2812 * certtool c k=/Library/Keychains/System.keychain
2815 static CFArrayRef
/* O - Array of certificates */
2816 get_cdsa_server_certs(void)
2818 OSStatus err
; /* Error info */
2819 SecKeychainRef kcRef
; /* Keychain reference */
2820 SecIdentitySearchRef srchRef
; /* Search reference */
2821 SecIdentityRef identity
; /* Identity */
2822 CFArrayRef ca
; /* Certificate array */
2829 err
= SecKeychainOpen(ServerCertificate
, &kcRef
);
2832 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot open keychain \"%s\", error %d.",
2833 ServerCertificate
, (int)err
);
2837 * Search for "any" identity matching specified key use;
2838 * in this app, we expect there to be exactly one.
2841 err
= SecIdentitySearchCreate(kcRef
, CSSM_KEYUSE_SIGN
, &srchRef
);
2844 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2845 "Cannot find signing key in keychain \"%s\", error %d",
2846 ServerCertificate
, (int)err
);
2849 err
= SecIdentitySearchCopyNext(srchRef
, &identity
);
2852 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2853 "Cannot find signing key in keychain \"%s\", error %d",
2854 ServerCertificate
, (int)err
);
2857 if (CFGetTypeID(identity
) != SecIdentityGetTypeID())
2858 cupsdLogMessage(CUPSD_LOG_ERROR
,
2859 "SecIdentitySearchCopyNext CFTypeID failure!");
2863 * Found one. Place it in a CFArray.
2864 * TBD: snag other (non-identity) certs from keychain and add them
2868 ca
= CFArrayCreate(NULL
, (const void **)&identity
, 1, &kCFTypeArrayCallBacks
);
2871 cupsdLogMessage(CUPSD_LOG_ERROR
, "CFArrayCreate error");
2874 CFRelease(identity
);
2885 #endif /* HAVE_CDSASSL */
2889 * 'get_file()' - Get a filename and state info.
2892 static char * /* O - Real filename */
2893 get_file(cupsd_client_t
*con
, /* I - Client connection */
2894 struct stat
*filestats
, /* O - File information */
2895 char *filename
, /* IO - Filename buffer */
2896 int len
) /* I - Buffer length */
2898 int status
; /* Status of filesystem calls */
2899 char *ptr
; /* Pointer info filename */
2900 int plen
; /* Remaining length after pointer */
2904 * Need to add DocumentRoot global...
2907 if (!strncmp(con
->uri
, "/ppd/", 5))
2908 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
);
2909 else if (!strncmp(con
->uri
, "/admin/conf/", 12))
2910 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
+ 11);
2911 else if (!strncmp(con
->uri
, "/admin/log/", 11))
2913 if (!strcmp(con
->uri
+ 11, "access_log") && AccessLog
[0] == '/')
2914 strlcpy(filename
, AccessLog
, len
);
2915 else if (!strcmp(con
->uri
+ 11, "error_log") && ErrorLog
[0] == '/')
2916 strlcpy(filename
, ErrorLog
, len
);
2917 else if (!strcmp(con
->uri
+ 11, "page_log") && PageLog
[0] == '/')
2918 strlcpy(filename
, PageLog
, len
);
2922 else if (con
->language
)
2923 snprintf(filename
, len
, "%s/%s%s", DocumentRoot
, con
->language
->language
,
2926 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
2928 if ((ptr
= strchr(filename
, '?')) != NULL
)
2932 * Grab the status for this language; if there isn't a language-specific file
2933 * then fallback to the default one...
2936 if ((status
= stat(filename
, filestats
)) != 0 && con
->language
&&
2937 strncmp(con
->uri
, "/ppd/", 5) &&
2938 strncmp(con
->uri
, "/admin/conf/", 12) &&
2939 strncmp(con
->uri
, "/admin/log/", 11))
2942 * Drop the country code...
2945 char ll
[3]; /* Short language name */
2948 strlcpy(ll
, con
->language
->language
, sizeof(ll
));
2949 snprintf(filename
, len
, "%s/%s%s", DocumentRoot
, ll
, con
->uri
);
2951 if ((ptr
= strchr(filename
, '?')) != NULL
)
2954 if ((status
= stat(filename
, filestats
)) != 0)
2957 * Drop the language prefix and try the root directory...
2960 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
2962 if ((ptr
= strchr(filename
, '?')) != NULL
)
2965 status
= stat(filename
, filestats
);
2970 * If we're found a directory, get the index.html file instead...
2973 if (!status
&& S_ISDIR(filestats
->st_mode
))
2975 if (filename
[strlen(filename
) - 1] != '/')
2976 strlcat(filename
, "/", len
);
2978 ptr
= filename
+ strlen(filename
);
2979 plen
= len
- (ptr
- filename
);
2981 strlcpy(ptr
, "index.html", plen
);
2982 status
= stat(filename
, filestats
);
2987 strlcpy(ptr
, "index.class", plen
);
2988 status
= stat(filename
, filestats
);
2990 #endif /* HAVE_JAVA */
2995 strlcpy(ptr
, "index.pl", plen
);
2996 status
= stat(filename
, filestats
);
2998 #endif /* HAVE_PERL */
3003 strlcpy(ptr
, "index.php", plen
);
3004 status
= stat(filename
, filestats
);
3006 #endif /* HAVE_PHP */
3011 strlcpy(ptr
, "index.pyc", plen
);
3012 status
= stat(filename
, filestats
);
3017 strlcpy(ptr
, "index.py", plen
);
3018 status
= stat(filename
, filestats
);
3020 #endif /* HAVE_PYTHON */
3023 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "get_file: %d filename=%s size=%d",
3024 con
->http
.fd
, filename
,
3025 status
? -1 : (int)filestats
->st_size
);
3028 con
->http
.data_remaining
= (int)filestats
->st_size
;
3038 * 'install_conf_file()' - Install a configuration file.
3041 static http_status_t
/* O - Status */
3042 install_conf_file(cupsd_client_t
*con
) /* I - Connection */
3044 cups_file_t
*in
, /* Input file */
3045 *out
; /* Output file */
3046 char buffer
[1024]; /* Copy buffer */
3047 int bytes
; /* Number of bytes */
3048 char conffile
[1024], /* Configuration filename */
3049 newfile
[1024], /* New config filename */
3050 oldfile
[1024]; /* Old config filename */
3051 struct stat confinfo
; /* Config file info */
3055 * First construct the filenames...
3058 snprintf(conffile
, sizeof(conffile
), "%s%s", ServerRoot
, con
->uri
+ 11);
3059 snprintf(newfile
, sizeof(newfile
), "%s%s.N", ServerRoot
, con
->uri
+ 11);
3060 snprintf(oldfile
, sizeof(oldfile
), "%s%s.O", ServerRoot
, con
->uri
+ 11);
3062 cupsdLogMessage(CUPSD_LOG_INFO
, "Installing config file \"%s\"...", conffile
);
3065 * Get the owner, group, and permissions of the configuration file.
3066 * If it doesn't exist, assign it to the User and Group in the
3067 * cupsd.conf file with mode 0640 permissions.
3070 if (stat(conffile
, &confinfo
))
3072 confinfo
.st_uid
= User
;
3073 confinfo
.st_gid
= Group
;
3074 confinfo
.st_mode
= ConfigFilePerm
;
3078 * Open the request file and new config file...
3081 if ((in
= cupsFileOpen(con
->filename
, "rb")) == NULL
)
3083 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open request file \"%s\" - %s",
3084 con
->filename
, strerror(errno
));
3085 return (HTTP_SERVER_ERROR
);
3088 if ((out
= cupsFileOpen(newfile
, "wb")) == NULL
)
3091 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open config file \"%s\" - %s",
3092 newfile
, strerror(errno
));
3093 return (HTTP_SERVER_ERROR
);
3096 fchmod(cupsFileNumber(out
), confinfo
.st_mode
);
3097 fchown(cupsFileNumber(out
), confinfo
.st_uid
, confinfo
.st_gid
);
3100 * Copy from the request to the new config file...
3103 while ((bytes
= cupsFileRead(in
, buffer
, sizeof(buffer
))) > 0)
3104 if (cupsFileWrite(out
, buffer
, bytes
) < bytes
)
3106 cupsdLogMessage(CUPSD_LOG_ERROR
,
3107 "Unable to copy to config file \"%s\" - %s",
3108 newfile
, strerror(errno
));
3114 return (HTTP_SERVER_ERROR
);
3118 * Close the files...
3122 if (cupsFileClose(out
))
3124 cupsdLogMessage(CUPSD_LOG_ERROR
,
3125 "Error file closing config file \"%s\" - %s",
3126 newfile
, strerror(errno
));
3130 return (HTTP_SERVER_ERROR
);
3134 * Remove the request file...
3137 unlink(con
->filename
);
3138 cupsdClearString(&con
->filename
);
3141 * Unlink the old backup, rename the current config file to the backup
3142 * filename, and rename the new config file to the config file name...
3145 if (unlink(oldfile
))
3146 if (errno
!= ENOENT
)
3148 cupsdLogMessage(CUPSD_LOG_ERROR
,
3149 "Unable to remove backup config file \"%s\" - %s",
3150 oldfile
, strerror(errno
));
3154 return (HTTP_SERVER_ERROR
);
3157 if (rename(conffile
, oldfile
))
3158 if (errno
!= ENOENT
)
3160 cupsdLogMessage(CUPSD_LOG_ERROR
,
3161 "Unable to rename old config file \"%s\" - %s",
3162 conffile
, strerror(errno
));
3166 return (HTTP_SERVER_ERROR
);
3169 if (rename(newfile
, conffile
))
3171 cupsdLogMessage(CUPSD_LOG_ERROR
,
3172 "Unable to rename new config file \"%s\" - %s",
3173 newfile
, strerror(errno
));
3175 rename(oldfile
, conffile
);
3178 return (HTTP_SERVER_ERROR
);
3182 * If the cupsd.conf file was updated, set the NeedReload flag...
3185 if (!strcmp(con
->uri
, "/admin/conf/cupsd.conf"))
3186 NeedReload
= RELOAD_CUPSD
;
3188 NeedReload
= RELOAD_ALL
;
3190 ReloadTime
= time(NULL
);
3193 * Return that the file was created successfully...
3196 return (HTTP_CREATED
);
3201 * 'is_cgi()' - Is the resource a CGI script/program?
3204 static int /* O - 1 = CGI, 0 = file */
3205 is_cgi(cupsd_client_t
*con
, /* I - Client connection */
3206 const char *filename
, /* I - Real filename */
3207 struct stat
*filestats
, /* I - File information */
3208 mime_type_t
*type
) /* I - MIME type */
3210 const char *options
; /* Options on URL */
3213 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3214 "is_cgi(con=%p, filename=\"%s\", filestats=%p, type=%s/%s)\n",
3215 con
, filename
, filestats
, type
? type
->super
: "unknown",
3216 type
? type
->type
: "unknown");
3219 * Get the options, if any...
3222 if ((options
= strchr(con
->uri
, '?')) != NULL
)
3226 * Check for known types...
3229 if (!type
|| strcasecmp(type
->super
, "application"))
3231 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "is_cgi: Returning 0...");
3235 if (!strcasecmp(type
->type
, "x-httpd-cgi") &&
3236 (filestats
->st_mode
& 0111))
3239 * "application/x-httpd-cgi" is a CGI script.
3242 cupsdSetString(&con
->command
, filename
);
3244 filename
= strrchr(filename
, '/') + 1; /* Filename always absolute */
3246 cupsdSetString(&con
->options
, options
);
3248 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3249 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3250 con
->command
, con
->options
);
3255 else if (!strcasecmp(type
->type
, "x-httpd-java"))
3258 * "application/x-httpd-java" is a Java servlet.
3261 cupsdSetString(&con
->command
, CUPS_JAVA
);
3264 cupsdSetStringf(&con
->options
, "%s %s", filename
, options
);
3266 cupsdSetString(&con
->options
, filename
);
3268 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3269 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3270 con
->command
, con
->options
);
3274 #endif /* HAVE_JAVA */
3276 else if (!strcasecmp(type
->type
, "x-httpd-perl"))
3279 * "application/x-httpd-perl" is a Perl page.
3282 cupsdSetString(&con
->command
, CUPS_PERL
);
3285 cupsdSetStringf(&con
->options
, "%s %s", filename
, options
);
3287 cupsdSetString(&con
->options
, filename
);
3289 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3290 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3291 con
->command
, con
->options
);
3295 #endif /* HAVE_PERL */
3297 else if (!strcasecmp(type
->type
, "x-httpd-php"))
3300 * "application/x-httpd-php" is a PHP page.
3303 cupsdSetString(&con
->command
, CUPS_PHP
);
3306 cupsdSetStringf(&con
->options
, "%s %s", filename
, options
);
3308 cupsdSetString(&con
->options
, filename
);
3310 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3311 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3312 con
->command
, con
->options
);
3316 #endif /* HAVE_PHP */
3318 else if (!strcasecmp(type
->type
, "x-httpd-python"))
3321 * "application/x-httpd-python" is a Python page.
3324 cupsdSetString(&con
->command
, CUPS_PYTHON
);
3327 cupsdSetStringf(&con
->options
, "%s %s", filename
, options
);
3329 cupsdSetString(&con
->options
, filename
);
3331 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3332 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3333 con
->command
, con
->options
);
3337 #endif /* HAVE_PYTHON */
3339 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "is_cgi: Returning 0...");
3346 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
3349 static int /* O - 0 if relative, 1 if absolute */
3350 is_path_absolute(const char *path
) /* I - Input path */
3353 * Check for a leading slash...
3360 * Check for "/.." in the path...
3363 while ((path
= strstr(path
, "/..")) != NULL
)
3365 if (!path
[3] || path
[3] == '/')
3372 * If we haven't found any relative paths, return 1 indicating an
3382 * 'make_certificate()' - Make a self-signed SSL/TLS certificate.
3385 static int /* O - 1 on success, 0 on failure */
3386 make_certificate(void)
3388 #if defined(HAVE_LIBSSL) && defined(HAVE_WAITPID)
3389 int pid
, /* Process ID of command */
3390 status
; /* Status of command */
3391 char command
[1024], /* Command */
3392 *argv
[11], /* Command-line arguments */
3393 *envp
[MAX_ENV
+ 1], /* Environment variables */
3394 home
[1024], /* HOME environment variable */
3395 infofile
[1024], /* Type-in information for cert */
3396 seedfile
[1024]; /* Random number seed file */
3397 int envc
, /* Number of environment variables */
3398 bytes
; /* Bytes written */
3399 cups_file_t
*fp
; /* Seed/info file */
3400 int infofd
; /* Info file descriptor */
3404 * Run the "openssl" command to seed the random number generator and
3405 * generate a self-signed certificate that is good for 10 years:
3407 * openssl rand -rand seedfile 1
3409 * openssl req -new -x509 -keyout ServerKey \
3410 * -out ServerCertificate -days 3650 -nodes
3412 * The seeding step is crucial in ensuring that the openssl command
3413 * does not block on systems without sufficient entropy...
3416 if (!cupsFileFind("openssl", getenv("PATH"), 1, command
, sizeof(command
)))
3418 cupsdLogMessage(CUPSD_LOG_ERROR
,
3419 "No SSL certificate and openssl command not found!");
3423 if (access("/dev/urandom", 0))
3426 * If the system doesn't provide /dev/urandom, then any random source
3427 * will probably be blocking-style, so generate some random data to
3428 * use as a seed for the certificate. Note that we have already
3429 * seeded the random number generator in cupsdInitCerts()...
3432 cupsdLogMessage(CUPSD_LOG_INFO
,
3433 "Seeding the random number generator...");
3435 snprintf(home
, sizeof(home
), "HOME=%s", TempDir
);
3438 * Write the seed file...
3441 if ((fp
= cupsTempFile2(seedfile
, sizeof(seedfile
))) == NULL
)
3443 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to create seed file %s - %s",
3444 seedfile
, strerror(errno
));
3448 for (bytes
= 0; bytes
< 262144; bytes
++)
3449 cupsFilePutChar(fp
, random());
3454 * Run the openssl command to seed its random number generator...
3457 argv
[0] = "openssl";
3464 envc
= cupsdLoadEnv(envp
, MAX_ENV
);
3465 envp
[envc
++] = home
;
3468 if (!cupsdStartProcess(command
, argv
, envp
, -1, -1, -1, -1, 1, &pid
))
3474 while (waitpid(pid
, &status
, 0) < 0)
3481 cupsdFinishProcess(pid
, command
, sizeof(command
));
3484 * Remove the seed file, as it is no longer needed...
3491 if (WIFEXITED(status
))
3492 cupsdLogMessage(CUPSD_LOG_ERROR
,
3493 "Unable to seed random number generator - "
3494 "the openssl command stopped with status %d!",
3495 WEXITSTATUS(status
));
3497 cupsdLogMessage(CUPSD_LOG_ERROR
,
3498 "Unable to seed random number generator - "
3499 "the openssl command crashed on signal %d!",
3507 * Create a file with the certificate information fields...
3509 * Note: This assumes that the default questions are asked by the openssl
3513 if ((fp
= cupsTempFile2(infofile
, sizeof(infofile
))) == NULL
)
3515 cupsdLogMessage(CUPSD_LOG_ERROR
,
3516 "Unable to create certificate information file %s - %s",
3517 infofile
, strerror(errno
));
3521 cupsFilePrintf(fp
, ".\n.\n.\n%s\n.\n%s\n%s\n",
3522 ServerName
, ServerName
, ServerAdmin
);
3525 cupsdLogMessage(CUPSD_LOG_INFO
,
3526 "Generating SSL server key and certificate...");
3528 argv
[0] = "openssl";
3532 argv
[4] = "-keyout";
3533 argv
[5] = ServerKey
;
3535 argv
[7] = ServerCertificate
;
3538 argv
[10] = "-nodes";
3541 cupsdLoadEnv(envp
, MAX_ENV
);
3543 infofd
= open(infofile
, O_RDONLY
);
3545 if (!cupsdStartProcess(command
, argv
, envp
, infofd
, -1, -1, -1, 1, &pid
))
3555 while (waitpid(pid
, &status
, 0) < 0)
3562 cupsdFinishProcess(pid
, command
, sizeof(command
));
3566 if (WIFEXITED(status
))
3567 cupsdLogMessage(CUPSD_LOG_ERROR
,
3568 "Unable to create SSL server key and certificate - "
3569 "the openssl command stopped with status %d!",
3570 WEXITSTATUS(status
));
3572 cupsdLogMessage(CUPSD_LOG_ERROR
,
3573 "Unable to create SSL server key and certificate - "
3574 "the openssl command crashed on signal %d!",
3579 cupsdLogMessage(CUPSD_LOG_INFO
, "Created SSL server key file \"%s\"...",
3581 cupsdLogMessage(CUPSD_LOG_INFO
,
3582 "Created SSL server certificate file \"%s\"...",
3588 #elif defined(HAVE_GNUTLS)
3589 gnutls_x509_crt crt
; /* Self-signed certificate */
3590 gnutls_x509_privkey key
; /* Encryption key */
3591 cups_lang_t
*language
; /* Default language info */
3592 cups_file_t
*fp
; /* Key/cert file */
3593 unsigned char buffer
[8192]; /* Buffer for x509 data */
3594 size_t bytes
; /* Number of bytes of data */
3595 unsigned char serial
[4]; /* Serial number buffer */
3596 time_t curtime
; /* Current time */
3597 int result
; /* Result of GNU TLS calls */
3601 * Create the encryption key...
3604 cupsdLogMessage(CUPSD_LOG_INFO
, "Generating SSL server key...");
3606 gnutls_x509_privkey_init(&key
);
3607 gnutls_x509_privkey_generate(key
, GNUTLS_PK_RSA
, 2048, 0);
3613 bytes
= sizeof(buffer
);
3615 if ((result
= gnutls_x509_privkey_export(key
, GNUTLS_X509_FMT_PEM
,
3616 buffer
, &bytes
)) < 0)
3618 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to export SSL server key - %s",
3619 gnutls_strerror(result
));
3620 gnutls_x509_privkey_deinit(key
);
3623 else if ((fp
= cupsFileOpen(ServerKey
, "w")) != NULL
)
3625 cupsFileWrite(fp
, (char *)buffer
, bytes
);
3628 cupsdLogMessage(CUPSD_LOG_INFO
, "Created SSL server key file \"%s\"...",
3633 cupsdLogMessage(CUPSD_LOG_ERROR
,
3634 "Unable to create SSL server key file \"%s\" - %s",
3635 ServerKey
, strerror(errno
));
3636 gnutls_x509_privkey_deinit(key
);
3641 * Create the self-signed certificate...
3644 cupsdLogMessage(CUPSD_LOG_INFO
, "Generating self-signed SSL certificate...");
3646 language
= cupsLangDefault();
3647 curtime
= time(NULL
);
3648 serial
[0] = curtime
>> 24;
3649 serial
[1] = curtime
>> 16;
3650 serial
[2] = curtime
>> 8;
3651 serial
[3] = curtime
;
3653 gnutls_x509_crt_init(&crt
);
3654 if (strlen(language
->language
) == 5)
3655 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
3656 language
->language
+ 3, 2);
3658 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
3660 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COMMON_NAME
, 0,
3661 ServerName
, strlen(ServerName
));
3662 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATION_NAME
, 0,
3663 ServerName
, strlen(ServerName
));
3664 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATIONAL_UNIT_NAME
,
3666 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_STATE_OR_PROVINCE_NAME
, 0,
3668 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_LOCALITY_NAME
, 0,
3670 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_PKCS9_EMAIL
, 0,
3671 ServerAdmin
, strlen(ServerAdmin
));
3672 gnutls_x509_crt_set_key(crt
, key
);
3673 gnutls_x509_crt_set_serial(crt
, serial
, sizeof(serial
));
3674 gnutls_x509_crt_set_activation_time(crt
, curtime
);
3675 gnutls_x509_crt_set_expiration_time(crt
, curtime
+ 10 * 365 * 86400);
3676 gnutls_x509_crt_set_ca_status(crt
, 0);
3677 gnutls_x509_crt_set_subject_alternative_name(crt
, GNUTLS_SAN_DNSNAME
,
3679 gnutls_x509_crt_set_key_purpose_oid(crt
, GNUTLS_KP_TLS_WWW_SERVER
, 0);
3680 gnutls_x509_crt_set_key_usage(crt
, GNUTLS_KEY_KEY_ENCIPHERMENT
);
3681 gnutls_x509_crt_set_version(crt
, 3);
3683 bytes
= sizeof(buffer
);
3684 if (gnutls_x509_crt_get_key_id(crt
, 0, buffer
, &bytes
) >= 0)
3685 gnutls_x509_crt_set_subject_key_id(crt
, buffer
, bytes
);
3687 gnutls_x509_crt_sign(crt
, crt
, key
);
3693 bytes
= sizeof(buffer
);
3694 if ((result
= gnutls_x509_crt_export(crt
, GNUTLS_X509_FMT_PEM
,
3695 buffer
, &bytes
)) < 0)
3696 cupsdLogMessage(CUPSD_LOG_ERROR
,
3697 "Unable to export SSL server certificate - %s",
3698 gnutls_strerror(result
));
3699 else if ((fp
= cupsFileOpen(ServerCertificate
, "w")) != NULL
)
3701 cupsFileWrite(fp
, (char *)buffer
, bytes
);
3704 cupsdLogMessage(CUPSD_LOG_INFO
,
3705 "Created SSL server certificate file \"%s\"...",
3709 cupsdLogMessage(CUPSD_LOG_ERROR
,
3710 "Unable to create SSL server certificate file \"%s\" - %s",
3711 ServerCertificate
, strerror(errno
));
3717 gnutls_x509_crt_deinit(crt
);
3718 gnutls_x509_privkey_deinit(key
);
3722 #elif defined(HAVE_CDSASSL) && defined(HAVE_WAITPID)
3723 int pid
, /* Process ID of command */
3724 status
; /* Status of command */
3725 char command
[1024], /* Command */
3726 keychain
[1024], /* Keychain argument */
3727 *argv
[5], /* Command-line arguments */
3728 *envp
[MAX_ENV
]; /* Environment variables */
3732 * Run the "certtool" command to generate a self-signed certificate:
3734 * certtool c Z k=ServerCertificate
3737 if (!cupsFileFind("certtool", getenv("PATH"), 1, command
, sizeof(command
)))
3739 cupsdLogMessage(CUPSD_LOG_ERROR
,
3740 "No SSL certificate and certtool command not found!");
3744 cupsdLogMessage(CUPSD_LOG_INFO
,
3745 "Generating SSL server key and certificate...");
3747 snprintf(keychain
, sizeof(keychain
), "k=%s", ServerCertificate
);
3749 argv
[0] = "certtool";
3755 cupsdLoadEnv(envp
, MAX_ENV
);
3757 if (!cupsdStartProcess(command
, argv
, envp
, -1, -1, -1, -1, 1, &pid
))
3760 while (waitpid(pid
, &status
, 0) < 0)
3767 cupsdFinishProcess(pid
, command
, sizeof(command
));
3771 if (WIFEXITED(status
))
3772 cupsdLogMessage(CUPSD_LOG_ERROR
,
3773 "Unable to create SSL server key and certificate - "
3774 "the certtool command stopped with status %d!",
3775 WEXITSTATUS(status
));
3777 cupsdLogMessage(CUPSD_LOG_ERROR
,
3778 "Unable to create SSL server key and certificate - "
3779 "the certtool command crashed on signal %d!",
3784 cupsdLogMessage(CUPSD_LOG_INFO
,
3785 "Created SSL server certificate file \"%s\"...",
3793 #endif /* HAVE_LIBSSL && HAVE_WAITPID */
3795 #endif /* HAVE_SSL */
3799 * 'pipe_command()' - Pipe the output of a command to the remote client.
3802 static int /* O - Process ID */
3803 pipe_command(cupsd_client_t
*con
, /* I - Client connection */
3804 int infile
, /* I - Standard input for command */
3805 int *outfile
, /* O - Standard output for command */
3806 char *command
, /* I - Command to run */
3807 char *options
, /* I - Options for command */
3808 int root
) /* I - Run as root? */
3810 int i
; /* Looping var */
3811 int pid
; /* Process ID */
3812 char *commptr
, /* Command string pointer */
3813 commch
; /* Command string character */
3814 char *uriptr
; /* URI string pointer */
3815 int fds
[2]; /* Pipe FDs */
3816 int argc
; /* Number of arguments */
3817 int envc
; /* Number of environment variables */
3818 char argbuf
[10240], /* Argument buffer */
3819 *argv
[100], /* Argument strings */
3820 *envp
[MAX_ENV
+ 17]; /* Environment variables */
3821 char content_length
[1024], /* CONTENT_LENGTH environment variable */
3822 content_type
[1024], /* CONTENT_TYPE environment variable */
3823 http_cookie
[32768], /* HTTP_COOKIE environment variable */
3824 http_user_agent
[1024], /* HTTP_USER_AGENT environment variable */
3825 lang
[1024], /* LANG environment variable */
3826 path_info
[1024], /* PATH_INFO environment variable */
3827 *query_string
, /* QUERY_STRING env variable */
3828 remote_addr
[1024], /* REMOTE_ADDR environment variable */
3829 remote_host
[1024], /* REMOTE_HOST environment variable */
3830 remote_user
[1024], /* REMOTE_USER environment variable */
3831 script_name
[1024], /* SCRIPT_NAME environment variable */
3832 server_name
[1024], /* SERVER_NAME environment variable */
3833 server_port
[1024]; /* SERVER_PORT environment variable */
3837 * Parse a copy of the options string, which is of the form:
3839 * argument+argument+argument
3840 * ?argument+argument+argument
3841 * param=value¶m=value
3842 * ?param=value¶m=value
3843 * /name?argument+argument+argument
3844 * /name?param=value¶m=value
3846 * If the string contains an "=" character after the initial name,
3847 * then we treat it as a HTTP GET form request and make a copy of
3848 * the remaining string for the environment variable.
3850 * The string is always parsed out as command-line arguments, to
3851 * be consistent with Apache...
3854 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3855 "pipe_command: command=\"%s\", options=\"%s\"",
3856 command
, options
? options
: "(null)");
3859 query_string
= NULL
;
3862 strlcpy(argbuf
, options
, sizeof(argbuf
));
3866 if (argbuf
[0] == '/')
3869 * Found some trailing path information, set PATH_INFO...
3872 if ((commptr
= strchr(argbuf
, '?')) == NULL
)
3873 commptr
= argbuf
+ strlen(argbuf
);
3877 snprintf(path_info
, sizeof(path_info
), "PATH_INFO=%s", argbuf
);
3883 path_info
[0] = '\0';
3886 if (*commptr
== '?' && con
->operation
== HTTP_GET
)
3889 cupsdSetStringf(&query_string
, "QUERY_STRING=%s", commptr
);
3896 argv
[argc
++] = commptr
;
3898 for (; *commptr
&& argc
< 99; commptr
++)
3901 * Break arguments whenever we see a + or space...
3904 if (*commptr
== ' ' || *commptr
== '+')
3906 while (*commptr
== ' ' || *commptr
== '+')
3910 * If we don't have a blank string, save it as another argument...
3915 argv
[argc
] = commptr
;
3921 else if (*commptr
== '%' && isxdigit(commptr
[1] & 255) &&
3922 isxdigit(commptr
[2] & 255))
3925 * Convert the %xx notation to the individual character.
3928 if (commptr
[1] >= '0' && commptr
[1] <= '9')
3929 *commptr
= (commptr
[1] - '0') << 4;
3931 *commptr
= (tolower(commptr
[1]) - 'a' + 10) << 4;
3933 if (commptr
[2] >= '0' && commptr
[2] <= '9')
3934 *commptr
|= commptr
[2] - '0';
3936 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
3938 _cups_strcpy(commptr
+ 1, commptr
+ 3);
3941 * Check for a %00 and break if that is the case...
3953 * Setup the environment variables as needed...
3957 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF-8", con
->language
->language
);
3959 strcpy(lang
, "LANG=C");
3961 strcpy(remote_addr
, "REMOTE_ADDR=");
3962 httpAddrString(con
->http
.hostaddr
, remote_addr
+ 12,
3963 sizeof(remote_addr
) - 12);
3965 snprintf(remote_host
, sizeof(remote_host
), "REMOTE_HOST=%s",
3966 con
->http
.hostname
);
3968 snprintf(script_name
, sizeof(script_name
), "SCRIPT_NAME=%s", con
->uri
);
3969 if ((uriptr
= strchr(script_name
, '?')) != NULL
)
3972 sprintf(server_port
, "SERVER_PORT=%d", con
->serverport
);
3974 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
3977 envc
= cupsdLoadEnv(envp
, (int)(sizeof(envp
) / sizeof(envp
[0])));
3979 envp
[envc
++] = lang
;
3980 envp
[envc
++] = "REDIRECT_STATUS=1";
3981 envp
[envc
++] = server_name
;
3982 envp
[envc
++] = server_port
;
3983 envp
[envc
++] = remote_addr
;
3984 envp
[envc
++] = remote_host
;
3985 envp
[envc
++] = script_name
;
3988 envp
[envc
++] = path_info
;
3990 if (con
->username
[0])
3992 snprintf(remote_user
, sizeof(remote_user
), "REMOTE_USER=%s", con
->username
);
3994 envp
[envc
++] = remote_user
;
3997 if (con
->http
.version
== HTTP_1_1
)
3998 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.1";
3999 else if (con
->http
.version
== HTTP_1_0
)
4000 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.0";
4002 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/0.9";
4004 if (con
->http
.cookie
)
4006 snprintf(http_cookie
, sizeof(http_cookie
), "HTTP_COOKIE=%s",
4008 envp
[envc
++] = http_cookie
;
4011 if (con
->http
.fields
[HTTP_FIELD_USER_AGENT
][0])
4013 snprintf(http_user_agent
, sizeof(http_user_agent
), "HTTP_USER_AGENT=%s",
4014 con
->http
.fields
[HTTP_FIELD_USER_AGENT
]);
4015 envp
[envc
++] = http_user_agent
;
4018 if (con
->operation
== HTTP_GET
)
4020 for (i
= 0; i
< argc
; i
++)
4021 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "argv[%d] = \"%s\"", i
, argv
[i
]);
4023 envp
[envc
++] = "REQUEST_METHOD=GET";
4028 * Add GET form variables after ?...
4031 envp
[envc
++] = query_string
;
4036 sprintf(content_length
, "CONTENT_LENGTH=" CUPS_LLFMT
,
4037 CUPS_LLCAST con
->bytes
);
4038 snprintf(content_type
, sizeof(content_type
), "CONTENT_TYPE=%s",
4039 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
4041 envp
[envc
++] = "REQUEST_METHOD=POST";
4042 envp
[envc
++] = content_length
;
4043 envp
[envc
++] = content_type
;
4047 * Tell the CGI if we are using encryption...
4051 envp
[envc
++] = "HTTPS=ON";
4054 * Terminate the environment array...
4059 if (LogLevel
== CUPSD_LOG_DEBUG2
)
4061 for (i
= 0; i
< argc
; i
++)
4062 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4063 "pipe_command: argv[%d] = \"%s\"", i
, argv
[i
]);
4064 for (i
= 0; i
< envc
; i
++)
4065 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4066 "pipe_command: envp[%d] = \"%s\"", i
, envp
[i
]);
4070 * Create a pipe for the output...
4073 if (cupsdOpenPipe(fds
))
4075 cupsdClearString(&query_string
);
4077 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to create pipes for CGI %s - %s",
4078 argv
[0], strerror(errno
));
4083 * Then execute the command...
4086 if (cupsdStartProcess(command
, argv
, envp
, infile
, fds
[1], CGIPipes
[1],
4087 -1, root
, &pid
) < 0)
4090 * Error - can't fork!
4093 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to fork for CGI %s - %s", argv
[0],
4096 cupsdClosePipe(fds
);
4102 * Fork successful - return the PID...
4105 if (con
->username
[0])
4106 cupsdAddCert(pid
, con
->username
);
4108 cupsdLogMessage(CUPSD_LOG_DEBUG
, "CGI %s started - PID = %d", command
, pid
);
4114 cupsdClearString(&query_string
);
4121 * 'write_file()' - Send a file via HTTP.
4124 static int /* O - 0 on failure, 1 on success */
4125 write_file(cupsd_client_t
*con
, /* I - Client connection */
4126 http_status_t code
, /* I - HTTP status */
4127 char *filename
, /* I - Filename */
4128 char *type
, /* I - File type */
4129 struct stat
*filestats
) /* O - File information */
4131 con
->file
= open(filename
, O_RDONLY
);
4133 cupsdLogMessage(CUPSD_LOG_DEBUG
, "write_file: %d file=%d", con
->http
.fd
,
4139 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
4143 if (!cupsdSendHeader(con
, code
, type
))
4146 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
4147 httpGetDateString(filestats
->st_mtime
)) < 0)
4149 if (httpPrintf(HTTP(con
), "Content-Length: " CUPS_LLFMT
"\r\n",
4150 CUPS_LLCAST filestats
->st_size
) < 0)
4152 if (httpPrintf(HTTP(con
), "\r\n") < 0)
4155 cupsdFlushHeader(con
);
4157 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
4158 con
->http
.data_remaining
= filestats
->st_size
;
4160 if (con
->http
.data_remaining
<= INT_MAX
)
4161 con
->http
._data_remaining
= con
->http
.data_remaining
;
4163 con
->http
._data_remaining
= INT_MAX
;
4165 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4166 "write_file: Adding fd %d to OutputSet...", con
->http
.fd
);
4168 FD_SET(con
->http
.fd
, OutputSet
);
4175 * End of "$Id: client.c 5898 2006-08-28 18:54:10Z mike $".