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 * cupsdReadClient() - Read data from a client.
30 * cupsdSendCommand() - Send output from a command via HTTP.
31 * cupsdSendError() - Send an error message via HTTP.
32 * cupsdSendHeader() - Send an HTTP request.
33 * cupsdUpdateCGI() - Read status messages from CGI scripts and programs.
34 * cupsdWriteClient() - Write data to a client as needed.
35 * check_if_modified() - Decode an "If-Modified-Since" line.
36 * encrypt_client() - Enable encryption for the client...
37 * get_cdsa_server_certs() - Convert a keychain name into the CFArrayRef
38 * required by SSLSetCertificate.
39 * get_file() - Get a filename and state info.
40 * install_conf_file() - Install a configuration file.
41 * is_cgi() - Is the resource a CGI script/program?
42 * is_path_absolute() - Is a path absolute and free of relative elements.
43 * make_certificate() - Make a self-signed SSL/TLS certificate.
44 * pipe_command() - Pipe the output of a command to the remote client.
45 * write_file() - Send a file via HTTP.
49 * Include necessary headers...
52 #include <cups/http-private.h>
56 # include <Security/Security.h>
57 # ifdef HAVE_SECBASEPRIV_H
58 # include <Security/SecBasePriv.h>
60 extern const char *cssmErrorString(int error
);
61 # endif /* HAVE_SECBASEPRIV_H */
62 #endif /* HAVE_CDSASSL */
64 # include <gnutls/x509.h>
65 #endif /* HAVE_GNUTLS */
72 static int check_if_modified(cupsd_client_t
*con
,
73 struct stat
*filestats
);
75 static int encrypt_client(cupsd_client_t
*con
);
78 static CFArrayRef
get_cdsa_server_certs(void);
79 #endif /* HAVE_CDSASSL */
80 static char *get_file(cupsd_client_t
*con
, struct stat
*filestats
,
81 char *filename
, int len
);
82 static http_status_t
install_conf_file(cupsd_client_t
*con
);
83 static int is_cgi(cupsd_client_t
*con
, const char *filename
,
84 struct stat
*filestats
, mime_type_t
*type
);
85 static int is_path_absolute(const char *path
);
87 static void make_certificate(void);
88 #endif /* HAVE_GNUTLS */
89 static int pipe_command(cupsd_client_t
*con
, int infile
, int *outfile
,
90 char *command
, char *options
, int root
);
91 static int write_file(cupsd_client_t
*con
, http_status_t code
,
92 char *filename
, char *type
,
93 struct stat
*filestats
);
97 * 'cupsdAcceptClient()' - Accept a new client.
101 cupsdAcceptClient(cupsd_listener_t
*lis
)/* I - Listener socket */
103 int count
; /* Count of connections on a host */
104 int val
; /* Parameter value */
105 cupsd_client_t
*con
, /* New client pointer */
106 *tempcon
; /* Temporary client pointer */
107 http_addrlist_t
*addrlist
, /* List of adddresses for host */
108 *addr
; /* Current address */
109 socklen_t addrlen
; /* Length of address */
110 char *hostname
; /* Hostname for address */
111 http_addr_t temp
; /* Temporary address variable */
112 static time_t last_dos
= 0; /* Time of last DoS attack */
115 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
116 "cupsdAcceptClient(lis=%p) %d Clients = %d",
117 lis
, lis
->fd
, cupsArrayCount(Clients
));
120 * Make sure we don't have a full set of clients already...
123 if (cupsArrayCount(Clients
) == MaxClients
)
127 * Get a pointer to the next available client...
131 Clients
= cupsArrayNew(NULL
, NULL
);
136 con
= calloc(1, sizeof(cupsd_client_t
));
138 con
->http
.activity
= time(NULL
);
140 con
->http
.hostaddr
= &(con
->clientaddr
);
143 * Accept the client and get the remote address...
146 addrlen
= sizeof(http_addr_t
);
148 if ((con
->http
.fd
= accept(lis
->fd
, (struct sockaddr
*)con
->http
.hostaddr
,
151 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to accept client connection - %s.",
158 if (lis
->address
.addr
.sa_family
== AF_INET6
)
161 * Save the connected port number...
164 con
->http
.hostaddr
->ipv6
.sin6_port
= lis
->address
.ipv6
.sin6_port
;
167 * Convert IPv4 over IPv6 addresses (::ffff:n.n.n.n) to IPv4 forms we
168 * can more easily use...
171 if (con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[0] == 0 &&
172 con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[1] == 0 &&
173 ntohl(con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[2]) == 0xffff)
174 con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[2] = 0;
177 #endif /* AF_INET6 */
178 if (lis
->address
.addr
.sa_family
== AF_INET
)
179 con
->http
.hostaddr
->ipv4
.sin_port
= lis
->address
.ipv4
.sin_port
;
182 * Check the number of clients on the same address...
185 for (count
= 0, tempcon
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
187 tempcon
= (cupsd_client_t
*)cupsArrayNext(Clients
))
188 if (httpAddrEqual(tempcon
->http
.hostaddr
, con
->http
.hostaddr
))
191 if (count
>= MaxClientsPerHost
)
195 if (count
>= MaxClientsPerHost
)
197 if ((time(NULL
) - last_dos
) >= 60)
199 last_dos
= time(NULL
);
200 cupsdLogMessage(CUPSD_LOG_WARN
,
201 "Possible DoS attack - more than %d clients connecting "
203 MaxClientsPerHost
, tempcon
->http
.hostname
);
207 closesocket(con
->http
.fd
);
217 * Get the hostname or format the IP address as needed...
220 if (httpAddrLocalhost(con
->http
.hostaddr
))
223 * Map accesses from the loopback interface to "localhost"...
226 strlcpy(con
->http
.hostname
, "localhost", sizeof(con
->http
.hostname
));
227 hostname
= con
->http
.hostname
;
232 * Map accesses from the same host to the server name.
235 for (addr
= ServerAddrs
; addr
; addr
= addr
->next
)
236 if (httpAddrEqual(con
->http
.hostaddr
, &(addr
->addr
)))
241 strlcpy(con
->http
.hostname
, ServerName
, sizeof(con
->http
.hostname
));
242 hostname
= con
->http
.hostname
;
244 else if (HostNameLookups
)
245 hostname
= httpAddrLookup(con
->http
.hostaddr
, con
->http
.hostname
,
246 sizeof(con
->http
.hostname
));
250 httpAddrString(con
->http
.hostaddr
, con
->http
.hostname
,
251 sizeof(con
->http
.hostname
));
255 if (hostname
== NULL
&& HostNameLookups
== 2)
258 * Can't have an unresolved IP address with double-lookups enabled...
261 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
262 "cupsdAcceptClient: Closing connection %d...",
266 closesocket(con
->http
.fd
);
271 cupsdLogMessage(CUPSD_LOG_WARN
,
272 "Name lookup failed - connection from %s closed!",
279 if (HostNameLookups
== 2)
282 * Do double lookups as needed...
285 if ((addrlist
= httpAddrGetList(con
->http
.hostname
, AF_UNSPEC
, NULL
)) != NULL
)
288 * See if the hostname maps to the same IP address...
291 for (addr
= addrlist
; addr
; addr
= addr
->next
)
292 if (httpAddrEqual(con
->http
.hostaddr
, &(addr
->addr
)))
298 httpAddrFreeList(addrlist
);
303 * Can't have a hostname that doesn't resolve to the same IP address
304 * with double-lookups enabled...
307 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
308 "cupsdAcceptClient: Closing connection %d...",
312 closesocket(con
->http
.fd
);
317 cupsdLogMessage(CUPSD_LOG_WARN
,
318 "IP lookup failed - connection from %s closed!",
326 if (con
->http
.hostaddr
->addr
.sa_family
== AF_INET6
)
327 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdAcceptClient: %d from %s:%d (IPv6)",
328 con
->http
.fd
, con
->http
.hostname
,
329 ntohs(con
->http
.hostaddr
->ipv6
.sin6_port
));
331 #endif /* AF_INET6 */
333 if (con
->http
.hostaddr
->addr
.sa_family
== AF_LOCAL
)
334 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdAcceptClient: %d from %s (Domain)",
335 con
->http
.fd
, con
->http
.hostname
);
337 #endif /* AF_LOCAL */
338 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdAcceptClient: %d from %s:%d (IPv4)",
339 con
->http
.fd
, con
->http
.hostname
,
340 ntohs(con
->http
.hostaddr
->ipv4
.sin_port
));
343 * Get the local address the client connected to...
346 addrlen
= sizeof(temp
);
347 if (getsockname(con
->http
.fd
, (struct sockaddr
*)&temp
, &addrlen
))
349 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to get local address - %s",
352 strcpy(con
->servername
, "localhost");
353 con
->serverport
= LocalPort
;
358 if (temp
.addr
.sa_family
== AF_INET6
)
360 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
361 con
->serverport
= ntohs(lis
->address
.ipv6
.sin6_port
);
364 #endif /* AF_INET6 */
365 if (temp
.addr
.sa_family
== AF_INET
)
367 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
368 con
->serverport
= ntohs(lis
->address
.ipv4
.sin_port
);
372 strcpy(con
->servername
, "localhost");
373 con
->serverport
= LocalPort
;
377 cupsArrayAdd(Clients
, con
);
379 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
380 "cupsdAcceptClient: %d connected to server on %s:%d",
381 con
->http
.fd
, con
->servername
, con
->serverport
);
384 * Using TCP_NODELAY improves responsiveness, especially on systems
385 * with a slow loopback interface... Since we write large buffers
386 * when sending print files and requests, there shouldn't be any
387 * performance penalty for this...
391 setsockopt(con
->http
.fd
, IPPROTO_TCP
, TCP_NODELAY
, &val
, sizeof(val
));
394 * Close this file on all execs...
397 fcntl(con
->http
.fd
, F_SETFD
, fcntl(con
->http
.fd
, F_GETFD
) | FD_CLOEXEC
);
400 * Add the socket to the select() input mask.
403 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
404 "cupsdAcceptClient: Adding fd %d to InputSet...",
406 FD_SET(con
->http
.fd
, InputSet
);
409 * Temporarily suspend accept()'s until we lose a client...
412 if (cupsArrayCount(Clients
) == MaxClients
)
413 cupsdPauseListening();
417 * See if we are connecting on a secure port...
420 if (lis
->encryption
== HTTP_ENCRYPT_ALWAYS
)
423 * https connection; go secure...
426 con
->http
.encryption
= HTTP_ENCRYPT_ALWAYS
;
432 #endif /* HAVE_SSL */
437 * 'cupsdCloseAllClients()' - Close all remote clients immediately.
441 cupsdCloseAllClients(void)
443 cupsd_client_t
*con
; /* Current client */
446 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
448 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
449 cupsdCloseClient(con
);
454 * 'cupsdCloseClient()' - Close a remote client.
457 int /* O - 1 if partial close, 0 if fully closed */
458 cupsdCloseClient(cupsd_client_t
*con
) /* I - Client to close */
460 int partial
; /* Do partial close for SSL? */
462 SSL_CTX
*context
; /* Context for encryption */
463 SSL
*conn
; /* Connection for encryption */
464 unsigned long error
; /* Error code */
465 #elif defined(HAVE_GNUTLS)
466 http_tls_t
*conn
; /* TLS connection information */
467 int error
; /* Error code */
468 gnutls_certificate_server_credentials
*credentials
;
469 /* TLS credentials */
470 # elif defined(HAVE_CDSASSL)
471 http_tls_t
*conn
; /* CDSA connection information */
472 #endif /* HAVE_LIBSSL */
475 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdCloseClient: %d", con
->http
.fd
);
478 * Flush pending writes before closing...
481 httpFlushWrite(HTTP(con
));
487 * Shutdown encryption as needed...
495 conn
= (SSL
*)(con
->http
.tls
);
496 context
= SSL_get_SSL_CTX(conn
);
498 switch (SSL_shutdown(conn
))
501 cupsdLogMessage(CUPSD_LOG_INFO
,
502 "cupsdCloseClient: SSL shutdown successful!");
505 cupsdLogMessage(CUPSD_LOG_ERROR
,
506 "cupsdCloseClient: Fatal error during SSL shutdown!");
508 while ((error
= ERR_get_error()) != 0)
509 cupsdLogMessage(CUPSD_LOG_ERROR
, "cupsdCloseClient: %s",
510 ERR_error_string(error
, NULL
));
514 SSL_CTX_free(context
);
517 # elif defined(HAVE_GNUTLS)
518 conn
= (http_tls_t
*)(con
->http
.tls
);
519 credentials
= (gnutls_certificate_server_credentials
*)(conn
->credentials
);
521 error
= gnutls_bye(conn
->session
, GNUTLS_SHUT_WR
);
524 case GNUTLS_E_SUCCESS
:
525 cupsdLogMessage(CUPSD_LOG_INFO
,
526 "cupsdCloseClient: SSL shutdown successful!");
529 cupsdLogMessage(CUPSD_LOG_ERROR
,
530 "cupsdCloseClient: %s", gnutls_strerror(error
));
534 gnutls_deinit(conn
->session
);
535 gnutls_certificate_free_credentials(*credentials
);
539 # elif defined(HAVE_CDSASSL)
540 conn
= (http_tls_t
*)(con
->http
.tls
);
542 while (SSLClose(conn
->session
) == errSSLWouldBlock
)
545 SSLDisposeContext(conn
->session
);
547 if (conn
->certsArray
)
548 CFRelease(conn
->certsArray
);
551 # endif /* HAVE_LIBSSL */
553 con
->http
.tls
= NULL
;
555 #endif /* HAVE_SSL */
557 if (con
->pipe_pid
!= 0)
560 * Stop any CGI process...
563 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
564 "cupsdCloseClient: %d Killing process ID %d...",
565 con
->http
.fd
, con
->pipe_pid
);
566 cupsdEndProcess(con
->pipe_pid
, 1);
572 if (FD_ISSET(con
->file
, InputSet
))
574 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
575 "cupsdCloseClient: %d Removing fd %d from InputSet...",
576 con
->http
.fd
, con
->file
);
577 FD_CLR(con
->file
, InputSet
);
580 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
581 "cupsdCloseClient: %d Closing data file %d.",
582 con
->http
.fd
, con
->file
);
589 * Close the socket and clear the file from the input set for select()...
592 if (con
->http
.fd
> 0)
597 * Only do a partial close so that the encrypted client gets everything.
600 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
601 "cupsdCloseClient: Removing fd %d from OutputSet...",
603 shutdown(con
->http
.fd
, 0);
604 FD_CLR(con
->http
.fd
, OutputSet
);
609 * Shut the socket down fully...
612 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
613 "cupsdCloseClient: Removing fd %d from InputSet and OutputSet...",
616 FD_CLR(con
->http
.fd
, InputSet
);
617 FD_CLR(con
->http
.fd
, OutputSet
);
628 if (con
->http
.input_set
)
629 free(con
->http
.input_set
);
631 httpClearCookie(HTTP(con
));
633 cupsdClearString(&con
->filename
);
634 cupsdClearString(&con
->command
);
635 cupsdClearString(&con
->options
);
639 ippDelete(con
->request
);
645 ippDelete(con
->response
);
646 con
->response
= NULL
;
651 cupsLangFree(con
->language
);
652 con
->language
= NULL
;
656 * Re-enable new client connections if we are going back under the
660 if (cupsArrayCount(Clients
) == MaxClients
)
661 cupsdResumeListening();
664 * Compact the list of clients as necessary...
667 cupsArrayRemove(Clients
, con
);
677 * 'cupsdReadClient()' - Read data from a client.
680 int /* O - 1 on success, 0 on error */
681 cupsdReadClient(cupsd_client_t
*con
) /* I - Client to read from */
683 char line
[32768], /* Line from client... */
684 operation
[64], /* Operation code from socket */
685 version
[64], /* HTTP version number string */
686 locale
[64], /* Locale */
687 *ptr
; /* Pointer into strings */
688 int major
, minor
; /* HTTP version numbers */
689 http_status_t status
; /* Transfer status */
690 ipp_state_t ipp_state
; /* State of IPP transfer */
691 int bytes
; /* Number of bytes to POST */
692 char *filename
; /* Name of file for GET/HEAD */
693 char buf
[1024]; /* Buffer for real filename */
694 struct stat filestats
; /* File information */
695 mime_type_t
*type
; /* MIME type of file */
696 cupsd_printer_t
*p
; /* Printer */
697 static unsigned request_id
= 0; /* Request ID for temp files */
700 status
= HTTP_CONTINUE
;
702 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
703 "cupsdReadClient: %d, used=%d, file=%d state=%d",
704 con
->http
.fd
, con
->http
.used
, con
->file
, con
->http
.state
);
708 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdReadClient: http error seen...");
709 return (cupsdCloseClient(con
));
716 * Automatically check for a SSL/TLS handshake...
721 if (recv(con
->http
.fd
, buf
, 1, MSG_PEEK
) == 1 &&
722 (!buf
[0] || !strchr("DGHOPT", buf
[0])))
725 * Encrypt this connection...
728 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
729 "cupsdReadClient: Saw first byte %02X, auto-negotiating SSL/TLS session...",
736 #endif /* HAVE_SSL */
738 switch (con
->http
.state
)
742 * See if we've received a request line...
745 if (httpGets(line
, sizeof(line
) - 1, HTTP(con
)) == NULL
)
747 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
748 "cupsdReadClient: httpGets returned EOF...");
749 return (cupsdCloseClient(con
));
753 * Ignore blank request lines...
760 * Clear other state variables...
763 httpClearFields(HTTP(con
));
765 con
->http
.activity
= time(NULL
);
766 con
->http
.version
= HTTP_1_0
;
767 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
768 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
769 con
->http
.data_remaining
= 0;
770 con
->http
._data_remaining
= 0;
771 con
->operation
= HTTP_WAITING
;
776 con
->username
[0] = '\0';
777 con
->password
[0] = '\0';
780 cupsdClearString(&con
->command
);
781 cupsdClearString(&con
->options
);
783 if (con
->language
!= NULL
)
785 cupsLangFree(con
->language
);
786 con
->language
= NULL
;
790 * Grab the request line...
793 switch (sscanf(line
, "%63s%1023s%63s", operation
, con
->uri
, version
))
796 cupsdLogMessage(CUPSD_LOG_ERROR
,
797 "Bad request line \"%s\" from %s!", line
,
799 cupsdSendError(con
, HTTP_BAD_REQUEST
);
800 return (cupsdCloseClient(con
));
802 con
->http
.version
= HTTP_0_9
;
805 if (sscanf(version
, "HTTP/%d.%d", &major
, &minor
) != 2)
807 cupsdLogMessage(CUPSD_LOG_ERROR
,
808 "Bad request line \"%s\" from %s!", line
,
810 cupsdSendError(con
, HTTP_BAD_REQUEST
);
811 return (cupsdCloseClient(con
));
816 con
->http
.version
= (http_version_t
)(major
* 100 + minor
);
817 if (con
->http
.version
== HTTP_1_1
&& KeepAlive
)
818 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
820 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
824 cupsdSendError(con
, HTTP_NOT_SUPPORTED
);
825 return (cupsdCloseClient(con
));
831 * Handle full URLs in the request line...
834 if (strcmp(con
->uri
, "*"))
836 char method
[HTTP_MAX_URI
], /* Method/scheme */
837 userpass
[HTTP_MAX_URI
], /* Username:password */
838 hostname
[HTTP_MAX_URI
], /* Hostname */
839 resource
[HTTP_MAX_URI
]; /* Resource path */
840 int port
; /* Port number */
844 * Separate the URI into its components...
847 httpSeparateURI(HTTP_URI_CODING_MOST
, con
->uri
,
848 method
, sizeof(method
),
849 userpass
, sizeof(userpass
),
850 hostname
, sizeof(hostname
), &port
,
851 resource
, sizeof(resource
));
854 * Only allow URIs with the servername, localhost, or an IP
858 if (strcmp(method
, "file") &&
859 strcasecmp(hostname
, ServerName
) &&
860 strcasecmp(hostname
, "localhost") &&
861 !isdigit(hostname
[0]))
864 * Nope, we don't do proxies...
867 cupsdLogMessage(CUPSD_LOG_ERROR
, "Bad URI \"%s\" in request!",
869 cupsdSendError(con
, HTTP_METHOD_NOT_ALLOWED
);
870 return (cupsdCloseClient(con
));
874 * Copy the resource portion back into the URI; both resource and
875 * con->uri are HTTP_MAX_URI bytes in size...
878 strcpy(con
->uri
, resource
);
882 * Process the request...
885 if (!strcmp(operation
, "GET"))
886 con
->http
.state
= HTTP_GET
;
887 else if (!strcmp(operation
, "PUT"))
888 con
->http
.state
= HTTP_PUT
;
889 else if (!strcmp(operation
, "POST"))
890 con
->http
.state
= HTTP_POST
;
891 else if (!strcmp(operation
, "DELETE"))
892 con
->http
.state
= HTTP_DELETE
;
893 else if (!strcmp(operation
, "TRACE"))
894 con
->http
.state
= HTTP_TRACE
;
895 else if (!strcmp(operation
, "OPTIONS"))
896 con
->http
.state
= HTTP_OPTIONS
;
897 else if (!strcmp(operation
, "HEAD"))
898 con
->http
.state
= HTTP_HEAD
;
901 cupsdLogMessage(CUPSD_LOG_ERROR
, "Bad operation \"%s\"!", operation
);
902 cupsdSendError(con
, HTTP_BAD_REQUEST
);
903 return (cupsdCloseClient(con
));
906 con
->start
= time(NULL
);
907 con
->operation
= con
->http
.state
;
909 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdReadClient: %d %s %s HTTP/%d.%d",
910 con
->http
.fd
, operation
, con
->uri
,
911 con
->http
.version
/ 100, con
->http
.version
% 100);
913 con
->http
.status
= HTTP_OK
;
923 * Parse incoming parameters until the status changes...
926 status
= httpUpdate(HTTP(con
));
928 if (status
!= HTTP_OK
&& status
!= HTTP_CONTINUE
)
930 cupsdSendError(con
, HTTP_BAD_REQUEST
);
931 return (cupsdCloseClient(con
));
936 break; /* Anti-compiler-warning-code */
940 * Handle new transfers...
943 if (status
== HTTP_OK
)
945 if (con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
][0])
948 * Figure out the locale from the Accept-Language and Content-Type
952 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ',')) != NULL
)
955 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ';')) != NULL
)
958 if ((ptr
= strstr(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
], "charset=")) != NULL
)
961 * Combine language and charset, and trim any extra params in the
965 snprintf(locale
, sizeof(locale
), "%s.%s",
966 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ptr
+ 8);
968 if ((ptr
= strchr(locale
, ',')) != NULL
)
972 snprintf(locale
, sizeof(locale
), "%s.%s",
973 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], DefaultCharset
);
975 cupsdLogMessage(CUPSD_LOG_DEBUG
,
976 "cupsdReadClient: %d Browser asked for language \"%s\"...",
977 con
->http
.fd
, locale
);
979 con
->language
= cupsLangGet(locale
);
982 con
->language
= cupsLangGet(DefaultLocale
);
986 if (!strncmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Keep-Alive", 10) &&
988 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
990 if (!con
->http
.fields
[HTTP_FIELD_HOST
][0] &&
991 con
->http
.version
>= HTTP_1_1
)
994 * HTTP/1.1 and higher require the "Host:" field...
997 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
))
998 return (cupsdCloseClient(con
));
1000 else if (con
->operation
== HTTP_OPTIONS
)
1003 * Do OPTIONS command...
1006 if (con
->best
&& con
->best
->type
!= AUTH_NONE
)
1008 if (!cupsdSendHeader(con
, HTTP_UNAUTHORIZED
, NULL
))
1009 return (cupsdCloseClient(con
));
1012 if (!strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") &&
1013 con
->http
.tls
== NULL
)
1017 * Do encryption stuff...
1020 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
))
1021 return (cupsdCloseClient(con
));
1023 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1024 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1025 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1026 httpPrintf(HTTP(con
), "\r\n");
1028 encrypt_client(con
);
1030 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
))
1031 return (cupsdCloseClient(con
));
1032 #endif /* HAVE_SSL */
1035 if (!cupsdSendHeader(con
, HTTP_OK
, NULL
))
1036 return (cupsdCloseClient(con
));
1038 httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n");
1039 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1040 httpPrintf(HTTP(con
), "\r\n");
1042 else if (!is_path_absolute(con
->uri
))
1045 * Protect against malicious users!
1048 if (!cupsdSendError(con
, HTTP_FORBIDDEN
))
1049 return (cupsdCloseClient(con
));
1053 if (!strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") &&
1054 con
->http
.tls
== NULL
)
1058 * Do encryption stuff...
1061 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
))
1062 return (cupsdCloseClient(con
));
1064 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1065 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1066 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1067 httpPrintf(HTTP(con
), "\r\n");
1069 encrypt_client(con
);
1071 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
))
1072 return (cupsdCloseClient(con
));
1073 #endif /* HAVE_SSL */
1076 if ((status
= cupsdIsAuthorized(con
, NULL
)) != HTTP_OK
)
1078 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1079 "cupsdReadClient: Unauthorized request for %s...\n",
1081 cupsdSendError(con
, status
);
1082 return (cupsdCloseClient(con
));
1085 if (con
->http
.expect
&&
1086 (con
->operation
== HTTP_POST
|| con
->operation
== HTTP_PUT
))
1088 if (con
->http
.expect
== HTTP_CONTINUE
)
1091 * Send 100-continue header...
1094 if (!cupsdSendHeader(con
, HTTP_CONTINUE
, NULL
))
1095 return (cupsdCloseClient(con
));
1100 * Send 417-expectation-failed header...
1103 if (!cupsdSendHeader(con
, HTTP_EXPECTATION_FAILED
, NULL
))
1104 return (cupsdCloseClient(con
));
1106 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1107 httpPrintf(HTTP(con
), "\r\n");
1111 switch (con
->http
.state
)
1113 case HTTP_GET_SEND
:
1114 if (!strncmp(con
->uri
, "/printers/", 10) &&
1115 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1118 * Send PPD file - get the real printer name since printer
1119 * names are not case sensitive but filenames can be...
1122 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1124 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1125 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1128 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
1129 return (cupsdCloseClient(con
));
1135 if ((!strncmp(con
->uri
, "/admin", 6) &&
1136 strncmp(con
->uri
, "/admin/conf/", 12) &&
1137 strncmp(con
->uri
, "/admin/log/", 11)) ||
1138 !strncmp(con
->uri
, "/printers", 9) ||
1139 !strncmp(con
->uri
, "/classes", 8) ||
1140 !strncmp(con
->uri
, "/help", 5) ||
1141 !strncmp(con
->uri
, "/jobs", 5))
1144 * Send CGI output...
1147 if (!strncmp(con
->uri
, "/admin", 6))
1149 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1152 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1154 else if (!strncmp(con
->uri
, "/printers", 9))
1156 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1159 if (con
->uri
[9] && con
->uri
[10])
1160 cupsdSetString(&con
->options
, con
->uri
+ 9);
1162 cupsdSetString(&con
->options
, NULL
);
1164 else if (!strncmp(con
->uri
, "/classes", 8))
1166 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1169 if (con
->uri
[8] && con
->uri
[9])
1170 cupsdSetString(&con
->options
, con
->uri
+ 8);
1172 cupsdSetString(&con
->options
, NULL
);
1174 else if (!strncmp(con
->uri
, "/jobs", 5))
1176 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1179 if (con
->uri
[5] && con
->uri
[6])
1180 cupsdSetString(&con
->options
, con
->uri
+ 5);
1182 cupsdSetString(&con
->options
, NULL
);
1186 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1189 if (con
->uri
[5] && con
->uri
[6])
1190 cupsdSetString(&con
->options
, con
->uri
+ 5);
1192 cupsdSetString(&con
->options
, NULL
);
1195 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1197 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
1198 return (cupsdCloseClient(con
));
1201 cupsdLogRequest(con
, HTTP_OK
);
1203 if (con
->http
.version
<= HTTP_1_0
)
1204 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1206 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1207 (strchr(con
->uri
+ 12, '/') ||
1208 strlen(con
->uri
) == 12)) ||
1209 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1210 (strchr(con
->uri
+ 11, '/') ||
1211 strlen(con
->uri
) == 11)))
1214 * GET can only be done to configuration files under
1218 if (!cupsdSendError(con
, HTTP_FORBIDDEN
))
1219 return (cupsdCloseClient(con
));
1229 if ((filename
= get_file(con
, &filestats
, buf
,
1230 sizeof(buf
))) == NULL
)
1232 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
1233 return (cupsdCloseClient(con
));
1238 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1240 if (is_cgi(con
, filename
, &filestats
, type
))
1243 * Note: con->command and con->options were set by
1247 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1249 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
1250 return (cupsdCloseClient(con
));
1253 cupsdLogRequest(con
, HTTP_OK
);
1255 if (con
->http
.version
<= HTTP_1_0
)
1256 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1260 if (!check_if_modified(con
, &filestats
))
1262 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
))
1263 return (cupsdCloseClient(con
));
1268 strcpy(line
, "text/plain");
1270 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1272 if (!write_file(con
, HTTP_OK
, filename
, line
, &filestats
))
1273 return (cupsdCloseClient(con
));
1278 case HTTP_POST_RECV
:
1280 * See if the POST request includes a Content-Length field, and if
1281 * so check the length against any limits that are set...
1284 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "POST %s", con
->uri
);
1285 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "CONTENT_TYPE = %s",
1286 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
1288 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1289 MaxRequestSize
> 0 &&
1290 con
->http
.data_remaining
> MaxRequestSize
)
1293 * Request too large...
1296 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1297 return (cupsdCloseClient(con
));
1301 else if (con
->http
.data_remaining
< 0)
1304 * Negative content lengths are invalid!
1307 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
))
1308 return (cupsdCloseClient(con
));
1314 * See what kind of POST request this is; for IPP requests the
1315 * content-type field will be "application/ipp"...
1318 if (!strcmp(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
],
1320 con
->request
= ippNew();
1321 else if ((!strncmp(con
->uri
, "/admin", 6) &&
1322 strncmp(con
->uri
, "/admin/conf/", 12) &&
1323 strncmp(con
->uri
, "/admin/log/", 11)) ||
1324 !strncmp(con
->uri
, "/printers", 9) ||
1325 !strncmp(con
->uri
, "/classes", 8) ||
1326 !strncmp(con
->uri
, "/help", 5) ||
1327 !strncmp(con
->uri
, "/jobs", 5))
1333 if (!strncmp(con
->uri
, "/admin", 6))
1335 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1338 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1340 else if (!strncmp(con
->uri
, "/printers", 9))
1342 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1345 if (con
->uri
[9] && con
->uri
[10])
1346 cupsdSetString(&con
->options
, con
->uri
+ 9);
1348 cupsdSetString(&con
->options
, NULL
);
1350 else if (!strncmp(con
->uri
, "/classes", 8))
1352 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1355 if (con
->uri
[8] && con
->uri
[9])
1356 cupsdSetString(&con
->options
, con
->uri
+ 8);
1358 cupsdSetString(&con
->options
, NULL
);
1360 else if (!strncmp(con
->uri
, "/jobs", 5))
1362 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1365 if (con
->uri
[5] && con
->uri
[6])
1366 cupsdSetString(&con
->options
, con
->uri
+ 5);
1368 cupsdSetString(&con
->options
, NULL
);
1372 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1375 if (con
->uri
[5] && con
->uri
[6])
1376 cupsdSetString(&con
->options
, con
->uri
+ 5);
1378 cupsdSetString(&con
->options
, NULL
);
1381 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1382 "cupsdReadClient: %d command=\"%s\", "
1384 con
->http
.fd
, con
->command
,
1385 con
->options
? con
->options
: "(null)");
1387 if (con
->http
.version
<= HTTP_1_0
)
1388 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1396 if ((filename
= get_file(con
, &filestats
, buf
,
1397 sizeof(buf
))) == NULL
)
1399 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
1400 return (cupsdCloseClient(con
));
1405 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1407 if (!is_cgi(con
, filename
, &filestats
, type
))
1410 * Only POST to CGI's...
1413 if (!cupsdSendError(con
, HTTP_UNAUTHORIZED
))
1414 return (cupsdCloseClient(con
));
1419 case HTTP_PUT_RECV
:
1421 * Validate the resource name...
1424 if (strncmp(con
->uri
, "/admin/conf/", 12) ||
1425 strchr(con
->uri
+ 12, '/') ||
1426 strlen(con
->uri
) == 12)
1429 * PUT can only be done to configuration files under
1433 if (!cupsdSendError(con
, HTTP_FORBIDDEN
))
1434 return (cupsdCloseClient(con
));
1440 * See if the PUT request includes a Content-Length field, and if
1441 * so check the length against any limits that are set...
1444 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "PUT %s", con
->uri
);
1445 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "CONTENT_TYPE = %s",
1446 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
1448 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1449 MaxRequestSize
> 0 &&
1450 con
->http
.data_remaining
> MaxRequestSize
)
1453 * Request too large...
1456 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1457 return (cupsdCloseClient(con
));
1461 else if (con
->http
.data_remaining
< 0)
1464 * Negative content lengths are invalid!
1467 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
))
1468 return (cupsdCloseClient(con
));
1474 * Open a temporary file to hold the request...
1477 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
1479 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1481 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1482 "cupsdReadClient: %d REQUEST %s=%d", con
->http
.fd
,
1483 con
->filename
, con
->file
);
1487 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1488 return (cupsdCloseClient(con
));
1491 fchmod(con
->file
, 0640);
1492 fchown(con
->file
, RunUser
, Group
);
1493 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1498 cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
);
1499 return (cupsdCloseClient(con
));
1502 if (!strncmp(con
->uri
, "/printers/", 10) &&
1503 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1506 * Send PPD file - get the real printer name since printer
1507 * names are not case sensitive but filenames can be...
1510 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1512 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1513 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1516 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
1517 return (cupsdCloseClient(con
));
1523 if ((!strncmp(con
->uri
, "/admin", 6) &&
1524 strncmp(con
->uri
, "/admin/conf/", 12) &&
1525 strncmp(con
->uri
, "/admin/log/", 11)) ||
1526 !strncmp(con
->uri
, "/printers", 9) ||
1527 !strncmp(con
->uri
, "/classes", 8) ||
1528 !strncmp(con
->uri
, "/help", 5) ||
1529 !strncmp(con
->uri
, "/jobs", 5))
1535 if (!cupsdSendHeader(con
, HTTP_OK
, "text/html"))
1536 return (cupsdCloseClient(con
));
1538 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1539 return (cupsdCloseClient(con
));
1541 cupsdLogRequest(con
, HTTP_OK
);
1543 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1544 (strchr(con
->uri
+ 12, '/') ||
1545 strlen(con
->uri
) == 12)) ||
1546 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1547 (strchr(con
->uri
+ 11, '/') ||
1548 strlen(con
->uri
) == 11)))
1551 * HEAD can only be done to configuration files under
1555 if (!cupsdSendError(con
, HTTP_FORBIDDEN
))
1556 return (cupsdCloseClient(con
));
1560 else if ((filename
= get_file(con
, &filestats
, buf
,
1561 sizeof(buf
))) == NULL
)
1563 if (!cupsdSendHeader(con
, HTTP_NOT_FOUND
, "text/html"))
1564 return (cupsdCloseClient(con
));
1566 cupsdLogRequest(con
, HTTP_NOT_FOUND
);
1568 else if (!check_if_modified(con
, &filestats
))
1570 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
))
1571 return (cupsdCloseClient(con
));
1573 cupsdLogRequest(con
, HTTP_NOT_MODIFIED
);
1581 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1583 strcpy(line
, "text/plain");
1585 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1587 if (!cupsdSendHeader(con
, HTTP_OK
, line
))
1588 return (cupsdCloseClient(con
));
1590 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
1591 httpGetDateString(filestats
.st_mtime
)) < 0)
1592 return (cupsdCloseClient(con
));
1594 if (httpPrintf(HTTP(con
), "Content-Length: %lu\r\n",
1595 (unsigned long)filestats
.st_size
) < 0)
1596 return (cupsdCloseClient(con
));
1598 cupsdLogRequest(con
, HTTP_OK
);
1601 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1602 return (cupsdCloseClient(con
));
1604 con
->http
.state
= HTTP_WAITING
;
1608 break; /* Anti-compiler-warning-code */
1614 * Handle any incoming data...
1617 switch (con
->http
.state
)
1619 case HTTP_PUT_RECV
:
1620 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1621 "cupsdReadClient: %d con->data_encoding=HTTP_ENCODE_%s, "
1622 "con->data_remaining=" CUPS_LLFMT
", con->file=%d",
1624 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
?
1625 "CHUNKED" : "LENGTH",
1626 CUPS_LLCAST con
->http
.data_remaining
, con
->file
);
1628 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
1629 return (cupsdCloseClient(con
));
1632 con
->bytes
+= bytes
;
1634 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1635 "cupsdReadClient: %d writing %d bytes to %d",
1636 con
->http
.fd
, bytes
, con
->file
);
1638 if (write(con
->file
, line
, bytes
) < bytes
)
1640 cupsdLogMessage(CUPSD_LOG_ERROR
,
1641 "cupsdReadClient: Unable to write %d bytes to %s: %s",
1642 bytes
, con
->filename
, strerror(errno
));
1644 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1645 "cupsdReadClient: Closing data file %d...",
1650 unlink(con
->filename
);
1651 cupsdClearString(&con
->filename
);
1653 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1654 return (cupsdCloseClient(con
));
1658 if (con
->http
.state
== HTTP_WAITING
)
1661 * End of file, see how big it is...
1664 fstat(con
->file
, &filestats
);
1666 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1667 "cupsdReadClient: %d Closing data file %d, size="
1669 con
->http
.fd
, con
->file
,
1670 CUPS_LLCAST filestats
.st_size
);
1675 if (filestats
.st_size
> MaxRequestSize
&&
1679 * Request is too big; remove it and send an error...
1682 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1683 "cupsdReadClient: %d Removing temp file %s",
1684 con
->http
.fd
, con
->filename
);
1685 unlink(con
->filename
);
1686 cupsdClearString(&con
->filename
);
1688 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1689 return (cupsdCloseClient(con
));
1693 * Install the configuration file...
1696 status
= install_conf_file(con
);
1699 * Return the status to the client...
1702 if (!cupsdSendError(con
, status
))
1703 return (cupsdCloseClient(con
));
1707 case HTTP_POST_RECV
:
1708 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1709 "cupsdReadClient: %d con->data_encoding=HTTP_ENCODE_"
1710 "%s, con->data_remaining=" CUPS_LLFMT
", con->file=%d",
1712 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
?
1713 "CHUNKED" : "LENGTH",
1714 CUPS_LLCAST con
->http
.data_remaining
, con
->file
);
1716 if (con
->request
!= NULL
)
1719 * Grab any request data from the connection...
1722 if ((ipp_state
= ippRead(&(con
->http
), con
->request
)) == IPP_ERROR
)
1724 cupsdLogMessage(CUPSD_LOG_ERROR
,
1725 "cupsdReadClient: %d IPP Read Error!",
1728 cupsdSendError(con
, HTTP_BAD_REQUEST
);
1729 return (cupsdCloseClient(con
));
1731 else if (ipp_state
!= IPP_DATA
)
1733 if (con
->http
.state
== HTTP_POST_SEND
)
1735 cupsdSendError(con
, HTTP_BAD_REQUEST
);
1736 return (cupsdCloseClient(con
));
1742 con
->bytes
+= ippLength(con
->request
);
1745 if (con
->file
< 0 && con
->http
.state
!= HTTP_POST_SEND
)
1748 * Create a file as needed for the request data...
1751 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
, request_id
++);
1752 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1754 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdReadClient: %d REQUEST %s=%d", con
->http
.fd
,
1755 con
->filename
, con
->file
);
1759 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1760 return (cupsdCloseClient(con
));
1763 fchmod(con
->file
, 0640);
1764 fchown(con
->file
, RunUser
, Group
);
1765 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1768 if (con
->http
.state
!= HTTP_POST_SEND
)
1770 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
1771 return (cupsdCloseClient(con
));
1774 con
->bytes
+= bytes
;
1776 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1777 "cupsdReadClient: %d writing %d bytes to %d",
1778 con
->http
.fd
, bytes
, con
->file
);
1780 if (write(con
->file
, line
, bytes
) < bytes
)
1782 cupsdLogMessage(CUPSD_LOG_ERROR
,
1783 "cupsdReadClient: Unable to write %d bytes to %s: %s",
1784 bytes
, con
->filename
, strerror(errno
));
1786 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1787 "cupsdReadClient: Closing file %d...",
1792 unlink(con
->filename
);
1793 cupsdClearString(&con
->filename
);
1795 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1796 return (cupsdCloseClient(con
));
1799 else if (con
->http
.state
== HTTP_POST_RECV
)
1800 return (1); /* ??? */
1801 else if (con
->http
.state
!= HTTP_POST_SEND
)
1802 return (cupsdCloseClient(con
));
1805 if (con
->http
.state
== HTTP_POST_SEND
)
1809 fstat(con
->file
, &filestats
);
1811 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1812 "cupsdReadClient: %d Closing data file %d, "
1813 "size=" CUPS_LLFMT
".",
1814 con
->http
.fd
, con
->file
,
1815 CUPS_LLCAST filestats
.st_size
);
1820 if (filestats
.st_size
> MaxRequestSize
&&
1824 * Request is too big; remove it and send an error...
1827 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1828 "cupsdReadClient: %d Removing temp file %s",
1829 con
->http
.fd
, con
->filename
);
1830 unlink(con
->filename
);
1831 cupsdClearString(&con
->filename
);
1836 * Delete any IPP request data...
1839 ippDelete(con
->request
);
1840 con
->request
= NULL
;
1843 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1844 return (cupsdCloseClient(con
));
1849 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1851 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
1852 return (cupsdCloseClient(con
));
1855 cupsdLogRequest(con
, HTTP_OK
);
1860 return (cupsdProcessIPPRequest(con
));
1865 break; /* Anti-compiler-warning-code */
1868 if (!con
->http
.keep_alive
&& con
->http
.state
== HTTP_WAITING
)
1869 return (cupsdCloseClient(con
));
1876 * 'cupsdSendCommand()' - Send output from a command via HTTP.
1879 int /* O - 1 on success, 0 on failure */
1881 cupsd_client_t
*con
, /* I - Client connection */
1882 char *command
, /* I - Command to run */
1883 char *options
, /* I - Command-line options */
1884 int root
) /* I - Run as root? */
1886 int fd
; /* Standard input file descriptor */
1891 fd
= open(con
->filename
, O_RDONLY
);
1895 cupsdLogMessage(CUPSD_LOG_ERROR
,
1896 "cupsdSendCommand: %d Unable to open \"%s\" for reading: %s",
1897 con
->http
.fd
, con
->filename
? con
->filename
: "/dev/null",
1902 fcntl(fd
, F_SETFD
, fcntl(fd
, F_GETFD
) | FD_CLOEXEC
);
1907 con
->pipe_pid
= pipe_command(con
, fd
, &(con
->file
), command
, options
, root
);
1912 cupsdLogMessage(CUPSD_LOG_INFO
, "Started \"%s\" (pid=%d)", command
,
1915 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendCommand: %d file=%d",
1916 con
->http
.fd
, con
->file
);
1918 if (con
->pipe_pid
== 0)
1921 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1923 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1924 "cupsdSendCommand: Adding fd %d to InputSet...", con
->file
);
1925 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1926 "cupsdSendCommand: Adding fd %d to OutputSet...",
1929 FD_SET(con
->file
, InputSet
);
1930 FD_SET(con
->http
.fd
, OutputSet
);
1932 con
->sent_header
= 0;
1933 con
->file_ready
= 0;
1934 con
->got_fields
= 0;
1942 * 'cupsdSendError()' - Send an error message via HTTP.
1945 int /* O - 1 if successful, 0 otherwise */
1946 cupsdSendError(cupsd_client_t
*con
, /* I - Connection */
1947 http_status_t code
) /* I - Error code */
1951 * Force client to upgrade for authentication if that is how the
1952 * server is configured...
1955 if (code
== HTTP_UNAUTHORIZED
&&
1956 DefaultEncryption
== HTTP_ENCRYPT_REQUIRED
&&
1957 strcasecmp(con
->http
.hostname
, "localhost") &&
1960 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1961 "cupsdSendError: Encryption before authentication!");
1962 code
= HTTP_UPGRADE_REQUIRED
;
1964 #endif /* HAVE_SSL */
1967 * Put the request in the access_log file...
1970 cupsdLogRequest(con
, code
);
1972 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendError: %d code=%d (%s)",
1973 con
->http
.fd
, code
, httpStatus(code
));
1976 * To work around bugs in some proxies, don't use Keep-Alive for some
1980 if (code
>= HTTP_BAD_REQUEST
)
1981 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1984 * Send an error message back to the client. If the error code is a
1985 * 400 or 500 series, make sure the message contains some text, too!
1988 if (!cupsdSendHeader(con
, code
, NULL
))
1992 if (code
== HTTP_UPGRADE_REQUIRED
)
1993 if (httpPrintf(HTTP(con
), "Connection: Upgrade\r\n") < 0)
1996 if (httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n") < 0)
1998 #endif /* HAVE_SSL */
2000 if ((con
->http
.version
>= HTTP_1_1
&& !con
->http
.keep_alive
) ||
2001 (code
>= HTTP_BAD_REQUEST
&& code
!= HTTP_UPGRADE_REQUIRED
))
2003 if (httpPrintf(HTTP(con
), "Connection: close\r\n") < 0)
2007 if (code
>= HTTP_BAD_REQUEST
)
2010 * Send a human-readable error message.
2013 char message
[4096], /* Message for user */
2014 urltext
[1024], /* URL redirection text */
2015 redirect
[1024]; /* Redirection link */
2016 const char *text
; /* Status-specific text */
2021 if (code
== HTTP_UNAUTHORIZED
)
2022 text
= _cupsLangString(con
->language
,
2023 _("Enter your username and password or the "
2024 "root username and password to access this "
2026 else if (code
== HTTP_UPGRADE_REQUIRED
)
2030 snprintf(urltext
, sizeof(urltext
),
2031 _cupsLangString(con
->language
,
2032 _("You must access this page using the URL "
2033 "<A HREF=\"https://%s:%d%s\">"
2034 "https://%s:%d%s</A>.")),
2035 con
->servername
, con
->serverport
, con
->uri
,
2036 con
->servername
, con
->serverport
, con
->uri
);
2038 snprintf(redirect
, sizeof(redirect
),
2039 "<META HTTP-EQUIV=\"Refresh\" CONTENT=\"3;https://%s:%d%s\">\n",
2040 con
->servername
, con
->serverport
, con
->uri
);
2045 snprintf(message
, sizeof(message
),
2046 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" "
2047 "\"http://www.w3.org/TR/REC-html40/loose.dtd\">\n"
2050 "\t<META HTTP-EQUIV=\"Content-Type\" "
2051 "CONTENT=\"text/html; charset=utf-8\">\n"
2052 "\t<TITLE>%d %s</TITLE>\n"
2053 "\t<LINK REL=\"STYLESHEET\" TYPE=\"text/css\" "
2054 "HREF=\"/cups.css\">\n"
2062 code
, httpStatus(code
), redirect
, code
, httpStatus(code
), text
);
2064 if (httpPrintf(HTTP(con
), "Content-Type: text/html; charset=utf-8\r\n") < 0)
2066 if (httpPrintf(HTTP(con
), "Content-Length: %d\r\n",
2067 (int)strlen(message
)) < 0)
2069 if (httpPrintf(HTTP(con
), "\r\n") < 0)
2071 if (httpPrintf(HTTP(con
), "%s", message
) < 0)
2074 else if (httpPrintf(HTTP(con
), "\r\n") < 0)
2077 con
->http
.state
= HTTP_WAITING
;
2084 * 'cupsdSendHeader()' - Send an HTTP request.
2087 int /* O - 1 on success, 0 on failure */
2088 cupsdSendHeader(cupsd_client_t
*con
, /* I - Client to send to */
2089 http_status_t code
, /* I - HTTP status code */
2090 char *type
) /* I - MIME type of document */
2093 * Send the HTTP status header...
2096 if (httpPrintf(HTTP(con
), "HTTP/%d.%d %d %s\r\n", con
->http
.version
/ 100,
2097 con
->http
.version
% 100, code
, httpStatus(code
)) < 0)
2100 if (code
== HTTP_CONTINUE
)
2103 * 100-continue doesn't send any headers...
2106 if (httpPrintf(HTTP(con
), "\r\n") < 0)
2112 if (httpPrintf(HTTP(con
), "Date: %s\r\n", httpGetDateString(time(NULL
))) < 0)
2115 if (httpPrintf(HTTP(con
), "Server: %s\r\n", ServerHeader
) < 0)
2117 if (con
->http
.keep_alive
&& con
->http
.version
>= HTTP_1_0
)
2119 if (httpPrintf(HTTP(con
), "Connection: Keep-Alive\r\n") < 0)
2121 if (httpPrintf(HTTP(con
), "Keep-Alive: timeout=%d\r\n",
2122 KeepAliveTimeout
) < 0)
2125 if (code
== HTTP_METHOD_NOT_ALLOWED
)
2126 if (httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST\r\n") < 0)
2129 if (code
== HTTP_UNAUTHORIZED
)
2131 int auth_type
; /* Authentication type */
2134 if (!con
->best
|| con
->best
->type
== AUTH_NONE
)
2135 auth_type
= DefaultAuthType
;
2137 auth_type
= con
->best
->type
;
2139 if (auth_type
!= AUTH_DIGEST
)
2141 if (httpPrintf(HTTP(con
),
2142 "WWW-Authenticate: Basic realm=\"CUPS\"\r\n") < 0)
2147 if (httpPrintf(HTTP(con
),
2148 "WWW-Authenticate: Digest realm=\"CUPS\", nonce=\"%s\"\r\n",
2149 con
->http
.hostname
) < 0)
2154 if (con
->language
&& strcmp(con
->language
->language
, "C"))
2156 if (httpPrintf(HTTP(con
), "Content-Language: %s\r\n",
2157 con
->language
->language
) < 0)
2163 if (!strcmp(type
, "text/html"))
2165 if (httpPrintf(HTTP(con
),
2166 "Content-Type: text/html; charset=utf-8\r\n") < 0)
2169 else if (httpPrintf(HTTP(con
), "Content-Type: %s\r\n", type
) < 0)
2178 * 'cupsdUpdateCGI()' - Read status messages from CGI scripts and programs.
2182 cupsdUpdateCGI(void)
2184 char *ptr
, /* Pointer to end of line in buffer */
2185 message
[1024]; /* Pointer to message text */
2186 int loglevel
; /* Log level for message */
2189 while ((ptr
= cupsdStatBufUpdate(CGIStatusBuffer
, &loglevel
,
2190 message
, sizeof(message
))) != NULL
)
2191 if (!strchr(CGIStatusBuffer
->buffer
, '\n'))
2194 if (ptr
== NULL
&& errno
)
2197 * Fatal error on pipe - should never happen!
2200 cupsdLogMessage(CUPSD_LOG_CRIT
,
2201 "cupsdUpdateCGI: error reading from CGI error pipe - %s",
2208 * 'cupsdWriteClient()' - Write data to a client as needed.
2211 int /* O - 1 if success, 0 if fail */
2212 cupsdWriteClient(cupsd_client_t
*con
) /* I - Client connection */
2214 int bytes
; /* Number of bytes written */
2215 char buf
[16385]; /* Data buffer */
2216 char *bufptr
; /* Pointer into buffer */
2217 ipp_state_t ipp_state
; /* IPP state value */
2221 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2222 "cupsdWriteClient(con=%p) %d response=%p, file=%d "
2223 "pipe_pid=%d state=%d",
2224 con
, con
->http
.fd
, con
->response
, con
->file
, con
->pipe_pid
,
2228 if (con
->http
.state
!= HTTP_GET_SEND
&&
2229 con
->http
.state
!= HTTP_POST_SEND
)
2232 if (con
->response
!= NULL
)
2234 ipp_state
= ippWrite(&(con
->http
), con
->response
);
2235 bytes
= ipp_state
!= IPP_ERROR
&& ipp_state
!= IPP_DATA
;
2237 else if ((bytes
= read(con
->file
, buf
, sizeof(buf
) - 1)) > 0)
2239 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2240 "cupsdWriteClient: Read %d bytes from file %d...",
2243 if (con
->pipe_pid
&& !con
->got_fields
)
2246 * Inspect the data for Content-Type and other fields.
2251 for (bufptr
= buf
; !con
->got_fields
&& *bufptr
; bufptr
++)
2252 if (*bufptr
== '\n')
2255 * Send line to client...
2258 if (bufptr
> buf
&& bufptr
[-1] == '\r')
2262 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "Script header: %s", buf
);
2264 if (!con
->sent_header
)
2267 * Handle redirection and CGI status codes...
2270 if (!strncasecmp(buf
, "Location:", 9))
2272 cupsdSendHeader(con
, HTTP_SEE_OTHER
, NULL
);
2273 if (httpPrintf(HTTP(con
), "Content-Length: 0\r\n") < 0)
2276 else if (!strncasecmp(buf
, "Status:", 7))
2277 cupsdSendError(con
, atoi(buf
+ 7));
2280 cupsdSendHeader(con
, HTTP_OK
, NULL
);
2282 if (con
->http
.version
== HTTP_1_1
)
2284 con
->http
.data_encoding
= HTTP_ENCODE_CHUNKED
;
2286 if (httpPrintf(HTTP(con
), "Transfer-Encoding: chunked\r\n") < 0)
2291 con
->sent_header
= 1;
2294 if (strncasecmp(buf
, "Status:", 7))
2295 httpPrintf(HTTP(con
), "%s\r\n", buf
);
2297 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdWriteClient: %d %s",
2304 bytes
-= (bufptr
- buf
);
2305 memmove(buf
, bufptr
, bytes
+ 1);
2309 * See if the line was empty...
2312 if (con
->field_col
== 0)
2313 con
->got_fields
= 1;
2317 else if (*bufptr
!= '\r')
2320 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2321 "cupsdWriteClient: %d bytes=%d, got_fields=%d",
2322 con
->http
.fd
, bytes
, con
->got_fields
);
2324 if (bytes
> 0 && !con
->got_fields
)
2327 * Remaining text needs to go out...
2330 httpPrintf(HTTP(con
), "%s", buf
);
2332 con
->http
.activity
= time(NULL
);
2335 else if (bytes
== 0)
2336 con
->http
.activity
= time(NULL
);
2341 if (httpWrite2(HTTP(con
), buf
, bytes
) < 0)
2343 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2344 "cupsdWriteClient: %d Write of %d bytes failed!",
2345 con
->http
.fd
, bytes
);
2347 cupsdCloseClient(con
);
2351 con
->bytes
+= bytes
;
2353 if (con
->http
.state
== HTTP_WAITING
)
2360 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdWriteClient: %d bytes < 0",
2363 cupsdLogRequest(con
, HTTP_OK
);
2365 httpFlushWrite(HTTP(con
));
2367 if (con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
)
2369 if (httpPrintf(HTTP(con
), "0\r\n\r\n") < 0)
2371 cupsdCloseClient(con
);
2376 con
->http
.state
= HTTP_WAITING
;
2378 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2379 "cupsdWriteClient: Removing fd %d from OutputSet...",
2382 FD_CLR(con
->http
.fd
, OutputSet
);
2386 if (FD_ISSET(con
->file
, InputSet
))
2388 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2389 "cupsdWriteClient: Removing fd %d from InputSet...",
2391 FD_CLR(con
->file
, InputSet
);
2395 cupsdEndProcess(con
->pipe_pid
, 0);
2397 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2398 "cupsdWriteClient: %d Closing data file %d.",
2399 con
->http
.fd
, con
->file
);
2408 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2409 "cupsdWriteClient: %d Removing temp file %s",
2410 con
->http
.fd
, con
->filename
);
2411 unlink(con
->filename
);
2412 cupsdClearString(&con
->filename
);
2415 if (con
->request
!= NULL
)
2417 ippDelete(con
->request
);
2418 con
->request
= NULL
;
2421 if (con
->response
!= NULL
)
2423 ippDelete(con
->response
);
2424 con
->response
= NULL
;
2427 cupsdClearString(&con
->command
);
2428 cupsdClearString(&con
->options
);
2430 if (!con
->http
.keep_alive
)
2432 cupsdCloseClient(con
);
2438 con
->file_ready
= 0;
2440 if (con
->pipe_pid
&& !FD_ISSET(con
->file
, InputSet
))
2442 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2443 "cupsdWriteClient: Adding fd %d to InputSet...",
2445 FD_SET(con
->file
, InputSet
);
2449 con
->http
.activity
= time(NULL
);
2456 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
2459 static int /* O - 1 if modified since */
2461 cupsd_client_t
*con
, /* I - Client connection */
2462 struct stat
*filestats
) /* I - File information */
2464 char *ptr
; /* Pointer into field */
2465 time_t date
; /* Time/date value */
2466 off_t size
; /* Size/length value */
2471 ptr
= con
->http
.fields
[HTTP_FIELD_IF_MODIFIED_SINCE
];
2476 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2477 "check_if_modified: %d If-Modified-Since=\"%s\"",
2480 while (*ptr
!= '\0')
2482 while (isspace(*ptr
) || *ptr
== ';')
2485 if (strncasecmp(ptr
, "length=", 7) == 0)
2488 size
= strtoll(ptr
, NULL
, 10);
2490 while (isdigit(*ptr
))
2493 else if (isalpha(*ptr
))
2495 date
= httpGetDateTime(ptr
);
2496 while (*ptr
!= '\0' && *ptr
!= ';')
2503 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2504 "check_if_modified: %d sizes=" CUPS_LLFMT
","
2505 CUPS_LLFMT
" dates=%d,%d",
2506 con
->http
.fd
, CUPS_LLCAST size
,
2507 CUPS_LLCAST filestats
->st_size
, (int)date
,
2508 (int)filestats
->st_mtime
);
2510 return ((size
!= filestats
->st_size
&& size
!= 0) ||
2511 (date
< filestats
->st_mtime
&& date
!= 0) ||
2512 (size
== 0 && date
== 0));
2518 * 'encrypt_client()' - Enable encryption for the client...
2521 static int /* O - 1 on success, 0 on error */
2522 encrypt_client(cupsd_client_t
*con
) /* I - Client to encrypt */
2525 SSL_CTX
*context
; /* Context for encryption */
2526 SSL
*conn
; /* Connection for encryption */
2527 unsigned long error
; /* Error code */
2531 * Create the SSL context and accept the connection...
2534 context
= SSL_CTX_new(SSLv23_server_method());
2536 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
2537 SSL_CTX_use_PrivateKey_file(context
, ServerKey
, SSL_FILETYPE_PEM
);
2538 SSL_CTX_use_certificate_file(context
, ServerCertificate
, SSL_FILETYPE_PEM
);
2540 conn
= SSL_new(context
);
2542 SSL_set_fd(conn
, con
->http
.fd
);
2543 if (SSL_accept(conn
) != 1)
2545 cupsdLogMessage(CUPSD_LOG_ERROR
,
2546 "encrypt_client: Unable to encrypt connection from %s!",
2547 con
->http
.hostname
);
2549 while ((error
= ERR_get_error()) != 0)
2550 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s",
2551 ERR_error_string(error
, NULL
));
2553 SSL_CTX_free(context
);
2558 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2559 "encrypt_client: %d Connection from %s now encrypted.",
2560 con
->http
.fd
, con
->http
.hostname
);
2562 con
->http
.tls
= conn
;
2565 # elif defined(HAVE_GNUTLS)
2566 http_tls_t
*conn
; /* TLS session object */
2567 int error
; /* Error code */
2568 gnutls_certificate_server_credentials
*credentials
;
2569 /* TLS credentials */
2573 * Verify that we have a certificate...
2576 if (access(ServerKey
, 0) || access(ServerCertificate
, 0))
2579 * Nope, make a self-signed certificate...
2586 * Create the SSL object and perform the SSL handshake...
2589 conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
));
2594 credentials
= (gnutls_certificate_server_credentials
*)
2595 malloc(sizeof(gnutls_certificate_server_credentials
));
2596 if (credentials
== NULL
)
2598 cupsdLogMessage(CUPSD_LOG_ERROR
,
2599 "encrypt_client: Unable to encrypt connection from %s!",
2600 con
->http
.hostname
);
2601 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s", strerror(errno
));
2607 gnutls_certificate_allocate_credentials(credentials
);
2608 gnutls_certificate_set_x509_key_file(*credentials
, ServerCertificate
,
2609 ServerKey
, GNUTLS_X509_FMT_PEM
);
2611 gnutls_init(&(conn
->session
), GNUTLS_SERVER
);
2612 gnutls_set_default_priority(conn
->session
);
2613 gnutls_credentials_set(conn
->session
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
2614 gnutls_transport_set_ptr(conn
->session
,
2615 (gnutls_transport_ptr
)((long)con
->http
.fd
));
2617 error
= gnutls_handshake(conn
->session
);
2619 if (error
!= GNUTLS_E_SUCCESS
)
2621 cupsdLogMessage(CUPSD_LOG_ERROR
,
2622 "encrypt_client: Unable to encrypt connection from %s!",
2623 con
->http
.hostname
);
2624 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s",
2625 gnutls_strerror(error
));
2627 gnutls_deinit(conn
->session
);
2628 gnutls_certificate_free_credentials(*credentials
);
2634 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2635 "encrypt_client: %d Connection from %s now encrypted.",
2636 con
->http
.fd
, con
->http
.hostname
);
2638 conn
->credentials
= credentials
;
2639 con
->http
.tls
= conn
;
2642 # elif defined(HAVE_CDSASSL)
2643 OSStatus error
; /* Error code */
2644 http_tls_t
*conn
; /* CDSA connection information */
2645 cdsa_conn_ref_t u
; /* Connection reference union */
2648 if ((conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
))) == NULL
)
2652 conn
->session
= NULL
;
2653 conn
->certsArray
= get_cdsa_server_certs();
2655 if (!conn
->certsArray
)
2657 cupsdLogMessage(CUPSD_LOG_ERROR
,
2658 "EncryptClient: Could not find signing key in keychain "
2659 "\"%s\"", ServerCertificate
);
2660 error
= errSSLBadCert
; /* errSSLBadConfiguration is a better choice, but not available on 10.2.x */
2664 error
= SSLNewContext(true, &conn
->session
);
2667 error
= SSLSetIOFuncs(conn
->session
, _httpReadCDSA
, _httpWriteCDSA
);
2670 error
= SSLSetProtocolVersionEnabled(conn
->session
, kSSLProtocol2
, false);
2675 * Use a union to resolve warnings about int/pointer size mismatches...
2678 u
.connection
= NULL
;
2679 u
.sock
= con
->http
.fd
;
2680 error
= SSLSetConnection(conn
->session
, u
.connection
);
2684 error
= SSLSetAllowsExpiredCerts(conn
->session
, true);
2687 error
= SSLSetAllowsAnyRoot(conn
->session
, true);
2690 error
= SSLSetCertificate(conn
->session
, conn
->certsArray
);
2695 * Perform SSL/TLS handshake
2698 while ((error
= SSLHandshake(conn
->session
)) == errSSLWouldBlock
)
2704 cupsdLogMessage(CUPSD_LOG_ERROR
,
2705 "encrypt_client: Unable to encrypt connection from %s!",
2706 con
->http
.hostname
);
2708 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s (%d)",
2709 cssmErrorString(error
), (int)error
);
2711 con
->http
.error
= error
;
2712 con
->http
.status
= HTTP_ERROR
;
2715 SSLDisposeContext(conn
->session
);
2717 if (conn
->certsArray
)
2718 CFRelease(conn
->certsArray
);
2725 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2726 "encrypt_client: %d Connection from %s now encrypted.",
2727 con
->http
.fd
, con
->http
.hostname
);
2729 con
->http
.tls
= conn
;
2732 # endif /* HAVE_LIBSSL */
2734 #endif /* HAVE_SSL */
2739 * 'get_cdsa_server_certs()' - Convert a keychain name into the CFArrayRef
2740 * required by SSLSetCertificate.
2742 * For now we assumes that there is exactly one SecIdentity in the
2743 * keychain - i.e. there is exactly one matching cert/private key pair.
2744 * In the future we will search a keychain for a SecIdentity matching a
2745 * specific criteria. We also skip the operation of adding additional
2746 * non-signing certs from the keychain to the CFArrayRef.
2748 * To create a self-signed certificate for testing use the certtool.
2749 * Executing the following as root will do it:
2751 * certtool c k=/Library/Keychains/System.keychain
2754 static CFArrayRef
/* O - Array of certificates */
2755 get_cdsa_server_certs(void)
2757 OSStatus err
; /* Error info */
2758 SecKeychainRef kcRef
; /* Keychain reference */
2759 SecIdentitySearchRef srchRef
; /* Search reference */
2760 SecIdentityRef identity
; /* Identity */
2761 CFArrayRef ca
; /* Certificate array */
2768 err
= SecKeychainOpen(ServerCertificate
, &kcRef
);
2771 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot open keychain \"%s\", error %d.",
2772 ServerCertificate
, (int)err
);
2776 * Search for "any" identity matching specified key use;
2777 * in this app, we expect there to be exactly one.
2780 err
= SecIdentitySearchCreate(kcRef
, CSSM_KEYUSE_SIGN
, &srchRef
);
2783 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2784 "Cannot find signing key in keychain \"%s\", error %d",
2785 ServerCertificate
, (int)err
);
2788 err
= SecIdentitySearchCopyNext(srchRef
, &identity
);
2791 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2792 "Cannot find signing key in keychain \"%s\", error %d",
2793 ServerCertificate
, (int)err
);
2796 if (CFGetTypeID(identity
) != SecIdentityGetTypeID())
2797 cupsdLogMessage(CUPSD_LOG_ERROR
,
2798 "SecIdentitySearchCopyNext CFTypeID failure!");
2802 * Found one. Place it in a CFArray.
2803 * TBD: snag other (non-identity) certs from keychain and add them
2807 ca
= CFArrayCreate(NULL
, (const void **)&identity
, 1, &kCFTypeArrayCallBacks
);
2810 cupsdLogMessage(CUPSD_LOG_ERROR
, "CFArrayCreate error");
2813 CFRelease(identity
);
2824 #endif /* HAVE_CDSASSL */
2828 * 'get_file()' - Get a filename and state info.
2831 static char * /* O - Real filename */
2832 get_file(cupsd_client_t
*con
, /* I - Client connection */
2833 struct stat
*filestats
, /* O - File information */
2834 char *filename
, /* IO - Filename buffer */
2835 int len
) /* I - Buffer length */
2837 int status
; /* Status of filesystem calls */
2838 char *ptr
; /* Pointer info filename */
2839 int plen
; /* Remaining length after pointer */
2843 * Need to add DocumentRoot global...
2846 if (!strncmp(con
->uri
, "/ppd/", 5))
2847 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
);
2848 else if (!strncmp(con
->uri
, "/admin/conf/", 12))
2849 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
+ 11);
2850 else if (!strncmp(con
->uri
, "/admin/log/", 11))
2852 if (!strcmp(con
->uri
+ 11, "access_log") && AccessLog
[0] == '/')
2853 strlcpy(filename
, AccessLog
, len
);
2854 else if (!strcmp(con
->uri
+ 11, "error_log") && ErrorLog
[0] == '/')
2855 strlcpy(filename
, ErrorLog
, len
);
2856 else if (!strcmp(con
->uri
+ 11, "page_log") && PageLog
[0] == '/')
2857 strlcpy(filename
, PageLog
, len
);
2861 else if (con
->language
)
2862 snprintf(filename
, len
, "%s/%s%s", DocumentRoot
, con
->language
->language
,
2865 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
2867 if ((ptr
= strchr(filename
, '?')) != NULL
)
2871 * Grab the status for this language; if there isn't a language-specific file
2872 * then fallback to the default one...
2875 if ((status
= stat(filename
, filestats
)) != 0 && con
->language
&&
2876 strncmp(con
->uri
, "/ppd/", 5) &&
2877 strncmp(con
->uri
, "/admin/conf/", 12) &&
2878 strncmp(con
->uri
, "/admin/log/", 11))
2881 * Drop the country code...
2884 char ll
[3]; /* Short language name */
2887 strlcpy(ll
, con
->language
->language
, sizeof(ll
));
2888 snprintf(filename
, len
, "%s/%s%s", DocumentRoot
, ll
, con
->uri
);
2890 if ((ptr
= strchr(filename
, '?')) != NULL
)
2893 if ((status
= stat(filename
, filestats
)) != 0)
2896 * Drop the language prefix and try the root directory...
2899 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
2901 if ((ptr
= strchr(filename
, '?')) != NULL
)
2904 status
= stat(filename
, filestats
);
2909 * If we're found a directory, get the index.html file instead...
2912 if (!status
&& S_ISDIR(filestats
->st_mode
))
2914 if (filename
[strlen(filename
) - 1] != '/')
2915 strlcat(filename
, "/", len
);
2917 ptr
= filename
+ strlen(filename
);
2918 plen
= len
- (ptr
- filename
);
2920 strlcpy(ptr
, "index.html", plen
);
2921 status
= stat(filename
, filestats
);
2926 strlcpy(ptr
, "index.class", plen
);
2927 status
= stat(filename
, filestats
);
2929 #endif /* HAVE_JAVA */
2934 strlcpy(ptr
, "index.pl", plen
);
2935 status
= stat(filename
, filestats
);
2937 #endif /* HAVE_PERL */
2942 strlcpy(ptr
, "index.php", plen
);
2943 status
= stat(filename
, filestats
);
2945 #endif /* HAVE_PHP */
2950 strlcpy(ptr
, "index.pyc", plen
);
2951 status
= stat(filename
, filestats
);
2956 strlcpy(ptr
, "index.py", plen
);
2957 status
= stat(filename
, filestats
);
2959 #endif /* HAVE_PYTHON */
2962 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "get_file: %d filename=%s size=%d",
2963 con
->http
.fd
, filename
,
2964 status
? -1 : (int)filestats
->st_size
);
2967 con
->http
.data_remaining
= (int)filestats
->st_size
;
2977 * 'install_conf_file()' - Install a configuration file.
2980 static http_status_t
/* O - Status */
2981 install_conf_file(cupsd_client_t
*con
) /* I - Connection */
2983 cups_file_t
*in
, /* Input file */
2984 *out
; /* Output file */
2985 char buffer
[1024]; /* Copy buffer */
2986 int bytes
; /* Number of bytes */
2987 char conffile
[1024], /* Configuration filename */
2988 newfile
[1024], /* New config filename */
2989 oldfile
[1024]; /* Old config filename */
2990 struct stat confinfo
; /* Config file info */
2994 * First construct the filenames...
2997 snprintf(conffile
, sizeof(conffile
), "%s%s", ServerRoot
, con
->uri
+ 11);
2998 snprintf(newfile
, sizeof(newfile
), "%s%s.N", ServerRoot
, con
->uri
+ 11);
2999 snprintf(oldfile
, sizeof(oldfile
), "%s%s.O", ServerRoot
, con
->uri
+ 11);
3001 cupsdLogMessage(CUPSD_LOG_INFO
, "Installing config file \"%s\"...", conffile
);
3004 * Get the owner, group, and permissions of the configuration file.
3005 * If it doesn't exist, assign it to the User and Group in the
3006 * cupsd.conf file with mode 0640 permissions.
3009 if (stat(conffile
, &confinfo
))
3011 confinfo
.st_uid
= User
;
3012 confinfo
.st_gid
= Group
;
3013 confinfo
.st_mode
= ConfigFilePerm
;
3017 * Open the request file and new config file...
3020 if ((in
= cupsFileOpen(con
->filename
, "rb")) == NULL
)
3022 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open request file \"%s\" - %s",
3023 con
->filename
, strerror(errno
));
3024 return (HTTP_SERVER_ERROR
);
3027 if ((out
= cupsFileOpen(newfile
, "wb")) == NULL
)
3030 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open config file \"%s\" - %s",
3031 newfile
, strerror(errno
));
3032 return (HTTP_SERVER_ERROR
);
3035 fchmod(cupsFileNumber(out
), confinfo
.st_mode
);
3036 fchown(cupsFileNumber(out
), confinfo
.st_uid
, confinfo
.st_gid
);
3039 * Copy from the request to the new config file...
3042 while ((bytes
= cupsFileRead(in
, buffer
, sizeof(buffer
))) > 0)
3043 if (cupsFileWrite(out
, buffer
, bytes
) < bytes
)
3045 cupsdLogMessage(CUPSD_LOG_ERROR
,
3046 "Unable to copy to config file \"%s\" - %s",
3047 newfile
, strerror(errno
));
3053 return (HTTP_SERVER_ERROR
);
3057 * Close the files...
3061 if (cupsFileClose(out
))
3063 cupsdLogMessage(CUPSD_LOG_ERROR
,
3064 "Error file closing config file \"%s\" - %s",
3065 newfile
, strerror(errno
));
3069 return (HTTP_SERVER_ERROR
);
3073 * Remove the request file...
3076 unlink(con
->filename
);
3077 cupsdClearString(&con
->filename
);
3080 * Unlink the old backup, rename the current config file to the backup
3081 * filename, and rename the new config file to the config file name...
3084 if (unlink(oldfile
))
3085 if (errno
!= ENOENT
)
3087 cupsdLogMessage(CUPSD_LOG_ERROR
,
3088 "Unable to remove backup config file \"%s\" - %s",
3089 oldfile
, strerror(errno
));
3093 return (HTTP_SERVER_ERROR
);
3096 if (rename(conffile
, oldfile
))
3097 if (errno
!= ENOENT
)
3099 cupsdLogMessage(CUPSD_LOG_ERROR
,
3100 "Unable to rename old config file \"%s\" - %s",
3101 conffile
, strerror(errno
));
3105 return (HTTP_SERVER_ERROR
);
3108 if (rename(newfile
, conffile
))
3110 cupsdLogMessage(CUPSD_LOG_ERROR
,
3111 "Unable to rename new config file \"%s\" - %s",
3112 newfile
, strerror(errno
));
3114 rename(oldfile
, conffile
);
3117 return (HTTP_SERVER_ERROR
);
3121 * If the cupsd.conf file was updated, set the NeedReload flag...
3124 if (!strcmp(con
->uri
, "/admin/conf/cupsd.conf"))
3125 NeedReload
= RELOAD_CUPSD
;
3127 NeedReload
= RELOAD_ALL
;
3129 ReloadTime
= time(NULL
);
3132 * Return that the file was created successfully...
3135 return (HTTP_CREATED
);
3140 * 'is_cgi()' - Is the resource a CGI script/program?
3143 static int /* O - 1 = CGI, 0 = file */
3144 is_cgi(cupsd_client_t
*con
, /* I - Client connection */
3145 const char *filename
, /* I - Real filename */
3146 struct stat
*filestats
, /* I - File information */
3147 mime_type_t
*type
) /* I - MIME type */
3149 const char *options
; /* Options on URL */
3152 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3153 "is_cgi(con=%p, filename=\"%s\", filestats=%p, type=%s/%s)\n",
3154 con
, filename
, filestats
, type
? type
->super
: "unknown",
3155 type
? type
->type
: "unknown");
3158 * Get the options, if any...
3161 if ((options
= strchr(con
->uri
, '?')) != NULL
)
3165 * Check for known types...
3168 if (!type
|| strcasecmp(type
->super
, "application"))
3170 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "is_cgi: Returning 0...");
3174 if (!strcasecmp(type
->type
, "x-httpd-cgi") &&
3175 (filestats
->st_mode
& 0111))
3178 * "application/x-httpd-cgi" is a CGI script.
3181 cupsdSetString(&con
->command
, filename
);
3183 filename
= strrchr(filename
, '/') + 1; /* Filename always absolute */
3185 cupsdSetString(&con
->options
, options
);
3187 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3188 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3189 con
->command
, con
->options
);
3194 else if (!strcasecmp(type
->type
, "x-httpd-java"))
3197 * "application/x-httpd-java" is a Java servlet.
3200 cupsdSetString(&con
->command
, CUPS_JAVA
);
3203 cupsdSetStringf(&con
->options
, "%s %s", filename
, options
);
3205 cupsdSetString(&con
->options
, filename
);
3207 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3208 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3209 con
->command
, con
->options
);
3213 #endif /* HAVE_JAVA */
3215 else if (!strcasecmp(type
->type
, "x-httpd-perl"))
3218 * "application/x-httpd-perl" is a Perl page.
3221 cupsdSetString(&con
->command
, CUPS_PERL
);
3224 cupsdSetStringf(&con
->options
, "%s %s", filename
, options
);
3226 cupsdSetString(&con
->options
, filename
);
3228 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3229 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3230 con
->command
, con
->options
);
3234 #endif /* HAVE_PERL */
3236 else if (!strcasecmp(type
->type
, "x-httpd-php"))
3239 * "application/x-httpd-php" is a PHP page.
3242 cupsdSetString(&con
->command
, CUPS_PHP
);
3245 cupsdSetStringf(&con
->options
, "%s %s", filename
, options
);
3247 cupsdSetString(&con
->options
, filename
);
3249 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3250 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3251 con
->command
, con
->options
);
3255 #endif /* HAVE_PHP */
3257 else if (!strcasecmp(type
->type
, "x-httpd-python"))
3260 * "application/x-httpd-python" is a Python page.
3263 cupsdSetString(&con
->command
, CUPS_PYTHON
);
3266 cupsdSetStringf(&con
->options
, "%s %s", filename
, options
);
3268 cupsdSetString(&con
->options
, filename
);
3270 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3271 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3272 con
->command
, con
->options
);
3276 #endif /* HAVE_PYTHON */
3278 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "is_cgi: Returning 0...");
3285 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
3288 static int /* O - 0 if relative, 1 if absolute */
3289 is_path_absolute(const char *path
) /* I - Input path */
3292 * Check for a leading slash...
3299 * Check for "/.." in the path...
3302 while ((path
= strstr(path
, "/..")) != NULL
)
3304 if (!path
[3] || path
[3] == '/')
3311 * If we haven't found any relative paths, return 1 indicating an
3321 * 'make_certificate()' - Make a self-signed SSL/TLS certificate.
3325 make_certificate(void)
3327 gnutls_x509_crt crt
; /* Self-signed certificate */
3328 gnutls_x509_privkey key
; /* Encryption key */
3329 cups_lang_t
*language
; /* Default language info */
3330 cups_file_t
*fp
; /* Key/cert file */
3331 unsigned char buffer
[8192]; /* Buffer for x509 data */
3332 size_t bytes
; /* Number of bytes of data */
3333 unsigned char serial
[4]; /* Serial number buffer */
3334 time_t curtime
; /* Current time */
3335 int result
; /* Result of GNU TLS calls */
3339 * Create the encryption key...
3342 cupsdLogMessage(CUPSD_LOG_INFO
, "Generating server key...");
3344 gnutls_x509_privkey_init(&key
);
3345 gnutls_x509_privkey_generate(key
, GNUTLS_PK_RSA
, 2048, 0);
3351 bytes
= sizeof(buffer
);
3353 if ((result
= gnutls_x509_privkey_export(key
, GNUTLS_X509_FMT_PEM
,
3354 buffer
, &bytes
)) < 0)
3356 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to export server key - %s",
3357 gnutls_strerror(result
));
3358 gnutls_x509_privkey_deinit(key
);
3361 else if ((fp
= cupsFileOpen(ServerKey
, "w")) != NULL
)
3363 cupsFileWrite(fp
, (char *)buffer
, bytes
);
3366 cupsdLogMessage(CUPSD_LOG_INFO
, "Created server key file \"%s\"...",
3371 cupsdLogMessage(CUPSD_LOG_ERROR
,
3372 "Unable to create server key file \"%s\" - %s",
3373 ServerKey
, strerror(errno
));
3374 gnutls_x509_privkey_deinit(key
);
3379 * Create the self-signed certificate...
3382 cupsdLogMessage(CUPSD_LOG_INFO
, "Generating self-signed certificate...");
3384 language
= cupsLangDefault();
3385 curtime
= time(NULL
);
3386 serial
[0] = curtime
>> 24;
3387 serial
[1] = curtime
>> 16;
3388 serial
[2] = curtime
>> 8;
3389 serial
[3] = curtime
;
3391 gnutls_x509_crt_init(&crt
);
3392 if (strlen(language
->language
) == 5)
3393 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
3394 language
->language
+ 3, 2);
3396 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
3398 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COMMON_NAME
, 0,
3399 ServerName
, strlen(ServerName
));
3400 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATION_NAME
, 0,
3401 ServerName
, strlen(ServerName
));
3402 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATIONAL_UNIT_NAME
,
3404 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_STATE_OR_PROVINCE_NAME
, 0,
3406 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_LOCALITY_NAME
, 0,
3408 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_PKCS9_EMAIL
, 0,
3409 ServerAdmin
, strlen(ServerAdmin
));
3410 gnutls_x509_crt_set_key(crt
, key
);
3411 gnutls_x509_crt_set_serial(crt
, serial
, sizeof(serial
));
3412 gnutls_x509_crt_set_activation_time(crt
, curtime
);
3413 gnutls_x509_crt_set_expiration_time(crt
, curtime
+ 10 * 365 * 86400);
3414 gnutls_x509_crt_set_ca_status(crt
, 0);
3415 gnutls_x509_crt_set_subject_alternative_name(crt
, GNUTLS_SAN_DNSNAME
,
3417 gnutls_x509_crt_set_key_purpose_oid(crt
, GNUTLS_KP_TLS_WWW_SERVER
, 0);
3418 gnutls_x509_crt_set_key_usage(crt
, GNUTLS_KEY_KEY_ENCIPHERMENT
);
3419 gnutls_x509_crt_set_version(crt
, 3);
3421 bytes
= sizeof(buffer
);
3422 if (gnutls_x509_crt_get_key_id(crt
, 0, buffer
, &bytes
) >= 0)
3423 gnutls_x509_crt_set_subject_key_id(crt
, buffer
, bytes
);
3425 gnutls_x509_crt_sign(crt
, crt
, key
);
3431 bytes
= sizeof(buffer
);
3432 if ((result
= gnutls_x509_crt_export(crt
, GNUTLS_X509_FMT_PEM
,
3433 buffer
, &bytes
)) < 0)
3434 cupsdLogMessage(CUPSD_LOG_ERROR
,
3435 "Unable to export server certificate - %s",
3436 gnutls_strerror(result
));
3437 else if ((fp
= cupsFileOpen(ServerCertificate
, "w")) != NULL
)
3439 cupsFileWrite(fp
, (char *)buffer
, bytes
);
3442 cupsdLogMessage(CUPSD_LOG_INFO
,
3443 "Created 10-year server certificate file \"%s\"...",
3447 cupsdLogMessage(CUPSD_LOG_ERROR
,
3448 "Unable to create server certificate file \"%s\" - %s",
3449 ServerCertificate
, strerror(errno
));
3455 gnutls_x509_crt_deinit(crt
);
3456 gnutls_x509_privkey_deinit(key
);
3458 #endif /* HAVE_GNUTLS */
3462 * 'pipe_command()' - Pipe the output of a command to the remote client.
3465 static int /* O - Process ID */
3466 pipe_command(cupsd_client_t
*con
, /* I - Client connection */
3467 int infile
, /* I - Standard input for command */
3468 int *outfile
, /* O - Standard output for command */
3469 char *command
, /* I - Command to run */
3470 char *options
, /* I - Options for command */
3471 int root
) /* I - Run as root? */
3473 int i
; /* Looping var */
3474 int pid
; /* Process ID */
3475 char *commptr
, /* Command string pointer */
3476 commch
; /* Command string character */
3477 char *uriptr
; /* URI string pointer */
3478 int fds
[2]; /* Pipe FDs */
3479 int argc
; /* Number of arguments */
3480 int envc
; /* Number of environment variables */
3481 char argbuf
[10240], /* Argument buffer */
3482 *argv
[100], /* Argument strings */
3483 *envp
[MAX_ENV
+ 17]; /* Environment variables */
3484 char content_length
[1024], /* CONTENT_LENGTH environment variable */
3485 content_type
[1024], /* CONTENT_TYPE environment variable */
3486 http_cookie
[32768], /* HTTP_COOKIE environment variable */
3487 http_user_agent
[1024], /* HTTP_USER_AGENT environment variable */
3488 lang
[1024], /* LANG environment variable */
3489 path_info
[1024], /* PATH_INFO environment variable */
3490 *query_string
, /* QUERY_STRING env variable */
3491 remote_addr
[1024], /* REMOTE_ADDR environment variable */
3492 remote_host
[1024], /* REMOTE_HOST environment variable */
3493 remote_user
[1024], /* REMOTE_USER environment variable */
3494 script_name
[1024], /* SCRIPT_NAME environment variable */
3495 server_name
[1024], /* SERVER_NAME environment variable */
3496 server_port
[1024]; /* SERVER_PORT environment variable */
3500 * Parse a copy of the options string, which is of the form:
3502 * argument+argument+argument
3503 * ?argument+argument+argument
3504 * param=value¶m=value
3505 * ?param=value¶m=value
3506 * /name?argument+argument+argument
3507 * /name?param=value¶m=value
3509 * If the string contains an "=" character after the initial name,
3510 * then we treat it as a HTTP GET form request and make a copy of
3511 * the remaining string for the environment variable.
3513 * The string is always parsed out as command-line arguments, to
3514 * be consistent with Apache...
3517 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3518 "pipe_command: command=\"%s\", options=\"%s\"",
3519 command
, options
? options
: "(null)");
3522 query_string
= NULL
;
3525 strlcpy(argbuf
, options
, sizeof(argbuf
));
3529 if (argbuf
[0] == '/')
3532 * Found some trailing path information, set PATH_INFO...
3535 if ((commptr
= strchr(argbuf
, '?')) == NULL
)
3536 commptr
= argbuf
+ strlen(argbuf
);
3540 snprintf(path_info
, sizeof(path_info
), "PATH_INFO=%s", argbuf
);
3546 path_info
[0] = '\0';
3549 if (*commptr
== '?' && con
->operation
== HTTP_GET
)
3552 cupsdSetStringf(&query_string
, "QUERY_STRING=%s", commptr
);
3559 argv
[argc
++] = commptr
;
3561 for (; *commptr
&& argc
< 99; commptr
++)
3564 * Break arguments whenever we see a + or space...
3567 if (*commptr
== ' ' || *commptr
== '+')
3569 while (*commptr
== ' ' || *commptr
== '+')
3573 * If we don't have a blank string, save it as another argument...
3578 argv
[argc
] = commptr
;
3584 else if (*commptr
== '%' && isxdigit(commptr
[1] & 255) &&
3585 isxdigit(commptr
[2] & 255))
3588 * Convert the %xx notation to the individual character.
3591 if (commptr
[1] >= '0' && commptr
[1] <= '9')
3592 *commptr
= (commptr
[1] - '0') << 4;
3594 *commptr
= (tolower(commptr
[1]) - 'a' + 10) << 4;
3596 if (commptr
[2] >= '0' && commptr
[2] <= '9')
3597 *commptr
|= commptr
[2] - '0';
3599 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
3601 _cups_strcpy(commptr
+ 1, commptr
+ 3);
3604 * Check for a %00 and break if that is the case...
3616 * Setup the environment variables as needed...
3620 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF-8", con
->language
->language
);
3622 strcpy(lang
, "LANG=C");
3624 strcpy(remote_addr
, "REMOTE_ADDR=");
3625 httpAddrString(con
->http
.hostaddr
, remote_addr
+ 12,
3626 sizeof(remote_addr
) - 12);
3628 snprintf(remote_host
, sizeof(remote_host
), "REMOTE_HOST=%s",
3629 con
->http
.hostname
);
3631 snprintf(script_name
, sizeof(script_name
), "SCRIPT_NAME=%s", con
->uri
);
3632 if ((uriptr
= strchr(script_name
, '?')) != NULL
)
3635 sprintf(server_port
, "SERVER_PORT=%d", con
->serverport
);
3637 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
3640 envc
= cupsdLoadEnv(envp
, (int)(sizeof(envp
) / sizeof(envp
[0])));
3642 envp
[envc
++] = lang
;
3643 envp
[envc
++] = "REDIRECT_STATUS=1";
3644 envp
[envc
++] = server_name
;
3645 envp
[envc
++] = server_port
;
3646 envp
[envc
++] = remote_addr
;
3647 envp
[envc
++] = remote_host
;
3648 envp
[envc
++] = script_name
;
3651 envp
[envc
++] = path_info
;
3653 if (con
->username
[0])
3655 snprintf(remote_user
, sizeof(remote_user
), "REMOTE_USER=%s", con
->username
);
3657 envp
[envc
++] = remote_user
;
3660 if (con
->http
.version
== HTTP_1_1
)
3661 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.1";
3662 else if (con
->http
.version
== HTTP_1_0
)
3663 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.0";
3665 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/0.9";
3667 if (con
->http
.cookie
)
3669 snprintf(http_cookie
, sizeof(http_cookie
), "HTTP_COOKIE=%s",
3671 envp
[envc
++] = http_cookie
;
3674 if (con
->http
.fields
[HTTP_FIELD_USER_AGENT
][0])
3676 snprintf(http_user_agent
, sizeof(http_user_agent
), "HTTP_USER_AGENT=%s",
3677 con
->http
.fields
[HTTP_FIELD_USER_AGENT
]);
3678 envp
[envc
++] = http_user_agent
;
3681 if (con
->operation
== HTTP_GET
)
3683 for (i
= 0; i
< argc
; i
++)
3684 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "argv[%d] = \"%s\"", i
, argv
[i
]);
3686 envp
[envc
++] = "REQUEST_METHOD=GET";
3691 * Add GET form variables after ?...
3694 envp
[envc
++] = query_string
;
3699 sprintf(content_length
, "CONTENT_LENGTH=" CUPS_LLFMT
,
3700 CUPS_LLCAST con
->bytes
);
3701 snprintf(content_type
, sizeof(content_type
), "CONTENT_TYPE=%s",
3702 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
3704 envp
[envc
++] = "REQUEST_METHOD=POST";
3705 envp
[envc
++] = content_length
;
3706 envp
[envc
++] = content_type
;
3710 * Tell the CGI if we are using encryption...
3714 envp
[envc
++] = "HTTPS=ON";
3717 * Terminate the environment array...
3722 if (LogLevel
== CUPSD_LOG_DEBUG2
)
3724 for (i
= 0; i
< argc
; i
++)
3725 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3726 "pipe_command: argv[%d] = \"%s\"", i
, argv
[i
]);
3727 for (i
= 0; i
< envc
; i
++)
3728 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3729 "pipe_command: envp[%d] = \"%s\"", i
, envp
[i
]);
3733 * Create a pipe for the output...
3736 if (cupsdOpenPipe(fds
))
3738 cupsdClearString(&query_string
);
3740 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to create pipes for CGI %s - %s",
3741 argv
[0], strerror(errno
));
3746 * Then execute the command...
3749 if (cupsdStartProcess(command
, argv
, envp
, infile
, fds
[1], CGIPipes
[1],
3750 -1, root
, &pid
) < 0)
3753 * Error - can't fork!
3756 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to fork for CGI %s - %s", argv
[0],
3759 cupsdClosePipe(fds
);
3765 * Fork successful - return the PID...
3768 if (con
->username
[0])
3769 cupsdAddCert(pid
, con
->username
);
3771 cupsdLogMessage(CUPSD_LOG_DEBUG
, "CGI %s started - PID = %d", command
, pid
);
3777 cupsdClearString(&query_string
);
3784 * 'write_file()' - Send a file via HTTP.
3787 static int /* O - 0 on failure, 1 on success */
3788 write_file(cupsd_client_t
*con
, /* I - Client connection */
3789 http_status_t code
, /* I - HTTP status */
3790 char *filename
, /* I - Filename */
3791 char *type
, /* I - File type */
3792 struct stat
*filestats
) /* O - File information */
3794 con
->file
= open(filename
, O_RDONLY
);
3796 cupsdLogMessage(CUPSD_LOG_DEBUG
, "write_file: %d file=%d", con
->http
.fd
,
3802 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
3806 if (!cupsdSendHeader(con
, code
, type
))
3809 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
3810 httpGetDateString(filestats
->st_mtime
)) < 0)
3812 if (httpPrintf(HTTP(con
), "Content-Length: " CUPS_LLFMT
"\r\n",
3813 CUPS_LLCAST filestats
->st_size
) < 0)
3815 if (httpPrintf(HTTP(con
), "\r\n") < 0)
3818 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
3819 con
->http
.data_remaining
= filestats
->st_size
;
3821 if (con
->http
.data_remaining
<= INT_MAX
)
3822 con
->http
._data_remaining
= con
->http
.data_remaining
;
3824 con
->http
._data_remaining
= INT_MAX
;
3826 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3827 "write_file: Adding fd %d to OutputSet...", con
->http
.fd
);
3829 FD_SET(con
->http
.fd
, OutputSet
);