2 * "$Id: client.c 5972 2006-09-19 20:44:07Z 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
);
799 if (con
->language
!= NULL
)
801 cupsLangFree(con
->language
);
802 con
->language
= NULL
;
806 * Grab the request line...
809 switch (sscanf(line
, "%63s%1023s%63s", operation
, con
->uri
, version
))
812 cupsdLogMessage(CUPSD_LOG_ERROR
,
813 "Bad request line \"%s\" from %s!", line
,
815 cupsdSendError(con
, HTTP_BAD_REQUEST
);
816 return (cupsdCloseClient(con
));
818 con
->http
.version
= HTTP_0_9
;
821 if (sscanf(version
, "HTTP/%d.%d", &major
, &minor
) != 2)
823 cupsdLogMessage(CUPSD_LOG_ERROR
,
824 "Bad request line \"%s\" from %s!", line
,
826 cupsdSendError(con
, HTTP_BAD_REQUEST
);
827 return (cupsdCloseClient(con
));
832 con
->http
.version
= (http_version_t
)(major
* 100 + minor
);
833 if (con
->http
.version
== HTTP_1_1
&& KeepAlive
)
834 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
836 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
840 cupsdSendError(con
, HTTP_NOT_SUPPORTED
);
841 return (cupsdCloseClient(con
));
847 * Handle full URLs in the request line...
850 if (strcmp(con
->uri
, "*"))
852 char method
[HTTP_MAX_URI
], /* Method/scheme */
853 userpass
[HTTP_MAX_URI
], /* Username:password */
854 hostname
[HTTP_MAX_URI
], /* Hostname */
855 resource
[HTTP_MAX_URI
]; /* Resource path */
856 int port
; /* Port number */
860 * Separate the URI into its components...
863 httpSeparateURI(HTTP_URI_CODING_MOST
, con
->uri
,
864 method
, sizeof(method
),
865 userpass
, sizeof(userpass
),
866 hostname
, sizeof(hostname
), &port
,
867 resource
, sizeof(resource
));
870 * Only allow URIs with the servername, localhost, or an IP
874 if (strcmp(method
, "file") &&
875 strcasecmp(hostname
, ServerName
) &&
876 strcasecmp(hostname
, "localhost") &&
877 !isdigit(hostname
[0]))
880 * Nope, we don't do proxies...
883 cupsdLogMessage(CUPSD_LOG_ERROR
, "Bad URI \"%s\" in request!",
885 cupsdSendError(con
, HTTP_METHOD_NOT_ALLOWED
);
886 return (cupsdCloseClient(con
));
890 * Copy the resource portion back into the URI; both resource and
891 * con->uri are HTTP_MAX_URI bytes in size...
894 strcpy(con
->uri
, resource
);
898 * Process the request...
901 if (!strcmp(operation
, "GET"))
902 con
->http
.state
= HTTP_GET
;
903 else if (!strcmp(operation
, "PUT"))
904 con
->http
.state
= HTTP_PUT
;
905 else if (!strcmp(operation
, "POST"))
906 con
->http
.state
= HTTP_POST
;
907 else if (!strcmp(operation
, "DELETE"))
908 con
->http
.state
= HTTP_DELETE
;
909 else if (!strcmp(operation
, "TRACE"))
910 con
->http
.state
= HTTP_TRACE
;
911 else if (!strcmp(operation
, "OPTIONS"))
912 con
->http
.state
= HTTP_OPTIONS
;
913 else if (!strcmp(operation
, "HEAD"))
914 con
->http
.state
= HTTP_HEAD
;
917 cupsdLogMessage(CUPSD_LOG_ERROR
, "Bad operation \"%s\"!", operation
);
918 cupsdSendError(con
, HTTP_BAD_REQUEST
);
919 return (cupsdCloseClient(con
));
922 con
->start
= time(NULL
);
923 con
->operation
= con
->http
.state
;
925 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdReadClient: %d %s %s HTTP/%d.%d",
926 con
->http
.fd
, operation
, con
->uri
,
927 con
->http
.version
/ 100, con
->http
.version
% 100);
929 con
->http
.status
= HTTP_OK
;
939 * Parse incoming parameters until the status changes...
942 status
= httpUpdate(HTTP(con
));
944 if (status
!= HTTP_OK
&& status
!= HTTP_CONTINUE
)
946 cupsdSendError(con
, HTTP_BAD_REQUEST
);
947 return (cupsdCloseClient(con
));
952 break; /* Anti-compiler-warning-code */
956 * Handle new transfers...
959 if (status
== HTTP_OK
)
961 if (con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
][0])
964 * Figure out the locale from the Accept-Language and Content-Type
968 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ',')) != NULL
)
971 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ';')) != NULL
)
974 if ((ptr
= strstr(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
], "charset=")) != NULL
)
977 * Combine language and charset, and trim any extra params in the
981 snprintf(locale
, sizeof(locale
), "%s.%s",
982 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ptr
+ 8);
984 if ((ptr
= strchr(locale
, ',')) != NULL
)
988 snprintf(locale
, sizeof(locale
), "%s.%s",
989 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], DefaultCharset
);
991 cupsdLogMessage(CUPSD_LOG_DEBUG
,
992 "cupsdReadClient: %d Browser asked for language \"%s\"...",
993 con
->http
.fd
, locale
);
995 con
->language
= cupsLangGet(locale
);
998 con
->language
= cupsLangGet(DefaultLocale
);
1000 cupsdAuthorize(con
);
1002 if (!strncmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Keep-Alive", 10) &&
1004 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
1006 if (!con
->http
.fields
[HTTP_FIELD_HOST
][0] &&
1007 con
->http
.version
>= HTTP_1_1
)
1010 * HTTP/1.1 and higher require the "Host:" field...
1013 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
))
1014 return (cupsdCloseClient(con
));
1016 else if (con
->operation
== HTTP_OPTIONS
)
1019 * Do OPTIONS command...
1022 if (con
->best
&& con
->best
->type
!= AUTH_NONE
)
1024 if (!cupsdSendHeader(con
, HTTP_UNAUTHORIZED
, NULL
))
1025 return (cupsdCloseClient(con
));
1028 if (!strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") &&
1029 con
->http
.tls
== NULL
)
1033 * Do encryption stuff...
1036 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
))
1037 return (cupsdCloseClient(con
));
1039 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1040 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1041 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1042 httpPrintf(HTTP(con
), "\r\n");
1044 if (cupsdFlushHeader(con
) < 0)
1045 return (cupsdCloseClient(con
));
1047 encrypt_client(con
);
1049 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
))
1050 return (cupsdCloseClient(con
));
1051 #endif /* HAVE_SSL */
1054 if (!cupsdSendHeader(con
, HTTP_OK
, NULL
))
1055 return (cupsdCloseClient(con
));
1057 httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n");
1058 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1059 httpPrintf(HTTP(con
), "\r\n");
1061 if (cupsdFlushHeader(con
) < 0)
1062 return (cupsdCloseClient(con
));
1064 else if (!is_path_absolute(con
->uri
))
1067 * Protect against malicious users!
1070 if (!cupsdSendError(con
, HTTP_FORBIDDEN
))
1071 return (cupsdCloseClient(con
));
1075 if (!strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") &&
1076 con
->http
.tls
== NULL
)
1080 * Do encryption stuff...
1083 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
))
1084 return (cupsdCloseClient(con
));
1086 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1087 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1088 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1089 httpPrintf(HTTP(con
), "\r\n");
1091 if (cupsdFlushHeader(con
) < 0)
1092 return (cupsdCloseClient(con
));
1094 encrypt_client(con
);
1096 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
))
1097 return (cupsdCloseClient(con
));
1098 #endif /* HAVE_SSL */
1101 if ((status
= cupsdIsAuthorized(con
, NULL
)) != HTTP_OK
)
1103 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1104 "cupsdReadClient: Unauthorized request for %s...\n",
1106 cupsdSendError(con
, status
);
1107 return (cupsdCloseClient(con
));
1110 if (con
->http
.expect
&&
1111 (con
->operation
== HTTP_POST
|| con
->operation
== HTTP_PUT
))
1113 if (con
->http
.expect
== HTTP_CONTINUE
)
1116 * Send 100-continue header...
1119 if (!cupsdSendHeader(con
, HTTP_CONTINUE
, NULL
))
1120 return (cupsdCloseClient(con
));
1125 * Send 417-expectation-failed header...
1128 if (!cupsdSendHeader(con
, HTTP_EXPECTATION_FAILED
, NULL
))
1129 return (cupsdCloseClient(con
));
1131 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1132 httpPrintf(HTTP(con
), "\r\n");
1134 if (cupsdFlushHeader(con
) < 0)
1135 return (cupsdCloseClient(con
));
1139 switch (con
->http
.state
)
1141 case HTTP_GET_SEND
:
1142 if (!strncmp(con
->uri
, "/printers/", 10) &&
1143 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1146 * Send PPD file - get the real printer name since printer
1147 * names are not case sensitive but filenames can be...
1150 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1152 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1153 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1156 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
1157 return (cupsdCloseClient(con
));
1163 if ((!strncmp(con
->uri
, "/admin", 6) &&
1164 strncmp(con
->uri
, "/admin/conf/", 12) &&
1165 strncmp(con
->uri
, "/admin/log/", 11)) ||
1166 !strncmp(con
->uri
, "/printers", 9) ||
1167 !strncmp(con
->uri
, "/classes", 8) ||
1168 !strncmp(con
->uri
, "/help", 5) ||
1169 !strncmp(con
->uri
, "/jobs", 5))
1172 * Send CGI output...
1175 if (!strncmp(con
->uri
, "/admin", 6))
1177 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1180 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1182 else if (!strncmp(con
->uri
, "/printers", 9))
1184 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1187 if (con
->uri
[9] && con
->uri
[10])
1188 cupsdSetString(&con
->options
, con
->uri
+ 9);
1190 cupsdSetString(&con
->options
, NULL
);
1192 else if (!strncmp(con
->uri
, "/classes", 8))
1194 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1197 if (con
->uri
[8] && con
->uri
[9])
1198 cupsdSetString(&con
->options
, con
->uri
+ 8);
1200 cupsdSetString(&con
->options
, NULL
);
1202 else if (!strncmp(con
->uri
, "/jobs", 5))
1204 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1207 if (con
->uri
[5] && con
->uri
[6])
1208 cupsdSetString(&con
->options
, con
->uri
+ 5);
1210 cupsdSetString(&con
->options
, NULL
);
1214 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1217 if (con
->uri
[5] && con
->uri
[6])
1218 cupsdSetString(&con
->options
, con
->uri
+ 5);
1220 cupsdSetString(&con
->options
, NULL
);
1223 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1225 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
1226 return (cupsdCloseClient(con
));
1229 cupsdLogRequest(con
, HTTP_OK
);
1231 if (con
->http
.version
<= HTTP_1_0
)
1232 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1234 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1235 (strchr(con
->uri
+ 12, '/') ||
1236 strlen(con
->uri
) == 12)) ||
1237 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1238 (strchr(con
->uri
+ 11, '/') ||
1239 strlen(con
->uri
) == 11)))
1242 * GET can only be done to configuration files under
1246 if (!cupsdSendError(con
, HTTP_FORBIDDEN
))
1247 return (cupsdCloseClient(con
));
1257 if ((filename
= get_file(con
, &filestats
, buf
,
1258 sizeof(buf
))) == NULL
)
1260 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
1261 return (cupsdCloseClient(con
));
1266 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1268 if (is_cgi(con
, filename
, &filestats
, type
))
1271 * Note: con->command and con->options were set by
1275 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1277 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
1278 return (cupsdCloseClient(con
));
1281 cupsdLogRequest(con
, HTTP_OK
);
1283 if (con
->http
.version
<= HTTP_1_0
)
1284 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1288 if (!check_if_modified(con
, &filestats
))
1290 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
))
1291 return (cupsdCloseClient(con
));
1296 strcpy(line
, "text/plain");
1298 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1300 if (!write_file(con
, HTTP_OK
, filename
, line
, &filestats
))
1301 return (cupsdCloseClient(con
));
1306 case HTTP_POST_RECV
:
1308 * See if the POST request includes a Content-Length field, and if
1309 * so check the length against any limits that are set...
1312 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "POST %s", con
->uri
);
1313 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "CONTENT_TYPE = %s",
1314 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
1316 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1317 MaxRequestSize
> 0 &&
1318 con
->http
.data_remaining
> MaxRequestSize
)
1321 * Request too large...
1324 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1325 return (cupsdCloseClient(con
));
1329 else if (con
->http
.data_remaining
< 0)
1332 * Negative content lengths are invalid!
1335 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
))
1336 return (cupsdCloseClient(con
));
1342 * See what kind of POST request this is; for IPP requests the
1343 * content-type field will be "application/ipp"...
1346 if (!strcmp(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
],
1348 con
->request
= ippNew();
1349 else if ((!strncmp(con
->uri
, "/admin", 6) &&
1350 strncmp(con
->uri
, "/admin/conf/", 12) &&
1351 strncmp(con
->uri
, "/admin/log/", 11)) ||
1352 !strncmp(con
->uri
, "/printers", 9) ||
1353 !strncmp(con
->uri
, "/classes", 8) ||
1354 !strncmp(con
->uri
, "/help", 5) ||
1355 !strncmp(con
->uri
, "/jobs", 5))
1361 if (!strncmp(con
->uri
, "/admin", 6))
1363 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1366 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1368 else if (!strncmp(con
->uri
, "/printers", 9))
1370 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1373 if (con
->uri
[9] && con
->uri
[10])
1374 cupsdSetString(&con
->options
, con
->uri
+ 9);
1376 cupsdSetString(&con
->options
, NULL
);
1378 else if (!strncmp(con
->uri
, "/classes", 8))
1380 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1383 if (con
->uri
[8] && con
->uri
[9])
1384 cupsdSetString(&con
->options
, con
->uri
+ 8);
1386 cupsdSetString(&con
->options
, NULL
);
1388 else if (!strncmp(con
->uri
, "/jobs", 5))
1390 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1393 if (con
->uri
[5] && con
->uri
[6])
1394 cupsdSetString(&con
->options
, con
->uri
+ 5);
1396 cupsdSetString(&con
->options
, NULL
);
1400 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1403 if (con
->uri
[5] && con
->uri
[6])
1404 cupsdSetString(&con
->options
, con
->uri
+ 5);
1406 cupsdSetString(&con
->options
, NULL
);
1409 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1410 "cupsdReadClient: %d command=\"%s\", "
1412 con
->http
.fd
, con
->command
,
1413 con
->options
? con
->options
: "(null)");
1415 if (con
->http
.version
<= HTTP_1_0
)
1416 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1424 if ((filename
= get_file(con
, &filestats
, buf
,
1425 sizeof(buf
))) == NULL
)
1427 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
1428 return (cupsdCloseClient(con
));
1433 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1435 if (!is_cgi(con
, filename
, &filestats
, type
))
1438 * Only POST to CGI's...
1441 if (!cupsdSendError(con
, HTTP_UNAUTHORIZED
))
1442 return (cupsdCloseClient(con
));
1447 case HTTP_PUT_RECV
:
1449 * Validate the resource name...
1452 if (strncmp(con
->uri
, "/admin/conf/", 12) ||
1453 strchr(con
->uri
+ 12, '/') ||
1454 strlen(con
->uri
) == 12)
1457 * PUT can only be done to configuration files under
1461 if (!cupsdSendError(con
, HTTP_FORBIDDEN
))
1462 return (cupsdCloseClient(con
));
1468 * See if the PUT request includes a Content-Length field, and if
1469 * so check the length against any limits that are set...
1472 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "PUT %s", con
->uri
);
1473 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "CONTENT_TYPE = %s",
1474 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
1476 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1477 MaxRequestSize
> 0 &&
1478 con
->http
.data_remaining
> MaxRequestSize
)
1481 * Request too large...
1484 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1485 return (cupsdCloseClient(con
));
1489 else if (con
->http
.data_remaining
< 0)
1492 * Negative content lengths are invalid!
1495 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
))
1496 return (cupsdCloseClient(con
));
1502 * Open a temporary file to hold the request...
1505 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
1507 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1509 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1510 "cupsdReadClient: %d REQUEST %s=%d", con
->http
.fd
,
1511 con
->filename
, con
->file
);
1515 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1516 return (cupsdCloseClient(con
));
1519 fchmod(con
->file
, 0640);
1520 fchown(con
->file
, RunUser
, Group
);
1521 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1526 cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
);
1527 return (cupsdCloseClient(con
));
1530 if (!strncmp(con
->uri
, "/printers/", 10) &&
1531 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1534 * Send PPD file - get the real printer name since printer
1535 * names are not case sensitive but filenames can be...
1538 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1540 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1541 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1544 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
1545 return (cupsdCloseClient(con
));
1551 if ((!strncmp(con
->uri
, "/admin", 6) &&
1552 strncmp(con
->uri
, "/admin/conf/", 12) &&
1553 strncmp(con
->uri
, "/admin/log/", 11)) ||
1554 !strncmp(con
->uri
, "/printers", 9) ||
1555 !strncmp(con
->uri
, "/classes", 8) ||
1556 !strncmp(con
->uri
, "/help", 5) ||
1557 !strncmp(con
->uri
, "/jobs", 5))
1563 if (!cupsdSendHeader(con
, HTTP_OK
, "text/html"))
1564 return (cupsdCloseClient(con
));
1566 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1567 return (cupsdCloseClient(con
));
1569 if (cupsdFlushHeader(con
) < 0)
1570 return (cupsdCloseClient(con
));
1572 cupsdLogRequest(con
, HTTP_OK
);
1574 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1575 (strchr(con
->uri
+ 12, '/') ||
1576 strlen(con
->uri
) == 12)) ||
1577 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1578 (strchr(con
->uri
+ 11, '/') ||
1579 strlen(con
->uri
) == 11)))
1582 * HEAD can only be done to configuration files under
1586 if (!cupsdSendError(con
, HTTP_FORBIDDEN
))
1587 return (cupsdCloseClient(con
));
1591 else if ((filename
= get_file(con
, &filestats
, buf
,
1592 sizeof(buf
))) == NULL
)
1594 if (!cupsdSendHeader(con
, HTTP_NOT_FOUND
, "text/html"))
1595 return (cupsdCloseClient(con
));
1597 cupsdLogRequest(con
, HTTP_NOT_FOUND
);
1599 else if (!check_if_modified(con
, &filestats
))
1601 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
))
1602 return (cupsdCloseClient(con
));
1604 cupsdLogRequest(con
, HTTP_NOT_MODIFIED
);
1612 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1614 strcpy(line
, "text/plain");
1616 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1618 if (!cupsdSendHeader(con
, HTTP_OK
, line
))
1619 return (cupsdCloseClient(con
));
1621 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
1622 httpGetDateString(filestats
.st_mtime
)) < 0)
1623 return (cupsdCloseClient(con
));
1625 if (httpPrintf(HTTP(con
), "Content-Length: %lu\r\n",
1626 (unsigned long)filestats
.st_size
) < 0)
1627 return (cupsdCloseClient(con
));
1629 cupsdLogRequest(con
, HTTP_OK
);
1632 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1633 return (cupsdCloseClient(con
));
1635 if (cupsdFlushHeader(con
) < 0)
1636 return (cupsdCloseClient(con
));
1638 con
->http
.state
= HTTP_WAITING
;
1642 break; /* Anti-compiler-warning-code */
1648 * Handle any incoming data...
1651 switch (con
->http
.state
)
1653 case HTTP_PUT_RECV
:
1654 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1655 "cupsdReadClient: %d con->data_encoding=HTTP_ENCODE_%s, "
1656 "con->data_remaining=" CUPS_LLFMT
", con->file=%d",
1658 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
?
1659 "CHUNKED" : "LENGTH",
1660 CUPS_LLCAST con
->http
.data_remaining
, con
->file
);
1662 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
1663 return (cupsdCloseClient(con
));
1666 con
->bytes
+= bytes
;
1668 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1669 "cupsdReadClient: %d writing %d bytes to %d",
1670 con
->http
.fd
, bytes
, con
->file
);
1672 if (write(con
->file
, line
, bytes
) < bytes
)
1674 cupsdLogMessage(CUPSD_LOG_ERROR
,
1675 "cupsdReadClient: Unable to write %d bytes to %s: %s",
1676 bytes
, con
->filename
, strerror(errno
));
1678 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1679 "cupsdReadClient: Closing data file %d...",
1684 unlink(con
->filename
);
1685 cupsdClearString(&con
->filename
);
1687 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1688 return (cupsdCloseClient(con
));
1692 if (con
->http
.state
== HTTP_WAITING
)
1695 * End of file, see how big it is...
1698 fstat(con
->file
, &filestats
);
1700 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1701 "cupsdReadClient: %d Closing data file %d, size="
1703 con
->http
.fd
, con
->file
,
1704 CUPS_LLCAST filestats
.st_size
);
1709 if (filestats
.st_size
> MaxRequestSize
&&
1713 * Request is too big; remove it and send an error...
1716 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1717 "cupsdReadClient: %d Removing temp file %s",
1718 con
->http
.fd
, con
->filename
);
1719 unlink(con
->filename
);
1720 cupsdClearString(&con
->filename
);
1722 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1723 return (cupsdCloseClient(con
));
1727 * Install the configuration file...
1730 status
= install_conf_file(con
);
1733 * Return the status to the client...
1736 if (!cupsdSendError(con
, status
))
1737 return (cupsdCloseClient(con
));
1741 case HTTP_POST_RECV
:
1742 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1743 "cupsdReadClient: %d con->data_encoding=HTTP_ENCODE_"
1744 "%s, con->data_remaining=" CUPS_LLFMT
", con->file=%d",
1746 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
?
1747 "CHUNKED" : "LENGTH",
1748 CUPS_LLCAST con
->http
.data_remaining
, con
->file
);
1750 if (con
->request
!= NULL
)
1753 * Grab any request data from the connection...
1756 if ((ipp_state
= ippRead(&(con
->http
), con
->request
)) == IPP_ERROR
)
1758 cupsdLogMessage(CUPSD_LOG_ERROR
,
1759 "cupsdReadClient: %d IPP Read Error!",
1762 cupsdSendError(con
, HTTP_BAD_REQUEST
);
1763 return (cupsdCloseClient(con
));
1765 else if (ipp_state
!= IPP_DATA
)
1767 if (con
->http
.state
== HTTP_POST_SEND
)
1769 cupsdSendError(con
, HTTP_BAD_REQUEST
);
1770 return (cupsdCloseClient(con
));
1776 con
->bytes
+= ippLength(con
->request
);
1779 if (con
->file
< 0 && con
->http
.state
!= HTTP_POST_SEND
)
1782 * Create a file as needed for the request data...
1785 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
, request_id
++);
1786 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1788 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdReadClient: %d REQUEST %s=%d", con
->http
.fd
,
1789 con
->filename
, con
->file
);
1793 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1794 return (cupsdCloseClient(con
));
1797 fchmod(con
->file
, 0640);
1798 fchown(con
->file
, RunUser
, Group
);
1799 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1802 if (con
->http
.state
!= HTTP_POST_SEND
)
1804 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
1805 return (cupsdCloseClient(con
));
1808 con
->bytes
+= bytes
;
1810 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1811 "cupsdReadClient: %d writing %d bytes to %d",
1812 con
->http
.fd
, bytes
, con
->file
);
1814 if (write(con
->file
, line
, bytes
) < bytes
)
1816 cupsdLogMessage(CUPSD_LOG_ERROR
,
1817 "cupsdReadClient: Unable to write %d bytes to %s: %s",
1818 bytes
, con
->filename
, strerror(errno
));
1820 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1821 "cupsdReadClient: Closing file %d...",
1826 unlink(con
->filename
);
1827 cupsdClearString(&con
->filename
);
1829 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1830 return (cupsdCloseClient(con
));
1833 else if (con
->http
.state
== HTTP_POST_RECV
)
1834 return (1); /* ??? */
1835 else if (con
->http
.state
!= HTTP_POST_SEND
)
1836 return (cupsdCloseClient(con
));
1839 if (con
->http
.state
== HTTP_POST_SEND
)
1843 fstat(con
->file
, &filestats
);
1845 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1846 "cupsdReadClient: %d Closing data file %d, "
1847 "size=" CUPS_LLFMT
".",
1848 con
->http
.fd
, con
->file
,
1849 CUPS_LLCAST filestats
.st_size
);
1854 if (filestats
.st_size
> MaxRequestSize
&&
1858 * Request is too big; remove it and send an error...
1861 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1862 "cupsdReadClient: %d Removing temp file %s",
1863 con
->http
.fd
, con
->filename
);
1864 unlink(con
->filename
);
1865 cupsdClearString(&con
->filename
);
1870 * Delete any IPP request data...
1873 ippDelete(con
->request
);
1874 con
->request
= NULL
;
1877 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1878 return (cupsdCloseClient(con
));
1883 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1885 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
1886 return (cupsdCloseClient(con
));
1889 cupsdLogRequest(con
, HTTP_OK
);
1894 return (cupsdProcessIPPRequest(con
));
1899 break; /* Anti-compiler-warning-code */
1902 if (!con
->http
.keep_alive
&& con
->http
.state
== HTTP_WAITING
)
1903 return (cupsdCloseClient(con
));
1910 * 'cupsdSendCommand()' - Send output from a command via HTTP.
1913 int /* O - 1 on success, 0 on failure */
1915 cupsd_client_t
*con
, /* I - Client connection */
1916 char *command
, /* I - Command to run */
1917 char *options
, /* I - Command-line options */
1918 int root
) /* I - Run as root? */
1920 int fd
; /* Standard input file descriptor */
1925 fd
= open(con
->filename
, O_RDONLY
);
1929 cupsdLogMessage(CUPSD_LOG_ERROR
,
1930 "cupsdSendCommand: %d Unable to open \"%s\" for reading: %s",
1931 con
->http
.fd
, con
->filename
? con
->filename
: "/dev/null",
1936 fcntl(fd
, F_SETFD
, fcntl(fd
, F_GETFD
) | FD_CLOEXEC
);
1941 con
->pipe_pid
= pipe_command(con
, fd
, &(con
->file
), command
, options
, root
);
1946 cupsdLogMessage(CUPSD_LOG_INFO
, "Started \"%s\" (pid=%d)", command
,
1949 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendCommand: %d file=%d",
1950 con
->http
.fd
, con
->file
);
1952 if (con
->pipe_pid
== 0)
1955 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1957 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1958 "cupsdSendCommand: Adding fd %d to InputSet...", con
->file
);
1959 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1960 "cupsdSendCommand: Adding fd %d to OutputSet...",
1963 FD_SET(con
->file
, InputSet
);
1964 FD_SET(con
->http
.fd
, OutputSet
);
1966 con
->sent_header
= 0;
1967 con
->file_ready
= 0;
1968 con
->got_fields
= 0;
1976 * 'cupsdSendError()' - Send an error message via HTTP.
1979 int /* O - 1 if successful, 0 otherwise */
1980 cupsdSendError(cupsd_client_t
*con
, /* I - Connection */
1981 http_status_t code
) /* I - Error code */
1985 * Force client to upgrade for authentication if that is how the
1986 * server is configured...
1989 if (code
== HTTP_UNAUTHORIZED
&&
1990 DefaultEncryption
== HTTP_ENCRYPT_REQUIRED
&&
1991 strcasecmp(con
->http
.hostname
, "localhost") &&
1994 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1995 "cupsdSendError: Encryption before authentication!");
1996 code
= HTTP_UPGRADE_REQUIRED
;
1998 #endif /* HAVE_SSL */
2001 * Put the request in the access_log file...
2004 cupsdLogRequest(con
, code
);
2006 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendError: %d code=%d (%s)",
2007 con
->http
.fd
, code
, httpStatus(code
));
2010 * To work around bugs in some proxies, don't use Keep-Alive for some
2014 if (code
>= HTTP_BAD_REQUEST
)
2015 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
2018 * Send an error message back to the client. If the error code is a
2019 * 400 or 500 series, make sure the message contains some text, too!
2022 if (!cupsdSendHeader(con
, code
, NULL
))
2026 if (code
== HTTP_UPGRADE_REQUIRED
)
2027 if (httpPrintf(HTTP(con
), "Connection: Upgrade\r\n") < 0)
2030 if (httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n") < 0)
2032 #endif /* HAVE_SSL */
2034 if ((con
->http
.version
>= HTTP_1_1
&& !con
->http
.keep_alive
) ||
2035 (code
>= HTTP_BAD_REQUEST
&& code
!= HTTP_UPGRADE_REQUIRED
))
2037 if (httpPrintf(HTTP(con
), "Connection: close\r\n") < 0)
2041 if (code
>= HTTP_BAD_REQUEST
)
2044 * Send a human-readable error message.
2047 char message
[4096], /* Message for user */
2048 urltext
[1024], /* URL redirection text */
2049 redirect
[1024]; /* Redirection link */
2050 const char *text
; /* Status-specific text */
2055 if (code
== HTTP_UNAUTHORIZED
)
2056 text
= _cupsLangString(con
->language
,
2057 _("Enter your username and password or the "
2058 "root username and password to access this "
2060 else if (code
== HTTP_UPGRADE_REQUIRED
)
2064 snprintf(urltext
, sizeof(urltext
),
2065 _cupsLangString(con
->language
,
2066 _("You must access this page using the URL "
2067 "<A HREF=\"https://%s:%d%s\">"
2068 "https://%s:%d%s</A>.")),
2069 con
->servername
, con
->serverport
, con
->uri
,
2070 con
->servername
, con
->serverport
, con
->uri
);
2072 snprintf(redirect
, sizeof(redirect
),
2073 "<META HTTP-EQUIV=\"Refresh\" CONTENT=\"3;https://%s:%d%s\">\n",
2074 con
->servername
, con
->serverport
, con
->uri
);
2079 snprintf(message
, sizeof(message
),
2080 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" "
2081 "\"http://www.w3.org/TR/REC-html40/loose.dtd\">\n"
2084 "\t<META HTTP-EQUIV=\"Content-Type\" "
2085 "CONTENT=\"text/html; charset=utf-8\">\n"
2086 "\t<TITLE>%d %s</TITLE>\n"
2087 "\t<LINK REL=\"STYLESHEET\" TYPE=\"text/css\" "
2088 "HREF=\"/cups.css\">\n"
2096 code
, httpStatus(code
), redirect
, code
, httpStatus(code
), text
);
2098 if (httpPrintf(HTTP(con
), "Content-Type: text/html; charset=utf-8\r\n") < 0)
2100 if (httpPrintf(HTTP(con
), "Content-Length: %d\r\n",
2101 (int)strlen(message
)) < 0)
2103 if (httpPrintf(HTTP(con
), "\r\n") < 0)
2105 if (httpPrintf(HTTP(con
), "%s", message
) < 0)
2108 else if (httpPrintf(HTTP(con
), "\r\n") < 0)
2111 if (cupsdFlushHeader(con
) < 0)
2114 con
->http
.state
= HTTP_WAITING
;
2121 * 'cupsdSendHeader()' - Send an HTTP request.
2124 int /* O - 1 on success, 0 on failure */
2125 cupsdSendHeader(cupsd_client_t
*con
, /* I - Client to send to */
2126 http_status_t code
, /* I - HTTP status code */
2127 char *type
) /* I - MIME type of document */
2130 * Send the HTTP status header...
2133 if (code
== HTTP_CONTINUE
)
2136 * 100-continue doesn't send any headers...
2139 return (httpPrintf(HTTP(con
), "HTTP/%d.%d 100 Continue\r\n\r\n",
2140 con
->http
.version
/ 100, con
->http
.version
% 100) > 0);
2143 httpFlushWrite(HTTP(con
));
2145 con
->http
.data_encoding
= HTTP_ENCODE_FIELDS
;
2147 if (httpPrintf(HTTP(con
), "HTTP/%d.%d %d %s\r\n", con
->http
.version
/ 100,
2148 con
->http
.version
% 100, code
, httpStatus(code
)) < 0)
2150 if (httpPrintf(HTTP(con
), "Date: %s\r\n", httpGetDateString(time(NULL
))) < 0)
2153 if (httpPrintf(HTTP(con
), "Server: %s\r\n", ServerHeader
) < 0)
2155 if (con
->http
.keep_alive
&& con
->http
.version
>= HTTP_1_0
)
2157 if (httpPrintf(HTTP(con
), "Connection: Keep-Alive\r\n") < 0)
2159 if (httpPrintf(HTTP(con
), "Keep-Alive: timeout=%d\r\n",
2160 KeepAliveTimeout
) < 0)
2163 if (code
== HTTP_METHOD_NOT_ALLOWED
)
2164 if (httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST\r\n") < 0)
2167 if (code
== HTTP_UNAUTHORIZED
)
2169 int auth_type
; /* Authentication type */
2172 if (!con
->best
|| con
->best
->type
== AUTH_NONE
)
2173 auth_type
= DefaultAuthType
;
2175 auth_type
= con
->best
->type
;
2177 if (auth_type
!= AUTH_DIGEST
)
2179 if (httpPrintf(HTTP(con
),
2180 "WWW-Authenticate: Basic realm=\"CUPS\"\r\n") < 0)
2185 if (httpPrintf(HTTP(con
),
2186 "WWW-Authenticate: Digest realm=\"CUPS\", nonce=\"%s\"\r\n",
2187 con
->http
.hostname
) < 0)
2192 if (con
->language
&& strcmp(con
->language
->language
, "C"))
2194 if (httpPrintf(HTTP(con
), "Content-Language: %s\r\n",
2195 con
->language
->language
) < 0)
2201 if (!strcmp(type
, "text/html"))
2203 if (httpPrintf(HTTP(con
),
2204 "Content-Type: text/html; charset=utf-8\r\n") < 0)
2207 else if (httpPrintf(HTTP(con
), "Content-Type: %s\r\n", type
) < 0)
2216 * 'cupsdUpdateCGI()' - Read status messages from CGI scripts and programs.
2220 cupsdUpdateCGI(void)
2222 char *ptr
, /* Pointer to end of line in buffer */
2223 message
[1024]; /* Pointer to message text */
2224 int loglevel
; /* Log level for message */
2227 while ((ptr
= cupsdStatBufUpdate(CGIStatusBuffer
, &loglevel
,
2228 message
, sizeof(message
))) != NULL
)
2229 if (!strchr(CGIStatusBuffer
->buffer
, '\n'))
2232 if (ptr
== NULL
&& !CGIStatusBuffer
->bufused
)
2235 * Fatal error on pipe - should never happen!
2238 cupsdLogMessage(CUPSD_LOG_CRIT
,
2239 "cupsdUpdateCGI: error reading from CGI error pipe - %s",
2246 * 'cupsdWriteClient()' - Write data to a client as needed.
2249 int /* O - 1 if success, 0 if fail */
2250 cupsdWriteClient(cupsd_client_t
*con
) /* I - Client connection */
2252 int bytes
; /* Number of bytes written */
2253 char buf
[16385]; /* Data buffer */
2254 char *bufptr
; /* Pointer into buffer */
2255 ipp_state_t ipp_state
; /* IPP state value */
2259 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2260 "cupsdWriteClient(con=%p) %d response=%p, file=%d "
2261 "pipe_pid=%d state=%d",
2262 con
, con
->http
.fd
, con
->response
, con
->file
, con
->pipe_pid
,
2266 if (con
->http
.state
!= HTTP_GET_SEND
&&
2267 con
->http
.state
!= HTTP_POST_SEND
)
2270 if (con
->response
!= NULL
)
2272 ipp_state
= ippWrite(HTTP(con
), con
->response
);
2273 bytes
= ipp_state
!= IPP_ERROR
&& ipp_state
!= IPP_DATA
;
2275 else if ((bytes
= read(con
->file
, buf
, sizeof(buf
) - 1)) > 0)
2277 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2278 "cupsdWriteClient: Read %d bytes from file %d...",
2281 if (con
->pipe_pid
&& !con
->got_fields
)
2284 * Inspect the data for Content-Type and other fields.
2289 for (bufptr
= buf
; !con
->got_fields
&& *bufptr
; bufptr
++)
2290 if (*bufptr
== '\n')
2293 * Send line to client...
2296 if (bufptr
> buf
&& bufptr
[-1] == '\r')
2300 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "Script header: %s", buf
);
2302 if (!con
->sent_header
)
2305 * Handle redirection and CGI status codes...
2308 if (!strncasecmp(buf
, "Location:", 9))
2310 cupsdSendHeader(con
, HTTP_SEE_OTHER
, NULL
);
2311 con
->sent_header
= 2;
2313 if (httpPrintf(HTTP(con
), "Content-Length: 0\r\n") < 0)
2316 else if (!strncasecmp(buf
, "Status:", 7))
2318 cupsdSendError(con
, (http_status_t
)atoi(buf
+ 7));
2319 con
->sent_header
= 2;
2323 cupsdSendHeader(con
, HTTP_OK
, NULL
);
2324 con
->sent_header
= 1;
2326 if (con
->http
.version
== HTTP_1_1
)
2328 if (httpPrintf(HTTP(con
), "Transfer-Encoding: chunked\r\n") < 0)
2334 if (strncasecmp(buf
, "Status:", 7))
2335 httpPrintf(HTTP(con
), "%s\r\n", buf
);
2337 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdWriteClient: %d %s",
2344 bytes
-= (bufptr
- buf
);
2345 memmove(buf
, bufptr
, bytes
+ 1);
2349 * See if the line was empty...
2352 if (con
->field_col
== 0)
2354 con
->got_fields
= 1;
2356 if (cupsdFlushHeader(con
) < 0)
2358 cupsdCloseClient(con
);
2362 if (con
->http
.version
== HTTP_1_1
)
2363 con
->http
.data_encoding
= HTTP_ENCODE_CHUNKED
;
2368 else if (*bufptr
!= '\r')
2371 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2372 "cupsdWriteClient: %d bytes=%d, got_fields=%d",
2373 con
->http
.fd
, bytes
, con
->got_fields
);
2375 if (bytes
> 0 && !con
->got_fields
)
2378 * Remaining text needs to go out...
2381 httpPrintf(HTTP(con
), "%s", buf
);
2383 con
->http
.activity
= time(NULL
);
2386 else if (bytes
== 0)
2387 con
->http
.activity
= time(NULL
);
2392 if (httpWrite2(HTTP(con
), buf
, bytes
) < 0)
2394 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2395 "cupsdWriteClient: %d Write of %d bytes failed!",
2396 con
->http
.fd
, bytes
);
2398 cupsdCloseClient(con
);
2402 con
->bytes
+= bytes
;
2404 if (con
->http
.state
== HTTP_WAITING
)
2411 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdWriteClient: %d bytes < 0",
2414 cupsdLogRequest(con
, HTTP_OK
);
2416 httpFlushWrite(HTTP(con
));
2418 if (con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
&& con
->sent_header
== 1)
2420 if (httpWrite2(HTTP(con
), "", 0) < 0)
2422 cupsdCloseClient(con
);
2427 con
->http
.state
= HTTP_WAITING
;
2429 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2430 "cupsdWriteClient: Removing fd %d from OutputSet...",
2433 FD_CLR(con
->http
.fd
, OutputSet
);
2437 if (FD_ISSET(con
->file
, InputSet
))
2439 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2440 "cupsdWriteClient: Removing fd %d from InputSet...",
2442 FD_CLR(con
->file
, InputSet
);
2446 cupsdEndProcess(con
->pipe_pid
, 0);
2448 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2449 "cupsdWriteClient: %d Closing data file %d.",
2450 con
->http
.fd
, con
->file
);
2459 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2460 "cupsdWriteClient: %d Removing temp file %s",
2461 con
->http
.fd
, con
->filename
);
2462 unlink(con
->filename
);
2463 cupsdClearString(&con
->filename
);
2466 if (con
->request
!= NULL
)
2468 ippDelete(con
->request
);
2469 con
->request
= NULL
;
2472 if (con
->response
!= NULL
)
2474 ippDelete(con
->response
);
2475 con
->response
= NULL
;
2478 cupsdClearString(&con
->command
);
2479 cupsdClearString(&con
->options
);
2481 if (!con
->http
.keep_alive
)
2483 cupsdCloseClient(con
);
2489 con
->file_ready
= 0;
2491 if (con
->pipe_pid
&& !FD_ISSET(con
->file
, InputSet
))
2493 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2494 "cupsdWriteClient: Adding fd %d to InputSet...",
2496 FD_SET(con
->file
, InputSet
);
2500 con
->http
.activity
= time(NULL
);
2507 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
2510 static int /* O - 1 if modified since */
2512 cupsd_client_t
*con
, /* I - Client connection */
2513 struct stat
*filestats
) /* I - File information */
2515 char *ptr
; /* Pointer into field */
2516 time_t date
; /* Time/date value */
2517 off_t size
; /* Size/length value */
2522 ptr
= con
->http
.fields
[HTTP_FIELD_IF_MODIFIED_SINCE
];
2527 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2528 "check_if_modified: %d If-Modified-Since=\"%s\"",
2531 while (*ptr
!= '\0')
2533 while (isspace(*ptr
) || *ptr
== ';')
2536 if (strncasecmp(ptr
, "length=", 7) == 0)
2539 size
= strtoll(ptr
, NULL
, 10);
2541 while (isdigit(*ptr
))
2544 else if (isalpha(*ptr
))
2546 date
= httpGetDateTime(ptr
);
2547 while (*ptr
!= '\0' && *ptr
!= ';')
2554 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2555 "check_if_modified: %d sizes=" CUPS_LLFMT
","
2556 CUPS_LLFMT
" dates=%d,%d",
2557 con
->http
.fd
, CUPS_LLCAST size
,
2558 CUPS_LLCAST filestats
->st_size
, (int)date
,
2559 (int)filestats
->st_mtime
);
2561 return ((size
!= filestats
->st_size
&& size
!= 0) ||
2562 (date
< filestats
->st_mtime
&& date
!= 0) ||
2563 (size
== 0 && date
== 0));
2569 * 'encrypt_client()' - Enable encryption for the client...
2572 static int /* O - 1 on success, 0 on error */
2573 encrypt_client(cupsd_client_t
*con
) /* I - Client to encrypt */
2576 SSL_CTX
*context
; /* Context for encryption */
2577 SSL
*conn
; /* Connection for encryption */
2578 unsigned long error
; /* Error code */
2582 * Verify that we have a certificate...
2585 if (access(ServerKey
, 0) || access(ServerCertificate
, 0))
2588 * Nope, make a self-signed certificate...
2591 if (!make_certificate())
2596 * Create the SSL context and accept the connection...
2599 context
= SSL_CTX_new(SSLv23_server_method());
2601 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
2602 SSL_CTX_use_PrivateKey_file(context
, ServerKey
, SSL_FILETYPE_PEM
);
2603 SSL_CTX_use_certificate_file(context
, ServerCertificate
, SSL_FILETYPE_PEM
);
2605 conn
= SSL_new(context
);
2607 SSL_set_fd(conn
, con
->http
.fd
);
2608 if (SSL_accept(conn
) != 1)
2610 cupsdLogMessage(CUPSD_LOG_ERROR
,
2611 "encrypt_client: Unable to encrypt connection from %s!",
2612 con
->http
.hostname
);
2614 while ((error
= ERR_get_error()) != 0)
2615 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s",
2616 ERR_error_string(error
, NULL
));
2618 SSL_CTX_free(context
);
2623 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2624 "encrypt_client: %d Connection from %s now encrypted.",
2625 con
->http
.fd
, con
->http
.hostname
);
2627 con
->http
.tls
= conn
;
2630 # elif defined(HAVE_GNUTLS)
2631 http_tls_t
*conn
; /* TLS session object */
2632 int error
; /* Error code */
2633 gnutls_certificate_server_credentials
*credentials
;
2634 /* TLS credentials */
2638 * Verify that we have a certificate...
2641 if (access(ServerKey
, 0) || access(ServerCertificate
, 0))
2644 * Nope, make a self-signed certificate...
2647 if (!make_certificate())
2652 * Create the SSL object and perform the SSL handshake...
2655 conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
));
2660 credentials
= (gnutls_certificate_server_credentials
*)
2661 malloc(sizeof(gnutls_certificate_server_credentials
));
2662 if (credentials
== NULL
)
2664 cupsdLogMessage(CUPSD_LOG_ERROR
,
2665 "encrypt_client: Unable to encrypt connection from %s!",
2666 con
->http
.hostname
);
2667 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s", strerror(errno
));
2673 gnutls_certificate_allocate_credentials(credentials
);
2674 gnutls_certificate_set_x509_key_file(*credentials
, ServerCertificate
,
2675 ServerKey
, GNUTLS_X509_FMT_PEM
);
2677 gnutls_init(&(conn
->session
), GNUTLS_SERVER
);
2678 gnutls_set_default_priority(conn
->session
);
2679 gnutls_credentials_set(conn
->session
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
2680 gnutls_transport_set_ptr(conn
->session
,
2681 (gnutls_transport_ptr
)((long)con
->http
.fd
));
2683 error
= gnutls_handshake(conn
->session
);
2685 if (error
!= GNUTLS_E_SUCCESS
)
2687 cupsdLogMessage(CUPSD_LOG_ERROR
,
2688 "encrypt_client: Unable to encrypt connection from %s!",
2689 con
->http
.hostname
);
2690 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s",
2691 gnutls_strerror(error
));
2693 gnutls_deinit(conn
->session
);
2694 gnutls_certificate_free_credentials(*credentials
);
2700 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2701 "encrypt_client: %d Connection from %s now encrypted.",
2702 con
->http
.fd
, con
->http
.hostname
);
2704 conn
->credentials
= credentials
;
2705 con
->http
.tls
= conn
;
2708 # elif defined(HAVE_CDSASSL)
2709 OSStatus error
; /* Error code */
2710 http_tls_t
*conn
; /* CDSA connection information */
2711 cdsa_conn_ref_t u
; /* Connection reference union */
2714 if ((conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
))) == NULL
)
2718 conn
->session
= NULL
;
2719 conn
->certsArray
= get_cdsa_server_certs();
2721 if (!conn
->certsArray
)
2724 * No keychain (yet), make a self-signed certificate...
2727 if (make_certificate())
2728 conn
->certsArray
= get_cdsa_server_certs();
2731 if (!conn
->certsArray
)
2733 cupsdLogMessage(CUPSD_LOG_ERROR
,
2734 "EncryptClient: Could not find signing key in keychain "
2735 "\"%s\"", ServerCertificate
);
2736 error
= errSSLBadCert
; /* errSSLBadConfiguration is a better choice, but not available on 10.2.x */
2740 error
= SSLNewContext(true, &conn
->session
);
2743 error
= SSLSetIOFuncs(conn
->session
, _httpReadCDSA
, _httpWriteCDSA
);
2746 error
= SSLSetProtocolVersionEnabled(conn
->session
, kSSLProtocol2
, false);
2751 * Use a union to resolve warnings about int/pointer size mismatches...
2754 u
.connection
= NULL
;
2755 u
.sock
= con
->http
.fd
;
2756 error
= SSLSetConnection(conn
->session
, u
.connection
);
2760 error
= SSLSetAllowsExpiredCerts(conn
->session
, true);
2763 error
= SSLSetAllowsAnyRoot(conn
->session
, true);
2766 error
= SSLSetCertificate(conn
->session
, conn
->certsArray
);
2771 * Perform SSL/TLS handshake
2774 while ((error
= SSLHandshake(conn
->session
)) == errSSLWouldBlock
)
2780 cupsdLogMessage(CUPSD_LOG_ERROR
,
2781 "encrypt_client: Unable to encrypt connection from %s!",
2782 con
->http
.hostname
);
2784 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s (%d)",
2785 cssmErrorString(error
), (int)error
);
2787 con
->http
.error
= error
;
2788 con
->http
.status
= HTTP_ERROR
;
2791 SSLDisposeContext(conn
->session
);
2793 if (conn
->certsArray
)
2794 CFRelease(conn
->certsArray
);
2801 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2802 "encrypt_client: %d Connection from %s now encrypted.",
2803 con
->http
.fd
, con
->http
.hostname
);
2805 con
->http
.tls
= conn
;
2808 # endif /* HAVE_LIBSSL */
2810 #endif /* HAVE_SSL */
2815 * 'get_cdsa_server_certs()' - Convert a keychain name into the CFArrayRef
2816 * required by SSLSetCertificate.
2818 * For now we assumes that there is exactly one SecIdentity in the
2819 * keychain - i.e. there is exactly one matching cert/private key pair.
2820 * In the future we will search a keychain for a SecIdentity matching a
2821 * specific criteria. We also skip the operation of adding additional
2822 * non-signing certs from the keychain to the CFArrayRef.
2824 * To create a self-signed certificate for testing use the certtool.
2825 * Executing the following as root will do it:
2827 * certtool c k=/Library/Keychains/System.keychain
2830 static CFArrayRef
/* O - Array of certificates */
2831 get_cdsa_server_certs(void)
2833 OSStatus err
; /* Error info */
2834 SecKeychainRef kcRef
; /* Keychain reference */
2835 SecIdentitySearchRef srchRef
; /* Search reference */
2836 SecIdentityRef identity
; /* Identity */
2837 CFArrayRef ca
; /* Certificate array */
2844 err
= SecKeychainOpen(ServerCertificate
, &kcRef
);
2847 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot open keychain \"%s\", error %d.",
2848 ServerCertificate
, (int)err
);
2852 * Search for "any" identity matching specified key use;
2853 * in this app, we expect there to be exactly one.
2856 err
= SecIdentitySearchCreate(kcRef
, CSSM_KEYUSE_SIGN
, &srchRef
);
2859 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2860 "Cannot find signing key in keychain \"%s\", error %d",
2861 ServerCertificate
, (int)err
);
2864 err
= SecIdentitySearchCopyNext(srchRef
, &identity
);
2867 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2868 "Cannot find signing key in keychain \"%s\", error %d",
2869 ServerCertificate
, (int)err
);
2872 if (CFGetTypeID(identity
) != SecIdentityGetTypeID())
2873 cupsdLogMessage(CUPSD_LOG_ERROR
,
2874 "SecIdentitySearchCopyNext CFTypeID failure!");
2878 * Found one. Place it in a CFArray.
2879 * TBD: snag other (non-identity) certs from keychain and add them
2883 ca
= CFArrayCreate(NULL
, (const void **)&identity
, 1, &kCFTypeArrayCallBacks
);
2886 cupsdLogMessage(CUPSD_LOG_ERROR
, "CFArrayCreate error");
2889 CFRelease(identity
);
2900 #endif /* HAVE_CDSASSL */
2904 * 'get_file()' - Get a filename and state info.
2907 static char * /* O - Real filename */
2908 get_file(cupsd_client_t
*con
, /* I - Client connection */
2909 struct stat
*filestats
, /* O - File information */
2910 char *filename
, /* IO - Filename buffer */
2911 int len
) /* I - Buffer length */
2913 int status
; /* Status of filesystem calls */
2914 char *ptr
; /* Pointer info filename */
2915 int plen
; /* Remaining length after pointer */
2919 * Need to add DocumentRoot global...
2922 if (!strncmp(con
->uri
, "/ppd/", 5))
2923 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
);
2924 else if (!strncmp(con
->uri
, "/admin/conf/", 12))
2925 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
+ 11);
2926 else if (!strncmp(con
->uri
, "/admin/log/", 11))
2928 if (!strcmp(con
->uri
+ 11, "access_log") && AccessLog
[0] == '/')
2929 strlcpy(filename
, AccessLog
, len
);
2930 else if (!strcmp(con
->uri
+ 11, "error_log") && ErrorLog
[0] == '/')
2931 strlcpy(filename
, ErrorLog
, len
);
2932 else if (!strcmp(con
->uri
+ 11, "page_log") && PageLog
[0] == '/')
2933 strlcpy(filename
, PageLog
, len
);
2937 else if (con
->language
)
2938 snprintf(filename
, len
, "%s/%s%s", DocumentRoot
, con
->language
->language
,
2941 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
2943 if ((ptr
= strchr(filename
, '?')) != NULL
)
2947 * Grab the status for this language; if there isn't a language-specific file
2948 * then fallback to the default one...
2951 if ((status
= stat(filename
, filestats
)) != 0 && con
->language
&&
2952 strncmp(con
->uri
, "/ppd/", 5) &&
2953 strncmp(con
->uri
, "/admin/conf/", 12) &&
2954 strncmp(con
->uri
, "/admin/log/", 11))
2957 * Drop the country code...
2960 char ll
[3]; /* Short language name */
2963 strlcpy(ll
, con
->language
->language
, sizeof(ll
));
2964 snprintf(filename
, len
, "%s/%s%s", DocumentRoot
, ll
, con
->uri
);
2966 if ((ptr
= strchr(filename
, '?')) != NULL
)
2969 if ((status
= stat(filename
, filestats
)) != 0)
2972 * Drop the language prefix and try the root directory...
2975 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
2977 if ((ptr
= strchr(filename
, '?')) != NULL
)
2980 status
= stat(filename
, filestats
);
2985 * If we're found a directory, get the index.html file instead...
2988 if (!status
&& S_ISDIR(filestats
->st_mode
))
2990 if (filename
[strlen(filename
) - 1] != '/')
2991 strlcat(filename
, "/", len
);
2993 ptr
= filename
+ strlen(filename
);
2994 plen
= len
- (ptr
- filename
);
2996 strlcpy(ptr
, "index.html", plen
);
2997 status
= stat(filename
, filestats
);
3002 strlcpy(ptr
, "index.class", plen
);
3003 status
= stat(filename
, filestats
);
3005 #endif /* HAVE_JAVA */
3010 strlcpy(ptr
, "index.pl", plen
);
3011 status
= stat(filename
, filestats
);
3013 #endif /* HAVE_PERL */
3018 strlcpy(ptr
, "index.php", plen
);
3019 status
= stat(filename
, filestats
);
3021 #endif /* HAVE_PHP */
3026 strlcpy(ptr
, "index.pyc", plen
);
3027 status
= stat(filename
, filestats
);
3032 strlcpy(ptr
, "index.py", plen
);
3033 status
= stat(filename
, filestats
);
3035 #endif /* HAVE_PYTHON */
3038 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "get_file: %d filename=%s size=%d",
3039 con
->http
.fd
, filename
,
3040 status
? -1 : (int)filestats
->st_size
);
3043 con
->http
.data_remaining
= (int)filestats
->st_size
;
3053 * 'install_conf_file()' - Install a configuration file.
3056 static http_status_t
/* O - Status */
3057 install_conf_file(cupsd_client_t
*con
) /* I - Connection */
3059 cups_file_t
*in
, /* Input file */
3060 *out
; /* Output file */
3061 char buffer
[1024]; /* Copy buffer */
3062 int bytes
; /* Number of bytes */
3063 char conffile
[1024], /* Configuration filename */
3064 newfile
[1024], /* New config filename */
3065 oldfile
[1024]; /* Old config filename */
3066 struct stat confinfo
; /* Config file info */
3070 * First construct the filenames...
3073 snprintf(conffile
, sizeof(conffile
), "%s%s", ServerRoot
, con
->uri
+ 11);
3074 snprintf(newfile
, sizeof(newfile
), "%s%s.N", ServerRoot
, con
->uri
+ 11);
3075 snprintf(oldfile
, sizeof(oldfile
), "%s%s.O", ServerRoot
, con
->uri
+ 11);
3077 cupsdLogMessage(CUPSD_LOG_INFO
, "Installing config file \"%s\"...", conffile
);
3080 * Get the owner, group, and permissions of the configuration file.
3081 * If it doesn't exist, assign it to the User and Group in the
3082 * cupsd.conf file with mode 0640 permissions.
3085 if (stat(conffile
, &confinfo
))
3087 confinfo
.st_uid
= User
;
3088 confinfo
.st_gid
= Group
;
3089 confinfo
.st_mode
= ConfigFilePerm
;
3093 * Open the request file and new config file...
3096 if ((in
= cupsFileOpen(con
->filename
, "rb")) == NULL
)
3098 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open request file \"%s\" - %s",
3099 con
->filename
, strerror(errno
));
3100 return (HTTP_SERVER_ERROR
);
3103 if ((out
= cupsFileOpen(newfile
, "wb")) == NULL
)
3106 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open config file \"%s\" - %s",
3107 newfile
, strerror(errno
));
3108 return (HTTP_SERVER_ERROR
);
3111 fchmod(cupsFileNumber(out
), confinfo
.st_mode
);
3112 fchown(cupsFileNumber(out
), confinfo
.st_uid
, confinfo
.st_gid
);
3115 * Copy from the request to the new config file...
3118 while ((bytes
= cupsFileRead(in
, buffer
, sizeof(buffer
))) > 0)
3119 if (cupsFileWrite(out
, buffer
, bytes
) < bytes
)
3121 cupsdLogMessage(CUPSD_LOG_ERROR
,
3122 "Unable to copy to config file \"%s\" - %s",
3123 newfile
, strerror(errno
));
3129 return (HTTP_SERVER_ERROR
);
3133 * Close the files...
3137 if (cupsFileClose(out
))
3139 cupsdLogMessage(CUPSD_LOG_ERROR
,
3140 "Error file closing config file \"%s\" - %s",
3141 newfile
, strerror(errno
));
3145 return (HTTP_SERVER_ERROR
);
3149 * Remove the request file...
3152 unlink(con
->filename
);
3153 cupsdClearString(&con
->filename
);
3156 * Unlink the old backup, rename the current config file to the backup
3157 * filename, and rename the new config file to the config file name...
3160 if (unlink(oldfile
))
3161 if (errno
!= ENOENT
)
3163 cupsdLogMessage(CUPSD_LOG_ERROR
,
3164 "Unable to remove backup config file \"%s\" - %s",
3165 oldfile
, strerror(errno
));
3169 return (HTTP_SERVER_ERROR
);
3172 if (rename(conffile
, oldfile
))
3173 if (errno
!= ENOENT
)
3175 cupsdLogMessage(CUPSD_LOG_ERROR
,
3176 "Unable to rename old config file \"%s\" - %s",
3177 conffile
, strerror(errno
));
3181 return (HTTP_SERVER_ERROR
);
3184 if (rename(newfile
, conffile
))
3186 cupsdLogMessage(CUPSD_LOG_ERROR
,
3187 "Unable to rename new config file \"%s\" - %s",
3188 newfile
, strerror(errno
));
3190 rename(oldfile
, conffile
);
3193 return (HTTP_SERVER_ERROR
);
3197 * If the cupsd.conf file was updated, set the NeedReload flag...
3200 if (!strcmp(con
->uri
, "/admin/conf/cupsd.conf"))
3201 NeedReload
= RELOAD_CUPSD
;
3203 NeedReload
= RELOAD_ALL
;
3205 ReloadTime
= time(NULL
);
3208 * Return that the file was created successfully...
3211 return (HTTP_CREATED
);
3216 * 'is_cgi()' - Is the resource a CGI script/program?
3219 static int /* O - 1 = CGI, 0 = file */
3220 is_cgi(cupsd_client_t
*con
, /* I - Client connection */
3221 const char *filename
, /* I - Real filename */
3222 struct stat
*filestats
, /* I - File information */
3223 mime_type_t
*type
) /* I - MIME type */
3225 const char *options
; /* Options on URL */
3228 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3229 "is_cgi(con=%p, filename=\"%s\", filestats=%p, type=%s/%s)\n",
3230 con
, filename
, filestats
, type
? type
->super
: "unknown",
3231 type
? type
->type
: "unknown");
3234 * Get the options, if any...
3237 if ((options
= strchr(con
->uri
, '?')) != NULL
)
3241 * Check for known types...
3244 if (!type
|| strcasecmp(type
->super
, "application"))
3246 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "is_cgi: Returning 0...");
3250 if (!strcasecmp(type
->type
, "x-httpd-cgi") &&
3251 (filestats
->st_mode
& 0111))
3254 * "application/x-httpd-cgi" is a CGI script.
3257 cupsdSetString(&con
->command
, filename
);
3259 filename
= strrchr(filename
, '/') + 1; /* Filename always absolute */
3261 cupsdSetString(&con
->options
, options
);
3263 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3264 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3265 con
->command
, con
->options
);
3270 else if (!strcasecmp(type
->type
, "x-httpd-java"))
3273 * "application/x-httpd-java" is a Java servlet.
3276 cupsdSetString(&con
->command
, CUPS_JAVA
);
3279 cupsdSetStringf(&con
->options
, "%s %s", filename
, options
);
3281 cupsdSetString(&con
->options
, filename
);
3283 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3284 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3285 con
->command
, con
->options
);
3289 #endif /* HAVE_JAVA */
3291 else if (!strcasecmp(type
->type
, "x-httpd-perl"))
3294 * "application/x-httpd-perl" is a Perl page.
3297 cupsdSetString(&con
->command
, CUPS_PERL
);
3300 cupsdSetStringf(&con
->options
, "%s %s", filename
, options
);
3302 cupsdSetString(&con
->options
, filename
);
3304 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3305 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3306 con
->command
, con
->options
);
3310 #endif /* HAVE_PERL */
3312 else if (!strcasecmp(type
->type
, "x-httpd-php"))
3315 * "application/x-httpd-php" is a PHP page.
3318 cupsdSetString(&con
->command
, CUPS_PHP
);
3321 cupsdSetStringf(&con
->options
, "%s %s", filename
, options
);
3323 cupsdSetString(&con
->options
, filename
);
3325 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3326 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3327 con
->command
, con
->options
);
3331 #endif /* HAVE_PHP */
3333 else if (!strcasecmp(type
->type
, "x-httpd-python"))
3336 * "application/x-httpd-python" is a Python page.
3339 cupsdSetString(&con
->command
, CUPS_PYTHON
);
3342 cupsdSetStringf(&con
->options
, "%s %s", filename
, options
);
3344 cupsdSetString(&con
->options
, filename
);
3346 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3347 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3348 con
->command
, con
->options
);
3352 #endif /* HAVE_PYTHON */
3354 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "is_cgi: Returning 0...");
3361 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
3364 static int /* O - 0 if relative, 1 if absolute */
3365 is_path_absolute(const char *path
) /* I - Input path */
3368 * Check for a leading slash...
3375 * Check for "/.." in the path...
3378 while ((path
= strstr(path
, "/..")) != NULL
)
3380 if (!path
[3] || path
[3] == '/')
3387 * If we haven't found any relative paths, return 1 indicating an
3397 * 'make_certificate()' - Make a self-signed SSL/TLS certificate.
3400 static int /* O - 1 on success, 0 on failure */
3401 make_certificate(void)
3403 #if defined(HAVE_LIBSSL) && defined(HAVE_WAITPID)
3404 int pid
, /* Process ID of command */
3405 status
; /* Status of command */
3406 char command
[1024], /* Command */
3407 *argv
[11], /* Command-line arguments */
3408 *envp
[MAX_ENV
+ 1], /* Environment variables */
3409 home
[1024], /* HOME environment variable */
3410 infofile
[1024], /* Type-in information for cert */
3411 seedfile
[1024]; /* Random number seed file */
3412 int envc
, /* Number of environment variables */
3413 bytes
; /* Bytes written */
3414 cups_file_t
*fp
; /* Seed/info file */
3415 int infofd
; /* Info file descriptor */
3419 * Run the "openssl" command to seed the random number generator and
3420 * generate a self-signed certificate that is good for 10 years:
3422 * openssl rand -rand seedfile 1
3424 * openssl req -new -x509 -keyout ServerKey \
3425 * -out ServerCertificate -days 3650 -nodes
3427 * The seeding step is crucial in ensuring that the openssl command
3428 * does not block on systems without sufficient entropy...
3431 if (!cupsFileFind("openssl", getenv("PATH"), 1, command
, sizeof(command
)))
3433 cupsdLogMessage(CUPSD_LOG_ERROR
,
3434 "No SSL certificate and openssl command not found!");
3438 if (access("/dev/urandom", 0))
3441 * If the system doesn't provide /dev/urandom, then any random source
3442 * will probably be blocking-style, so generate some random data to
3443 * use as a seed for the certificate. Note that we have already
3444 * seeded the random number generator in cupsdInitCerts()...
3447 cupsdLogMessage(CUPSD_LOG_INFO
,
3448 "Seeding the random number generator...");
3450 snprintf(home
, sizeof(home
), "HOME=%s", TempDir
);
3453 * Write the seed file...
3456 if ((fp
= cupsTempFile2(seedfile
, sizeof(seedfile
))) == NULL
)
3458 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to create seed file %s - %s",
3459 seedfile
, strerror(errno
));
3463 for (bytes
= 0; bytes
< 262144; bytes
++)
3464 cupsFilePutChar(fp
, random());
3469 * Run the openssl command to seed its random number generator...
3472 argv
[0] = "openssl";
3479 envc
= cupsdLoadEnv(envp
, MAX_ENV
);
3480 envp
[envc
++] = home
;
3483 if (!cupsdStartProcess(command
, argv
, envp
, -1, -1, -1, -1, 1, &pid
))
3489 while (waitpid(pid
, &status
, 0) < 0)
3496 cupsdFinishProcess(pid
, command
, sizeof(command
));
3499 * Remove the seed file, as it is no longer needed...
3506 if (WIFEXITED(status
))
3507 cupsdLogMessage(CUPSD_LOG_ERROR
,
3508 "Unable to seed random number generator - "
3509 "the openssl command stopped with status %d!",
3510 WEXITSTATUS(status
));
3512 cupsdLogMessage(CUPSD_LOG_ERROR
,
3513 "Unable to seed random number generator - "
3514 "the openssl command crashed on signal %d!",
3522 * Create a file with the certificate information fields...
3524 * Note: This assumes that the default questions are asked by the openssl
3528 if ((fp
= cupsTempFile2(infofile
, sizeof(infofile
))) == NULL
)
3530 cupsdLogMessage(CUPSD_LOG_ERROR
,
3531 "Unable to create certificate information file %s - %s",
3532 infofile
, strerror(errno
));
3536 cupsFilePrintf(fp
, ".\n.\n.\n%s\n.\n%s\n%s\n",
3537 ServerName
, ServerName
, ServerAdmin
);
3540 cupsdLogMessage(CUPSD_LOG_INFO
,
3541 "Generating SSL server key and certificate...");
3543 argv
[0] = "openssl";
3547 argv
[4] = "-keyout";
3548 argv
[5] = ServerKey
;
3550 argv
[7] = ServerCertificate
;
3553 argv
[10] = "-nodes";
3556 cupsdLoadEnv(envp
, MAX_ENV
);
3558 infofd
= open(infofile
, O_RDONLY
);
3560 if (!cupsdStartProcess(command
, argv
, envp
, infofd
, -1, -1, -1, 1, &pid
))
3570 while (waitpid(pid
, &status
, 0) < 0)
3577 cupsdFinishProcess(pid
, command
, sizeof(command
));
3581 if (WIFEXITED(status
))
3582 cupsdLogMessage(CUPSD_LOG_ERROR
,
3583 "Unable to create SSL server key and certificate - "
3584 "the openssl command stopped with status %d!",
3585 WEXITSTATUS(status
));
3587 cupsdLogMessage(CUPSD_LOG_ERROR
,
3588 "Unable to create SSL server key and certificate - "
3589 "the openssl command crashed on signal %d!",
3594 cupsdLogMessage(CUPSD_LOG_INFO
, "Created SSL server key file \"%s\"...",
3596 cupsdLogMessage(CUPSD_LOG_INFO
,
3597 "Created SSL server certificate file \"%s\"...",
3603 #elif defined(HAVE_GNUTLS)
3604 gnutls_x509_crt crt
; /* Self-signed certificate */
3605 gnutls_x509_privkey key
; /* Encryption key */
3606 cups_lang_t
*language
; /* Default language info */
3607 cups_file_t
*fp
; /* Key/cert file */
3608 unsigned char buffer
[8192]; /* Buffer for x509 data */
3609 size_t bytes
; /* Number of bytes of data */
3610 unsigned char serial
[4]; /* Serial number buffer */
3611 time_t curtime
; /* Current time */
3612 int result
; /* Result of GNU TLS calls */
3616 * Create the encryption key...
3619 cupsdLogMessage(CUPSD_LOG_INFO
, "Generating SSL server key...");
3621 gnutls_x509_privkey_init(&key
);
3622 gnutls_x509_privkey_generate(key
, GNUTLS_PK_RSA
, 2048, 0);
3628 bytes
= sizeof(buffer
);
3630 if ((result
= gnutls_x509_privkey_export(key
, GNUTLS_X509_FMT_PEM
,
3631 buffer
, &bytes
)) < 0)
3633 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to export SSL server key - %s",
3634 gnutls_strerror(result
));
3635 gnutls_x509_privkey_deinit(key
);
3638 else if ((fp
= cupsFileOpen(ServerKey
, "w")) != NULL
)
3640 cupsFileWrite(fp
, (char *)buffer
, bytes
);
3643 cupsdLogMessage(CUPSD_LOG_INFO
, "Created SSL server key file \"%s\"...",
3648 cupsdLogMessage(CUPSD_LOG_ERROR
,
3649 "Unable to create SSL server key file \"%s\" - %s",
3650 ServerKey
, strerror(errno
));
3651 gnutls_x509_privkey_deinit(key
);
3656 * Create the self-signed certificate...
3659 cupsdLogMessage(CUPSD_LOG_INFO
, "Generating self-signed SSL certificate...");
3661 language
= cupsLangDefault();
3662 curtime
= time(NULL
);
3663 serial
[0] = curtime
>> 24;
3664 serial
[1] = curtime
>> 16;
3665 serial
[2] = curtime
>> 8;
3666 serial
[3] = curtime
;
3668 gnutls_x509_crt_init(&crt
);
3669 if (strlen(language
->language
) == 5)
3670 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
3671 language
->language
+ 3, 2);
3673 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
3675 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COMMON_NAME
, 0,
3676 ServerName
, strlen(ServerName
));
3677 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATION_NAME
, 0,
3678 ServerName
, strlen(ServerName
));
3679 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATIONAL_UNIT_NAME
,
3681 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_STATE_OR_PROVINCE_NAME
, 0,
3683 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_LOCALITY_NAME
, 0,
3685 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_PKCS9_EMAIL
, 0,
3686 ServerAdmin
, strlen(ServerAdmin
));
3687 gnutls_x509_crt_set_key(crt
, key
);
3688 gnutls_x509_crt_set_serial(crt
, serial
, sizeof(serial
));
3689 gnutls_x509_crt_set_activation_time(crt
, curtime
);
3690 gnutls_x509_crt_set_expiration_time(crt
, curtime
+ 10 * 365 * 86400);
3691 gnutls_x509_crt_set_ca_status(crt
, 0);
3692 gnutls_x509_crt_set_subject_alternative_name(crt
, GNUTLS_SAN_DNSNAME
,
3694 gnutls_x509_crt_set_key_purpose_oid(crt
, GNUTLS_KP_TLS_WWW_SERVER
, 0);
3695 gnutls_x509_crt_set_key_usage(crt
, GNUTLS_KEY_KEY_ENCIPHERMENT
);
3696 gnutls_x509_crt_set_version(crt
, 3);
3698 bytes
= sizeof(buffer
);
3699 if (gnutls_x509_crt_get_key_id(crt
, 0, buffer
, &bytes
) >= 0)
3700 gnutls_x509_crt_set_subject_key_id(crt
, buffer
, bytes
);
3702 gnutls_x509_crt_sign(crt
, crt
, key
);
3708 bytes
= sizeof(buffer
);
3709 if ((result
= gnutls_x509_crt_export(crt
, GNUTLS_X509_FMT_PEM
,
3710 buffer
, &bytes
)) < 0)
3711 cupsdLogMessage(CUPSD_LOG_ERROR
,
3712 "Unable to export SSL server certificate - %s",
3713 gnutls_strerror(result
));
3714 else if ((fp
= cupsFileOpen(ServerCertificate
, "w")) != NULL
)
3716 cupsFileWrite(fp
, (char *)buffer
, bytes
);
3719 cupsdLogMessage(CUPSD_LOG_INFO
,
3720 "Created SSL server certificate file \"%s\"...",
3724 cupsdLogMessage(CUPSD_LOG_ERROR
,
3725 "Unable to create SSL server certificate file \"%s\" - %s",
3726 ServerCertificate
, strerror(errno
));
3732 gnutls_x509_crt_deinit(crt
);
3733 gnutls_x509_privkey_deinit(key
);
3737 #elif defined(HAVE_CDSASSL) && defined(HAVE_WAITPID)
3738 int pid
, /* Process ID of command */
3739 status
; /* Status of command */
3740 char command
[1024], /* Command */
3741 keychain
[1024], /* Keychain argument */
3742 *argv
[5], /* Command-line arguments */
3743 *envp
[MAX_ENV
]; /* Environment variables */
3747 * Run the "certtool" command to generate a self-signed certificate:
3749 * certtool c Z k=ServerCertificate
3752 if (!cupsFileFind("certtool", getenv("PATH"), 1, command
, sizeof(command
)))
3754 cupsdLogMessage(CUPSD_LOG_ERROR
,
3755 "No SSL certificate and certtool command not found!");
3759 cupsdLogMessage(CUPSD_LOG_INFO
,
3760 "Generating SSL server key and certificate...");
3762 snprintf(keychain
, sizeof(keychain
), "k=%s", ServerCertificate
);
3764 argv
[0] = "certtool";
3770 cupsdLoadEnv(envp
, MAX_ENV
);
3772 if (!cupsdStartProcess(command
, argv
, envp
, -1, -1, -1, -1, 1, &pid
))
3775 while (waitpid(pid
, &status
, 0) < 0)
3782 cupsdFinishProcess(pid
, command
, sizeof(command
));
3786 if (WIFEXITED(status
))
3787 cupsdLogMessage(CUPSD_LOG_ERROR
,
3788 "Unable to create SSL server key and certificate - "
3789 "the certtool command stopped with status %d!",
3790 WEXITSTATUS(status
));
3792 cupsdLogMessage(CUPSD_LOG_ERROR
,
3793 "Unable to create SSL server key and certificate - "
3794 "the certtool command crashed on signal %d!",
3799 cupsdLogMessage(CUPSD_LOG_INFO
,
3800 "Created SSL server certificate file \"%s\"...",
3808 #endif /* HAVE_LIBSSL && HAVE_WAITPID */
3810 #endif /* HAVE_SSL */
3814 * 'pipe_command()' - Pipe the output of a command to the remote client.
3817 static int /* O - Process ID */
3818 pipe_command(cupsd_client_t
*con
, /* I - Client connection */
3819 int infile
, /* I - Standard input for command */
3820 int *outfile
, /* O - Standard output for command */
3821 char *command
, /* I - Command to run */
3822 char *options
, /* I - Options for command */
3823 int root
) /* I - Run as root? */
3825 int i
; /* Looping var */
3826 int pid
; /* Process ID */
3827 char *commptr
, /* Command string pointer */
3828 commch
; /* Command string character */
3829 char *uriptr
; /* URI string pointer */
3830 int fds
[2]; /* Pipe FDs */
3831 int argc
; /* Number of arguments */
3832 int envc
; /* Number of environment variables */
3833 char argbuf
[10240], /* Argument buffer */
3834 *argv
[100], /* Argument strings */
3835 *envp
[MAX_ENV
+ 17]; /* Environment variables */
3836 char content_length
[1024], /* CONTENT_LENGTH environment variable */
3837 content_type
[1024], /* CONTENT_TYPE environment variable */
3838 http_cookie
[32768], /* HTTP_COOKIE environment variable */
3839 http_user_agent
[1024], /* HTTP_USER_AGENT environment variable */
3840 lang
[1024], /* LANG environment variable */
3841 path_info
[1024], /* PATH_INFO environment variable */
3842 *query_string
, /* QUERY_STRING env variable */
3843 remote_addr
[1024], /* REMOTE_ADDR environment variable */
3844 remote_host
[1024], /* REMOTE_HOST environment variable */
3845 remote_user
[1024], /* REMOTE_USER environment variable */
3846 script_name
[1024], /* SCRIPT_NAME environment variable */
3847 server_name
[1024], /* SERVER_NAME environment variable */
3848 server_port
[1024]; /* SERVER_PORT environment variable */
3852 * Parse a copy of the options string, which is of the form:
3854 * argument+argument+argument
3855 * ?argument+argument+argument
3856 * param=value¶m=value
3857 * ?param=value¶m=value
3858 * /name?argument+argument+argument
3859 * /name?param=value¶m=value
3861 * If the string contains an "=" character after the initial name,
3862 * then we treat it as a HTTP GET form request and make a copy of
3863 * the remaining string for the environment variable.
3865 * The string is always parsed out as command-line arguments, to
3866 * be consistent with Apache...
3869 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3870 "pipe_command: command=\"%s\", options=\"%s\"",
3871 command
, options
? options
: "(null)");
3874 query_string
= NULL
;
3877 strlcpy(argbuf
, options
, sizeof(argbuf
));
3881 if (argbuf
[0] == '/')
3884 * Found some trailing path information, set PATH_INFO...
3887 if ((commptr
= strchr(argbuf
, '?')) == NULL
)
3888 commptr
= argbuf
+ strlen(argbuf
);
3892 snprintf(path_info
, sizeof(path_info
), "PATH_INFO=%s", argbuf
);
3898 path_info
[0] = '\0';
3901 if (*commptr
== '?' && con
->operation
== HTTP_GET
)
3904 cupsdSetStringf(&query_string
, "QUERY_STRING=%s", commptr
);
3911 argv
[argc
++] = commptr
;
3913 for (; *commptr
&& argc
< 99; commptr
++)
3916 * Break arguments whenever we see a + or space...
3919 if (*commptr
== ' ' || *commptr
== '+')
3921 while (*commptr
== ' ' || *commptr
== '+')
3925 * If we don't have a blank string, save it as another argument...
3930 argv
[argc
] = commptr
;
3936 else if (*commptr
== '%' && isxdigit(commptr
[1] & 255) &&
3937 isxdigit(commptr
[2] & 255))
3940 * Convert the %xx notation to the individual character.
3943 if (commptr
[1] >= '0' && commptr
[1] <= '9')
3944 *commptr
= (commptr
[1] - '0') << 4;
3946 *commptr
= (tolower(commptr
[1]) - 'a' + 10) << 4;
3948 if (commptr
[2] >= '0' && commptr
[2] <= '9')
3949 *commptr
|= commptr
[2] - '0';
3951 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
3953 _cups_strcpy(commptr
+ 1, commptr
+ 3);
3956 * Check for a %00 and break if that is the case...
3968 * Setup the environment variables as needed...
3972 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF-8", con
->language
->language
);
3974 strcpy(lang
, "LANG=C");
3976 strcpy(remote_addr
, "REMOTE_ADDR=");
3977 httpAddrString(con
->http
.hostaddr
, remote_addr
+ 12,
3978 sizeof(remote_addr
) - 12);
3980 snprintf(remote_host
, sizeof(remote_host
), "REMOTE_HOST=%s",
3981 con
->http
.hostname
);
3983 snprintf(script_name
, sizeof(script_name
), "SCRIPT_NAME=%s", con
->uri
);
3984 if ((uriptr
= strchr(script_name
, '?')) != NULL
)
3987 sprintf(server_port
, "SERVER_PORT=%d", con
->serverport
);
3989 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
3992 envc
= cupsdLoadEnv(envp
, (int)(sizeof(envp
) / sizeof(envp
[0])));
3994 envp
[envc
++] = lang
;
3995 envp
[envc
++] = "REDIRECT_STATUS=1";
3996 envp
[envc
++] = server_name
;
3997 envp
[envc
++] = server_port
;
3998 envp
[envc
++] = remote_addr
;
3999 envp
[envc
++] = remote_host
;
4000 envp
[envc
++] = script_name
;
4003 envp
[envc
++] = path_info
;
4005 if (con
->username
[0])
4007 snprintf(remote_user
, sizeof(remote_user
), "REMOTE_USER=%s", con
->username
);
4009 envp
[envc
++] = remote_user
;
4012 if (con
->http
.version
== HTTP_1_1
)
4013 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.1";
4014 else if (con
->http
.version
== HTTP_1_0
)
4015 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.0";
4017 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/0.9";
4019 if (con
->http
.cookie
)
4021 snprintf(http_cookie
, sizeof(http_cookie
), "HTTP_COOKIE=%s",
4023 envp
[envc
++] = http_cookie
;
4026 if (con
->http
.fields
[HTTP_FIELD_USER_AGENT
][0])
4028 snprintf(http_user_agent
, sizeof(http_user_agent
), "HTTP_USER_AGENT=%s",
4029 con
->http
.fields
[HTTP_FIELD_USER_AGENT
]);
4030 envp
[envc
++] = http_user_agent
;
4033 if (con
->operation
== HTTP_GET
)
4035 for (i
= 0; i
< argc
; i
++)
4036 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "argv[%d] = \"%s\"", i
, argv
[i
]);
4038 envp
[envc
++] = "REQUEST_METHOD=GET";
4043 * Add GET form variables after ?...
4046 envp
[envc
++] = query_string
;
4051 sprintf(content_length
, "CONTENT_LENGTH=" CUPS_LLFMT
,
4052 CUPS_LLCAST con
->bytes
);
4053 snprintf(content_type
, sizeof(content_type
), "CONTENT_TYPE=%s",
4054 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
4056 envp
[envc
++] = "REQUEST_METHOD=POST";
4057 envp
[envc
++] = content_length
;
4058 envp
[envc
++] = content_type
;
4062 * Tell the CGI if we are using encryption...
4066 envp
[envc
++] = "HTTPS=ON";
4069 * Terminate the environment array...
4074 if (LogLevel
== CUPSD_LOG_DEBUG2
)
4076 for (i
= 0; i
< argc
; i
++)
4077 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4078 "pipe_command: argv[%d] = \"%s\"", i
, argv
[i
]);
4079 for (i
= 0; i
< envc
; i
++)
4080 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4081 "pipe_command: envp[%d] = \"%s\"", i
, envp
[i
]);
4085 * Create a pipe for the output...
4088 if (cupsdOpenPipe(fds
))
4090 cupsdClearString(&query_string
);
4092 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to create pipes for CGI %s - %s",
4093 argv
[0], strerror(errno
));
4098 * Then execute the command...
4101 if (cupsdStartProcess(command
, argv
, envp
, infile
, fds
[1], CGIPipes
[1],
4102 -1, root
, &pid
) < 0)
4105 * Error - can't fork!
4108 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to fork for CGI %s - %s", argv
[0],
4111 cupsdClosePipe(fds
);
4117 * Fork successful - return the PID...
4120 if (con
->username
[0])
4121 cupsdAddCert(pid
, con
->username
);
4123 cupsdLogMessage(CUPSD_LOG_DEBUG
, "CGI %s started - PID = %d", command
, pid
);
4129 cupsdClearString(&query_string
);
4136 * 'write_file()' - Send a file via HTTP.
4139 static int /* O - 0 on failure, 1 on success */
4140 write_file(cupsd_client_t
*con
, /* I - Client connection */
4141 http_status_t code
, /* I - HTTP status */
4142 char *filename
, /* I - Filename */
4143 char *type
, /* I - File type */
4144 struct stat
*filestats
) /* O - File information */
4146 con
->file
= open(filename
, O_RDONLY
);
4148 cupsdLogMessage(CUPSD_LOG_DEBUG
, "write_file: %d file=%d", con
->http
.fd
,
4154 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
4158 if (!cupsdSendHeader(con
, code
, type
))
4161 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
4162 httpGetDateString(filestats
->st_mtime
)) < 0)
4164 if (httpPrintf(HTTP(con
), "Content-Length: " CUPS_LLFMT
"\r\n",
4165 CUPS_LLCAST filestats
->st_size
) < 0)
4167 if (httpPrintf(HTTP(con
), "\r\n") < 0)
4170 if (cupsdFlushHeader(con
) < 0)
4173 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
4174 con
->http
.data_remaining
= filestats
->st_size
;
4176 if (con
->http
.data_remaining
<= INT_MAX
)
4177 con
->http
._data_remaining
= con
->http
.data_remaining
;
4179 con
->http
._data_remaining
= INT_MAX
;
4181 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4182 "write_file: Adding fd %d to OutputSet...", con
->http
.fd
);
4184 FD_SET(con
->http
.fd
, OutputSet
);
4191 * End of "$Id: client.c 5972 2006-09-19 20:44:07Z mike $".