2 * "$Id: client.c 6027 2006-10-11 21:04:58Z 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.
681 int /* I - Bytes written or -1 on error */
682 cupsdFlushHeader(cupsd_client_t
*con
) /* I - Client to flush to */
684 int bytes
= httpFlushWrite(HTTP(con
));
686 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
693 * 'cupsdReadClient()' - Read data from a client.
696 int /* O - 1 on success, 0 on error */
697 cupsdReadClient(cupsd_client_t
*con
) /* I - Client to read from */
699 char line
[32768], /* Line from client... */
700 operation
[64], /* Operation code from socket */
701 version
[64], /* HTTP version number string */
702 locale
[64], /* Locale */
703 *ptr
; /* Pointer into strings */
704 int major
, minor
; /* HTTP version numbers */
705 http_status_t status
; /* Transfer status */
706 ipp_state_t ipp_state
; /* State of IPP transfer */
707 int bytes
; /* Number of bytes to POST */
708 char *filename
; /* Name of file for GET/HEAD */
709 char buf
[1024]; /* Buffer for real filename */
710 struct stat filestats
; /* File information */
711 mime_type_t
*type
; /* MIME type of file */
712 cupsd_printer_t
*p
; /* Printer */
713 static unsigned request_id
= 0; /* Request ID for temp files */
716 status
= HTTP_CONTINUE
;
718 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
719 "cupsdReadClient: %d, used=%d, file=%d state=%d",
720 con
->http
.fd
, con
->http
.used
, con
->file
, con
->http
.state
);
724 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdReadClient: http error seen...");
725 return (cupsdCloseClient(con
));
732 * Automatically check for a SSL/TLS handshake...
737 if (recv(con
->http
.fd
, buf
, 1, MSG_PEEK
) == 1 &&
738 (!buf
[0] || !strchr("DGHOPT", buf
[0])))
741 * Encrypt this connection...
744 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
745 "cupsdReadClient: Saw first byte %02X, auto-negotiating SSL/TLS session...",
752 #endif /* HAVE_SSL */
754 switch (con
->http
.state
)
758 * See if we've received a request line...
761 if (httpGets(line
, sizeof(line
) - 1, HTTP(con
)) == NULL
)
763 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
764 "cupsdReadClient: httpGets returned EOF...");
765 return (cupsdCloseClient(con
));
769 * Ignore blank request lines...
776 * Clear other state variables...
779 httpClearFields(HTTP(con
));
781 con
->http
.activity
= time(NULL
);
782 con
->http
.version
= HTTP_1_0
;
783 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
784 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
785 con
->http
.data_remaining
= 0;
786 con
->http
._data_remaining
= 0;
787 con
->operation
= HTTP_WAITING
;
792 con
->username
[0] = '\0';
793 con
->password
[0] = '\0';
796 cupsdClearString(&con
->command
);
797 cupsdClearString(&con
->options
);
801 ippDelete(con
->request
);
807 ippDelete(con
->response
);
808 con
->response
= NULL
;
813 cupsLangFree(con
->language
);
814 con
->language
= NULL
;
818 * Grab the request line...
821 switch (sscanf(line
, "%63s%1023s%63s", operation
, con
->uri
, version
))
824 cupsdLogMessage(CUPSD_LOG_ERROR
,
825 "Bad request line \"%s\" from %s!", line
,
827 cupsdSendError(con
, HTTP_BAD_REQUEST
);
828 return (cupsdCloseClient(con
));
830 con
->http
.version
= HTTP_0_9
;
833 if (sscanf(version
, "HTTP/%d.%d", &major
, &minor
) != 2)
835 cupsdLogMessage(CUPSD_LOG_ERROR
,
836 "Bad request line \"%s\" from %s!", line
,
838 cupsdSendError(con
, HTTP_BAD_REQUEST
);
839 return (cupsdCloseClient(con
));
844 con
->http
.version
= (http_version_t
)(major
* 100 + minor
);
845 if (con
->http
.version
== HTTP_1_1
&& KeepAlive
)
846 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
848 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
852 cupsdSendError(con
, HTTP_NOT_SUPPORTED
);
853 return (cupsdCloseClient(con
));
859 * Handle full URLs in the request line...
862 if (strcmp(con
->uri
, "*"))
864 char method
[HTTP_MAX_URI
], /* Method/scheme */
865 userpass
[HTTP_MAX_URI
], /* Username:password */
866 hostname
[HTTP_MAX_URI
], /* Hostname */
867 resource
[HTTP_MAX_URI
]; /* Resource path */
868 int port
; /* Port number */
872 * Separate the URI into its components...
875 httpSeparateURI(HTTP_URI_CODING_MOST
, con
->uri
,
876 method
, sizeof(method
),
877 userpass
, sizeof(userpass
),
878 hostname
, sizeof(hostname
), &port
,
879 resource
, sizeof(resource
));
882 * Only allow URIs with the servername, localhost, or an IP
886 if (strcmp(method
, "file") &&
887 strcasecmp(hostname
, ServerName
) &&
888 strcasecmp(hostname
, "localhost") &&
889 !isdigit(hostname
[0]))
892 * Nope, we don't do proxies...
895 cupsdLogMessage(CUPSD_LOG_ERROR
, "Bad URI \"%s\" in request!",
897 cupsdSendError(con
, HTTP_METHOD_NOT_ALLOWED
);
898 return (cupsdCloseClient(con
));
902 * Copy the resource portion back into the URI; both resource and
903 * con->uri are HTTP_MAX_URI bytes in size...
906 strcpy(con
->uri
, resource
);
910 * Process the request...
913 if (!strcmp(operation
, "GET"))
914 con
->http
.state
= HTTP_GET
;
915 else if (!strcmp(operation
, "PUT"))
916 con
->http
.state
= HTTP_PUT
;
917 else if (!strcmp(operation
, "POST"))
918 con
->http
.state
= HTTP_POST
;
919 else if (!strcmp(operation
, "DELETE"))
920 con
->http
.state
= HTTP_DELETE
;
921 else if (!strcmp(operation
, "TRACE"))
922 con
->http
.state
= HTTP_TRACE
;
923 else if (!strcmp(operation
, "OPTIONS"))
924 con
->http
.state
= HTTP_OPTIONS
;
925 else if (!strcmp(operation
, "HEAD"))
926 con
->http
.state
= HTTP_HEAD
;
929 cupsdLogMessage(CUPSD_LOG_ERROR
, "Bad operation \"%s\"!", operation
);
930 cupsdSendError(con
, HTTP_BAD_REQUEST
);
931 return (cupsdCloseClient(con
));
934 con
->start
= time(NULL
);
935 con
->operation
= con
->http
.state
;
937 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdReadClient: %d %s %s HTTP/%d.%d",
938 con
->http
.fd
, operation
, con
->uri
,
939 con
->http
.version
/ 100, con
->http
.version
% 100);
941 con
->http
.status
= HTTP_OK
;
951 * Parse incoming parameters until the status changes...
954 status
= httpUpdate(HTTP(con
));
956 if (status
!= HTTP_OK
&& status
!= HTTP_CONTINUE
)
958 cupsdSendError(con
, HTTP_BAD_REQUEST
);
959 return (cupsdCloseClient(con
));
964 break; /* Anti-compiler-warning-code */
968 * Handle new transfers...
971 if (status
== HTTP_OK
)
973 if (con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
][0])
976 * Figure out the locale from the Accept-Language and Content-Type
980 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ',')) != NULL
)
983 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ';')) != NULL
)
986 if ((ptr
= strstr(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
], "charset=")) != NULL
)
989 * Combine language and charset, and trim any extra params in the
993 snprintf(locale
, sizeof(locale
), "%s.%s",
994 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ptr
+ 8);
996 if ((ptr
= strchr(locale
, ',')) != NULL
)
1000 snprintf(locale
, sizeof(locale
), "%s.%s",
1001 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], DefaultCharset
);
1003 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1004 "cupsdReadClient: %d Browser asked for language \"%s\"...",
1005 con
->http
.fd
, locale
);
1007 con
->language
= cupsLangGet(locale
);
1010 con
->language
= cupsLangGet(DefaultLocale
);
1012 cupsdAuthorize(con
);
1014 if (!strncmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Keep-Alive", 10) &&
1016 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
1018 if (!con
->http
.fields
[HTTP_FIELD_HOST
][0] &&
1019 con
->http
.version
>= HTTP_1_1
)
1022 * HTTP/1.1 and higher require the "Host:" field...
1025 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
))
1026 return (cupsdCloseClient(con
));
1028 else if (con
->operation
== HTTP_OPTIONS
)
1031 * Do OPTIONS command...
1034 if (con
->best
&& con
->best
->type
!= AUTH_NONE
)
1036 if (!cupsdSendHeader(con
, HTTP_UNAUTHORIZED
, NULL
))
1037 return (cupsdCloseClient(con
));
1040 if (!strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") &&
1041 con
->http
.tls
== NULL
)
1045 * Do encryption stuff...
1048 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
))
1049 return (cupsdCloseClient(con
));
1051 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1052 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1053 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1054 httpPrintf(HTTP(con
), "\r\n");
1056 if (cupsdFlushHeader(con
) < 0)
1057 return (cupsdCloseClient(con
));
1059 encrypt_client(con
);
1061 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
))
1062 return (cupsdCloseClient(con
));
1063 #endif /* HAVE_SSL */
1066 if (!cupsdSendHeader(con
, HTTP_OK
, NULL
))
1067 return (cupsdCloseClient(con
));
1069 httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n");
1070 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1071 httpPrintf(HTTP(con
), "\r\n");
1073 if (cupsdFlushHeader(con
) < 0)
1074 return (cupsdCloseClient(con
));
1076 else if (!is_path_absolute(con
->uri
))
1079 * Protect against malicious users!
1082 if (!cupsdSendError(con
, HTTP_FORBIDDEN
))
1083 return (cupsdCloseClient(con
));
1087 if (!strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") &&
1088 con
->http
.tls
== NULL
)
1092 * Do encryption stuff...
1095 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
))
1096 return (cupsdCloseClient(con
));
1098 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1099 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1100 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1101 httpPrintf(HTTP(con
), "\r\n");
1103 if (cupsdFlushHeader(con
) < 0)
1104 return (cupsdCloseClient(con
));
1106 encrypt_client(con
);
1108 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
))
1109 return (cupsdCloseClient(con
));
1110 #endif /* HAVE_SSL */
1113 if ((status
= cupsdIsAuthorized(con
, NULL
)) != HTTP_OK
)
1115 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1116 "cupsdReadClient: Unauthorized request for %s...\n",
1118 cupsdSendError(con
, status
);
1119 return (cupsdCloseClient(con
));
1122 if (con
->http
.expect
&&
1123 (con
->operation
== HTTP_POST
|| con
->operation
== HTTP_PUT
))
1125 if (con
->http
.expect
== HTTP_CONTINUE
)
1128 * Send 100-continue header...
1131 if (!cupsdSendHeader(con
, HTTP_CONTINUE
, NULL
))
1132 return (cupsdCloseClient(con
));
1137 * Send 417-expectation-failed header...
1140 if (!cupsdSendHeader(con
, HTTP_EXPECTATION_FAILED
, NULL
))
1141 return (cupsdCloseClient(con
));
1143 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1144 httpPrintf(HTTP(con
), "\r\n");
1146 if (cupsdFlushHeader(con
) < 0)
1147 return (cupsdCloseClient(con
));
1151 switch (con
->http
.state
)
1153 case HTTP_GET_SEND
:
1154 if (!strncmp(con
->uri
, "/printers/", 10) &&
1155 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1158 * Send PPD file - get the real printer name since printer
1159 * names are not case sensitive but filenames can be...
1162 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1164 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1165 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1168 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
1169 return (cupsdCloseClient(con
));
1175 if ((!strncmp(con
->uri
, "/admin", 6) &&
1176 strncmp(con
->uri
, "/admin/conf/", 12) &&
1177 strncmp(con
->uri
, "/admin/log/", 11)) ||
1178 !strncmp(con
->uri
, "/printers", 9) ||
1179 !strncmp(con
->uri
, "/classes", 8) ||
1180 !strncmp(con
->uri
, "/help", 5) ||
1181 !strncmp(con
->uri
, "/jobs", 5))
1184 * Send CGI output...
1187 if (!strncmp(con
->uri
, "/admin", 6))
1189 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1192 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1194 else if (!strncmp(con
->uri
, "/printers", 9))
1196 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1199 if (con
->uri
[9] && con
->uri
[10])
1200 cupsdSetString(&con
->options
, con
->uri
+ 9);
1202 cupsdSetString(&con
->options
, NULL
);
1204 else if (!strncmp(con
->uri
, "/classes", 8))
1206 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1209 if (con
->uri
[8] && con
->uri
[9])
1210 cupsdSetString(&con
->options
, con
->uri
+ 8);
1212 cupsdSetString(&con
->options
, NULL
);
1214 else if (!strncmp(con
->uri
, "/jobs", 5))
1216 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1219 if (con
->uri
[5] && con
->uri
[6])
1220 cupsdSetString(&con
->options
, con
->uri
+ 5);
1222 cupsdSetString(&con
->options
, NULL
);
1226 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1229 if (con
->uri
[5] && con
->uri
[6])
1230 cupsdSetString(&con
->options
, con
->uri
+ 5);
1232 cupsdSetString(&con
->options
, NULL
);
1235 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1237 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
1238 return (cupsdCloseClient(con
));
1241 cupsdLogRequest(con
, HTTP_OK
);
1243 if (con
->http
.version
<= HTTP_1_0
)
1244 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1246 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1247 (strchr(con
->uri
+ 12, '/') ||
1248 strlen(con
->uri
) == 12)) ||
1249 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1250 (strchr(con
->uri
+ 11, '/') ||
1251 strlen(con
->uri
) == 11)))
1254 * GET can only be done to configuration files under
1258 if (!cupsdSendError(con
, HTTP_FORBIDDEN
))
1259 return (cupsdCloseClient(con
));
1269 if ((filename
= get_file(con
, &filestats
, buf
,
1270 sizeof(buf
))) == NULL
)
1272 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
1273 return (cupsdCloseClient(con
));
1278 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1280 if (is_cgi(con
, filename
, &filestats
, type
))
1283 * Note: con->command and con->options were set by
1287 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1289 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
1290 return (cupsdCloseClient(con
));
1293 cupsdLogRequest(con
, HTTP_OK
);
1295 if (con
->http
.version
<= HTTP_1_0
)
1296 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1300 if (!check_if_modified(con
, &filestats
))
1302 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
))
1303 return (cupsdCloseClient(con
));
1308 strcpy(line
, "text/plain");
1310 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1312 if (!write_file(con
, HTTP_OK
, filename
, line
, &filestats
))
1313 return (cupsdCloseClient(con
));
1318 case HTTP_POST_RECV
:
1320 * See if the POST request includes a Content-Length field, and if
1321 * so check the length against any limits that are set...
1324 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "POST %s", con
->uri
);
1325 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "CONTENT_TYPE = %s",
1326 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
1328 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1329 MaxRequestSize
> 0 &&
1330 con
->http
.data_remaining
> MaxRequestSize
)
1333 * Request too large...
1336 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1337 return (cupsdCloseClient(con
));
1341 else if (con
->http
.data_remaining
< 0)
1344 * Negative content lengths are invalid!
1347 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
))
1348 return (cupsdCloseClient(con
));
1354 * See what kind of POST request this is; for IPP requests the
1355 * content-type field will be "application/ipp"...
1358 if (!strcmp(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
],
1360 con
->request
= ippNew();
1361 else if ((!strncmp(con
->uri
, "/admin", 6) &&
1362 strncmp(con
->uri
, "/admin/conf/", 12) &&
1363 strncmp(con
->uri
, "/admin/log/", 11)) ||
1364 !strncmp(con
->uri
, "/printers", 9) ||
1365 !strncmp(con
->uri
, "/classes", 8) ||
1366 !strncmp(con
->uri
, "/help", 5) ||
1367 !strncmp(con
->uri
, "/jobs", 5))
1373 if (!strncmp(con
->uri
, "/admin", 6))
1375 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1378 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1380 else if (!strncmp(con
->uri
, "/printers", 9))
1382 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1385 if (con
->uri
[9] && con
->uri
[10])
1386 cupsdSetString(&con
->options
, con
->uri
+ 9);
1388 cupsdSetString(&con
->options
, NULL
);
1390 else if (!strncmp(con
->uri
, "/classes", 8))
1392 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1395 if (con
->uri
[8] && con
->uri
[9])
1396 cupsdSetString(&con
->options
, con
->uri
+ 8);
1398 cupsdSetString(&con
->options
, NULL
);
1400 else if (!strncmp(con
->uri
, "/jobs", 5))
1402 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1405 if (con
->uri
[5] && con
->uri
[6])
1406 cupsdSetString(&con
->options
, con
->uri
+ 5);
1408 cupsdSetString(&con
->options
, NULL
);
1412 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1415 if (con
->uri
[5] && con
->uri
[6])
1416 cupsdSetString(&con
->options
, con
->uri
+ 5);
1418 cupsdSetString(&con
->options
, NULL
);
1421 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1422 "cupsdReadClient: %d command=\"%s\", "
1424 con
->http
.fd
, con
->command
,
1425 con
->options
? con
->options
: "(null)");
1427 if (con
->http
.version
<= HTTP_1_0
)
1428 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1436 if ((filename
= get_file(con
, &filestats
, buf
,
1437 sizeof(buf
))) == NULL
)
1439 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
1440 return (cupsdCloseClient(con
));
1445 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1447 if (!is_cgi(con
, filename
, &filestats
, type
))
1450 * Only POST to CGI's...
1453 if (!cupsdSendError(con
, HTTP_UNAUTHORIZED
))
1454 return (cupsdCloseClient(con
));
1459 case HTTP_PUT_RECV
:
1461 * Validate the resource name...
1464 if (strncmp(con
->uri
, "/admin/conf/", 12) ||
1465 strchr(con
->uri
+ 12, '/') ||
1466 strlen(con
->uri
) == 12)
1469 * PUT can only be done to configuration files under
1473 if (!cupsdSendError(con
, HTTP_FORBIDDEN
))
1474 return (cupsdCloseClient(con
));
1480 * See if the PUT request includes a Content-Length field, and if
1481 * so check the length against any limits that are set...
1484 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "PUT %s", con
->uri
);
1485 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "CONTENT_TYPE = %s",
1486 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
1488 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1489 MaxRequestSize
> 0 &&
1490 con
->http
.data_remaining
> MaxRequestSize
)
1493 * Request too large...
1496 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1497 return (cupsdCloseClient(con
));
1501 else if (con
->http
.data_remaining
< 0)
1504 * Negative content lengths are invalid!
1507 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
))
1508 return (cupsdCloseClient(con
));
1514 * Open a temporary file to hold the request...
1517 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
1519 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1521 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1522 "cupsdReadClient: %d REQUEST %s=%d", con
->http
.fd
,
1523 con
->filename
, con
->file
);
1527 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1528 return (cupsdCloseClient(con
));
1531 fchmod(con
->file
, 0640);
1532 fchown(con
->file
, RunUser
, Group
);
1533 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1538 cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
);
1539 return (cupsdCloseClient(con
));
1542 if (!strncmp(con
->uri
, "/printers/", 10) &&
1543 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1546 * Send PPD file - get the real printer name since printer
1547 * names are not case sensitive but filenames can be...
1550 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1552 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1553 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1556 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
1557 return (cupsdCloseClient(con
));
1563 if ((!strncmp(con
->uri
, "/admin", 6) &&
1564 strncmp(con
->uri
, "/admin/conf/", 12) &&
1565 strncmp(con
->uri
, "/admin/log/", 11)) ||
1566 !strncmp(con
->uri
, "/printers", 9) ||
1567 !strncmp(con
->uri
, "/classes", 8) ||
1568 !strncmp(con
->uri
, "/help", 5) ||
1569 !strncmp(con
->uri
, "/jobs", 5))
1575 if (!cupsdSendHeader(con
, HTTP_OK
, "text/html"))
1576 return (cupsdCloseClient(con
));
1578 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1579 return (cupsdCloseClient(con
));
1581 if (cupsdFlushHeader(con
) < 0)
1582 return (cupsdCloseClient(con
));
1584 cupsdLogRequest(con
, HTTP_OK
);
1586 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1587 (strchr(con
->uri
+ 12, '/') ||
1588 strlen(con
->uri
) == 12)) ||
1589 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1590 (strchr(con
->uri
+ 11, '/') ||
1591 strlen(con
->uri
) == 11)))
1594 * HEAD can only be done to configuration files under
1598 if (!cupsdSendError(con
, HTTP_FORBIDDEN
))
1599 return (cupsdCloseClient(con
));
1603 else if ((filename
= get_file(con
, &filestats
, buf
,
1604 sizeof(buf
))) == NULL
)
1606 if (!cupsdSendHeader(con
, HTTP_NOT_FOUND
, "text/html"))
1607 return (cupsdCloseClient(con
));
1609 cupsdLogRequest(con
, HTTP_NOT_FOUND
);
1611 else if (!check_if_modified(con
, &filestats
))
1613 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
))
1614 return (cupsdCloseClient(con
));
1616 cupsdLogRequest(con
, HTTP_NOT_MODIFIED
);
1624 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1626 strcpy(line
, "text/plain");
1628 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1630 if (!cupsdSendHeader(con
, HTTP_OK
, line
))
1631 return (cupsdCloseClient(con
));
1633 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
1634 httpGetDateString(filestats
.st_mtime
)) < 0)
1635 return (cupsdCloseClient(con
));
1637 if (httpPrintf(HTTP(con
), "Content-Length: %lu\r\n",
1638 (unsigned long)filestats
.st_size
) < 0)
1639 return (cupsdCloseClient(con
));
1641 cupsdLogRequest(con
, HTTP_OK
);
1644 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1645 return (cupsdCloseClient(con
));
1647 if (cupsdFlushHeader(con
) < 0)
1648 return (cupsdCloseClient(con
));
1650 con
->http
.state
= HTTP_WAITING
;
1654 break; /* Anti-compiler-warning-code */
1660 * Handle any incoming data...
1663 switch (con
->http
.state
)
1665 case HTTP_PUT_RECV
:
1666 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1667 "cupsdReadClient: %d con->data_encoding=HTTP_ENCODE_%s, "
1668 "con->data_remaining=" CUPS_LLFMT
", con->file=%d",
1670 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
?
1671 "CHUNKED" : "LENGTH",
1672 CUPS_LLCAST con
->http
.data_remaining
, con
->file
);
1674 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
1675 return (cupsdCloseClient(con
));
1678 con
->bytes
+= bytes
;
1680 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1681 "cupsdReadClient: %d writing %d bytes to %d",
1682 con
->http
.fd
, bytes
, con
->file
);
1684 if (write(con
->file
, line
, bytes
) < bytes
)
1686 cupsdLogMessage(CUPSD_LOG_ERROR
,
1687 "cupsdReadClient: Unable to write %d bytes to %s: %s",
1688 bytes
, con
->filename
, strerror(errno
));
1690 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1691 "cupsdReadClient: Closing data file %d...",
1696 unlink(con
->filename
);
1697 cupsdClearString(&con
->filename
);
1699 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1700 return (cupsdCloseClient(con
));
1704 if (con
->http
.state
== HTTP_WAITING
)
1707 * End of file, see how big it is...
1710 fstat(con
->file
, &filestats
);
1712 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1713 "cupsdReadClient: %d Closing data file %d, size="
1715 con
->http
.fd
, con
->file
,
1716 CUPS_LLCAST filestats
.st_size
);
1721 if (filestats
.st_size
> MaxRequestSize
&&
1725 * Request is too big; remove it and send an error...
1728 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1729 "cupsdReadClient: %d Removing temp file %s",
1730 con
->http
.fd
, con
->filename
);
1731 unlink(con
->filename
);
1732 cupsdClearString(&con
->filename
);
1734 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1735 return (cupsdCloseClient(con
));
1739 * Install the configuration file...
1742 status
= install_conf_file(con
);
1745 * Return the status to the client...
1748 if (!cupsdSendError(con
, status
))
1749 return (cupsdCloseClient(con
));
1753 case HTTP_POST_RECV
:
1754 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1755 "cupsdReadClient: %d con->data_encoding=HTTP_ENCODE_"
1756 "%s, con->data_remaining=" CUPS_LLFMT
", con->file=%d",
1758 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
?
1759 "CHUNKED" : "LENGTH",
1760 CUPS_LLCAST con
->http
.data_remaining
, con
->file
);
1765 * Grab any request data from the connection...
1768 if ((ipp_state
= ippRead(&(con
->http
), con
->request
)) == IPP_ERROR
)
1770 cupsdLogMessage(CUPSD_LOG_ERROR
,
1771 "cupsdReadClient: %d IPP Read Error!",
1774 cupsdSendError(con
, HTTP_BAD_REQUEST
);
1775 return (cupsdCloseClient(con
));
1777 else if (ipp_state
!= IPP_DATA
)
1779 if (con
->http
.state
== HTTP_POST_SEND
)
1781 cupsdSendError(con
, HTTP_BAD_REQUEST
);
1782 return (cupsdCloseClient(con
));
1788 con
->bytes
+= ippLength(con
->request
);
1791 if (con
->file
< 0 && con
->http
.state
!= HTTP_POST_SEND
)
1794 * Create a file as needed for the request data...
1797 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
, request_id
++);
1798 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1800 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdReadClient: %d REQUEST %s=%d", con
->http
.fd
,
1801 con
->filename
, con
->file
);
1805 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1806 return (cupsdCloseClient(con
));
1809 fchmod(con
->file
, 0640);
1810 fchown(con
->file
, RunUser
, Group
);
1811 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1814 if (con
->http
.state
!= HTTP_POST_SEND
)
1816 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
1817 return (cupsdCloseClient(con
));
1820 con
->bytes
+= bytes
;
1822 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1823 "cupsdReadClient: %d writing %d bytes to %d",
1824 con
->http
.fd
, bytes
, con
->file
);
1826 if (write(con
->file
, line
, bytes
) < bytes
)
1828 cupsdLogMessage(CUPSD_LOG_ERROR
,
1829 "cupsdReadClient: Unable to write %d bytes to %s: %s",
1830 bytes
, con
->filename
, strerror(errno
));
1832 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1833 "cupsdReadClient: Closing file %d...",
1838 unlink(con
->filename
);
1839 cupsdClearString(&con
->filename
);
1841 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1842 return (cupsdCloseClient(con
));
1845 else if (con
->http
.state
== HTTP_POST_RECV
)
1846 return (1); /* ??? */
1847 else if (con
->http
.state
!= HTTP_POST_SEND
)
1848 return (cupsdCloseClient(con
));
1851 if (con
->http
.state
== HTTP_POST_SEND
)
1855 fstat(con
->file
, &filestats
);
1857 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1858 "cupsdReadClient: %d Closing data file %d, "
1859 "size=" CUPS_LLFMT
".",
1860 con
->http
.fd
, con
->file
,
1861 CUPS_LLCAST filestats
.st_size
);
1866 if (filestats
.st_size
> MaxRequestSize
&&
1870 * Request is too big; remove it and send an error...
1873 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1874 "cupsdReadClient: %d Removing temp file %s",
1875 con
->http
.fd
, con
->filename
);
1876 unlink(con
->filename
);
1877 cupsdClearString(&con
->filename
);
1882 * Delete any IPP request data...
1885 ippDelete(con
->request
);
1886 con
->request
= NULL
;
1889 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1890 return (cupsdCloseClient(con
));
1895 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1897 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
1898 return (cupsdCloseClient(con
));
1901 cupsdLogRequest(con
, HTTP_OK
);
1906 return (cupsdProcessIPPRequest(con
));
1911 break; /* Anti-compiler-warning-code */
1914 if (!con
->http
.keep_alive
&& con
->http
.state
== HTTP_WAITING
)
1915 return (cupsdCloseClient(con
));
1922 * 'cupsdSendCommand()' - Send output from a command via HTTP.
1925 int /* O - 1 on success, 0 on failure */
1927 cupsd_client_t
*con
, /* I - Client connection */
1928 char *command
, /* I - Command to run */
1929 char *options
, /* I - Command-line options */
1930 int root
) /* I - Run as root? */
1932 int fd
; /* Standard input file descriptor */
1937 fd
= open(con
->filename
, O_RDONLY
);
1941 cupsdLogMessage(CUPSD_LOG_ERROR
,
1942 "cupsdSendCommand: %d Unable to open \"%s\" for reading: %s",
1943 con
->http
.fd
, con
->filename
? con
->filename
: "/dev/null",
1948 fcntl(fd
, F_SETFD
, fcntl(fd
, F_GETFD
) | FD_CLOEXEC
);
1953 con
->pipe_pid
= pipe_command(con
, fd
, &(con
->file
), command
, options
, root
);
1958 cupsdLogMessage(CUPSD_LOG_INFO
, "Started \"%s\" (pid=%d)", command
,
1961 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendCommand: %d file=%d",
1962 con
->http
.fd
, con
->file
);
1964 if (con
->pipe_pid
== 0)
1967 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1969 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1970 "cupsdSendCommand: Adding fd %d to InputSet...", con
->file
);
1971 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1972 "cupsdSendCommand: Adding fd %d to OutputSet...",
1975 FD_SET(con
->file
, InputSet
);
1976 FD_SET(con
->http
.fd
, OutputSet
);
1978 con
->sent_header
= 0;
1979 con
->file_ready
= 0;
1980 con
->got_fields
= 0;
1988 * 'cupsdSendError()' - Send an error message via HTTP.
1991 int /* O - 1 if successful, 0 otherwise */
1992 cupsdSendError(cupsd_client_t
*con
, /* I - Connection */
1993 http_status_t code
) /* I - Error code */
1997 * Force client to upgrade for authentication if that is how the
1998 * server is configured...
2001 if (code
== HTTP_UNAUTHORIZED
&&
2002 DefaultEncryption
== HTTP_ENCRYPT_REQUIRED
&&
2003 strcasecmp(con
->http
.hostname
, "localhost") &&
2006 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2007 "cupsdSendError: Encryption before authentication!");
2008 code
= HTTP_UPGRADE_REQUIRED
;
2010 #endif /* HAVE_SSL */
2013 * Put the request in the access_log file...
2016 cupsdLogRequest(con
, code
);
2018 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendError: %d code=%d (%s)",
2019 con
->http
.fd
, code
, httpStatus(code
));
2022 * To work around bugs in some proxies, don't use Keep-Alive for some
2026 if (code
>= HTTP_BAD_REQUEST
)
2027 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
2030 * Send an error message back to the client. If the error code is a
2031 * 400 or 500 series, make sure the message contains some text, too!
2034 if (!cupsdSendHeader(con
, code
, NULL
))
2038 if (code
== HTTP_UPGRADE_REQUIRED
)
2039 if (httpPrintf(HTTP(con
), "Connection: Upgrade\r\n") < 0)
2042 if (httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n") < 0)
2044 #endif /* HAVE_SSL */
2046 if ((con
->http
.version
>= HTTP_1_1
&& !con
->http
.keep_alive
) ||
2047 (code
>= HTTP_BAD_REQUEST
&& code
!= HTTP_UPGRADE_REQUIRED
))
2049 if (httpPrintf(HTTP(con
), "Connection: close\r\n") < 0)
2053 if (code
>= HTTP_BAD_REQUEST
)
2056 * Send a human-readable error message.
2059 char message
[4096], /* Message for user */
2060 urltext
[1024], /* URL redirection text */
2061 redirect
[1024]; /* Redirection link */
2062 const char *text
; /* Status-specific text */
2067 if (code
== HTTP_UNAUTHORIZED
)
2068 text
= _cupsLangString(con
->language
,
2069 _("Enter your username and password or the "
2070 "root username and password to access this "
2072 else if (code
== HTTP_UPGRADE_REQUIRED
)
2076 snprintf(urltext
, sizeof(urltext
),
2077 _cupsLangString(con
->language
,
2078 _("You must access this page using the URL "
2079 "<A HREF=\"https://%s:%d%s\">"
2080 "https://%s:%d%s</A>.")),
2081 con
->servername
, con
->serverport
, con
->uri
,
2082 con
->servername
, con
->serverport
, con
->uri
);
2084 snprintf(redirect
, sizeof(redirect
),
2085 "<META HTTP-EQUIV=\"Refresh\" CONTENT=\"3;https://%s:%d%s\">\n",
2086 con
->servername
, con
->serverport
, con
->uri
);
2091 snprintf(message
, sizeof(message
),
2092 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" "
2093 "\"http://www.w3.org/TR/REC-html40/loose.dtd\">\n"
2096 "\t<META HTTP-EQUIV=\"Content-Type\" "
2097 "CONTENT=\"text/html; charset=utf-8\">\n"
2098 "\t<TITLE>%d %s</TITLE>\n"
2099 "\t<LINK REL=\"STYLESHEET\" TYPE=\"text/css\" "
2100 "HREF=\"/cups.css\">\n"
2108 code
, httpStatus(code
), redirect
, code
, httpStatus(code
), text
);
2110 if (httpPrintf(HTTP(con
), "Content-Type: text/html; charset=utf-8\r\n") < 0)
2112 if (httpPrintf(HTTP(con
), "Content-Length: %d\r\n",
2113 (int)strlen(message
)) < 0)
2115 if (httpPrintf(HTTP(con
), "\r\n") < 0)
2117 if (httpPrintf(HTTP(con
), "%s", message
) < 0)
2120 else if (httpPrintf(HTTP(con
), "\r\n") < 0)
2123 if (cupsdFlushHeader(con
) < 0)
2126 con
->http
.state
= HTTP_WAITING
;
2133 * 'cupsdSendHeader()' - Send an HTTP request.
2136 int /* O - 1 on success, 0 on failure */
2137 cupsdSendHeader(cupsd_client_t
*con
, /* I - Client to send to */
2138 http_status_t code
, /* I - HTTP status code */
2139 char *type
) /* I - MIME type of document */
2142 * Send the HTTP status header...
2145 if (code
== HTTP_CONTINUE
)
2148 * 100-continue doesn't send any headers...
2151 return (httpPrintf(HTTP(con
), "HTTP/%d.%d 100 Continue\r\n\r\n",
2152 con
->http
.version
/ 100, con
->http
.version
% 100) > 0);
2155 httpFlushWrite(HTTP(con
));
2157 con
->http
.data_encoding
= HTTP_ENCODE_FIELDS
;
2159 if (httpPrintf(HTTP(con
), "HTTP/%d.%d %d %s\r\n", con
->http
.version
/ 100,
2160 con
->http
.version
% 100, code
, httpStatus(code
)) < 0)
2162 if (httpPrintf(HTTP(con
), "Date: %s\r\n", httpGetDateString(time(NULL
))) < 0)
2165 if (httpPrintf(HTTP(con
), "Server: %s\r\n", ServerHeader
) < 0)
2167 if (con
->http
.keep_alive
&& con
->http
.version
>= HTTP_1_0
)
2169 if (httpPrintf(HTTP(con
), "Connection: Keep-Alive\r\n") < 0)
2171 if (httpPrintf(HTTP(con
), "Keep-Alive: timeout=%d\r\n",
2172 KeepAliveTimeout
) < 0)
2175 if (code
== HTTP_METHOD_NOT_ALLOWED
)
2176 if (httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST\r\n") < 0)
2179 if (code
== HTTP_UNAUTHORIZED
)
2181 int auth_type
; /* Authentication type */
2184 if (!con
->best
|| con
->best
->type
== AUTH_NONE
)
2185 auth_type
= DefaultAuthType
;
2187 auth_type
= con
->best
->type
;
2189 if (auth_type
!= AUTH_DIGEST
)
2191 if (httpPrintf(HTTP(con
),
2192 "WWW-Authenticate: Basic realm=\"CUPS\"\r\n") < 0)
2197 if (httpPrintf(HTTP(con
),
2198 "WWW-Authenticate: Digest realm=\"CUPS\", nonce=\"%s\"\r\n",
2199 con
->http
.hostname
) < 0)
2204 if (con
->language
&& strcmp(con
->language
->language
, "C"))
2206 if (httpPrintf(HTTP(con
), "Content-Language: %s\r\n",
2207 con
->language
->language
) < 0)
2213 if (!strcmp(type
, "text/html"))
2215 if (httpPrintf(HTTP(con
),
2216 "Content-Type: text/html; charset=utf-8\r\n") < 0)
2219 else if (httpPrintf(HTTP(con
), "Content-Type: %s\r\n", type
) < 0)
2228 * 'cupsdUpdateCGI()' - Read status messages from CGI scripts and programs.
2232 cupsdUpdateCGI(void)
2234 char *ptr
, /* Pointer to end of line in buffer */
2235 message
[1024]; /* Pointer to message text */
2236 int loglevel
; /* Log level for message */
2239 while ((ptr
= cupsdStatBufUpdate(CGIStatusBuffer
, &loglevel
,
2240 message
, sizeof(message
))) != NULL
)
2241 if (!strchr(CGIStatusBuffer
->buffer
, '\n'))
2244 if (ptr
== NULL
&& !CGIStatusBuffer
->bufused
)
2247 * Fatal error on pipe - should never happen!
2250 cupsdLogMessage(CUPSD_LOG_CRIT
,
2251 "cupsdUpdateCGI: error reading from CGI error pipe - %s",
2258 * 'cupsdWriteClient()' - Write data to a client as needed.
2261 int /* O - 1 if success, 0 if fail */
2262 cupsdWriteClient(cupsd_client_t
*con
) /* I - Client connection */
2264 int bytes
; /* Number of bytes written */
2265 char buf
[16385]; /* Data buffer */
2266 char *bufptr
; /* Pointer into buffer */
2267 ipp_state_t ipp_state
; /* IPP state value */
2271 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2272 "cupsdWriteClient(con=%p) %d response=%p, file=%d "
2273 "pipe_pid=%d state=%d",
2274 con
, con
->http
.fd
, con
->response
, con
->file
, con
->pipe_pid
,
2278 if (con
->http
.state
!= HTTP_GET_SEND
&&
2279 con
->http
.state
!= HTTP_POST_SEND
)
2284 ipp_state
= ippWrite(HTTP(con
), con
->response
);
2285 bytes
= ipp_state
!= IPP_ERROR
&& ipp_state
!= IPP_DATA
;
2287 else if ((bytes
= read(con
->file
, buf
, sizeof(buf
) - 1)) > 0)
2289 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2290 "cupsdWriteClient: Read %d bytes from file %d...",
2293 if (con
->pipe_pid
&& !con
->got_fields
)
2296 * Inspect the data for Content-Type and other fields.
2301 for (bufptr
= buf
; !con
->got_fields
&& *bufptr
; bufptr
++)
2302 if (*bufptr
== '\n')
2305 * Send line to client...
2308 if (bufptr
> buf
&& bufptr
[-1] == '\r')
2312 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "Script header: %s", buf
);
2314 if (!con
->sent_header
)
2317 * Handle redirection and CGI status codes...
2320 if (!strncasecmp(buf
, "Location:", 9))
2322 cupsdSendHeader(con
, HTTP_SEE_OTHER
, NULL
);
2323 con
->sent_header
= 2;
2325 if (httpPrintf(HTTP(con
), "Content-Length: 0\r\n") < 0)
2328 else if (!strncasecmp(buf
, "Status:", 7))
2330 cupsdSendError(con
, (http_status_t
)atoi(buf
+ 7));
2331 con
->sent_header
= 2;
2335 cupsdSendHeader(con
, HTTP_OK
, NULL
);
2336 con
->sent_header
= 1;
2338 if (con
->http
.version
== HTTP_1_1
)
2340 if (httpPrintf(HTTP(con
), "Transfer-Encoding: chunked\r\n") < 0)
2346 if (strncasecmp(buf
, "Status:", 7))
2347 httpPrintf(HTTP(con
), "%s\r\n", buf
);
2349 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdWriteClient: %d %s",
2356 bytes
-= (bufptr
- buf
);
2357 memmove(buf
, bufptr
, bytes
+ 1);
2361 * See if the line was empty...
2364 if (con
->field_col
== 0)
2366 con
->got_fields
= 1;
2368 if (cupsdFlushHeader(con
) < 0)
2370 cupsdCloseClient(con
);
2374 if (con
->http
.version
== HTTP_1_1
)
2375 con
->http
.data_encoding
= HTTP_ENCODE_CHUNKED
;
2380 else if (*bufptr
!= '\r')
2383 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2384 "cupsdWriteClient: %d bytes=%d, got_fields=%d",
2385 con
->http
.fd
, bytes
, con
->got_fields
);
2387 if (bytes
> 0 && !con
->got_fields
)
2390 * Remaining text needs to go out...
2393 httpPrintf(HTTP(con
), "%s", buf
);
2395 con
->http
.activity
= time(NULL
);
2398 else if (bytes
== 0)
2399 con
->http
.activity
= time(NULL
);
2404 if (httpWrite2(HTTP(con
), buf
, bytes
) < 0)
2406 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2407 "cupsdWriteClient: %d Write of %d bytes failed!",
2408 con
->http
.fd
, bytes
);
2410 cupsdCloseClient(con
);
2414 con
->bytes
+= bytes
;
2416 if (con
->http
.state
== HTTP_WAITING
)
2423 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdWriteClient: %d bytes < 0",
2426 cupsdLogRequest(con
, HTTP_OK
);
2428 httpFlushWrite(HTTP(con
));
2430 if (con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
&& con
->sent_header
== 1)
2432 if (httpWrite2(HTTP(con
), "", 0) < 0)
2434 cupsdCloseClient(con
);
2439 con
->http
.state
= HTTP_WAITING
;
2441 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2442 "cupsdWriteClient: Removing fd %d from OutputSet...",
2445 FD_CLR(con
->http
.fd
, OutputSet
);
2449 if (FD_ISSET(con
->file
, InputSet
))
2451 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2452 "cupsdWriteClient: Removing fd %d from InputSet...",
2454 FD_CLR(con
->file
, InputSet
);
2458 cupsdEndProcess(con
->pipe_pid
, 0);
2460 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2461 "cupsdWriteClient: %d Closing data file %d.",
2462 con
->http
.fd
, con
->file
);
2471 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2472 "cupsdWriteClient: %d Removing temp file %s",
2473 con
->http
.fd
, con
->filename
);
2474 unlink(con
->filename
);
2475 cupsdClearString(&con
->filename
);
2480 ippDelete(con
->request
);
2481 con
->request
= NULL
;
2486 ippDelete(con
->response
);
2487 con
->response
= NULL
;
2490 cupsdClearString(&con
->command
);
2491 cupsdClearString(&con
->options
);
2493 if (!con
->http
.keep_alive
)
2495 cupsdCloseClient(con
);
2501 con
->file_ready
= 0;
2503 if (con
->pipe_pid
&& !FD_ISSET(con
->file
, InputSet
))
2505 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2506 "cupsdWriteClient: Adding fd %d to InputSet...",
2508 FD_SET(con
->file
, InputSet
);
2512 con
->http
.activity
= time(NULL
);
2519 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
2522 static int /* O - 1 if modified since */
2524 cupsd_client_t
*con
, /* I - Client connection */
2525 struct stat
*filestats
) /* I - File information */
2527 char *ptr
; /* Pointer into field */
2528 time_t date
; /* Time/date value */
2529 off_t size
; /* Size/length value */
2534 ptr
= con
->http
.fields
[HTTP_FIELD_IF_MODIFIED_SINCE
];
2539 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2540 "check_if_modified: %d If-Modified-Since=\"%s\"",
2543 while (*ptr
!= '\0')
2545 while (isspace(*ptr
) || *ptr
== ';')
2548 if (strncasecmp(ptr
, "length=", 7) == 0)
2551 size
= strtoll(ptr
, NULL
, 10);
2553 while (isdigit(*ptr
))
2556 else if (isalpha(*ptr
))
2558 date
= httpGetDateTime(ptr
);
2559 while (*ptr
!= '\0' && *ptr
!= ';')
2566 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2567 "check_if_modified: %d sizes=" CUPS_LLFMT
","
2568 CUPS_LLFMT
" dates=%d,%d",
2569 con
->http
.fd
, CUPS_LLCAST size
,
2570 CUPS_LLCAST filestats
->st_size
, (int)date
,
2571 (int)filestats
->st_mtime
);
2573 return ((size
!= filestats
->st_size
&& size
!= 0) ||
2574 (date
< filestats
->st_mtime
&& date
!= 0) ||
2575 (size
== 0 && date
== 0));
2581 * 'encrypt_client()' - Enable encryption for the client...
2584 static int /* O - 1 on success, 0 on error */
2585 encrypt_client(cupsd_client_t
*con
) /* I - Client to encrypt */
2588 SSL_CTX
*context
; /* Context for encryption */
2589 SSL
*conn
; /* Connection for encryption */
2590 unsigned long error
; /* Error code */
2594 * Verify that we have a certificate...
2597 if (access(ServerKey
, 0) || access(ServerCertificate
, 0))
2600 * Nope, make a self-signed certificate...
2603 if (!make_certificate())
2608 * Create the SSL context and accept the connection...
2611 context
= SSL_CTX_new(SSLv23_server_method());
2613 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
2614 SSL_CTX_use_PrivateKey_file(context
, ServerKey
, SSL_FILETYPE_PEM
);
2615 SSL_CTX_use_certificate_file(context
, ServerCertificate
, SSL_FILETYPE_PEM
);
2617 conn
= SSL_new(context
);
2619 SSL_set_fd(conn
, con
->http
.fd
);
2620 if (SSL_accept(conn
) != 1)
2622 cupsdLogMessage(CUPSD_LOG_ERROR
,
2623 "encrypt_client: Unable to encrypt connection from %s!",
2624 con
->http
.hostname
);
2626 while ((error
= ERR_get_error()) != 0)
2627 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s",
2628 ERR_error_string(error
, NULL
));
2630 SSL_CTX_free(context
);
2635 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2636 "encrypt_client: %d Connection from %s now encrypted.",
2637 con
->http
.fd
, con
->http
.hostname
);
2639 con
->http
.tls
= conn
;
2642 # elif defined(HAVE_GNUTLS)
2643 http_tls_t
*conn
; /* TLS session object */
2644 int error
; /* Error code */
2645 gnutls_certificate_server_credentials
*credentials
;
2646 /* TLS credentials */
2650 * Verify that we have a certificate...
2653 if (access(ServerKey
, 0) || access(ServerCertificate
, 0))
2656 * Nope, make a self-signed certificate...
2659 if (!make_certificate())
2664 * Create the SSL object and perform the SSL handshake...
2667 conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
));
2672 credentials
= (gnutls_certificate_server_credentials
*)
2673 malloc(sizeof(gnutls_certificate_server_credentials
));
2674 if (credentials
== NULL
)
2676 cupsdLogMessage(CUPSD_LOG_ERROR
,
2677 "encrypt_client: Unable to encrypt connection from %s!",
2678 con
->http
.hostname
);
2679 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s", strerror(errno
));
2685 gnutls_certificate_allocate_credentials(credentials
);
2686 gnutls_certificate_set_x509_key_file(*credentials
, ServerCertificate
,
2687 ServerKey
, GNUTLS_X509_FMT_PEM
);
2689 gnutls_init(&(conn
->session
), GNUTLS_SERVER
);
2690 gnutls_set_default_priority(conn
->session
);
2691 gnutls_credentials_set(conn
->session
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
2692 gnutls_transport_set_ptr(conn
->session
,
2693 (gnutls_transport_ptr
)((long)con
->http
.fd
));
2695 error
= gnutls_handshake(conn
->session
);
2697 if (error
!= GNUTLS_E_SUCCESS
)
2699 cupsdLogMessage(CUPSD_LOG_ERROR
,
2700 "encrypt_client: Unable to encrypt connection from %s!",
2701 con
->http
.hostname
);
2702 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s",
2703 gnutls_strerror(error
));
2705 gnutls_deinit(conn
->session
);
2706 gnutls_certificate_free_credentials(*credentials
);
2712 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2713 "encrypt_client: %d Connection from %s now encrypted.",
2714 con
->http
.fd
, con
->http
.hostname
);
2716 conn
->credentials
= credentials
;
2717 con
->http
.tls
= conn
;
2720 # elif defined(HAVE_CDSASSL)
2721 OSStatus error
; /* Error code */
2722 http_tls_t
*conn
; /* CDSA connection information */
2723 cdsa_conn_ref_t u
; /* Connection reference union */
2726 if ((conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
))) == NULL
)
2730 conn
->session
= NULL
;
2731 conn
->certsArray
= get_cdsa_server_certs();
2733 if (!conn
->certsArray
)
2736 * No keychain (yet), make a self-signed certificate...
2739 if (make_certificate())
2740 conn
->certsArray
= get_cdsa_server_certs();
2743 if (!conn
->certsArray
)
2745 cupsdLogMessage(CUPSD_LOG_ERROR
,
2746 "EncryptClient: Could not find signing key in keychain "
2747 "\"%s\"", ServerCertificate
);
2748 error
= errSSLBadCert
; /* errSSLBadConfiguration is a better choice, but not available on 10.2.x */
2752 error
= SSLNewContext(true, &conn
->session
);
2755 error
= SSLSetIOFuncs(conn
->session
, _httpReadCDSA
, _httpWriteCDSA
);
2758 error
= SSLSetProtocolVersionEnabled(conn
->session
, kSSLProtocol2
, false);
2763 * Use a union to resolve warnings about int/pointer size mismatches...
2766 u
.connection
= NULL
;
2767 u
.sock
= con
->http
.fd
;
2768 error
= SSLSetConnection(conn
->session
, u
.connection
);
2772 error
= SSLSetAllowsExpiredCerts(conn
->session
, true);
2775 error
= SSLSetAllowsAnyRoot(conn
->session
, true);
2778 error
= SSLSetCertificate(conn
->session
, conn
->certsArray
);
2783 * Perform SSL/TLS handshake
2786 while ((error
= SSLHandshake(conn
->session
)) == errSSLWouldBlock
)
2792 cupsdLogMessage(CUPSD_LOG_ERROR
,
2793 "encrypt_client: Unable to encrypt connection from %s!",
2794 con
->http
.hostname
);
2796 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s (%d)",
2797 cssmErrorString(error
), (int)error
);
2799 con
->http
.error
= error
;
2800 con
->http
.status
= HTTP_ERROR
;
2803 SSLDisposeContext(conn
->session
);
2805 if (conn
->certsArray
)
2806 CFRelease(conn
->certsArray
);
2813 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2814 "encrypt_client: %d Connection from %s now encrypted.",
2815 con
->http
.fd
, con
->http
.hostname
);
2817 con
->http
.tls
= conn
;
2820 # endif /* HAVE_LIBSSL */
2822 #endif /* HAVE_SSL */
2827 * 'get_cdsa_server_certs()' - Convert a keychain name into the CFArrayRef
2828 * required by SSLSetCertificate.
2830 * For now we assumes that there is exactly one SecIdentity in the
2831 * keychain - i.e. there is exactly one matching cert/private key pair.
2832 * In the future we will search a keychain for a SecIdentity matching a
2833 * specific criteria. We also skip the operation of adding additional
2834 * non-signing certs from the keychain to the CFArrayRef.
2836 * To create a self-signed certificate for testing use the certtool.
2837 * Executing the following as root will do it:
2839 * certtool c k=/Library/Keychains/System.keychain
2842 static CFArrayRef
/* O - Array of certificates */
2843 get_cdsa_server_certs(void)
2845 OSStatus err
; /* Error info */
2846 SecKeychainRef kcRef
; /* Keychain reference */
2847 SecIdentitySearchRef srchRef
; /* Search reference */
2848 SecIdentityRef identity
; /* Identity */
2849 CFArrayRef ca
; /* Certificate array */
2856 err
= SecKeychainOpen(ServerCertificate
, &kcRef
);
2859 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot open keychain \"%s\", error %d.",
2860 ServerCertificate
, (int)err
);
2864 * Search for "any" identity matching specified key use;
2865 * in this app, we expect there to be exactly one.
2868 err
= SecIdentitySearchCreate(kcRef
, CSSM_KEYUSE_SIGN
, &srchRef
);
2871 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2872 "Cannot find signing key in keychain \"%s\", error %d",
2873 ServerCertificate
, (int)err
);
2876 err
= SecIdentitySearchCopyNext(srchRef
, &identity
);
2879 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2880 "Cannot find signing key in keychain \"%s\", error %d",
2881 ServerCertificate
, (int)err
);
2884 if (CFGetTypeID(identity
) != SecIdentityGetTypeID())
2885 cupsdLogMessage(CUPSD_LOG_ERROR
,
2886 "SecIdentitySearchCopyNext CFTypeID failure!");
2890 * Found one. Place it in a CFArray.
2891 * TBD: snag other (non-identity) certs from keychain and add them
2895 ca
= CFArrayCreate(NULL
, (const void **)&identity
, 1, &kCFTypeArrayCallBacks
);
2898 cupsdLogMessage(CUPSD_LOG_ERROR
, "CFArrayCreate error");
2901 CFRelease(identity
);
2912 #endif /* HAVE_CDSASSL */
2916 * 'get_file()' - Get a filename and state info.
2919 static char * /* O - Real filename */
2920 get_file(cupsd_client_t
*con
, /* I - Client connection */
2921 struct stat
*filestats
, /* O - File information */
2922 char *filename
, /* IO - Filename buffer */
2923 int len
) /* I - Buffer length */
2925 int status
; /* Status of filesystem calls */
2926 char *ptr
; /* Pointer info filename */
2927 int plen
; /* Remaining length after pointer */
2931 * Need to add DocumentRoot global...
2934 if (!strncmp(con
->uri
, "/ppd/", 5))
2935 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
);
2936 else if (!strncmp(con
->uri
, "/admin/conf/", 12))
2937 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
+ 11);
2938 else if (!strncmp(con
->uri
, "/admin/log/", 11))
2940 if (!strcmp(con
->uri
+ 11, "access_log") && AccessLog
[0] == '/')
2941 strlcpy(filename
, AccessLog
, len
);
2942 else if (!strcmp(con
->uri
+ 11, "error_log") && ErrorLog
[0] == '/')
2943 strlcpy(filename
, ErrorLog
, len
);
2944 else if (!strcmp(con
->uri
+ 11, "page_log") && PageLog
[0] == '/')
2945 strlcpy(filename
, PageLog
, len
);
2949 else if (con
->language
)
2950 snprintf(filename
, len
, "%s/%s%s", DocumentRoot
, con
->language
->language
,
2953 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
2955 if ((ptr
= strchr(filename
, '?')) != NULL
)
2959 * Grab the status for this language; if there isn't a language-specific file
2960 * then fallback to the default one...
2963 if ((status
= stat(filename
, filestats
)) != 0 && con
->language
&&
2964 strncmp(con
->uri
, "/ppd/", 5) &&
2965 strncmp(con
->uri
, "/admin/conf/", 12) &&
2966 strncmp(con
->uri
, "/admin/log/", 11))
2969 * Drop the country code...
2972 char ll
[3]; /* Short language name */
2975 strlcpy(ll
, con
->language
->language
, sizeof(ll
));
2976 snprintf(filename
, len
, "%s/%s%s", DocumentRoot
, ll
, con
->uri
);
2978 if ((ptr
= strchr(filename
, '?')) != NULL
)
2981 if ((status
= stat(filename
, filestats
)) != 0)
2984 * Drop the language prefix and try the root directory...
2987 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
2989 if ((ptr
= strchr(filename
, '?')) != NULL
)
2992 status
= stat(filename
, filestats
);
2997 * If we're found a directory, get the index.html file instead...
3000 if (!status
&& S_ISDIR(filestats
->st_mode
))
3002 if (filename
[strlen(filename
) - 1] != '/')
3003 strlcat(filename
, "/", len
);
3005 ptr
= filename
+ strlen(filename
);
3006 plen
= len
- (ptr
- filename
);
3008 strlcpy(ptr
, "index.html", plen
);
3009 status
= stat(filename
, filestats
);
3014 strlcpy(ptr
, "index.class", plen
);
3015 status
= stat(filename
, filestats
);
3017 #endif /* HAVE_JAVA */
3022 strlcpy(ptr
, "index.pl", plen
);
3023 status
= stat(filename
, filestats
);
3025 #endif /* HAVE_PERL */
3030 strlcpy(ptr
, "index.php", plen
);
3031 status
= stat(filename
, filestats
);
3033 #endif /* HAVE_PHP */
3038 strlcpy(ptr
, "index.pyc", plen
);
3039 status
= stat(filename
, filestats
);
3044 strlcpy(ptr
, "index.py", plen
);
3045 status
= stat(filename
, filestats
);
3047 #endif /* HAVE_PYTHON */
3050 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "get_file: %d filename=%s size=%d",
3051 con
->http
.fd
, filename
,
3052 status
? -1 : (int)filestats
->st_size
);
3055 con
->http
.data_remaining
= (int)filestats
->st_size
;
3065 * 'install_conf_file()' - Install a configuration file.
3068 static http_status_t
/* O - Status */
3069 install_conf_file(cupsd_client_t
*con
) /* I - Connection */
3071 cups_file_t
*in
, /* Input file */
3072 *out
; /* Output file */
3073 char buffer
[1024]; /* Copy buffer */
3074 int bytes
; /* Number of bytes */
3075 char conffile
[1024], /* Configuration filename */
3076 newfile
[1024], /* New config filename */
3077 oldfile
[1024]; /* Old config filename */
3078 struct stat confinfo
; /* Config file info */
3082 * First construct the filenames...
3085 snprintf(conffile
, sizeof(conffile
), "%s%s", ServerRoot
, con
->uri
+ 11);
3086 snprintf(newfile
, sizeof(newfile
), "%s%s.N", ServerRoot
, con
->uri
+ 11);
3087 snprintf(oldfile
, sizeof(oldfile
), "%s%s.O", ServerRoot
, con
->uri
+ 11);
3089 cupsdLogMessage(CUPSD_LOG_INFO
, "Installing config file \"%s\"...", conffile
);
3092 * Get the owner, group, and permissions of the configuration file.
3093 * If it doesn't exist, assign it to the User and Group in the
3094 * cupsd.conf file with mode 0640 permissions.
3097 if (stat(conffile
, &confinfo
))
3099 confinfo
.st_uid
= User
;
3100 confinfo
.st_gid
= Group
;
3101 confinfo
.st_mode
= ConfigFilePerm
;
3105 * Open the request file and new config file...
3108 if ((in
= cupsFileOpen(con
->filename
, "rb")) == NULL
)
3110 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open request file \"%s\" - %s",
3111 con
->filename
, strerror(errno
));
3112 return (HTTP_SERVER_ERROR
);
3115 if ((out
= cupsFileOpen(newfile
, "wb")) == NULL
)
3118 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open config file \"%s\" - %s",
3119 newfile
, strerror(errno
));
3120 return (HTTP_SERVER_ERROR
);
3123 fchmod(cupsFileNumber(out
), confinfo
.st_mode
);
3124 fchown(cupsFileNumber(out
), confinfo
.st_uid
, confinfo
.st_gid
);
3127 * Copy from the request to the new config file...
3130 while ((bytes
= cupsFileRead(in
, buffer
, sizeof(buffer
))) > 0)
3131 if (cupsFileWrite(out
, buffer
, bytes
) < bytes
)
3133 cupsdLogMessage(CUPSD_LOG_ERROR
,
3134 "Unable to copy to config file \"%s\" - %s",
3135 newfile
, strerror(errno
));
3141 return (HTTP_SERVER_ERROR
);
3145 * Close the files...
3149 if (cupsFileClose(out
))
3151 cupsdLogMessage(CUPSD_LOG_ERROR
,
3152 "Error file closing config file \"%s\" - %s",
3153 newfile
, strerror(errno
));
3157 return (HTTP_SERVER_ERROR
);
3161 * Remove the request file...
3164 unlink(con
->filename
);
3165 cupsdClearString(&con
->filename
);
3168 * Unlink the old backup, rename the current config file to the backup
3169 * filename, and rename the new config file to the config file name...
3172 if (unlink(oldfile
))
3173 if (errno
!= ENOENT
)
3175 cupsdLogMessage(CUPSD_LOG_ERROR
,
3176 "Unable to remove backup config file \"%s\" - %s",
3177 oldfile
, strerror(errno
));
3181 return (HTTP_SERVER_ERROR
);
3184 if (rename(conffile
, oldfile
))
3185 if (errno
!= ENOENT
)
3187 cupsdLogMessage(CUPSD_LOG_ERROR
,
3188 "Unable to rename old config file \"%s\" - %s",
3189 conffile
, strerror(errno
));
3193 return (HTTP_SERVER_ERROR
);
3196 if (rename(newfile
, conffile
))
3198 cupsdLogMessage(CUPSD_LOG_ERROR
,
3199 "Unable to rename new config file \"%s\" - %s",
3200 newfile
, strerror(errno
));
3202 rename(oldfile
, conffile
);
3205 return (HTTP_SERVER_ERROR
);
3209 * If the cupsd.conf file was updated, set the NeedReload flag...
3212 if (!strcmp(con
->uri
, "/admin/conf/cupsd.conf"))
3213 NeedReload
= RELOAD_CUPSD
;
3215 NeedReload
= RELOAD_ALL
;
3217 ReloadTime
= time(NULL
);
3220 * Return that the file was created successfully...
3223 return (HTTP_CREATED
);
3228 * 'is_cgi()' - Is the resource a CGI script/program?
3231 static int /* O - 1 = CGI, 0 = file */
3232 is_cgi(cupsd_client_t
*con
, /* I - Client connection */
3233 const char *filename
, /* I - Real filename */
3234 struct stat
*filestats
, /* I - File information */
3235 mime_type_t
*type
) /* I - MIME type */
3237 const char *options
; /* Options on URL */
3240 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3241 "is_cgi(con=%p, filename=\"%s\", filestats=%p, type=%s/%s)\n",
3242 con
, filename
, filestats
, type
? type
->super
: "unknown",
3243 type
? type
->type
: "unknown");
3246 * Get the options, if any...
3249 if ((options
= strchr(con
->uri
, '?')) != NULL
)
3253 * Check for known types...
3256 if (!type
|| strcasecmp(type
->super
, "application"))
3258 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "is_cgi: Returning 0...");
3262 if (!strcasecmp(type
->type
, "x-httpd-cgi") &&
3263 (filestats
->st_mode
& 0111))
3266 * "application/x-httpd-cgi" is a CGI script.
3269 cupsdSetString(&con
->command
, filename
);
3271 filename
= strrchr(filename
, '/') + 1; /* Filename always absolute */
3273 cupsdSetString(&con
->options
, options
);
3275 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3276 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3277 con
->command
, con
->options
);
3282 else if (!strcasecmp(type
->type
, "x-httpd-java"))
3285 * "application/x-httpd-java" is a Java servlet.
3288 cupsdSetString(&con
->command
, CUPS_JAVA
);
3291 cupsdSetStringf(&con
->options
, "%s %s", filename
, options
);
3293 cupsdSetString(&con
->options
, filename
);
3295 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3296 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3297 con
->command
, con
->options
);
3301 #endif /* HAVE_JAVA */
3303 else if (!strcasecmp(type
->type
, "x-httpd-perl"))
3306 * "application/x-httpd-perl" is a Perl page.
3309 cupsdSetString(&con
->command
, CUPS_PERL
);
3312 cupsdSetStringf(&con
->options
, "%s %s", filename
, options
);
3314 cupsdSetString(&con
->options
, filename
);
3316 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3317 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3318 con
->command
, con
->options
);
3322 #endif /* HAVE_PERL */
3324 else if (!strcasecmp(type
->type
, "x-httpd-php"))
3327 * "application/x-httpd-php" is a PHP page.
3330 cupsdSetString(&con
->command
, CUPS_PHP
);
3333 cupsdSetStringf(&con
->options
, "%s %s", filename
, options
);
3335 cupsdSetString(&con
->options
, filename
);
3337 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3338 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3339 con
->command
, con
->options
);
3343 #endif /* HAVE_PHP */
3345 else if (!strcasecmp(type
->type
, "x-httpd-python"))
3348 * "application/x-httpd-python" is a Python page.
3351 cupsdSetString(&con
->command
, CUPS_PYTHON
);
3354 cupsdSetStringf(&con
->options
, "%s %s", filename
, options
);
3356 cupsdSetString(&con
->options
, filename
);
3358 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3359 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3360 con
->command
, con
->options
);
3364 #endif /* HAVE_PYTHON */
3366 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "is_cgi: Returning 0...");
3373 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
3376 static int /* O - 0 if relative, 1 if absolute */
3377 is_path_absolute(const char *path
) /* I - Input path */
3380 * Check for a leading slash...
3387 * Check for "/.." in the path...
3390 while ((path
= strstr(path
, "/..")) != NULL
)
3392 if (!path
[3] || path
[3] == '/')
3399 * If we haven't found any relative paths, return 1 indicating an
3409 * 'make_certificate()' - Make a self-signed SSL/TLS certificate.
3412 static int /* O - 1 on success, 0 on failure */
3413 make_certificate(void)
3415 #if defined(HAVE_LIBSSL) && defined(HAVE_WAITPID)
3416 int pid
, /* Process ID of command */
3417 status
; /* Status of command */
3418 char command
[1024], /* Command */
3419 *argv
[11], /* Command-line arguments */
3420 *envp
[MAX_ENV
+ 1], /* Environment variables */
3421 home
[1024], /* HOME environment variable */
3422 infofile
[1024], /* Type-in information for cert */
3423 seedfile
[1024]; /* Random number seed file */
3424 int envc
, /* Number of environment variables */
3425 bytes
; /* Bytes written */
3426 cups_file_t
*fp
; /* Seed/info file */
3427 int infofd
; /* Info file descriptor */
3431 * Run the "openssl" command to seed the random number generator and
3432 * generate a self-signed certificate that is good for 10 years:
3434 * openssl rand -rand seedfile 1
3436 * openssl req -new -x509 -keyout ServerKey \
3437 * -out ServerCertificate -days 3650 -nodes
3439 * The seeding step is crucial in ensuring that the openssl command
3440 * does not block on systems without sufficient entropy...
3443 if (!cupsFileFind("openssl", getenv("PATH"), 1, command
, sizeof(command
)))
3445 cupsdLogMessage(CUPSD_LOG_ERROR
,
3446 "No SSL certificate and openssl command not found!");
3450 if (access("/dev/urandom", 0))
3453 * If the system doesn't provide /dev/urandom, then any random source
3454 * will probably be blocking-style, so generate some random data to
3455 * use as a seed for the certificate. Note that we have already
3456 * seeded the random number generator in cupsdInitCerts()...
3459 cupsdLogMessage(CUPSD_LOG_INFO
,
3460 "Seeding the random number generator...");
3462 snprintf(home
, sizeof(home
), "HOME=%s", TempDir
);
3465 * Write the seed file...
3468 if ((fp
= cupsTempFile2(seedfile
, sizeof(seedfile
))) == NULL
)
3470 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to create seed file %s - %s",
3471 seedfile
, strerror(errno
));
3475 for (bytes
= 0; bytes
< 262144; bytes
++)
3476 cupsFilePutChar(fp
, random());
3481 * Run the openssl command to seed its random number generator...
3484 argv
[0] = "openssl";
3491 envc
= cupsdLoadEnv(envp
, MAX_ENV
);
3492 envp
[envc
++] = home
;
3495 if (!cupsdStartProcess(command
, argv
, envp
, -1, -1, -1, -1, 1, &pid
))
3501 while (waitpid(pid
, &status
, 0) < 0)
3508 cupsdFinishProcess(pid
, command
, sizeof(command
));
3511 * Remove the seed file, as it is no longer needed...
3518 if (WIFEXITED(status
))
3519 cupsdLogMessage(CUPSD_LOG_ERROR
,
3520 "Unable to seed random number generator - "
3521 "the openssl command stopped with status %d!",
3522 WEXITSTATUS(status
));
3524 cupsdLogMessage(CUPSD_LOG_ERROR
,
3525 "Unable to seed random number generator - "
3526 "the openssl command crashed on signal %d!",
3534 * Create a file with the certificate information fields...
3536 * Note: This assumes that the default questions are asked by the openssl
3540 if ((fp
= cupsTempFile2(infofile
, sizeof(infofile
))) == NULL
)
3542 cupsdLogMessage(CUPSD_LOG_ERROR
,
3543 "Unable to create certificate information file %s - %s",
3544 infofile
, strerror(errno
));
3548 cupsFilePrintf(fp
, ".\n.\n.\n%s\n.\n%s\n%s\n",
3549 ServerName
, ServerName
, ServerAdmin
);
3552 cupsdLogMessage(CUPSD_LOG_INFO
,
3553 "Generating SSL server key and certificate...");
3555 argv
[0] = "openssl";
3559 argv
[4] = "-keyout";
3560 argv
[5] = ServerKey
;
3562 argv
[7] = ServerCertificate
;
3565 argv
[10] = "-nodes";
3568 cupsdLoadEnv(envp
, MAX_ENV
);
3570 infofd
= open(infofile
, O_RDONLY
);
3572 if (!cupsdStartProcess(command
, argv
, envp
, infofd
, -1, -1, -1, 1, &pid
))
3582 while (waitpid(pid
, &status
, 0) < 0)
3589 cupsdFinishProcess(pid
, command
, sizeof(command
));
3593 if (WIFEXITED(status
))
3594 cupsdLogMessage(CUPSD_LOG_ERROR
,
3595 "Unable to create SSL server key and certificate - "
3596 "the openssl command stopped with status %d!",
3597 WEXITSTATUS(status
));
3599 cupsdLogMessage(CUPSD_LOG_ERROR
,
3600 "Unable to create SSL server key and certificate - "
3601 "the openssl command crashed on signal %d!",
3606 cupsdLogMessage(CUPSD_LOG_INFO
, "Created SSL server key file \"%s\"...",
3608 cupsdLogMessage(CUPSD_LOG_INFO
,
3609 "Created SSL server certificate file \"%s\"...",
3615 #elif defined(HAVE_GNUTLS)
3616 gnutls_x509_crt crt
; /* Self-signed certificate */
3617 gnutls_x509_privkey key
; /* Encryption key */
3618 cups_lang_t
*language
; /* Default language info */
3619 cups_file_t
*fp
; /* Key/cert file */
3620 unsigned char buffer
[8192]; /* Buffer for x509 data */
3621 size_t bytes
; /* Number of bytes of data */
3622 unsigned char serial
[4]; /* Serial number buffer */
3623 time_t curtime
; /* Current time */
3624 int result
; /* Result of GNU TLS calls */
3628 * Create the encryption key...
3631 cupsdLogMessage(CUPSD_LOG_INFO
, "Generating SSL server key...");
3633 gnutls_x509_privkey_init(&key
);
3634 gnutls_x509_privkey_generate(key
, GNUTLS_PK_RSA
, 2048, 0);
3640 bytes
= sizeof(buffer
);
3642 if ((result
= gnutls_x509_privkey_export(key
, GNUTLS_X509_FMT_PEM
,
3643 buffer
, &bytes
)) < 0)
3645 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to export SSL server key - %s",
3646 gnutls_strerror(result
));
3647 gnutls_x509_privkey_deinit(key
);
3650 else if ((fp
= cupsFileOpen(ServerKey
, "w")) != NULL
)
3652 cupsFileWrite(fp
, (char *)buffer
, bytes
);
3655 cupsdLogMessage(CUPSD_LOG_INFO
, "Created SSL server key file \"%s\"...",
3660 cupsdLogMessage(CUPSD_LOG_ERROR
,
3661 "Unable to create SSL server key file \"%s\" - %s",
3662 ServerKey
, strerror(errno
));
3663 gnutls_x509_privkey_deinit(key
);
3668 * Create the self-signed certificate...
3671 cupsdLogMessage(CUPSD_LOG_INFO
, "Generating self-signed SSL certificate...");
3673 language
= cupsLangDefault();
3674 curtime
= time(NULL
);
3675 serial
[0] = curtime
>> 24;
3676 serial
[1] = curtime
>> 16;
3677 serial
[2] = curtime
>> 8;
3678 serial
[3] = curtime
;
3680 gnutls_x509_crt_init(&crt
);
3681 if (strlen(language
->language
) == 5)
3682 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
3683 language
->language
+ 3, 2);
3685 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
3687 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COMMON_NAME
, 0,
3688 ServerName
, strlen(ServerName
));
3689 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATION_NAME
, 0,
3690 ServerName
, strlen(ServerName
));
3691 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATIONAL_UNIT_NAME
,
3693 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_STATE_OR_PROVINCE_NAME
, 0,
3695 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_LOCALITY_NAME
, 0,
3697 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_PKCS9_EMAIL
, 0,
3698 ServerAdmin
, strlen(ServerAdmin
));
3699 gnutls_x509_crt_set_key(crt
, key
);
3700 gnutls_x509_crt_set_serial(crt
, serial
, sizeof(serial
));
3701 gnutls_x509_crt_set_activation_time(crt
, curtime
);
3702 gnutls_x509_crt_set_expiration_time(crt
, curtime
+ 10 * 365 * 86400);
3703 gnutls_x509_crt_set_ca_status(crt
, 0);
3704 gnutls_x509_crt_set_subject_alternative_name(crt
, GNUTLS_SAN_DNSNAME
,
3706 gnutls_x509_crt_set_key_purpose_oid(crt
, GNUTLS_KP_TLS_WWW_SERVER
, 0);
3707 gnutls_x509_crt_set_key_usage(crt
, GNUTLS_KEY_KEY_ENCIPHERMENT
);
3708 gnutls_x509_crt_set_version(crt
, 3);
3710 bytes
= sizeof(buffer
);
3711 if (gnutls_x509_crt_get_key_id(crt
, 0, buffer
, &bytes
) >= 0)
3712 gnutls_x509_crt_set_subject_key_id(crt
, buffer
, bytes
);
3714 gnutls_x509_crt_sign(crt
, crt
, key
);
3720 bytes
= sizeof(buffer
);
3721 if ((result
= gnutls_x509_crt_export(crt
, GNUTLS_X509_FMT_PEM
,
3722 buffer
, &bytes
)) < 0)
3723 cupsdLogMessage(CUPSD_LOG_ERROR
,
3724 "Unable to export SSL server certificate - %s",
3725 gnutls_strerror(result
));
3726 else if ((fp
= cupsFileOpen(ServerCertificate
, "w")) != NULL
)
3728 cupsFileWrite(fp
, (char *)buffer
, bytes
);
3731 cupsdLogMessage(CUPSD_LOG_INFO
,
3732 "Created SSL server certificate file \"%s\"...",
3736 cupsdLogMessage(CUPSD_LOG_ERROR
,
3737 "Unable to create SSL server certificate file \"%s\" - %s",
3738 ServerCertificate
, strerror(errno
));
3744 gnutls_x509_crt_deinit(crt
);
3745 gnutls_x509_privkey_deinit(key
);
3749 #elif defined(HAVE_CDSASSL) && defined(HAVE_WAITPID)
3750 int pid
, /* Process ID of command */
3751 status
; /* Status of command */
3752 char command
[1024], /* Command */
3753 keychain
[1024], /* Keychain argument */
3754 *argv
[5], /* Command-line arguments */
3755 *envp
[MAX_ENV
]; /* Environment variables */
3759 * Run the "certtool" command to generate a self-signed certificate:
3761 * certtool c Z k=ServerCertificate
3764 if (!cupsFileFind("certtool", getenv("PATH"), 1, command
, sizeof(command
)))
3766 cupsdLogMessage(CUPSD_LOG_ERROR
,
3767 "No SSL certificate and certtool command not found!");
3771 cupsdLogMessage(CUPSD_LOG_INFO
,
3772 "Generating SSL server key and certificate...");
3774 snprintf(keychain
, sizeof(keychain
), "k=%s", ServerCertificate
);
3776 argv
[0] = "certtool";
3782 cupsdLoadEnv(envp
, MAX_ENV
);
3784 if (!cupsdStartProcess(command
, argv
, envp
, -1, -1, -1, -1, 1, &pid
))
3787 while (waitpid(pid
, &status
, 0) < 0)
3794 cupsdFinishProcess(pid
, command
, sizeof(command
));
3798 if (WIFEXITED(status
))
3799 cupsdLogMessage(CUPSD_LOG_ERROR
,
3800 "Unable to create SSL server key and certificate - "
3801 "the certtool command stopped with status %d!",
3802 WEXITSTATUS(status
));
3804 cupsdLogMessage(CUPSD_LOG_ERROR
,
3805 "Unable to create SSL server key and certificate - "
3806 "the certtool command crashed on signal %d!",
3811 cupsdLogMessage(CUPSD_LOG_INFO
,
3812 "Created SSL server certificate file \"%s\"...",
3820 #endif /* HAVE_LIBSSL && HAVE_WAITPID */
3822 #endif /* HAVE_SSL */
3826 * 'pipe_command()' - Pipe the output of a command to the remote client.
3829 static int /* O - Process ID */
3830 pipe_command(cupsd_client_t
*con
, /* I - Client connection */
3831 int infile
, /* I - Standard input for command */
3832 int *outfile
, /* O - Standard output for command */
3833 char *command
, /* I - Command to run */
3834 char *options
, /* I - Options for command */
3835 int root
) /* I - Run as root? */
3837 int i
; /* Looping var */
3838 int pid
; /* Process ID */
3839 char *commptr
, /* Command string pointer */
3840 commch
; /* Command string character */
3841 char *uriptr
; /* URI string pointer */
3842 int fds
[2]; /* Pipe FDs */
3843 int argc
; /* Number of arguments */
3844 int envc
; /* Number of environment variables */
3845 char argbuf
[10240], /* Argument buffer */
3846 *argv
[100], /* Argument strings */
3847 *envp
[MAX_ENV
+ 17]; /* Environment variables */
3848 char content_length
[1024], /* CONTENT_LENGTH environment variable */
3849 content_type
[1024], /* CONTENT_TYPE environment variable */
3850 http_cookie
[32768], /* HTTP_COOKIE environment variable */
3851 http_user_agent
[1024], /* HTTP_USER_AGENT environment variable */
3852 lang
[1024], /* LANG environment variable */
3853 path_info
[1024], /* PATH_INFO environment variable */
3854 *query_string
, /* QUERY_STRING env variable */
3855 remote_addr
[1024], /* REMOTE_ADDR environment variable */
3856 remote_host
[1024], /* REMOTE_HOST environment variable */
3857 remote_user
[1024], /* REMOTE_USER environment variable */
3858 script_name
[1024], /* SCRIPT_NAME environment variable */
3859 server_name
[1024], /* SERVER_NAME environment variable */
3860 server_port
[1024]; /* SERVER_PORT environment variable */
3864 * Parse a copy of the options string, which is of the form:
3866 * argument+argument+argument
3867 * ?argument+argument+argument
3868 * param=value¶m=value
3869 * ?param=value¶m=value
3870 * /name?argument+argument+argument
3871 * /name?param=value¶m=value
3873 * If the string contains an "=" character after the initial name,
3874 * then we treat it as a HTTP GET form request and make a copy of
3875 * the remaining string for the environment variable.
3877 * The string is always parsed out as command-line arguments, to
3878 * be consistent with Apache...
3881 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3882 "pipe_command: command=\"%s\", options=\"%s\"",
3883 command
, options
? options
: "(null)");
3886 query_string
= NULL
;
3889 strlcpy(argbuf
, options
, sizeof(argbuf
));
3893 if (argbuf
[0] == '/')
3896 * Found some trailing path information, set PATH_INFO...
3899 if ((commptr
= strchr(argbuf
, '?')) == NULL
)
3900 commptr
= argbuf
+ strlen(argbuf
);
3904 snprintf(path_info
, sizeof(path_info
), "PATH_INFO=%s", argbuf
);
3910 path_info
[0] = '\0';
3913 if (*commptr
== '?' && con
->operation
== HTTP_GET
)
3916 cupsdSetStringf(&query_string
, "QUERY_STRING=%s", commptr
);
3923 argv
[argc
++] = commptr
;
3925 for (; *commptr
&& argc
< 99; commptr
++)
3928 * Break arguments whenever we see a + or space...
3931 if (*commptr
== ' ' || *commptr
== '+')
3933 while (*commptr
== ' ' || *commptr
== '+')
3937 * If we don't have a blank string, save it as another argument...
3942 argv
[argc
] = commptr
;
3948 else if (*commptr
== '%' && isxdigit(commptr
[1] & 255) &&
3949 isxdigit(commptr
[2] & 255))
3952 * Convert the %xx notation to the individual character.
3955 if (commptr
[1] >= '0' && commptr
[1] <= '9')
3956 *commptr
= (commptr
[1] - '0') << 4;
3958 *commptr
= (tolower(commptr
[1]) - 'a' + 10) << 4;
3960 if (commptr
[2] >= '0' && commptr
[2] <= '9')
3961 *commptr
|= commptr
[2] - '0';
3963 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
3965 _cups_strcpy(commptr
+ 1, commptr
+ 3);
3968 * Check for a %00 and break if that is the case...
3980 * Setup the environment variables as needed...
3984 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF-8", con
->language
->language
);
3986 strcpy(lang
, "LANG=C");
3988 strcpy(remote_addr
, "REMOTE_ADDR=");
3989 httpAddrString(con
->http
.hostaddr
, remote_addr
+ 12,
3990 sizeof(remote_addr
) - 12);
3992 snprintf(remote_host
, sizeof(remote_host
), "REMOTE_HOST=%s",
3993 con
->http
.hostname
);
3995 snprintf(script_name
, sizeof(script_name
), "SCRIPT_NAME=%s", con
->uri
);
3996 if ((uriptr
= strchr(script_name
, '?')) != NULL
)
3999 sprintf(server_port
, "SERVER_PORT=%d", con
->serverport
);
4001 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
4004 envc
= cupsdLoadEnv(envp
, (int)(sizeof(envp
) / sizeof(envp
[0])));
4006 envp
[envc
++] = lang
;
4007 envp
[envc
++] = "REDIRECT_STATUS=1";
4008 envp
[envc
++] = server_name
;
4009 envp
[envc
++] = server_port
;
4010 envp
[envc
++] = remote_addr
;
4011 envp
[envc
++] = remote_host
;
4012 envp
[envc
++] = script_name
;
4015 envp
[envc
++] = path_info
;
4017 if (con
->username
[0])
4019 snprintf(remote_user
, sizeof(remote_user
), "REMOTE_USER=%s", con
->username
);
4021 envp
[envc
++] = remote_user
;
4024 if (con
->http
.version
== HTTP_1_1
)
4025 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.1";
4026 else if (con
->http
.version
== HTTP_1_0
)
4027 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.0";
4029 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/0.9";
4031 if (con
->http
.cookie
)
4033 snprintf(http_cookie
, sizeof(http_cookie
), "HTTP_COOKIE=%s",
4035 envp
[envc
++] = http_cookie
;
4038 if (con
->http
.fields
[HTTP_FIELD_USER_AGENT
][0])
4040 snprintf(http_user_agent
, sizeof(http_user_agent
), "HTTP_USER_AGENT=%s",
4041 con
->http
.fields
[HTTP_FIELD_USER_AGENT
]);
4042 envp
[envc
++] = http_user_agent
;
4045 if (con
->operation
== HTTP_GET
)
4047 for (i
= 0; i
< argc
; i
++)
4048 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "argv[%d] = \"%s\"", i
, argv
[i
]);
4050 envp
[envc
++] = "REQUEST_METHOD=GET";
4055 * Add GET form variables after ?...
4058 envp
[envc
++] = query_string
;
4063 sprintf(content_length
, "CONTENT_LENGTH=" CUPS_LLFMT
,
4064 CUPS_LLCAST con
->bytes
);
4065 snprintf(content_type
, sizeof(content_type
), "CONTENT_TYPE=%s",
4066 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
4068 envp
[envc
++] = "REQUEST_METHOD=POST";
4069 envp
[envc
++] = content_length
;
4070 envp
[envc
++] = content_type
;
4074 * Tell the CGI if we are using encryption...
4078 envp
[envc
++] = "HTTPS=ON";
4081 * Terminate the environment array...
4086 if (LogLevel
== CUPSD_LOG_DEBUG2
)
4088 for (i
= 0; i
< argc
; i
++)
4089 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4090 "pipe_command: argv[%d] = \"%s\"", i
, argv
[i
]);
4091 for (i
= 0; i
< envc
; i
++)
4092 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4093 "pipe_command: envp[%d] = \"%s\"", i
, envp
[i
]);
4097 * Create a pipe for the output...
4100 if (cupsdOpenPipe(fds
))
4102 cupsdClearString(&query_string
);
4104 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to create pipes for CGI %s - %s",
4105 argv
[0], strerror(errno
));
4110 * Then execute the command...
4113 if (cupsdStartProcess(command
, argv
, envp
, infile
, fds
[1], CGIPipes
[1],
4114 -1, root
, &pid
) < 0)
4117 * Error - can't fork!
4120 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to fork for CGI %s - %s", argv
[0],
4123 cupsdClosePipe(fds
);
4129 * Fork successful - return the PID...
4132 if (con
->username
[0])
4133 cupsdAddCert(pid
, con
->username
);
4135 cupsdLogMessage(CUPSD_LOG_DEBUG
, "CGI %s started - PID = %d", command
, pid
);
4141 cupsdClearString(&query_string
);
4148 * 'write_file()' - Send a file via HTTP.
4151 static int /* O - 0 on failure, 1 on success */
4152 write_file(cupsd_client_t
*con
, /* I - Client connection */
4153 http_status_t code
, /* I - HTTP status */
4154 char *filename
, /* I - Filename */
4155 char *type
, /* I - File type */
4156 struct stat
*filestats
) /* O - File information */
4158 con
->file
= open(filename
, O_RDONLY
);
4160 cupsdLogMessage(CUPSD_LOG_DEBUG
, "write_file: %d file=%d", con
->http
.fd
,
4166 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
4170 if (!cupsdSendHeader(con
, code
, type
))
4173 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
4174 httpGetDateString(filestats
->st_mtime
)) < 0)
4176 if (httpPrintf(HTTP(con
), "Content-Length: " CUPS_LLFMT
"\r\n",
4177 CUPS_LLCAST filestats
->st_size
) < 0)
4179 if (httpPrintf(HTTP(con
), "\r\n") < 0)
4182 if (cupsdFlushHeader(con
) < 0)
4185 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
4186 con
->http
.data_remaining
= filestats
->st_size
;
4188 if (con
->http
.data_remaining
<= INT_MAX
)
4189 con
->http
._data_remaining
= con
->http
.data_remaining
;
4191 con
->http
._data_remaining
= INT_MAX
;
4193 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4194 "write_file: Adding fd %d to OutputSet...", con
->http
.fd
);
4196 FD_SET(con
->http
.fd
, OutputSet
);
4203 * End of "$Id: client.c 6027 2006-10-11 21:04:58Z mike $".