2 * "$Id: client.c 5416 2006-04-17 21:24:17Z 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 * 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 * send_file() - Send a file via HTTP.
49 * Include necessary headers...
52 #include <cups/http-private.h>
56 # include <Security/Security.h>
57 #endif /* HAVE_CDSASSL */
59 # include <gnutls/x509.h>
60 #endif /* HAVE_GNUTLS */
67 static int check_if_modified(cupsd_client_t
*con
,
68 struct stat
*filestats
);
70 static int encrypt_client(cupsd_client_t
*con
);
73 static CFArrayRef
get_cdsa_server_certs(void);
74 #endif /* HAVE_CDSASSL */
75 static char *get_file(cupsd_client_t
*con
, struct stat
*filestats
,
76 char *filename
, int len
);
77 static http_status_t
install_conf_file(cupsd_client_t
*con
);
78 static int is_cgi(cupsd_client_t
*con
, const char *filename
,
79 struct stat
*filestats
, mime_type_t
*type
);
80 static int is_path_absolute(const char *path
);
82 static void make_certificate(void);
83 #endif /* HAVE_GNUTLS */
84 static int pipe_command(cupsd_client_t
*con
, int infile
, int *outfile
,
85 char *command
, char *options
, int root
);
86 static int send_file(cupsd_client_t
*con
, http_status_t code
,
87 char *filename
, char *type
,
88 struct stat
*filestats
);
92 * 'cupsdAcceptClient()' - Accept a new client.
96 cupsdAcceptClient(cupsd_listener_t
*lis
)/* I - Listener socket */
98 int count
; /* Count of connections on a host */
99 int val
; /* Parameter value */
100 cupsd_client_t
*con
, /* New client pointer */
101 *tempcon
; /* Temporary client pointer */
102 http_addrlist_t
*addrlist
, /* List of adddresses for host */
103 *addr
; /* Current address */
104 socklen_t addrlen
; /* Length of address */
105 char *hostname
; /* Hostname for address */
106 http_addr_t temp
; /* Temporary address variable */
107 static time_t last_dos
= 0; /* Time of last DoS attack */
110 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
111 "cupsdAcceptClient(lis=%p) %d Clients = %d",
112 lis
, lis
->fd
, cupsArrayCount(Clients
));
115 * Make sure we don't have a full set of clients already...
118 if (cupsArrayCount(Clients
) == MaxClients
)
122 * Get a pointer to the next available client...
126 Clients
= cupsArrayNew(NULL
, NULL
);
131 con
= calloc(1, sizeof(cupsd_client_t
));
133 con
->http
.activity
= time(NULL
);
135 con
->http
.hostaddr
= &(con
->clientaddr
);
138 * Accept the client and get the remote address...
141 addrlen
= sizeof(http_addr_t
);
143 if ((con
->http
.fd
= accept(lis
->fd
, (struct sockaddr
*)con
->http
.hostaddr
,
146 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to accept client connection - %s.",
153 if (lis
->address
.addr
.sa_family
== AF_INET6
)
156 * Save the connected port number...
159 con
->http
.hostaddr
->ipv6
.sin6_port
= lis
->address
.ipv6
.sin6_port
;
162 * Convert IPv4 over IPv6 addresses (::ffff:n.n.n.n) to IPv4 forms we
163 * can more easily use...
166 if (con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[0] == 0 &&
167 con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[1] == 0 &&
168 ntohl(con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[2]) == 0xffff)
169 con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[2] = 0;
172 #endif /* AF_INET6 */
173 if (lis
->address
.addr
.sa_family
== AF_INET
)
174 con
->http
.hostaddr
->ipv4
.sin_port
= lis
->address
.ipv4
.sin_port
;
177 * Check the number of clients on the same address...
180 for (count
= 0, tempcon
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
182 tempcon
= (cupsd_client_t
*)cupsArrayNext(Clients
))
183 if (httpAddrEqual(tempcon
->http
.hostaddr
, con
->http
.hostaddr
))
186 if (count
>= MaxClientsPerHost
)
190 if (count
>= MaxClientsPerHost
)
192 if ((time(NULL
) - last_dos
) >= 60)
194 last_dos
= time(NULL
);
195 cupsdLogMessage(CUPSD_LOG_WARN
,
196 "Possible DoS attack - more than %d clients connecting "
198 MaxClientsPerHost
, tempcon
->http
.hostname
);
202 closesocket(con
->http
.fd
);
212 * Get the hostname or format the IP address as needed...
215 if (httpAddrLocalhost(con
->http
.hostaddr
))
218 * Map accesses from the loopback interface to "localhost"...
221 strlcpy(con
->http
.hostname
, "localhost", sizeof(con
->http
.hostname
));
222 hostname
= con
->http
.hostname
;
227 * Map accesses from the same host to the server name.
230 for (addr
= ServerAddrs
; addr
; addr
= addr
->next
)
231 if (httpAddrEqual(con
->http
.hostaddr
, &(addr
->addr
)))
236 strlcpy(con
->http
.hostname
, ServerName
, sizeof(con
->http
.hostname
));
237 hostname
= con
->http
.hostname
;
239 else if (HostNameLookups
)
240 hostname
= httpAddrLookup(con
->http
.hostaddr
, con
->http
.hostname
,
241 sizeof(con
->http
.hostname
));
245 httpAddrString(con
->http
.hostaddr
, con
->http
.hostname
,
246 sizeof(con
->http
.hostname
));
250 if (hostname
== NULL
&& HostNameLookups
== 2)
253 * Can't have an unresolved IP address with double-lookups enabled...
256 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
257 "cupsdAcceptClient: Closing connection %d...",
261 closesocket(con
->http
.fd
);
266 cupsdLogMessage(CUPSD_LOG_WARN
,
267 "Name lookup failed - connection from %s closed!",
274 if (HostNameLookups
== 2)
277 * Do double lookups as needed...
280 if ((addrlist
= httpAddrGetList(con
->http
.hostname
, AF_UNSPEC
, NULL
)) != NULL
)
283 * See if the hostname maps to the same IP address...
286 for (addr
= addrlist
; addr
; addr
= addr
->next
)
287 if (httpAddrEqual(con
->http
.hostaddr
, &(addr
->addr
)))
293 httpAddrFreeList(addrlist
);
298 * Can't have a hostname that doesn't resolve to the same IP address
299 * with double-lookups enabled...
302 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
303 "cupsdAcceptClient: Closing connection %d...",
307 closesocket(con
->http
.fd
);
312 cupsdLogMessage(CUPSD_LOG_WARN
,
313 "IP lookup failed - connection from %s closed!",
321 if (con
->http
.hostaddr
->addr
.sa_family
== AF_INET6
)
322 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdAcceptClient: %d from %s:%d (IPv6)",
323 con
->http
.fd
, con
->http
.hostname
,
324 ntohs(con
->http
.hostaddr
->ipv6
.sin6_port
));
326 #endif /* AF_INET6 */
328 if (con
->http
.hostaddr
->addr
.sa_family
== AF_LOCAL
)
329 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdAcceptClient: %d from %s (Domain)",
330 con
->http
.fd
, con
->http
.hostname
);
332 #endif /* AF_LOCAL */
333 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdAcceptClient: %d from %s:%d (IPv4)",
334 con
->http
.fd
, con
->http
.hostname
,
335 ntohs(con
->http
.hostaddr
->ipv4
.sin_port
));
338 * Get the local address the client connected to...
341 addrlen
= sizeof(temp
);
342 if (getsockname(con
->http
.fd
, (struct sockaddr
*)&temp
, &addrlen
))
344 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to get local address - %s",
347 strcpy(con
->servername
, "localhost");
348 con
->serverport
= LocalPort
;
353 if (temp
.addr
.sa_family
== AF_INET6
)
355 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
356 con
->serverport
= ntohs(lis
->address
.ipv6
.sin6_port
);
359 #endif /* AF_INET6 */
360 if (temp
.addr
.sa_family
== AF_INET
)
362 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
363 con
->serverport
= ntohs(lis
->address
.ipv4
.sin_port
);
367 strcpy(con
->servername
, "localhost");
368 con
->serverport
= LocalPort
;
372 cupsArrayAdd(Clients
, con
);
374 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
375 "cupsdAcceptClient: %d connected to server on %s:%d",
376 con
->http
.fd
, con
->servername
, con
->serverport
);
379 * Using TCP_NODELAY improves responsiveness, especially on systems
380 * with a slow loopback interface... Since we write large buffers
381 * when sending print files and requests, there shouldn't be any
382 * performance penalty for this...
386 setsockopt(con
->http
.fd
, IPPROTO_TCP
, TCP_NODELAY
, &val
, sizeof(val
));
389 * Close this file on all execs...
392 fcntl(con
->http
.fd
, F_SETFD
, fcntl(con
->http
.fd
, F_GETFD
) | FD_CLOEXEC
);
395 * Add the socket to the select() input mask.
398 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
399 "cupsdAcceptClient: Adding fd %d to InputSet...",
401 FD_SET(con
->http
.fd
, InputSet
);
404 * Temporarily suspend accept()'s until we lose a client...
407 if (cupsArrayCount(Clients
) == MaxClients
)
408 cupsdPauseListening();
412 * See if we are connecting on a secure port...
415 if (lis
->encryption
== HTTP_ENCRYPT_ALWAYS
)
418 * https connection; go secure...
421 con
->http
.encryption
= HTTP_ENCRYPT_ALWAYS
;
427 #endif /* HAVE_SSL */
432 * 'cupsdCloseAllClients()' - Close all remote clients immediately.
436 cupsdCloseAllClients(void)
438 cupsd_client_t
*con
; /* Current client */
441 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
443 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
444 cupsdCloseClient(con
);
449 * 'cupsdCloseClient()' - Close a remote client.
452 int /* O - 1 if partial close, 0 if fully closed */
453 cupsdCloseClient(cupsd_client_t
*con
) /* I - Client to close */
455 int partial
; /* Do partial close for SSL? */
457 SSL_CTX
*context
; /* Context for encryption */
458 SSL
*conn
; /* Connection for encryption */
459 unsigned long error
; /* Error code */
460 #elif defined(HAVE_GNUTLS)
461 http_tls_t
*conn
; /* TLS connection information */
462 int error
; /* Error code */
463 gnutls_certificate_server_credentials
*credentials
;
464 /* TLS credentials */
465 # elif defined(HAVE_CDSASSL)
466 http_tls_t
*conn
; /* CDSA connection information */
467 #endif /* HAVE_LIBSSL */
470 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdCloseClient: %d", con
->http
.fd
);
473 * Flush pending writes before closing...
476 httpFlushWrite(HTTP(con
));
482 * Shutdown encryption as needed...
490 conn
= (SSL
*)(con
->http
.tls
);
491 context
= SSL_get_SSL_CTX(conn
);
493 switch (SSL_shutdown(conn
))
496 cupsdLogMessage(CUPSD_LOG_INFO
,
497 "cupsdCloseClient: SSL shutdown successful!");
500 cupsdLogMessage(CUPSD_LOG_ERROR
,
501 "cupsdCloseClient: Fatal error during SSL shutdown!");
503 while ((error
= ERR_get_error()) != 0)
504 cupsdLogMessage(CUPSD_LOG_ERROR
, "cupsdCloseClient: %s",
505 ERR_error_string(error
, NULL
));
509 SSL_CTX_free(context
);
512 # elif defined(HAVE_GNUTLS)
513 conn
= (http_tls_t
*)(con
->http
.tls
);
514 credentials
= (gnutls_certificate_server_credentials
*)(conn
->credentials
);
516 error
= gnutls_bye(conn
->session
, GNUTLS_SHUT_WR
);
519 case GNUTLS_E_SUCCESS
:
520 cupsdLogMessage(CUPSD_LOG_INFO
,
521 "cupsdCloseClient: SSL shutdown successful!");
524 cupsdLogMessage(CUPSD_LOG_ERROR
,
525 "cupsdCloseClient: %s", gnutls_strerror(error
));
529 gnutls_deinit(conn
->session
);
530 gnutls_certificate_free_credentials(*credentials
);
534 # elif defined(HAVE_CDSASSL)
535 conn
= (http_tls_t
*)(con
->http
.tls
);
537 while (SSLClose(conn
->session
) == errSSLWouldBlock
)
540 SSLDisposeContext(conn
->session
);
542 if (conn
->certsArray
)
543 CFRelease(conn
->certsArray
);
546 # endif /* HAVE_LIBSSL */
548 con
->http
.tls
= NULL
;
550 #endif /* HAVE_SSL */
552 if (con
->pipe_pid
!= 0)
555 * Stop any CGI process...
558 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
559 "cupsdCloseClient: %d Killing process ID %d...",
560 con
->http
.fd
, con
->pipe_pid
);
561 cupsdEndProcess(con
->pipe_pid
, 1);
567 if (FD_ISSET(con
->file
, InputSet
))
569 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
570 "cupsdCloseClient: %d Removing fd %d from InputSet...",
571 con
->http
.fd
, con
->file
);
572 FD_CLR(con
->file
, InputSet
);
575 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
576 "cupsdCloseClient: %d Closing data file %d.",
577 con
->http
.fd
, con
->file
);
584 * Close the socket and clear the file from the input set for select()...
587 if (con
->http
.fd
> 0)
592 * Only do a partial close so that the encrypted client gets everything.
595 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
596 "cupsdCloseClient: Removing fd %d from OutputSet...",
598 shutdown(con
->http
.fd
, 0);
599 FD_CLR(con
->http
.fd
, OutputSet
);
604 * Shut the socket down fully...
607 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
608 "cupsdCloseClient: Removing fd %d from InputSet and OutputSet...",
611 FD_CLR(con
->http
.fd
, InputSet
);
612 FD_CLR(con
->http
.fd
, OutputSet
);
623 if (con
->http
.input_set
)
624 free(con
->http
.input_set
);
626 httpClearCookie(HTTP(con
));
628 cupsdClearString(&con
->filename
);
629 cupsdClearString(&con
->command
);
630 cupsdClearString(&con
->options
);
634 ippDelete(con
->request
);
640 ippDelete(con
->response
);
641 con
->response
= NULL
;
646 cupsLangFree(con
->language
);
647 con
->language
= NULL
;
651 * Re-enable new client connections if we are going back under the
655 if (cupsArrayCount(Clients
) == MaxClients
)
656 cupsdResumeListening();
659 * Compact the list of clients as necessary...
662 cupsArrayRemove(Clients
, con
);
672 * 'cupsdReadClient()' - Read data from a client.
675 int /* O - 1 on success, 0 on error */
676 cupsdReadClient(cupsd_client_t
*con
) /* I - Client to read from */
678 char line
[32768], /* Line from client... */
679 operation
[64], /* Operation code from socket */
680 version
[64], /* HTTP version number string */
681 locale
[64], /* Locale */
682 *ptr
; /* Pointer into strings */
683 int major
, minor
; /* HTTP version numbers */
684 http_status_t status
; /* Transfer status */
685 ipp_state_t ipp_state
; /* State of IPP transfer */
686 int bytes
; /* Number of bytes to POST */
687 char *filename
; /* Name of file for GET/HEAD */
688 char buf
[1024]; /* Buffer for real filename */
689 struct stat filestats
; /* File information */
690 mime_type_t
*type
; /* MIME type of file */
691 cupsd_printer_t
*p
; /* Printer */
692 static unsigned request_id
= 0; /* Request ID for temp files */
695 status
= HTTP_CONTINUE
;
697 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
698 "cupsdReadClient: %d, used=%d, file=%d state=%d",
699 con
->http
.fd
, con
->http
.used
, con
->file
, con
->http
.state
);
703 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdReadClient: http error seen...");
704 return (cupsdCloseClient(con
));
711 * Automatically check for a SSL/TLS handshake...
716 if (recv(con
->http
.fd
, buf
, 1, MSG_PEEK
) == 1 &&
717 (!buf
[0] || !strchr("DGHOPT", buf
[0])))
720 * Encrypt this connection...
723 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
724 "cupsdReadClient: Saw first byte %02X, auto-negotiating SSL/TLS session...",
731 #endif /* HAVE_SSL */
733 switch (con
->http
.state
)
737 * See if we've received a request line...
740 if (httpGets(line
, sizeof(line
) - 1, HTTP(con
)) == NULL
)
742 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
743 "cupsdReadClient: httpGets returned EOF...");
744 return (cupsdCloseClient(con
));
748 * Ignore blank request lines...
755 * Clear other state variables...
758 httpClearFields(HTTP(con
));
760 con
->http
.activity
= time(NULL
);
761 con
->http
.version
= HTTP_1_0
;
762 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
763 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
764 con
->http
.data_remaining
= 0;
765 con
->http
._data_remaining
= 0;
766 con
->operation
= HTTP_WAITING
;
771 con
->username
[0] = '\0';
772 con
->password
[0] = '\0';
775 cupsdClearString(&con
->command
);
776 cupsdClearString(&con
->options
);
778 if (con
->language
!= NULL
)
780 cupsLangFree(con
->language
);
781 con
->language
= NULL
;
785 * Grab the request line...
788 switch (sscanf(line
, "%63s%1023s%63s", operation
, con
->uri
, version
))
791 cupsdLogMessage(CUPSD_LOG_ERROR
,
792 "Bad request line \"%s\" from %s!", line
,
794 cupsdSendError(con
, HTTP_BAD_REQUEST
);
795 return (cupsdCloseClient(con
));
797 con
->http
.version
= HTTP_0_9
;
800 if (sscanf(version
, "HTTP/%d.%d", &major
, &minor
) != 2)
802 cupsdLogMessage(CUPSD_LOG_ERROR
,
803 "Bad request line \"%s\" from %s!", line
,
805 cupsdSendError(con
, HTTP_BAD_REQUEST
);
806 return (cupsdCloseClient(con
));
811 con
->http
.version
= (http_version_t
)(major
* 100 + minor
);
812 if (con
->http
.version
== HTTP_1_1
&& KeepAlive
)
813 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
815 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
819 cupsdSendError(con
, HTTP_NOT_SUPPORTED
);
820 return (cupsdCloseClient(con
));
826 * Handle full URLs in the request line...
829 if (strcmp(con
->uri
, "*"))
831 char method
[HTTP_MAX_URI
], /* Method/scheme */
832 userpass
[HTTP_MAX_URI
], /* Username:password */
833 hostname
[HTTP_MAX_URI
], /* Hostname */
834 resource
[HTTP_MAX_URI
]; /* Resource path */
835 int port
; /* Port number */
839 * Separate the URI into its components...
842 httpSeparateURI(HTTP_URI_CODING_MOST
, con
->uri
,
843 method
, sizeof(method
),
844 userpass
, sizeof(userpass
),
845 hostname
, sizeof(hostname
), &port
,
846 resource
, sizeof(resource
));
849 * Only allow URIs with the servername, localhost, or an IP
853 if (strcmp(method
, "file") &&
854 strcasecmp(hostname
, ServerName
) &&
855 strcasecmp(hostname
, "localhost") &&
856 !isdigit(hostname
[0]))
859 * Nope, we don't do proxies...
862 cupsdLogMessage(CUPSD_LOG_ERROR
, "Bad URI \"%s\" in request!",
864 cupsdSendError(con
, HTTP_METHOD_NOT_ALLOWED
);
865 return (cupsdCloseClient(con
));
869 * Copy the resource portion back into the URI; both resource and
870 * con->uri are HTTP_MAX_URI bytes in size...
873 strcpy(con
->uri
, resource
);
877 * Process the request...
880 if (!strcmp(operation
, "GET"))
881 con
->http
.state
= HTTP_GET
;
882 else if (!strcmp(operation
, "PUT"))
883 con
->http
.state
= HTTP_PUT
;
884 else if (!strcmp(operation
, "POST"))
885 con
->http
.state
= HTTP_POST
;
886 else if (!strcmp(operation
, "DELETE"))
887 con
->http
.state
= HTTP_DELETE
;
888 else if (!strcmp(operation
, "TRACE"))
889 con
->http
.state
= HTTP_TRACE
;
890 else if (!strcmp(operation
, "OPTIONS"))
891 con
->http
.state
= HTTP_OPTIONS
;
892 else if (!strcmp(operation
, "HEAD"))
893 con
->http
.state
= HTTP_HEAD
;
896 cupsdLogMessage(CUPSD_LOG_ERROR
, "Bad operation \"%s\"!", operation
);
897 cupsdSendError(con
, HTTP_BAD_REQUEST
);
898 return (cupsdCloseClient(con
));
901 con
->start
= time(NULL
);
902 con
->operation
= con
->http
.state
;
904 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdReadClient: %d %s %s HTTP/%d.%d",
905 con
->http
.fd
, operation
, con
->uri
,
906 con
->http
.version
/ 100, con
->http
.version
% 100);
908 con
->http
.status
= HTTP_OK
;
918 * Parse incoming parameters until the status changes...
921 status
= httpUpdate(HTTP(con
));
923 if (status
!= HTTP_OK
&& status
!= HTTP_CONTINUE
)
925 cupsdSendError(con
, HTTP_BAD_REQUEST
);
926 return (cupsdCloseClient(con
));
931 break; /* Anti-compiler-warning-code */
935 * Handle new transfers...
938 if (status
== HTTP_OK
)
940 if (con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
][0])
943 * Figure out the locale from the Accept-Language and Content-Type
947 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ',')) != NULL
)
950 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ';')) != NULL
)
953 if ((ptr
= strstr(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
], "charset=")) != NULL
)
956 * Combine language and charset, and trim any extra params in the
960 snprintf(locale
, sizeof(locale
), "%s.%s",
961 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ptr
+ 8);
963 if ((ptr
= strchr(locale
, ',')) != NULL
)
967 snprintf(locale
, sizeof(locale
), "%s.%s",
968 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], DefaultCharset
);
970 cupsdLogMessage(CUPSD_LOG_DEBUG
,
971 "cupsdReadClient: %d Browser asked for language \"%s\"...",
972 con
->http
.fd
, locale
);
974 con
->language
= cupsLangGet(locale
);
977 con
->language
= cupsLangGet(DefaultLocale
);
981 if (!strncmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Keep-Alive", 10) &&
983 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
985 if (!con
->http
.fields
[HTTP_FIELD_HOST
][0] &&
986 con
->http
.version
>= HTTP_1_1
)
989 * HTTP/1.1 and higher require the "Host:" field...
992 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
))
993 return (cupsdCloseClient(con
));
995 else if (con
->operation
== HTTP_OPTIONS
)
998 * Do OPTIONS command...
1001 if (con
->best
&& con
->best
->type
!= AUTH_NONE
)
1003 if (!cupsdSendHeader(con
, HTTP_UNAUTHORIZED
, NULL
))
1004 return (cupsdCloseClient(con
));
1007 if (!strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") &&
1008 con
->http
.tls
== NULL
)
1012 * Do encryption stuff...
1015 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
))
1016 return (cupsdCloseClient(con
));
1018 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1019 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1020 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1021 httpPrintf(HTTP(con
), "\r\n");
1023 encrypt_client(con
);
1025 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
))
1026 return (cupsdCloseClient(con
));
1027 #endif /* HAVE_SSL */
1030 if (!cupsdSendHeader(con
, HTTP_OK
, NULL
))
1031 return (cupsdCloseClient(con
));
1033 httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n");
1034 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1035 httpPrintf(HTTP(con
), "\r\n");
1037 else if (!is_path_absolute(con
->uri
))
1040 * Protect against malicious users!
1043 if (!cupsdSendError(con
, HTTP_FORBIDDEN
))
1044 return (cupsdCloseClient(con
));
1048 if (!strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") &&
1049 con
->http
.tls
== NULL
)
1053 * Do encryption stuff...
1056 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
))
1057 return (cupsdCloseClient(con
));
1059 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1060 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1061 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1062 httpPrintf(HTTP(con
), "\r\n");
1064 encrypt_client(con
);
1066 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
))
1067 return (cupsdCloseClient(con
));
1068 #endif /* HAVE_SSL */
1071 if ((status
= cupsdIsAuthorized(con
, NULL
)) != HTTP_OK
)
1073 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1074 "cupsdReadClient: Unauthorized request for %s...\n",
1076 cupsdSendError(con
, status
);
1077 return (cupsdCloseClient(con
));
1080 if (con
->http
.expect
&&
1081 (con
->operation
== HTTP_POST
|| con
->operation
== HTTP_PUT
))
1083 if (con
->http
.expect
== HTTP_CONTINUE
)
1086 * Send 100-continue header...
1089 if (!cupsdSendHeader(con
, HTTP_CONTINUE
, NULL
))
1090 return (cupsdCloseClient(con
));
1095 * Send 417-expectation-failed header...
1098 if (!cupsdSendHeader(con
, HTTP_EXPECTATION_FAILED
, NULL
))
1099 return (cupsdCloseClient(con
));
1101 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1102 httpPrintf(HTTP(con
), "\r\n");
1106 switch (con
->http
.state
)
1108 case HTTP_GET_SEND
:
1109 if (!strncmp(con
->uri
, "/printers/", 10) &&
1110 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1113 * Send PPD file - get the real printer name since printer
1114 * names are not case sensitive but filenames can be...
1117 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1119 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1120 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1123 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
1124 return (cupsdCloseClient(con
));
1130 if ((!strncmp(con
->uri
, "/admin", 6) &&
1131 strncmp(con
->uri
, "/admin/conf/", 12) &&
1132 strncmp(con
->uri
, "/admin/log/", 11)) ||
1133 !strncmp(con
->uri
, "/printers", 9) ||
1134 !strncmp(con
->uri
, "/classes", 8) ||
1135 !strncmp(con
->uri
, "/help", 5) ||
1136 !strncmp(con
->uri
, "/jobs", 5))
1139 * Send CGI output...
1142 if (!strncmp(con
->uri
, "/admin", 6))
1144 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1147 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1149 else if (!strncmp(con
->uri
, "/printers", 9))
1151 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1154 if (con
->uri
[9] && con
->uri
[10])
1155 cupsdSetString(&con
->options
, con
->uri
+ 9);
1157 cupsdSetString(&con
->options
, NULL
);
1159 else if (!strncmp(con
->uri
, "/classes", 8))
1161 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1164 if (con
->uri
[8] && con
->uri
[9])
1165 cupsdSetString(&con
->options
, con
->uri
+ 8);
1167 cupsdSetString(&con
->options
, NULL
);
1169 else if (!strncmp(con
->uri
, "/jobs", 5))
1171 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1174 if (con
->uri
[5] && con
->uri
[6])
1175 cupsdSetString(&con
->options
, con
->uri
+ 5);
1177 cupsdSetString(&con
->options
, NULL
);
1181 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1184 if (con
->uri
[5] && con
->uri
[6])
1185 cupsdSetString(&con
->options
, con
->uri
+ 5);
1187 cupsdSetString(&con
->options
, NULL
);
1190 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1192 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
1193 return (cupsdCloseClient(con
));
1196 cupsdLogRequest(con
, HTTP_OK
);
1198 if (con
->http
.version
<= HTTP_1_0
)
1199 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1201 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1202 (strchr(con
->uri
+ 12, '/') ||
1203 strlen(con
->uri
) == 12)) ||
1204 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1205 (strchr(con
->uri
+ 11, '/') ||
1206 strlen(con
->uri
) == 11)))
1209 * GET can only be done to configuration files under
1213 if (!cupsdSendError(con
, HTTP_FORBIDDEN
))
1214 return (cupsdCloseClient(con
));
1224 if ((filename
= get_file(con
, &filestats
, buf
,
1225 sizeof(buf
))) == NULL
)
1227 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
1228 return (cupsdCloseClient(con
));
1233 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1235 if (is_cgi(con
, filename
, &filestats
, type
))
1238 * Note: con->command and con->options were set by
1242 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1244 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
1245 return (cupsdCloseClient(con
));
1248 cupsdLogRequest(con
, HTTP_OK
);
1250 if (con
->http
.version
<= HTTP_1_0
)
1251 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1255 if (!check_if_modified(con
, &filestats
))
1257 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
))
1258 return (cupsdCloseClient(con
));
1263 strcpy(line
, "text/plain");
1265 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1267 if (!send_file(con
, HTTP_OK
, filename
, line
, &filestats
))
1268 return (cupsdCloseClient(con
));
1273 case HTTP_POST_RECV
:
1275 * See if the POST request includes a Content-Length field, and if
1276 * so check the length against any limits that are set...
1279 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "POST %s", con
->uri
);
1280 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "CONTENT_TYPE = %s",
1281 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
1283 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1284 MaxRequestSize
> 0 &&
1285 con
->http
.data_remaining
> MaxRequestSize
)
1288 * Request too large...
1291 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1292 return (cupsdCloseClient(con
));
1296 else if (con
->http
.data_remaining
< 0)
1299 * Negative content lengths are invalid!
1302 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
))
1303 return (cupsdCloseClient(con
));
1309 * See what kind of POST request this is; for IPP requests the
1310 * content-type field will be "application/ipp"...
1313 if (!strcmp(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
],
1315 con
->request
= ippNew();
1316 else if ((!strncmp(con
->uri
, "/admin", 6) &&
1317 strncmp(con
->uri
, "/admin/conf/", 12) &&
1318 strncmp(con
->uri
, "/admin/log/", 11)) ||
1319 !strncmp(con
->uri
, "/printers", 9) ||
1320 !strncmp(con
->uri
, "/classes", 8) ||
1321 !strncmp(con
->uri
, "/help", 5) ||
1322 !strncmp(con
->uri
, "/jobs", 5))
1328 if (!strncmp(con
->uri
, "/admin", 6))
1330 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1333 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1335 else if (!strncmp(con
->uri
, "/printers", 9))
1337 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1340 if (con
->uri
[9] && con
->uri
[10])
1341 cupsdSetString(&con
->options
, con
->uri
+ 9);
1343 cupsdSetString(&con
->options
, NULL
);
1345 else if (!strncmp(con
->uri
, "/classes", 8))
1347 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1350 if (con
->uri
[8] && con
->uri
[9])
1351 cupsdSetString(&con
->options
, con
->uri
+ 8);
1353 cupsdSetString(&con
->options
, NULL
);
1355 else if (!strncmp(con
->uri
, "/jobs", 5))
1357 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1360 if (con
->uri
[5] && con
->uri
[6])
1361 cupsdSetString(&con
->options
, con
->uri
+ 5);
1363 cupsdSetString(&con
->options
, NULL
);
1367 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1370 if (con
->uri
[5] && con
->uri
[6])
1371 cupsdSetString(&con
->options
, con
->uri
+ 5);
1373 cupsdSetString(&con
->options
, NULL
);
1376 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1377 "cupsdReadClient: %d command=\"%s\", "
1379 con
->http
.fd
, con
->command
, con
->options
);
1381 if (con
->http
.version
<= HTTP_1_0
)
1382 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1390 if ((filename
= get_file(con
, &filestats
, buf
,
1391 sizeof(buf
))) == NULL
)
1393 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
1394 return (cupsdCloseClient(con
));
1399 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1401 if (!is_cgi(con
, filename
, &filestats
, type
))
1404 * Only POST to CGI's...
1407 if (!cupsdSendError(con
, HTTP_UNAUTHORIZED
))
1408 return (cupsdCloseClient(con
));
1413 case HTTP_PUT_RECV
:
1415 * Validate the resource name...
1418 if (strncmp(con
->uri
, "/admin/conf/", 12) ||
1419 strchr(con
->uri
+ 12, '/') ||
1420 strlen(con
->uri
) == 12)
1423 * PUT can only be done to configuration files under
1427 if (!cupsdSendError(con
, HTTP_FORBIDDEN
))
1428 return (cupsdCloseClient(con
));
1434 * See if the PUT request includes a Content-Length field, and if
1435 * so check the length against any limits that are set...
1438 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "PUT %s", con
->uri
);
1439 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "CONTENT_TYPE = %s",
1440 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
1442 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1443 MaxRequestSize
> 0 &&
1444 con
->http
.data_remaining
> MaxRequestSize
)
1447 * Request too large...
1450 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1451 return (cupsdCloseClient(con
));
1455 else if (con
->http
.data_remaining
< 0)
1458 * Negative content lengths are invalid!
1461 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
))
1462 return (cupsdCloseClient(con
));
1468 * Open a temporary file to hold the request...
1471 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
1473 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1475 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1476 "cupsdReadClient: %d REQUEST %s=%d", con
->http
.fd
,
1477 con
->filename
, con
->file
);
1481 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1482 return (cupsdCloseClient(con
));
1485 fchmod(con
->file
, 0640);
1486 fchown(con
->file
, RunUser
, Group
);
1487 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1492 cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
);
1493 return (cupsdCloseClient(con
));
1496 if (!strncmp(con
->uri
, "/printers/", 10) &&
1497 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1500 * Send PPD file - get the real printer name since printer
1501 * names are not case sensitive but filenames can be...
1504 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1506 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1507 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1510 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
1511 return (cupsdCloseClient(con
));
1517 if ((!strncmp(con
->uri
, "/admin", 6) &&
1518 strncmp(con
->uri
, "/admin/conf/", 12) &&
1519 strncmp(con
->uri
, "/admin/log/", 11)) ||
1520 !strncmp(con
->uri
, "/printers", 9) ||
1521 !strncmp(con
->uri
, "/classes", 8) ||
1522 !strncmp(con
->uri
, "/help", 5) ||
1523 !strncmp(con
->uri
, "/jobs", 5))
1529 if (!cupsdSendHeader(con
, HTTP_OK
, "text/html"))
1530 return (cupsdCloseClient(con
));
1532 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1533 return (cupsdCloseClient(con
));
1535 cupsdLogRequest(con
, HTTP_OK
);
1537 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1538 (strchr(con
->uri
+ 12, '/') ||
1539 strlen(con
->uri
) == 12)) ||
1540 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1541 (strchr(con
->uri
+ 11, '/') ||
1542 strlen(con
->uri
) == 11)))
1545 * HEAD can only be done to configuration files under
1549 if (!cupsdSendError(con
, HTTP_FORBIDDEN
))
1550 return (cupsdCloseClient(con
));
1554 else if ((filename
= get_file(con
, &filestats
, buf
,
1555 sizeof(buf
))) == NULL
)
1557 if (!cupsdSendHeader(con
, HTTP_NOT_FOUND
, "text/html"))
1558 return (cupsdCloseClient(con
));
1560 cupsdLogRequest(con
, HTTP_NOT_FOUND
);
1562 else if (!check_if_modified(con
, &filestats
))
1564 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
))
1565 return (cupsdCloseClient(con
));
1567 cupsdLogRequest(con
, HTTP_NOT_MODIFIED
);
1575 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1577 strcpy(line
, "text/plain");
1579 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1581 if (!cupsdSendHeader(con
, HTTP_OK
, line
))
1582 return (cupsdCloseClient(con
));
1584 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
1585 httpGetDateString(filestats
.st_mtime
)) < 0)
1586 return (cupsdCloseClient(con
));
1588 if (httpPrintf(HTTP(con
), "Content-Length: %lu\r\n",
1589 (unsigned long)filestats
.st_size
) < 0)
1590 return (cupsdCloseClient(con
));
1592 cupsdLogRequest(con
, HTTP_OK
);
1595 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1596 return (cupsdCloseClient(con
));
1598 con
->http
.state
= HTTP_WAITING
;
1602 break; /* Anti-compiler-warning-code */
1608 * Handle any incoming data...
1611 switch (con
->http
.state
)
1613 case HTTP_PUT_RECV
:
1614 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1615 "cupsdReadClient: %d con->data_encoding=HTTP_ENCODE_%s, "
1616 "con->data_remaining=" CUPS_LLFMT
", con->file=%d",
1618 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
?
1619 "CHUNKED" : "LENGTH",
1620 CUPS_LLCAST con
->http
.data_remaining
, con
->file
);
1622 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
1623 return (cupsdCloseClient(con
));
1626 con
->bytes
+= bytes
;
1628 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1629 "cupsdReadClient: %d writing %d bytes to %d",
1630 con
->http
.fd
, bytes
, con
->file
);
1632 if (write(con
->file
, line
, bytes
) < bytes
)
1634 cupsdLogMessage(CUPSD_LOG_ERROR
,
1635 "cupsdReadClient: Unable to write %d bytes to %s: %s",
1636 bytes
, con
->filename
, strerror(errno
));
1638 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1639 "cupsdReadClient: Closing data file %d...",
1644 unlink(con
->filename
);
1645 cupsdClearString(&con
->filename
);
1647 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1648 return (cupsdCloseClient(con
));
1652 if (con
->http
.state
== HTTP_WAITING
)
1655 * End of file, see how big it is...
1658 fstat(con
->file
, &filestats
);
1660 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1661 "cupsdReadClient: %d Closing data file %d, size="
1663 con
->http
.fd
, con
->file
,
1664 CUPS_LLCAST filestats
.st_size
);
1669 if (filestats
.st_size
> MaxRequestSize
&&
1673 * Request is too big; remove it and send an error...
1676 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1677 "cupsdReadClient: %d Removing temp file %s",
1678 con
->http
.fd
, con
->filename
);
1679 unlink(con
->filename
);
1680 cupsdClearString(&con
->filename
);
1682 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1683 return (cupsdCloseClient(con
));
1687 * Install the configuration file...
1690 status
= install_conf_file(con
);
1693 * Return the status to the client...
1696 if (!cupsdSendError(con
, status
))
1697 return (cupsdCloseClient(con
));
1701 case HTTP_POST_RECV
:
1702 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1703 "cupsdReadClient: %d con->data_encoding=HTTP_ENCODE_"
1704 "%s, con->data_remaining=" CUPS_LLFMT
", con->file=%d",
1706 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
?
1707 "CHUNKED" : "LENGTH",
1708 CUPS_LLCAST con
->http
.data_remaining
, con
->file
);
1710 if (con
->request
!= NULL
)
1713 * Grab any request data from the connection...
1716 if ((ipp_state
= ippRead(&(con
->http
), con
->request
)) == IPP_ERROR
)
1718 cupsdLogMessage(CUPSD_LOG_ERROR
,
1719 "cupsdReadClient: %d IPP Read Error!",
1722 cupsdSendError(con
, HTTP_BAD_REQUEST
);
1723 return (cupsdCloseClient(con
));
1725 else if (ipp_state
!= IPP_DATA
)
1727 if (con
->http
.state
== HTTP_POST_SEND
)
1729 cupsdSendError(con
, HTTP_BAD_REQUEST
);
1730 return (cupsdCloseClient(con
));
1736 con
->bytes
+= ippLength(con
->request
);
1739 if (con
->file
< 0 && con
->http
.state
!= HTTP_POST_SEND
)
1742 * Create a file as needed for the request data...
1745 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
, request_id
++);
1746 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1748 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdReadClient: %d REQUEST %s=%d", con
->http
.fd
,
1749 con
->filename
, con
->file
);
1753 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1754 return (cupsdCloseClient(con
));
1757 fchmod(con
->file
, 0640);
1758 fchown(con
->file
, RunUser
, Group
);
1759 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1762 if (con
->http
.state
!= HTTP_POST_SEND
)
1764 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
1765 return (cupsdCloseClient(con
));
1768 con
->bytes
+= bytes
;
1770 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1771 "cupsdReadClient: %d writing %d bytes to %d",
1772 con
->http
.fd
, bytes
, con
->file
);
1774 if (write(con
->file
, line
, bytes
) < bytes
)
1776 cupsdLogMessage(CUPSD_LOG_ERROR
,
1777 "cupsdReadClient: Unable to write %d bytes to %s: %s",
1778 bytes
, con
->filename
, strerror(errno
));
1780 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1781 "cupsdReadClient: Closing file %d...",
1786 unlink(con
->filename
);
1787 cupsdClearString(&con
->filename
);
1789 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1790 return (cupsdCloseClient(con
));
1793 else if (con
->http
.state
== HTTP_POST_RECV
)
1794 return (1); /* ??? */
1795 else if (con
->http
.state
!= HTTP_POST_SEND
)
1796 return (cupsdCloseClient(con
));
1799 if (con
->http
.state
== HTTP_POST_SEND
)
1803 fstat(con
->file
, &filestats
);
1805 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1806 "cupsdReadClient: %d Closing data file %d, "
1807 "size=" CUPS_LLFMT
".",
1808 con
->http
.fd
, con
->file
,
1809 CUPS_LLCAST filestats
.st_size
);
1814 if (filestats
.st_size
> MaxRequestSize
&&
1818 * Request is too big; remove it and send an error...
1821 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1822 "cupsdReadClient: %d Removing temp file %s",
1823 con
->http
.fd
, con
->filename
);
1824 unlink(con
->filename
);
1825 cupsdClearString(&con
->filename
);
1830 * Delete any IPP request data...
1833 ippDelete(con
->request
);
1834 con
->request
= NULL
;
1837 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1838 return (cupsdCloseClient(con
));
1843 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1845 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
1846 return (cupsdCloseClient(con
));
1849 cupsdLogRequest(con
, HTTP_OK
);
1854 return (cupsdProcessIPPRequest(con
));
1859 break; /* Anti-compiler-warning-code */
1862 if (!con
->http
.keep_alive
&& con
->http
.state
== HTTP_WAITING
)
1863 return (cupsdCloseClient(con
));
1870 * 'cupsdSendCommand()' - Send output from a command via HTTP.
1873 int /* O - 1 on success, 0 on failure */
1875 cupsd_client_t
*con
, /* I - Client connection */
1876 char *command
, /* I - Command to run */
1877 char *options
, /* I - Command-line options */
1878 int root
) /* I - Run as root? */
1880 int fd
; /* Standard input file descriptor */
1884 fd
= open(con
->filename
, O_RDONLY
);
1886 fd
= open("/dev/null", O_RDONLY
);
1890 cupsdLogMessage(CUPSD_LOG_ERROR
,
1891 "cupsdSendCommand: %d Unable to open \"%s\" for reading: %s",
1892 con
->http
.fd
, con
->filename
? con
->filename
: "/dev/null",
1897 fcntl(fd
, F_SETFD
, fcntl(fd
, F_GETFD
) | FD_CLOEXEC
);
1899 con
->pipe_pid
= pipe_command(con
, fd
, &(con
->file
), command
, options
, root
);
1903 cupsdLogMessage(CUPSD_LOG_INFO
, "Started \"%s\" (pid=%d)", command
,
1906 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendCommand: %d file=%d",
1907 con
->http
.fd
, con
->file
);
1909 if (con
->pipe_pid
== 0)
1912 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1914 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1915 "cupsdSendCommand: Adding fd %d to InputSet...", con
->file
);
1916 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1917 "cupsdSendCommand: Adding fd %d to OutputSet...",
1920 FD_SET(con
->file
, InputSet
);
1921 FD_SET(con
->http
.fd
, OutputSet
);
1923 con
->sent_header
= 0;
1924 con
->file_ready
= 0;
1925 con
->got_fields
= 0;
1933 * 'cupsdSendError()' - Send an error message via HTTP.
1936 int /* O - 1 if successful, 0 otherwise */
1937 cupsdSendError(cupsd_client_t
*con
, /* I - Connection */
1938 http_status_t code
) /* I - Error code */
1942 * Force client to upgrade for authentication if that is how the
1943 * server is configured...
1946 if (code
== HTTP_UNAUTHORIZED
&&
1947 DefaultEncryption
== HTTP_ENCRYPT_REQUIRED
&&
1948 strcasecmp(con
->http
.hostname
, "localhost") &&
1951 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1952 "cupsdSendError: Encryption before authentication!");
1953 code
= HTTP_UPGRADE_REQUIRED
;
1955 #endif /* HAVE_SSL */
1958 * Put the request in the access_log file...
1961 cupsdLogRequest(con
, code
);
1963 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendError: %d code=%d (%s)",
1964 con
->http
.fd
, code
, httpStatus(code
));
1967 * To work around bugs in some proxies, don't use Keep-Alive for some
1971 if (code
>= HTTP_BAD_REQUEST
)
1972 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1975 * Send an error message back to the client. If the error code is a
1976 * 400 or 500 series, make sure the message contains some text, too!
1979 if (!cupsdSendHeader(con
, code
, NULL
))
1983 if (code
== HTTP_UPGRADE_REQUIRED
)
1984 if (httpPrintf(HTTP(con
), "Connection: Upgrade\r\n") < 0)
1987 if (httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n") < 0)
1989 #endif /* HAVE_SSL */
1991 if ((con
->http
.version
>= HTTP_1_1
&& !con
->http
.keep_alive
) ||
1992 (code
>= HTTP_BAD_REQUEST
&& code
!= HTTP_UPGRADE_REQUIRED
))
1994 if (httpPrintf(HTTP(con
), "Connection: close\r\n") < 0)
1998 if (code
>= HTTP_BAD_REQUEST
)
2001 * Send a human-readable error message.
2004 char message
[4096], /* Message for user */
2005 urltext
[1024], /* URL redirection text */
2006 redirect
[1024]; /* Redirection link */
2007 const char *text
; /* Status-specific text */
2012 if (code
== HTTP_UNAUTHORIZED
)
2013 text
= _cupsLangString(con
->language
,
2014 _("Enter your username and password or the "
2015 "root username and password to access this "
2017 else if (code
== HTTP_UPGRADE_REQUIRED
)
2021 snprintf(urltext
, sizeof(urltext
),
2022 _cupsLangString(con
->language
,
2023 _("You must access this page using the URL "
2024 "<A HREF=\"https://%s:%d%s\">"
2025 "https://%s:%d%s</A>.")),
2026 con
->servername
, con
->serverport
, con
->uri
,
2027 con
->servername
, con
->serverport
, con
->uri
);
2029 snprintf(redirect
, sizeof(redirect
),
2030 "<META HTTP-EQUIV=\"Refresh\" CONTENT=\"3;https://%s:%d%s\">\n",
2031 con
->servername
, con
->serverport
, con
->uri
);
2036 snprintf(message
, sizeof(message
),
2037 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" "
2038 "\"http://www.w3.org/TR/REC-html40/loose.dtd\">\n"
2041 "\t<META HTTP-EQUIV=\"Content-Type\" "
2042 "CONTENT=\"text/html; charset=utf-8\">\n"
2043 "\t<TITLE>%d %s</TITLE>\n"
2044 "\t<LINK REL=\"STYLESHEET\" TYPE=\"text/css\" "
2045 "HREF=\"/cups.css\">\n"
2053 code
, httpStatus(code
), redirect
, code
, httpStatus(code
), text
);
2055 if (httpPrintf(HTTP(con
), "Content-Type: text/html; charset=utf-8\r\n") < 0)
2057 if (httpPrintf(HTTP(con
), "Content-Length: %d\r\n",
2058 (int)strlen(message
)) < 0)
2060 if (httpPrintf(HTTP(con
), "\r\n") < 0)
2062 if (httpPrintf(HTTP(con
), "%s", message
) < 0)
2065 else if (httpPrintf(HTTP(con
), "\r\n") < 0)
2068 con
->http
.state
= HTTP_WAITING
;
2075 * 'cupsdSendHeader()' - Send an HTTP request.
2078 int /* O - 1 on success, 0 on failure */
2079 cupsdSendHeader(cupsd_client_t
*con
, /* I - Client to send to */
2080 http_status_t code
, /* I - HTTP status code */
2081 char *type
) /* I - MIME type of document */
2084 * Send the HTTP status header...
2087 if (httpPrintf(HTTP(con
), "HTTP/%d.%d %d %s\r\n", con
->http
.version
/ 100,
2088 con
->http
.version
% 100, code
, httpStatus(code
)) < 0)
2091 if (code
== HTTP_CONTINUE
)
2094 * 100-continue doesn't send any headers...
2097 if (httpPrintf(HTTP(con
), "\r\n") < 0)
2103 if (httpPrintf(HTTP(con
), "Date: %s\r\n", httpGetDateString(time(NULL
))) < 0)
2106 if (httpPrintf(HTTP(con
), "Server: %s\r\n", ServerHeader
) < 0)
2108 if (con
->http
.keep_alive
&& con
->http
.version
>= HTTP_1_0
)
2110 if (httpPrintf(HTTP(con
), "Connection: Keep-Alive\r\n") < 0)
2112 if (httpPrintf(HTTP(con
), "Keep-Alive: timeout=%d\r\n",
2113 KeepAliveTimeout
) < 0)
2116 if (code
== HTTP_METHOD_NOT_ALLOWED
)
2117 if (httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST\r\n") < 0)
2120 if (code
== HTTP_UNAUTHORIZED
)
2122 int auth_type
; /* Authentication type */
2125 if (!con
->best
|| con
->best
->type
== AUTH_NONE
)
2126 auth_type
= DefaultAuthType
;
2128 auth_type
= con
->best
->type
;
2130 if (auth_type
!= AUTH_DIGEST
)
2132 if (httpPrintf(HTTP(con
),
2133 "WWW-Authenticate: Basic realm=\"CUPS\"\r\n") < 0)
2138 if (httpPrintf(HTTP(con
),
2139 "WWW-Authenticate: Digest realm=\"CUPS\", nonce=\"%s\"\r\n",
2140 con
->http
.hostname
) < 0)
2145 if (con
->language
&& strcmp(con
->language
->language
, "C"))
2147 if (httpPrintf(HTTP(con
), "Content-Language: %s\r\n",
2148 con
->language
->language
) < 0)
2154 if (!strcmp(type
, "text/html"))
2156 if (httpPrintf(HTTP(con
),
2157 "Content-Type: text/html; charset=utf-8\r\n") < 0)
2160 else if (httpPrintf(HTTP(con
), "Content-Type: %s\r\n", type
) < 0)
2169 * 'cupsdUpdateCGI()' - Read status messages from CGI scripts and programs.
2173 cupsdUpdateCGI(void)
2175 char *ptr
, /* Pointer to end of line in buffer */
2176 message
[1024]; /* Pointer to message text */
2177 int loglevel
; /* Log level for message */
2180 while ((ptr
= cupsdStatBufUpdate(CGIStatusBuffer
, &loglevel
,
2181 message
, sizeof(message
))) != NULL
)
2182 if (!strchr(CGIStatusBuffer
->buffer
, '\n'))
2185 if (ptr
== NULL
&& errno
)
2188 * Fatal error on pipe - should never happen!
2191 cupsdLogMessage(CUPSD_LOG_CRIT
,
2192 "cupsdUpdateCGI: error reading from CGI error pipe - %s",
2199 * 'cupsdWriteClient()' - Write data to a client as needed.
2202 int /* O - 1 if success, 0 if fail */
2203 cupsdWriteClient(cupsd_client_t
*con
) /* I - Client connection */
2205 int bytes
; /* Number of bytes written */
2206 char buf
[16385]; /* Data buffer */
2207 char *bufptr
; /* Pointer into buffer */
2208 ipp_state_t ipp_state
; /* IPP state value */
2212 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2213 "cupsdWriteClient(con=%p) %d response=%p, file=%d "
2214 "pipe_pid=%d state=%d",
2215 con
, con
->http
.fd
, con
->response
, con
->file
, con
->pipe_pid
,
2219 if (con
->http
.state
!= HTTP_GET_SEND
&&
2220 con
->http
.state
!= HTTP_POST_SEND
)
2223 if (con
->response
!= NULL
)
2225 ipp_state
= ippWrite(&(con
->http
), con
->response
);
2226 bytes
= ipp_state
!= IPP_ERROR
&& ipp_state
!= IPP_DATA
;
2228 else if ((bytes
= read(con
->file
, buf
, sizeof(buf
) - 1)) > 0)
2230 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2231 "cupsdWriteClient: Read %d bytes from file %d...",
2234 if (con
->pipe_pid
&& !con
->got_fields
)
2237 * Inspect the data for Content-Type and other fields.
2242 for (bufptr
= buf
; !con
->got_fields
&& *bufptr
; bufptr
++)
2243 if (*bufptr
== '\n')
2246 * Send line to client...
2249 if (bufptr
> buf
&& bufptr
[-1] == '\r')
2253 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "Script header: %s", buf
);
2255 if (!con
->sent_header
)
2258 * Handle redirection and CGI status codes...
2261 if (!strncasecmp(buf
, "Location:", 9))
2263 cupsdSendHeader(con
, HTTP_SEE_OTHER
, NULL
);
2264 if (httpPrintf(HTTP(con
), "Content-Length: 0\r\n") < 0)
2267 else if (!strncasecmp(buf
, "Status:", 7))
2268 cupsdSendError(con
, atoi(buf
+ 7));
2271 cupsdSendHeader(con
, HTTP_OK
, NULL
);
2273 if (con
->http
.version
== HTTP_1_1
)
2275 con
->http
.data_encoding
= HTTP_ENCODE_CHUNKED
;
2277 if (httpPrintf(HTTP(con
), "Transfer-Encoding: chunked\r\n") < 0)
2282 con
->sent_header
= 1;
2285 if (strncasecmp(buf
, "Status:", 7))
2286 httpPrintf(HTTP(con
), "%s\r\n", buf
);
2288 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdWriteClient: %d %s",
2295 bytes
-= (bufptr
- buf
);
2296 memmove(buf
, bufptr
, bytes
+ 1);
2300 * See if the line was empty...
2303 if (con
->field_col
== 0)
2304 con
->got_fields
= 1;
2308 else if (*bufptr
!= '\r')
2311 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2312 "cupsdWriteClient: %d bytes=%d, got_fields=%d",
2313 con
->http
.fd
, bytes
, con
->got_fields
);
2315 if (bytes
> 0 && !con
->got_fields
)
2318 * Remaining text needs to go out...
2321 httpPrintf(HTTP(con
), "%s", buf
);
2323 con
->http
.activity
= time(NULL
);
2326 else if (bytes
== 0)
2327 con
->http
.activity
= time(NULL
);
2332 if (httpWrite2(HTTP(con
), buf
, bytes
) < 0)
2334 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2335 "cupsdWriteClient: %d Write of %d bytes failed!",
2336 con
->http
.fd
, bytes
);
2338 cupsdCloseClient(con
);
2342 con
->bytes
+= bytes
;
2344 if (con
->http
.state
== HTTP_WAITING
)
2351 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdWriteClient: %d bytes < 0",
2354 cupsdLogRequest(con
, HTTP_OK
);
2356 httpFlushWrite(HTTP(con
));
2358 if (con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
)
2360 if (httpPrintf(HTTP(con
), "0\r\n\r\n") < 0)
2362 cupsdCloseClient(con
);
2367 con
->http
.state
= HTTP_WAITING
;
2369 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2370 "cupsdWriteClient: Removing fd %d from OutputSet...",
2373 FD_CLR(con
->http
.fd
, OutputSet
);
2377 if (FD_ISSET(con
->file
, InputSet
))
2379 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2380 "cupsdWriteClient: Removing fd %d from InputSet...",
2382 FD_CLR(con
->file
, InputSet
);
2386 cupsdEndProcess(con
->pipe_pid
, 0);
2388 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2389 "cupsdWriteClient: %d Closing data file %d.",
2390 con
->http
.fd
, con
->file
);
2399 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2400 "cupsdWriteClient: %d Removing temp file %s",
2401 con
->http
.fd
, con
->filename
);
2402 unlink(con
->filename
);
2403 cupsdClearString(&con
->filename
);
2406 if (con
->request
!= NULL
)
2408 ippDelete(con
->request
);
2409 con
->request
= NULL
;
2412 if (con
->response
!= NULL
)
2414 ippDelete(con
->response
);
2415 con
->response
= NULL
;
2418 cupsdClearString(&con
->command
);
2419 cupsdClearString(&con
->options
);
2421 if (!con
->http
.keep_alive
)
2423 cupsdCloseClient(con
);
2429 con
->file_ready
= 0;
2431 if (con
->pipe_pid
&& !FD_ISSET(con
->file
, InputSet
))
2433 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2434 "cupsdWriteClient: Adding fd %d to InputSet...",
2436 FD_SET(con
->file
, InputSet
);
2440 con
->http
.activity
= time(NULL
);
2447 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
2450 static int /* O - 1 if modified since */
2452 cupsd_client_t
*con
, /* I - Client connection */
2453 struct stat
*filestats
) /* I - File information */
2455 char *ptr
; /* Pointer into field */
2456 time_t date
; /* Time/date value */
2457 off_t size
; /* Size/length value */
2462 ptr
= con
->http
.fields
[HTTP_FIELD_IF_MODIFIED_SINCE
];
2467 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2468 "check_if_modified: %d If-Modified-Since=\"%s\"",
2471 while (*ptr
!= '\0')
2473 while (isspace(*ptr
) || *ptr
== ';')
2476 if (strncasecmp(ptr
, "length=", 7) == 0)
2479 size
= strtoll(ptr
, NULL
, 10);
2481 while (isdigit(*ptr
))
2484 else if (isalpha(*ptr
))
2486 date
= httpGetDateTime(ptr
);
2487 while (*ptr
!= '\0' && *ptr
!= ';')
2494 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2495 "check_if_modified: %d sizes=" CUPS_LLFMT
","
2496 CUPS_LLFMT
" dates=%d,%d",
2497 con
->http
.fd
, CUPS_LLCAST size
,
2498 CUPS_LLCAST filestats
->st_size
, (int)date
,
2499 (int)filestats
->st_mtime
);
2501 return ((size
!= filestats
->st_size
&& size
!= 0) ||
2502 (date
< filestats
->st_mtime
&& date
!= 0) ||
2503 (size
== 0 && date
== 0));
2509 * 'encrypt_client()' - Enable encryption for the client...
2512 static int /* O - 1 on success, 0 on error */
2513 encrypt_client(cupsd_client_t
*con
) /* I - Client to encrypt */
2516 SSL_CTX
*context
; /* Context for encryption */
2517 SSL
*conn
; /* Connection for encryption */
2518 unsigned long error
; /* Error code */
2522 * Create the SSL context and accept the connection...
2525 context
= SSL_CTX_new(SSLv23_server_method());
2527 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
2528 SSL_CTX_use_PrivateKey_file(context
, ServerKey
, SSL_FILETYPE_PEM
);
2529 SSL_CTX_use_certificate_file(context
, ServerCertificate
, SSL_FILETYPE_PEM
);
2531 conn
= SSL_new(context
);
2533 SSL_set_fd(conn
, con
->http
.fd
);
2534 if (SSL_accept(conn
) != 1)
2536 cupsdLogMessage(CUPSD_LOG_ERROR
,
2537 "encrypt_client: Unable to encrypt connection from %s!",
2538 con
->http
.hostname
);
2540 while ((error
= ERR_get_error()) != 0)
2541 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s",
2542 ERR_error_string(error
, NULL
));
2544 SSL_CTX_free(context
);
2549 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2550 "encrypt_client: %d Connection from %s now encrypted.",
2551 con
->http
.fd
, con
->http
.hostname
);
2553 con
->http
.tls
= conn
;
2556 # elif defined(HAVE_GNUTLS)
2557 http_tls_t
*conn
; /* TLS session object */
2558 int error
; /* Error code */
2559 gnutls_certificate_server_credentials
*credentials
;
2560 /* TLS credentials */
2564 * Verify that we have a certificate...
2567 if (access(ServerKey
, 0) || access(ServerCertificate
, 0))
2570 * Nope, make a self-signed certificate...
2577 * Create the SSL object and perform the SSL handshake...
2580 conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
));
2585 credentials
= (gnutls_certificate_server_credentials
*)
2586 malloc(sizeof(gnutls_certificate_server_credentials
));
2587 if (credentials
== NULL
)
2589 cupsdLogMessage(CUPSD_LOG_ERROR
,
2590 "encrypt_client: Unable to encrypt connection from %s!",
2591 con
->http
.hostname
);
2592 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s", strerror(errno
));
2598 gnutls_certificate_allocate_credentials(credentials
);
2599 gnutls_certificate_set_x509_key_file(*credentials
, ServerCertificate
,
2600 ServerKey
, GNUTLS_X509_FMT_PEM
);
2602 gnutls_init(&(conn
->session
), GNUTLS_SERVER
);
2603 gnutls_set_default_priority(conn
->session
);
2604 gnutls_credentials_set(conn
->session
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
2605 gnutls_transport_set_ptr(conn
->session
,
2606 (gnutls_transport_ptr
)((long)con
->http
.fd
));
2608 error
= gnutls_handshake(conn
->session
);
2610 if (error
!= GNUTLS_E_SUCCESS
)
2612 cupsdLogMessage(CUPSD_LOG_ERROR
,
2613 "encrypt_client: Unable to encrypt connection from %s!",
2614 con
->http
.hostname
);
2615 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s",
2616 gnutls_strerror(error
));
2618 gnutls_deinit(conn
->session
);
2619 gnutls_certificate_free_credentials(*credentials
);
2625 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2626 "encrypt_client: %d Connection from %s now encrypted.",
2627 con
->http
.fd
, con
->http
.hostname
);
2629 conn
->credentials
= credentials
;
2630 con
->http
.tls
= conn
;
2633 # elif defined(HAVE_CDSASSL)
2634 OSStatus error
; /* Error code */
2635 http_tls_t
*conn
; /* CDSA connection information */
2636 cdsa_conn_ref_t u
; /* Connection reference union */
2639 if ((conn
= (http_tls_t
*)malloc(sizeof(http_tls_t
))) == NULL
)
2643 conn
->session
= NULL
;
2644 conn
->certsArray
= get_cdsa_server_certs();
2646 if (!conn
->certsArray
)
2648 cupsdLogMessage(CUPSD_LOG_ERROR
,
2649 "EncryptClient: Could not find signing key in keychain "
2650 "\"%s\"", ServerCertificate
);
2651 error
= errSSLBadCert
; /* errSSLBadConfiguration is a better choice, but not available on 10.2.x */
2655 error
= SSLNewContext(true, &conn
->session
);
2658 error
= SSLSetIOFuncs(conn
->session
, _httpReadCDSA
, _httpWriteCDSA
);
2661 error
= SSLSetProtocolVersion(conn
->session
, kSSLProtocol3
);
2666 * Use a union to resolve warnings about int/pointer size mismatches...
2669 u
.connection
= NULL
;
2670 u
.sock
= con
->http
.fd
;
2671 error
= SSLSetConnection(conn
->session
, u
.connection
);
2675 error
= SSLSetAllowsExpiredCerts(conn
->session
, true);
2678 error
= SSLSetAllowsAnyRoot(conn
->session
, true);
2681 error
= SSLSetCertificate(conn
->session
, conn
->certsArray
);
2686 * Perform SSL/TLS handshake
2689 while ((error
= SSLHandshake(conn
->session
)) == errSSLWouldBlock
)
2695 cupsdLogMessage(CUPSD_LOG_ERROR
,
2696 "encrypt_client: Unable to encrypt connection from %s!",
2697 con
->http
.hostname
);
2699 cupsdLogMessage(CUPSD_LOG_ERROR
,
2700 "encrypt_client: CDSA error code is %d", (int)error
);
2702 con
->http
.error
= error
;
2703 con
->http
.status
= HTTP_ERROR
;
2706 SSLDisposeContext(conn
->session
);
2708 if (conn
->certsArray
)
2709 CFRelease(conn
->certsArray
);
2716 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2717 "encrypt_client: %d Connection from %s now encrypted.",
2718 con
->http
.fd
, con
->http
.hostname
);
2720 con
->http
.tls
= conn
;
2723 # endif /* HAVE_LIBSSL */
2725 #endif /* HAVE_SSL */
2730 * 'get_cdsa_server_certs()' - Convert a keychain name into the CFArrayRef
2731 * required by SSLSetCertificate.
2733 * For now we assumes that there is exactly one SecIdentity in the
2734 * keychain - i.e. there is exactly one matching cert/private key pair.
2735 * In the future we will search a keychain for a SecIdentity matching a
2736 * specific criteria. We also skip the operation of adding additional
2737 * non-signing certs from the keychain to the CFArrayRef.
2739 * To create a self-signed certificate for testing use the certtool.
2740 * Executing the following as root will do it:
2742 * certtool c k=/Library/Keychains/System.keychain
2745 static CFArrayRef
/* O - Array of certificates */
2746 get_cdsa_server_certs(void)
2748 OSStatus err
; /* Error info */
2749 SecKeychainRef kcRef
; /* Keychain reference */
2750 SecIdentitySearchRef srchRef
; /* Search reference */
2751 SecIdentityRef identity
; /* Identity */
2752 CFArrayRef ca
; /* Certificate array */
2759 err
= SecKeychainOpen(ServerCertificate
, &kcRef
);
2762 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot open keychain \"%s\", error %d.",
2763 ServerCertificate
, (int)err
);
2767 * Search for "any" identity matching specified key use;
2768 * in this app, we expect there to be exactly one.
2771 err
= SecIdentitySearchCreate(kcRef
, CSSM_KEYUSE_SIGN
, &srchRef
);
2774 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2775 "Cannot find signing key in keychain \"%s\", error %d",
2776 ServerCertificate
, (int)err
);
2779 err
= SecIdentitySearchCopyNext(srchRef
, &identity
);
2782 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2783 "Cannot find signing key in keychain \"%s\", error %d",
2784 ServerCertificate
, (int)err
);
2787 if (CFGetTypeID(identity
) != SecIdentityGetTypeID())
2788 cupsdLogMessage(CUPSD_LOG_ERROR
,
2789 "SecIdentitySearchCopyNext CFTypeID failure!");
2793 * Found one. Place it in a CFArray.
2794 * TBD: snag other (non-identity) certs from keychain and add them
2798 ca
= CFArrayCreate(NULL
, (const void **)&identity
, 1, &kCFTypeArrayCallBacks
);
2801 cupsdLogMessage(CUPSD_LOG_ERROR
, "CFArrayCreate error");
2804 CFRelease(identity
);
2815 #endif /* HAVE_CDSASSL */
2819 * 'get_file()' - Get a filename and state info.
2822 static char * /* O - Real filename */
2823 get_file(cupsd_client_t
*con
, /* I - Client connection */
2824 struct stat
*filestats
, /* O - File information */
2825 char *filename
, /* IO - Filename buffer */
2826 int len
) /* I - Buffer length */
2828 int status
; /* Status of filesystem calls */
2829 char *ptr
; /* Pointer info filename */
2830 int plen
; /* Remaining length after pointer */
2834 * Need to add DocumentRoot global...
2837 if (!strncmp(con
->uri
, "/ppd/", 5))
2838 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
);
2839 else if (!strncmp(con
->uri
, "/admin/conf/", 12))
2840 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
+ 11);
2841 else if (!strncmp(con
->uri
, "/admin/log/", 11))
2843 if (!strcmp(con
->uri
+ 11, "access_log") && AccessLog
[0] == '/')
2844 strlcpy(filename
, AccessLog
, len
);
2845 else if (!strcmp(con
->uri
+ 11, "error_log") && ErrorLog
[0] == '/')
2846 strlcpy(filename
, ErrorLog
, len
);
2847 else if (!strcmp(con
->uri
+ 11, "page_log") && PageLog
[0] == '/')
2848 strlcpy(filename
, PageLog
, len
);
2852 else if (con
->language
)
2853 snprintf(filename
, len
, "%s/%s%s", DocumentRoot
, con
->language
->language
,
2856 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
2858 if ((ptr
= strchr(filename
, '?')) != NULL
)
2862 * Grab the status for this language; if there isn't a language-specific file
2863 * then fallback to the default one...
2866 if ((status
= stat(filename
, filestats
)) != 0 && con
->language
&&
2867 strncmp(con
->uri
, "/ppd/", 5) &&
2868 strncmp(con
->uri
, "/admin/conf/", 12) &&
2869 strncmp(con
->uri
, "/admin/log/", 11))
2872 * Drop the country code...
2875 char ll
[3]; /* Short language name */
2878 strlcpy(ll
, con
->language
->language
, sizeof(ll
));
2879 snprintf(filename
, len
, "%s/%s%s", DocumentRoot
, ll
, con
->uri
);
2881 if ((ptr
= strchr(filename
, '?')) != NULL
)
2884 if ((status
= stat(filename
, filestats
)) != 0)
2887 * Drop the language prefix and try the root directory...
2890 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
2892 if ((ptr
= strchr(filename
, '?')) != NULL
)
2895 status
= stat(filename
, filestats
);
2900 * If we're found a directory, get the index.html file instead...
2903 if (!status
&& S_ISDIR(filestats
->st_mode
))
2905 if (filename
[strlen(filename
) - 1] != '/')
2906 strlcat(filename
, "/", len
);
2908 ptr
= filename
+ strlen(filename
);
2909 plen
= len
- (ptr
- filename
);
2911 strlcpy(ptr
, "index.html", plen
);
2912 status
= stat(filename
, filestats
);
2917 strlcpy(ptr
, "index.class", plen
);
2918 status
= stat(filename
, filestats
);
2920 #endif /* HAVE_JAVA */
2925 strlcpy(ptr
, "index.pl", plen
);
2926 status
= stat(filename
, filestats
);
2928 #endif /* HAVE_PERL */
2933 strlcpy(ptr
, "index.php", plen
);
2934 status
= stat(filename
, filestats
);
2936 #endif /* HAVE_PHP */
2941 strlcpy(ptr
, "index.pyc", plen
);
2942 status
= stat(filename
, filestats
);
2947 strlcpy(ptr
, "index.py", plen
);
2948 status
= stat(filename
, filestats
);
2950 #endif /* HAVE_PYTHON */
2953 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "get_file: %d filename=%s size=%d",
2954 con
->http
.fd
, filename
,
2955 status
? -1 : (int)filestats
->st_size
);
2958 con
->http
.data_remaining
= (int)filestats
->st_size
;
2968 * 'install_conf_file()' - Install a configuration file.
2971 static http_status_t
/* O - Status */
2972 install_conf_file(cupsd_client_t
*con
) /* I - Connection */
2974 cups_file_t
*in
, /* Input file */
2975 *out
; /* Output file */
2976 char buffer
[1024]; /* Copy buffer */
2977 int bytes
; /* Number of bytes */
2978 char conffile
[1024], /* Configuration filename */
2979 newfile
[1024], /* New config filename */
2980 oldfile
[1024]; /* Old config filename */
2981 struct stat confinfo
; /* Config file info */
2985 * First construct the filenames...
2988 snprintf(conffile
, sizeof(conffile
), "%s%s", ServerRoot
, con
->uri
+ 11);
2989 snprintf(newfile
, sizeof(newfile
), "%s%s.N", ServerRoot
, con
->uri
+ 11);
2990 snprintf(oldfile
, sizeof(oldfile
), "%s%s.O", ServerRoot
, con
->uri
+ 11);
2992 cupsdLogMessage(CUPSD_LOG_INFO
, "Installing config file \"%s\"...", conffile
);
2995 * Get the owner, group, and permissions of the configuration file.
2996 * If it doesn't exist, assign it to the User and Group in the
2997 * cupsd.conf file with mode 0640 permissions.
3000 if (stat(conffile
, &confinfo
))
3002 confinfo
.st_uid
= User
;
3003 confinfo
.st_gid
= Group
;
3004 confinfo
.st_mode
= ConfigFilePerm
;
3008 * Open the request file and new config file...
3011 if ((in
= cupsFileOpen(con
->filename
, "rb")) == NULL
)
3013 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open request file \"%s\" - %s",
3014 con
->filename
, strerror(errno
));
3015 return (HTTP_SERVER_ERROR
);
3018 if ((out
= cupsFileOpen(newfile
, "wb")) == NULL
)
3021 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open config file \"%s\" - %s",
3022 newfile
, strerror(errno
));
3023 return (HTTP_SERVER_ERROR
);
3026 fchmod(cupsFileNumber(out
), confinfo
.st_mode
);
3027 fchown(cupsFileNumber(out
), confinfo
.st_uid
, confinfo
.st_gid
);
3030 * Copy from the request to the new config file...
3033 while ((bytes
= cupsFileRead(in
, buffer
, sizeof(buffer
))) > 0)
3034 if (cupsFileWrite(out
, buffer
, bytes
) < bytes
)
3036 cupsdLogMessage(CUPSD_LOG_ERROR
,
3037 "Unable to copy to config file \"%s\" - %s",
3038 newfile
, strerror(errno
));
3044 return (HTTP_SERVER_ERROR
);
3048 * Close the files...
3052 if (cupsFileClose(out
))
3054 cupsdLogMessage(CUPSD_LOG_ERROR
,
3055 "Error file closing config file \"%s\" - %s",
3056 newfile
, strerror(errno
));
3060 return (HTTP_SERVER_ERROR
);
3064 * Remove the request file...
3067 unlink(con
->filename
);
3068 cupsdClearString(&con
->filename
);
3071 * Unlink the old backup, rename the current config file to the backup
3072 * filename, and rename the new config file to the config file name...
3075 if (unlink(oldfile
))
3076 if (errno
!= ENOENT
)
3078 cupsdLogMessage(CUPSD_LOG_ERROR
,
3079 "Unable to remove backup config file \"%s\" - %s",
3080 oldfile
, strerror(errno
));
3084 return (HTTP_SERVER_ERROR
);
3087 if (rename(conffile
, oldfile
))
3088 if (errno
!= ENOENT
)
3090 cupsdLogMessage(CUPSD_LOG_ERROR
,
3091 "Unable to rename old config file \"%s\" - %s",
3092 conffile
, strerror(errno
));
3096 return (HTTP_SERVER_ERROR
);
3099 if (rename(newfile
, conffile
))
3101 cupsdLogMessage(CUPSD_LOG_ERROR
,
3102 "Unable to rename new config file \"%s\" - %s",
3103 newfile
, strerror(errno
));
3105 rename(oldfile
, conffile
);
3108 return (HTTP_SERVER_ERROR
);
3112 * If the cupsd.conf file was updated, set the NeedReload flag...
3115 if (!strcmp(con
->uri
, "/admin/conf/cupsd.conf"))
3116 NeedReload
= RELOAD_CUPSD
;
3118 NeedReload
= RELOAD_ALL
;
3120 ReloadTime
= time(NULL
);
3123 * Return that the file was created successfully...
3126 return (HTTP_CREATED
);
3131 * 'is_cgi()' - Is the resource a CGI script/program?
3134 static int /* O - 1 = CGI, 0 = file */
3135 is_cgi(cupsd_client_t
*con
, /* I - Client connection */
3136 const char *filename
, /* I - Real filename */
3137 struct stat
*filestats
, /* I - File information */
3138 mime_type_t
*type
) /* I - MIME type */
3140 const char *options
; /* Options on URL */
3143 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3144 "is_cgi(con=%p, filename=\"%s\", filestats=%p, type=%s/%s)\n",
3145 con
, filename
, filestats
, type
? type
->super
: "unknown",
3146 type
? type
->type
: "unknown");
3149 * Get the options, if any...
3152 if ((options
= strchr(con
->uri
, '?')) != NULL
)
3156 * Check for known types...
3159 if (!type
|| strcasecmp(type
->super
, "application"))
3161 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "is_cgi: Returning 0...");
3165 if (!strcasecmp(type
->type
, "x-httpd-cgi") &&
3166 (filestats
->st_mode
& 0111))
3169 * "application/x-httpd-cgi" is a CGI script.
3172 cupsdSetString(&con
->command
, filename
);
3174 filename
= strrchr(filename
, '/') + 1; /* Filename always absolute */
3176 cupsdSetString(&con
->options
, options
);
3178 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3179 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3180 con
->command
, con
->options
);
3185 else if (!strcasecmp(type
->type
, "x-httpd-java"))
3188 * "application/x-httpd-java" is a Java servlet.
3191 cupsdSetString(&con
->command
, CUPS_JAVA
);
3194 cupsdSetStringf(&con
->options
, "%s %s", filename
, options
);
3196 cupsdSetString(&con
->options
, filename
);
3198 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3199 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3200 con
->command
, con
->options
);
3204 #endif /* HAVE_JAVA */
3206 else if (!strcasecmp(type
->type
, "x-httpd-perl"))
3209 * "application/x-httpd-perl" is a Perl page.
3212 cupsdSetString(&con
->command
, CUPS_PERL
);
3215 cupsdSetStringf(&con
->options
, "%s %s", filename
, options
);
3217 cupsdSetString(&con
->options
, filename
);
3219 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3220 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3221 con
->command
, con
->options
);
3225 #endif /* HAVE_PERL */
3227 else if (!strcasecmp(type
->type
, "x-httpd-php"))
3230 * "application/x-httpd-php" is a PHP page.
3233 cupsdSetString(&con
->command
, CUPS_PHP
);
3236 cupsdSetStringf(&con
->options
, "%s %s", filename
, options
);
3238 cupsdSetString(&con
->options
, filename
);
3240 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3241 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3242 con
->command
, con
->options
);
3246 #endif /* HAVE_PHP */
3248 else if (!strcasecmp(type
->type
, "x-httpd-python"))
3251 * "application/x-httpd-python" is a Python page.
3254 cupsdSetString(&con
->command
, CUPS_PYTHON
);
3257 cupsdSetStringf(&con
->options
, "%s %s", filename
, options
);
3259 cupsdSetString(&con
->options
, filename
);
3261 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3262 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3263 con
->command
, con
->options
);
3267 #endif /* HAVE_PYTHON */
3269 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "is_cgi: Returning 0...");
3276 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
3279 static int /* O - 0 if relative, 1 if absolute */
3280 is_path_absolute(const char *path
) /* I - Input path */
3283 * Check for a leading slash...
3290 * Check for "/.." in the path...
3293 while ((path
= strstr(path
, "/..")) != NULL
)
3295 if (!path
[3] || path
[3] == '/')
3302 * If we haven't found any relative paths, return 1 indicating an
3312 * 'make_certificate()' - Make a self-signed SSL/TLS certificate.
3316 make_certificate(void)
3318 gnutls_x509_crt crt
; /* Self-signed certificate */
3319 gnutls_x509_privkey key
; /* Encryption key */
3320 cups_lang_t
*language
; /* Default language info */
3321 cups_file_t
*fp
; /* Key/cert file */
3322 unsigned char buffer
[8192]; /* Buffer for x509 data */
3323 size_t bytes
; /* Number of bytes of data */
3324 unsigned char serial
[4]; /* Serial number buffer */
3325 time_t curtime
; /* Current time */
3326 int result
; /* Result of GNU TLS calls */
3330 * Create the encryption key...
3333 cupsdLogMessage(CUPSD_LOG_INFO
, "Generating server key...");
3335 gnutls_x509_privkey_init(&key
);
3336 gnutls_x509_privkey_generate(key
, GNUTLS_PK_RSA
, 2048, 0);
3342 bytes
= sizeof(buffer
);
3344 if ((result
= gnutls_x509_privkey_export(key
, GNUTLS_X509_FMT_PEM
,
3345 buffer
, &bytes
)) < 0)
3347 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to export server key - %s",
3348 gnutls_strerror(result
));
3349 gnutls_x509_privkey_deinit(key
);
3352 else if ((fp
= cupsFileOpen(ServerKey
, "w")) != NULL
)
3354 cupsFileWrite(fp
, (char *)buffer
, bytes
);
3357 cupsdLogMessage(CUPSD_LOG_INFO
, "Created server key file \"%s\"...",
3362 cupsdLogMessage(CUPSD_LOG_ERROR
,
3363 "Unable to create server key file \"%s\" - %s",
3364 ServerKey
, strerror(errno
));
3365 gnutls_x509_privkey_deinit(key
);
3370 * Create the self-signed certificate...
3373 cupsdLogMessage(CUPSD_LOG_INFO
, "Generating self-signed certificate...");
3375 language
= cupsLangDefault();
3376 curtime
= time(NULL
);
3377 serial
[0] = curtime
>> 24;
3378 serial
[1] = curtime
>> 16;
3379 serial
[2] = curtime
>> 8;
3380 serial
[3] = curtime
;
3382 gnutls_x509_crt_init(&crt
);
3383 if (strlen(language
->language
) == 5)
3384 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
3385 language
->language
+ 3, 2);
3387 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
3389 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COMMON_NAME
, 0,
3390 ServerName
, strlen(ServerName
));
3391 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATION_NAME
, 0,
3392 ServerName
, strlen(ServerName
));
3393 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATIONAL_UNIT_NAME
,
3395 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_STATE_OR_PROVINCE_NAME
, 0,
3397 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_LOCALITY_NAME
, 0,
3399 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_PKCS9_EMAIL
, 0,
3400 ServerAdmin
, strlen(ServerAdmin
));
3401 gnutls_x509_crt_set_key(crt
, key
);
3402 gnutls_x509_crt_set_serial(crt
, serial
, sizeof(serial
));
3403 gnutls_x509_crt_set_activation_time(crt
, curtime
);
3404 gnutls_x509_crt_set_expiration_time(crt
, curtime
+ 10 * 365 * 86400);
3405 gnutls_x509_crt_set_ca_status(crt
, 0);
3406 gnutls_x509_crt_set_subject_alternative_name(crt
, GNUTLS_SAN_DNSNAME
,
3408 gnutls_x509_crt_set_key_purpose_oid(crt
, GNUTLS_KP_TLS_WWW_SERVER
, 0);
3409 gnutls_x509_crt_set_key_usage(crt
, GNUTLS_KEY_KEY_ENCIPHERMENT
);
3410 gnutls_x509_crt_set_version(crt
, 3);
3412 bytes
= sizeof(buffer
);
3413 if (gnutls_x509_crt_get_key_id(crt
, 0, buffer
, &bytes
) >= 0)
3414 gnutls_x509_crt_set_subject_key_id(crt
, buffer
, bytes
);
3416 gnutls_x509_crt_sign(crt
, crt
, key
);
3422 bytes
= sizeof(buffer
);
3423 if ((result
= gnutls_x509_crt_export(crt
, GNUTLS_X509_FMT_PEM
,
3424 buffer
, &bytes
)) < 0)
3425 cupsdLogMessage(CUPSD_LOG_ERROR
,
3426 "Unable to export server certificate - %s",
3427 gnutls_strerror(result
));
3428 else if ((fp
= cupsFileOpen(ServerCertificate
, "w")) != NULL
)
3430 cupsFileWrite(fp
, (char *)buffer
, bytes
);
3433 cupsdLogMessage(CUPSD_LOG_INFO
,
3434 "Created 10-year server certificate file \"%s\"...",
3438 cupsdLogMessage(CUPSD_LOG_ERROR
,
3439 "Unable to create server certificate file \"%s\" - %s",
3440 ServerCertificate
, strerror(errno
));
3446 gnutls_x509_crt_deinit(crt
);
3447 gnutls_x509_privkey_deinit(key
);
3449 #endif /* HAVE_GNUTLS */
3453 * 'pipe_command()' - Pipe the output of a command to the remote client.
3456 static int /* O - Process ID */
3457 pipe_command(cupsd_client_t
*con
, /* I - Client connection */
3458 int infile
, /* I - Standard input for command */
3459 int *outfile
, /* O - Standard output for command */
3460 char *command
, /* I - Command to run */
3461 char *options
, /* I - Options for command */
3462 int root
) /* I - Run as root? */
3464 int i
; /* Looping var */
3465 int pid
; /* Process ID */
3466 char *commptr
, /* Command string pointer */
3467 commch
; /* Command string character */
3468 char *uriptr
; /* URI string pointer */
3469 int fds
[2]; /* Pipe FDs */
3470 int argc
; /* Number of arguments */
3471 int envc
; /* Number of environment variables */
3472 char argbuf
[10240], /* Argument buffer */
3473 *argv
[100], /* Argument strings */
3474 *envp
[MAX_ENV
+ 17]; /* Environment variables */
3475 char content_length
[1024], /* CONTENT_LENGTH environment variable */
3476 content_type
[1024], /* CONTENT_TYPE environment variable */
3477 http_cookie
[32768], /* HTTP_COOKIE environment variable */
3478 http_user_agent
[1024], /* HTTP_USER_AGENT environment variable */
3479 lang
[1024], /* LANG environment variable */
3480 path_info
[1024], /* PATH_INFO environment variable */
3481 *query_string
, /* QUERY_STRING env variable */
3482 remote_addr
[1024], /* REMOTE_ADDR environment variable */
3483 remote_host
[1024], /* REMOTE_HOST environment variable */
3484 remote_user
[1024], /* REMOTE_USER environment variable */
3485 script_name
[1024], /* SCRIPT_NAME environment variable */
3486 server_name
[1024], /* SERVER_NAME environment variable */
3487 server_port
[1024]; /* SERVER_PORT environment variable */
3491 * Parse a copy of the options string, which is of the form:
3493 * argument+argument+argument
3494 * ?argument+argument+argument
3495 * param=value¶m=value
3496 * ?param=value¶m=value
3497 * /name?argument+argument+argument
3498 * /name?param=value¶m=value
3500 * If the string contains an "=" character after the initial name,
3501 * then we treat it as a HTTP GET form request and make a copy of
3502 * the remaining string for the environment variable.
3504 * The string is always parsed out as command-line arguments, to
3505 * be consistent with Apache...
3508 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3509 "pipe_command: command=\"%s\", options=\"%s\"",
3513 query_string
= NULL
;
3516 strlcpy(argbuf
, options
, sizeof(argbuf
));
3520 if (argbuf
[0] == '/')
3523 * Found some trailing path information, set PATH_INFO...
3526 if ((commptr
= strchr(argbuf
, '?')) == NULL
)
3527 commptr
= argbuf
+ strlen(argbuf
);
3531 snprintf(path_info
, sizeof(path_info
), "PATH_INFO=%s", argbuf
);
3537 path_info
[0] = '\0';
3540 if (*commptr
== '?' && con
->operation
== HTTP_GET
)
3543 cupsdSetStringf(&query_string
, "QUERY_STRING=%s", commptr
);
3550 argv
[argc
++] = commptr
;
3552 for (; *commptr
&& argc
< 99; commptr
++)
3555 * Break arguments whenever we see a + or space...
3558 if (*commptr
== ' ' || *commptr
== '+')
3560 while (*commptr
== ' ' || *commptr
== '+')
3564 * If we don't have a blank string, save it as another argument...
3569 argv
[argc
] = commptr
;
3575 else if (*commptr
== '%' && isxdigit(commptr
[1] & 255) &&
3576 isxdigit(commptr
[2] & 255))
3579 * Convert the %xx notation to the individual character.
3582 if (commptr
[1] >= '0' && commptr
[1] <= '9')
3583 *commptr
= (commptr
[1] - '0') << 4;
3585 *commptr
= (tolower(commptr
[1]) - 'a' + 10) << 4;
3587 if (commptr
[2] >= '0' && commptr
[2] <= '9')
3588 *commptr
|= commptr
[2] - '0';
3590 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
3592 _cups_strcpy(commptr
+ 1, commptr
+ 3);
3595 * Check for a %00 and break if that is the case...
3607 * Setup the environment variables as needed...
3611 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF-8", con
->language
->language
);
3613 strcpy(lang
, "LANG=C");
3615 strcpy(remote_addr
, "REMOTE_ADDR=");
3616 httpAddrString(con
->http
.hostaddr
, remote_addr
+ 12,
3617 sizeof(remote_addr
) - 12);
3619 snprintf(remote_host
, sizeof(remote_host
), "REMOTE_HOST=%s",
3620 con
->http
.hostname
);
3622 snprintf(script_name
, sizeof(script_name
), "SCRIPT_NAME=%s", con
->uri
);
3623 if ((uriptr
= strchr(script_name
, '?')) != NULL
)
3626 sprintf(server_port
, "SERVER_PORT=%d", con
->serverport
);
3628 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
3631 envc
= cupsdLoadEnv(envp
, (int)(sizeof(envp
) / sizeof(envp
[0])));
3633 envp
[envc
++] = lang
;
3634 envp
[envc
++] = "REDIRECT_STATUS=1";
3635 envp
[envc
++] = server_name
;
3636 envp
[envc
++] = server_port
;
3637 envp
[envc
++] = remote_addr
;
3638 envp
[envc
++] = remote_host
;
3639 envp
[envc
++] = script_name
;
3642 envp
[envc
++] = path_info
;
3644 if (con
->username
[0])
3646 snprintf(remote_user
, sizeof(remote_user
), "REMOTE_USER=%s", con
->username
);
3648 envp
[envc
++] = remote_user
;
3651 if (con
->http
.version
== HTTP_1_1
)
3652 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.1";
3653 else if (con
->http
.version
== HTTP_1_0
)
3654 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.0";
3656 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/0.9";
3658 if (con
->http
.cookie
)
3660 snprintf(http_cookie
, sizeof(http_cookie
), "HTTP_COOKIE=%s",
3662 envp
[envc
++] = http_cookie
;
3665 if (con
->http
.fields
[HTTP_FIELD_USER_AGENT
][0])
3667 snprintf(http_user_agent
, sizeof(http_user_agent
), "HTTP_USER_AGENT=%s",
3668 con
->http
.fields
[HTTP_FIELD_USER_AGENT
]);
3669 envp
[envc
++] = http_user_agent
;
3672 if (con
->operation
== HTTP_GET
)
3674 for (i
= 0; i
< argc
; i
++)
3675 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "argv[%d] = \"%s\"", i
, argv
[i
]);
3677 envp
[envc
++] = "REQUEST_METHOD=GET";
3682 * Add GET form variables after ?...
3685 envp
[envc
++] = query_string
;
3690 sprintf(content_length
, "CONTENT_LENGTH=" CUPS_LLFMT
,
3691 CUPS_LLCAST con
->bytes
);
3692 snprintf(content_type
, sizeof(content_type
), "CONTENT_TYPE=%s",
3693 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
3695 envp
[envc
++] = "REQUEST_METHOD=POST";
3696 envp
[envc
++] = content_length
;
3697 envp
[envc
++] = content_type
;
3701 * Tell the CGI if we are using encryption...
3704 if (con
->http
.encryption
== HTTP_ENCRYPT_ALWAYS
)
3705 envp
[envc
++] = "HTTPS=ON";
3708 * Terminate the environment array...
3713 if (LogLevel
== CUPSD_LOG_DEBUG2
)
3715 for (i
= 0; i
< argc
; i
++)
3716 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3717 "pipe_command: argv[%d] = \"%s\"", i
, argv
[i
]);
3718 for (i
= 0; i
< envc
; i
++)
3719 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3720 "pipe_command: envp[%d] = \"%s\"", i
, envp
[i
]);
3724 * Create a pipe for the output...
3727 if (cupsdOpenPipe(fds
))
3729 cupsdClearString(&query_string
);
3731 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to create pipes for CGI %s - %s",
3732 argv
[0], strerror(errno
));
3737 * Then execute the command...
3740 if (cupsdStartProcess(command
, argv
, envp
, infile
, fds
[1], CGIPipes
[1],
3741 -1, root
, &pid
) < 0)
3744 * Error - can't fork!
3747 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to fork for CGI %s - %s", argv
[0],
3750 cupsdClosePipe(fds
);
3756 * Fork successful - return the PID...
3759 if (con
->username
[0])
3760 cupsdAddCert(pid
, con
->username
);
3762 cupsdLogMessage(CUPSD_LOG_DEBUG
, "CGI %s started - PID = %d", command
, pid
);
3768 cupsdClearString(&query_string
);
3775 * 'send_file()' - Send a file via HTTP.
3778 static int /* O - 0 on failure, 1 on success */
3779 send_file(cupsd_client_t
*con
, /* I - Client connection */
3780 http_status_t code
, /* I - HTTP status */
3781 char *filename
, /* I - Filename */
3782 char *type
, /* I - File type */
3783 struct stat
*filestats
) /* O - File information */
3785 con
->file
= open(filename
, O_RDONLY
);
3787 cupsdLogMessage(CUPSD_LOG_DEBUG
, "send_file: %d file=%d", con
->http
.fd
,
3793 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
3797 if (!cupsdSendHeader(con
, code
, type
))
3800 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
3801 httpGetDateString(filestats
->st_mtime
)) < 0)
3803 if (httpPrintf(HTTP(con
), "Content-Length: " CUPS_LLFMT
"\r\n",
3804 CUPS_LLCAST filestats
->st_size
) < 0)
3806 if (httpPrintf(HTTP(con
), "\r\n") < 0)
3809 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
3810 con
->http
.data_remaining
= filestats
->st_size
;
3812 if (con
->http
.data_remaining
<= INT_MAX
)
3813 con
->http
._data_remaining
= con
->http
.data_remaining
;
3815 con
->http
._data_remaining
= INT_MAX
;
3817 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3818 "send_file: Adding fd %d to OutputSet...", con
->http
.fd
);
3820 FD_SET(con
->http
.fd
, OutputSet
);
3827 * End of "$Id: client.c 5416 2006-04-17 21:24:17Z mike $".