2 * "$Id: client.c 5305 2006-03-18 03:05:12Z 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
);
69 static int encrypt_client(cupsd_client_t
*con
);
71 static CFArrayRef
get_cdsa_server_certs(void);
72 #endif /* HAVE_CDSASSL */
73 static char *get_file(cupsd_client_t
*con
, struct stat
*filestats
,
74 char *filename
, int len
);
75 static http_status_t
install_conf_file(cupsd_client_t
*con
);
76 static int is_cgi(cupsd_client_t
*con
, const char *filename
,
77 struct stat
*filestats
, mime_type_t
*type
);
78 static int is_path_absolute(const char *path
);
80 static void make_certificate(void);
81 #endif /* HAVE_GNUTLS */
82 static int pipe_command(cupsd_client_t
*con
, int infile
, int *outfile
,
83 char *command
, char *options
, int root
);
84 static int send_file(cupsd_client_t
*con
, http_status_t code
,
85 char *filename
, char *type
,
86 struct stat
*filestats
);
90 * 'cupsdAcceptClient()' - Accept a new client.
94 cupsdAcceptClient(cupsd_listener_t
*lis
)/* I - Listener socket */
96 int count
; /* Count of connections on a host */
97 int val
; /* Parameter value */
98 cupsd_client_t
*con
, /* New client pointer */
99 *tempcon
; /* Temporary client pointer */
100 http_addrlist_t
*addrlist
, /* List of adddresses for host */
101 *addr
; /* Current address */
102 socklen_t addrlen
; /* Length of address */
103 char *hostname
; /* Hostname for address */
104 http_addr_t temp
; /* Temporary address variable */
105 static time_t last_dos
= 0; /* Time of last DoS attack */
108 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
109 "cupsdAcceptClient(lis=%p) %d Clients = %d",
110 lis
, lis
->fd
, cupsArrayCount(Clients
));
113 * Make sure we don't have a full set of clients already...
116 if (cupsArrayCount(Clients
) == MaxClients
)
120 * Get a pointer to the next available client...
124 Clients
= cupsArrayNew(NULL
, NULL
);
129 con
= calloc(1, sizeof(cupsd_client_t
));
131 con
->http
.activity
= time(NULL
);
133 con
->http
.hostaddr
= &(con
->clientaddr
);
136 * Accept the client and get the remote address...
139 addrlen
= sizeof(http_addr_t
);
141 if ((con
->http
.fd
= accept(lis
->fd
, (struct sockaddr
*)con
->http
.hostaddr
,
144 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to accept client connection - %s.",
151 if (lis
->address
.addr
.sa_family
== AF_INET6
)
154 * Save the connected port number...
157 con
->http
.hostaddr
->ipv6
.sin6_port
= lis
->address
.ipv6
.sin6_port
;
160 * Convert IPv4 over IPv6 addresses (::ffff:n.n.n.n) to IPv4 forms we
161 * can more easily use...
164 if (con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[0] == 0 &&
165 con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[1] == 0 &&
166 ntohl(con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[2]) == 0xffff)
167 con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[2] = 0;
170 #endif /* AF_INET6 */
171 if (lis
->address
.addr
.sa_family
== AF_INET
)
172 con
->http
.hostaddr
->ipv4
.sin_port
= lis
->address
.ipv4
.sin_port
;
175 * Check the number of clients on the same address...
178 for (count
= 0, tempcon
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
180 tempcon
= (cupsd_client_t
*)cupsArrayNext(Clients
))
181 if (httpAddrEqual(tempcon
->http
.hostaddr
, con
->http
.hostaddr
))
184 if (count
>= MaxClientsPerHost
)
188 if (count
>= MaxClientsPerHost
)
190 if ((time(NULL
) - last_dos
) >= 60)
192 last_dos
= time(NULL
);
193 cupsdLogMessage(CUPSD_LOG_WARN
,
194 "Possible DoS attack - more than %d clients connecting "
196 MaxClientsPerHost
, tempcon
->http
.hostname
);
200 closesocket(con
->http
.fd
);
210 * Get the hostname or format the IP address as needed...
213 if (httpAddrLocalhost(con
->http
.hostaddr
))
216 * Map accesses from the loopback interface to "localhost"...
219 strlcpy(con
->http
.hostname
, "localhost", sizeof(con
->http
.hostname
));
220 hostname
= con
->http
.hostname
;
225 * Map accesses from the same host to the server name.
228 for (addr
= ServerAddrs
; addr
; addr
= addr
->next
)
229 if (httpAddrEqual(con
->http
.hostaddr
, &(addr
->addr
)))
234 strlcpy(con
->http
.hostname
, ServerName
, sizeof(con
->http
.hostname
));
235 hostname
= con
->http
.hostname
;
237 else if (HostNameLookups
)
238 hostname
= httpAddrLookup(con
->http
.hostaddr
, con
->http
.hostname
,
239 sizeof(con
->http
.hostname
));
243 httpAddrString(con
->http
.hostaddr
, con
->http
.hostname
,
244 sizeof(con
->http
.hostname
));
248 if (hostname
== NULL
&& HostNameLookups
== 2)
251 * Can't have an unresolved IP address with double-lookups enabled...
254 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
255 "cupsdAcceptClient: Closing connection %d...",
259 closesocket(con
->http
.fd
);
264 cupsdLogMessage(CUPSD_LOG_WARN
,
265 "Name lookup failed - connection from %s closed!",
272 if (HostNameLookups
== 2)
275 * Do double lookups as needed...
278 if ((addrlist
= httpAddrGetList(con
->http
.hostname
, AF_UNSPEC
, NULL
)) != NULL
)
281 * See if the hostname maps to the same IP address...
284 for (addr
= addrlist
; addr
; addr
= addr
->next
)
285 if (httpAddrEqual(con
->http
.hostaddr
, &(addr
->addr
)))
291 httpAddrFreeList(addrlist
);
296 * Can't have a hostname that doesn't resolve to the same IP address
297 * with double-lookups enabled...
300 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
301 "cupsdAcceptClient: Closing connection %d...",
305 closesocket(con
->http
.fd
);
310 cupsdLogMessage(CUPSD_LOG_WARN
,
311 "IP lookup failed - connection from %s closed!",
319 if (con
->http
.hostaddr
->addr
.sa_family
== AF_INET6
)
320 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdAcceptClient: %d from %s:%d (IPv6)",
321 con
->http
.fd
, con
->http
.hostname
,
322 ntohs(con
->http
.hostaddr
->ipv6
.sin6_port
));
324 #endif /* AF_INET6 */
326 if (con
->http
.hostaddr
->addr
.sa_family
== AF_LOCAL
)
327 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdAcceptClient: %d from %s (Domain)",
328 con
->http
.fd
, con
->http
.hostname
);
330 #endif /* AF_LOCAL */
331 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdAcceptClient: %d from %s:%d (IPv4)",
332 con
->http
.fd
, con
->http
.hostname
,
333 ntohs(con
->http
.hostaddr
->ipv4
.sin_port
));
336 * Get the local address the client connected to...
339 addrlen
= sizeof(temp
);
340 if (getsockname(con
->http
.fd
, (struct sockaddr
*)&temp
, &addrlen
))
342 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to get local address - %s",
345 strcpy(con
->servername
, "localhost");
346 con
->serverport
= LocalPort
;
351 if (temp
.addr
.sa_family
== AF_INET6
)
353 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
354 con
->serverport
= ntohs(lis
->address
.ipv6
.sin6_port
);
357 #endif /* AF_INET6 */
358 if (temp
.addr
.sa_family
== AF_INET
)
360 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
361 con
->serverport
= ntohs(lis
->address
.ipv4
.sin_port
);
365 strcpy(con
->servername
, "localhost");
366 con
->serverport
= LocalPort
;
370 cupsArrayAdd(Clients
, con
);
372 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
373 "cupsdAcceptClient: %d connected to server on %s:%d",
374 con
->http
.fd
, con
->servername
, con
->serverport
);
377 * Using TCP_NODELAY improves responsiveness, especially on systems
378 * with a slow loopback interface... Since we write large buffers
379 * when sending print files and requests, there shouldn't be any
380 * performance penalty for this...
384 setsockopt(con
->http
.fd
, IPPROTO_TCP
, TCP_NODELAY
, &val
, sizeof(val
));
387 * Close this file on all execs...
390 fcntl(con
->http
.fd
, F_SETFD
, fcntl(con
->http
.fd
, F_GETFD
) | FD_CLOEXEC
);
393 * Add the socket to the select() input mask.
396 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
397 "cupsdAcceptClient: Adding fd %d to InputSet...",
399 FD_SET(con
->http
.fd
, InputSet
);
402 * Temporarily suspend accept()'s until we lose a client...
405 if (cupsArrayCount(Clients
) == MaxClients
)
406 cupsdPauseListening();
410 * See if we are connecting on a secure port...
413 if (lis
->encryption
== HTTP_ENCRYPT_ALWAYS
)
416 * https connection; go secure...
419 con
->http
.encryption
= HTTP_ENCRYPT_ALWAYS
;
425 #endif /* HAVE_SSL */
430 * 'cupsdCloseAllClients()' - Close all remote clients immediately.
434 cupsdCloseAllClients(void)
436 cupsd_client_t
*con
; /* Current client */
439 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
441 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
442 cupsdCloseClient(con
);
447 * 'cupsdCloseClient()' - Close a remote client.
450 int /* O - 1 if partial close, 0 if fully closed */
451 cupsdCloseClient(cupsd_client_t
*con
) /* I - Client to close */
453 int partial
; /* Do partial close for SSL? */
455 SSL_CTX
*context
; /* Context for encryption */
456 SSL
*conn
; /* Connection for encryption */
457 unsigned long error
; /* Error code */
458 #elif defined(HAVE_GNUTLS)
459 http_tls_t
*conn
; /* TLS connection information */
460 int error
; /* Error code */
461 gnutls_certificate_server_credentials
*credentials
;
462 /* TLS credentials */
463 #endif /* HAVE_LIBSSL */
466 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdCloseClient: %d", con
->http
.fd
);
469 * Flush pending writes before closing...
472 httpFlushWrite(HTTP(con
));
478 * Shutdown encryption as needed...
486 conn
= (SSL
*)(con
->http
.tls
);
487 context
= SSL_get_SSL_CTX(conn
);
489 switch (SSL_shutdown(conn
))
492 cupsdLogMessage(CUPSD_LOG_INFO
,
493 "cupsdCloseClient: SSL shutdown successful!");
496 cupsdLogMessage(CUPSD_LOG_ERROR
,
497 "cupsdCloseClient: Fatal error during SSL shutdown!");
499 while ((error
= ERR_get_error()) != 0)
500 cupsdLogMessage(CUPSD_LOG_ERROR
, "cupsdCloseClient: %s",
501 ERR_error_string(error
, NULL
));
505 SSL_CTX_free(context
);
508 # elif defined(HAVE_GNUTLS)
509 conn
= (http_tls_t
*)(con
->http
.tls
);
510 credentials
= (gnutls_certificate_server_credentials
*)(conn
->credentials
);
512 error
= gnutls_bye(conn
->session
, GNUTLS_SHUT_WR
);
515 case GNUTLS_E_SUCCESS
:
516 cupsdLogMessage(CUPSD_LOG_INFO
,
517 "cupsdCloseClient: SSL shutdown successful!");
520 cupsdLogMessage(CUPSD_LOG_ERROR
,
521 "cupsdCloseClient: %s", gnutls_strerror(error
));
525 gnutls_deinit(conn
->session
);
526 gnutls_certificate_free_credentials(*credentials
);
530 # elif defined(HAVE_CDSASSL)
531 while (SSLClose((SSLContextRef
)con
->http
.tls
) == errSSLWouldBlock
)
534 SSLDisposeContext((SSLContextRef
)con
->http
.tls
);
535 # endif /* HAVE_LIBSSL */
537 con
->http
.tls
= NULL
;
539 #endif /* HAVE_SSL */
541 if (con
->pipe_pid
!= 0)
544 * Stop any CGI process...
547 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
548 "cupsdCloseClient: %d Killing process ID %d...",
549 con
->http
.fd
, con
->pipe_pid
);
550 cupsdEndProcess(con
->pipe_pid
, 1);
556 if (FD_ISSET(con
->file
, InputSet
))
558 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
559 "cupsdCloseClient: %d Removing fd %d from InputSet...",
560 con
->http
.fd
, con
->file
);
561 FD_CLR(con
->file
, InputSet
);
564 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
565 "cupsdCloseClient: %d Closing data file %d.",
566 con
->http
.fd
, con
->file
);
573 * Close the socket and clear the file from the input set for select()...
576 if (con
->http
.fd
> 0)
581 * Only do a partial close so that the encrypted client gets everything.
584 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
585 "cupsdCloseClient: Removing fd %d from OutputSet...",
587 shutdown(con
->http
.fd
, 0);
588 FD_CLR(con
->http
.fd
, OutputSet
);
593 * Shut the socket down fully...
596 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
597 "cupsdCloseClient: Removing fd %d from InputSet and OutputSet...",
600 FD_CLR(con
->http
.fd
, InputSet
);
601 FD_CLR(con
->http
.fd
, OutputSet
);
612 if (con
->http
.input_set
)
613 free(con
->http
.input_set
);
615 httpClearCookie(HTTP(con
));
617 cupsdClearString(&con
->filename
);
618 cupsdClearString(&con
->command
);
619 cupsdClearString(&con
->options
);
623 ippDelete(con
->request
);
629 ippDelete(con
->response
);
630 con
->response
= NULL
;
635 cupsLangFree(con
->language
);
636 con
->language
= NULL
;
640 * Re-enable new client connections if we are going back under the
644 if (cupsArrayCount(Clients
) == MaxClients
)
645 cupsdResumeListening();
648 * Compact the list of clients as necessary...
651 cupsArrayRemove(Clients
, con
);
661 * 'cupsdReadClient()' - Read data from a client.
664 int /* O - 1 on success, 0 on error */
665 cupsdReadClient(cupsd_client_t
*con
) /* I - Client to read from */
667 char line
[32768], /* Line from client... */
668 operation
[64], /* Operation code from socket */
669 version
[64], /* HTTP version number string */
670 locale
[64], /* Locale */
671 *ptr
; /* Pointer into strings */
672 int major
, minor
; /* HTTP version numbers */
673 http_status_t status
; /* Transfer status */
674 ipp_state_t ipp_state
; /* State of IPP transfer */
675 int bytes
; /* Number of bytes to POST */
676 char *filename
; /* Name of file for GET/HEAD */
677 char buf
[1024]; /* Buffer for real filename */
678 struct stat filestats
; /* File information */
679 mime_type_t
*type
; /* MIME type of file */
680 cupsd_printer_t
*p
; /* Printer */
681 static unsigned request_id
= 0; /* Request ID for temp files */
684 status
= HTTP_CONTINUE
;
686 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
687 "cupsdReadClient: %d, used=%d, file=%d state=%d",
688 con
->http
.fd
, con
->http
.used
, con
->file
, con
->http
.state
);
692 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdReadClient: http error seen...");
693 return (cupsdCloseClient(con
));
700 * Automatically check for a SSL/TLS handshake...
705 if (recv(con
->http
.fd
, buf
, 1, MSG_PEEK
) == 1 &&
706 (!buf
[0] || !strchr("DGHOPT", buf
[0])))
709 * Encrypt this connection...
712 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
713 "cupsdReadClient: Saw first byte %02X, auto-negotiating SSL/TLS session...",
720 #endif /* HAVE_SSL */
722 switch (con
->http
.state
)
726 * See if we've received a request line...
729 if (httpGets(line
, sizeof(line
) - 1, HTTP(con
)) == NULL
)
731 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
732 "cupsdReadClient: httpGets returned EOF...");
733 return (cupsdCloseClient(con
));
737 * Ignore blank request lines...
744 * Clear other state variables...
747 httpClearFields(HTTP(con
));
749 con
->http
.activity
= time(NULL
);
750 con
->http
.version
= HTTP_1_0
;
751 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
752 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
753 con
->http
.data_remaining
= 0;
754 con
->http
._data_remaining
= 0;
755 con
->operation
= HTTP_WAITING
;
760 con
->username
[0] = '\0';
761 con
->password
[0] = '\0';
764 cupsdClearString(&con
->command
);
765 cupsdClearString(&con
->options
);
767 if (con
->language
!= NULL
)
769 cupsLangFree(con
->language
);
770 con
->language
= NULL
;
774 * Grab the request line...
777 switch (sscanf(line
, "%63s%1023s%63s", operation
, con
->uri
, version
))
780 cupsdLogMessage(CUPSD_LOG_ERROR
,
781 "Bad request line \"%s\" from %s!", line
,
783 cupsdSendError(con
, HTTP_BAD_REQUEST
);
784 return (cupsdCloseClient(con
));
786 con
->http
.version
= HTTP_0_9
;
789 if (sscanf(version
, "HTTP/%d.%d", &major
, &minor
) != 2)
791 cupsdLogMessage(CUPSD_LOG_ERROR
,
792 "Bad request line \"%s\" from %s!", line
,
794 cupsdSendError(con
, HTTP_BAD_REQUEST
);
795 return (cupsdCloseClient(con
));
800 con
->http
.version
= (http_version_t
)(major
* 100 + minor
);
801 if (con
->http
.version
== HTTP_1_1
&& KeepAlive
)
802 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
804 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
808 cupsdSendError(con
, HTTP_NOT_SUPPORTED
);
809 return (cupsdCloseClient(con
));
815 * Handle full URLs in the request line...
818 if (strcmp(con
->uri
, "*"))
820 char method
[HTTP_MAX_URI
], /* Method/scheme */
821 userpass
[HTTP_MAX_URI
], /* Username:password */
822 hostname
[HTTP_MAX_URI
], /* Hostname */
823 resource
[HTTP_MAX_URI
]; /* Resource path */
824 int port
; /* Port number */
828 * Separate the URI into its components...
831 httpSeparateURI(HTTP_URI_CODING_MOST
, con
->uri
,
832 method
, sizeof(method
),
833 userpass
, sizeof(userpass
),
834 hostname
, sizeof(hostname
), &port
,
835 resource
, sizeof(resource
));
838 * Only allow URIs with the servername, localhost, or an IP
842 if (strcmp(method
, "file") &&
843 strcasecmp(hostname
, ServerName
) &&
844 strcasecmp(hostname
, "localhost") &&
845 !isdigit(hostname
[0]))
848 * Nope, we don't do proxies...
851 cupsdLogMessage(CUPSD_LOG_ERROR
, "Bad URI \"%s\" in request!",
853 cupsdSendError(con
, HTTP_METHOD_NOT_ALLOWED
);
854 return (cupsdCloseClient(con
));
858 * Copy the resource portion back into the URI; both resource and
859 * con->uri are HTTP_MAX_URI bytes in size...
862 strcpy(con
->uri
, resource
);
866 * Process the request...
869 if (!strcmp(operation
, "GET"))
870 con
->http
.state
= HTTP_GET
;
871 else if (!strcmp(operation
, "PUT"))
872 con
->http
.state
= HTTP_PUT
;
873 else if (!strcmp(operation
, "POST"))
874 con
->http
.state
= HTTP_POST
;
875 else if (!strcmp(operation
, "DELETE"))
876 con
->http
.state
= HTTP_DELETE
;
877 else if (!strcmp(operation
, "TRACE"))
878 con
->http
.state
= HTTP_TRACE
;
879 else if (!strcmp(operation
, "OPTIONS"))
880 con
->http
.state
= HTTP_OPTIONS
;
881 else if (!strcmp(operation
, "HEAD"))
882 con
->http
.state
= HTTP_HEAD
;
885 cupsdLogMessage(CUPSD_LOG_ERROR
, "Bad operation \"%s\"!", operation
);
886 cupsdSendError(con
, HTTP_BAD_REQUEST
);
887 return (cupsdCloseClient(con
));
890 con
->start
= time(NULL
);
891 con
->operation
= con
->http
.state
;
893 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdReadClient: %d %s %s HTTP/%d.%d", con
->http
.fd
,
895 con
->http
.version
/ 100, con
->http
.version
% 100);
897 con
->http
.status
= HTTP_OK
;
907 * Parse incoming parameters until the status changes...
910 status
= httpUpdate(HTTP(con
));
912 if (status
!= HTTP_OK
&& status
!= HTTP_CONTINUE
)
914 cupsdSendError(con
, HTTP_BAD_REQUEST
);
915 return (cupsdCloseClient(con
));
920 break; /* Anti-compiler-warning-code */
924 * Handle new transfers...
927 if (status
== HTTP_OK
)
929 if (con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
][0])
932 * Figure out the locale from the Accept-Language and Content-Type
936 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ',')) != NULL
)
939 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ';')) != NULL
)
942 if ((ptr
= strstr(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
], "charset=")) != NULL
)
945 * Combine language and charset, and trim any extra params in the
949 snprintf(locale
, sizeof(locale
), "%s.%s",
950 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ptr
+ 8);
952 if ((ptr
= strchr(locale
, ',')) != NULL
)
956 snprintf(locale
, sizeof(locale
), "%s.%s",
957 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], DefaultCharset
);
959 con
->language
= cupsLangGet(locale
);
962 con
->language
= cupsLangGet(DefaultLocale
);
966 if (!strncmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Keep-Alive", 10) &&
968 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
970 if (!con
->http
.fields
[HTTP_FIELD_HOST
][0] &&
971 con
->http
.version
>= HTTP_1_1
)
974 * HTTP/1.1 and higher require the "Host:" field...
977 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
))
978 return (cupsdCloseClient(con
));
980 else if (con
->operation
== HTTP_OPTIONS
)
983 * Do OPTIONS command...
986 if (con
->best
&& con
->best
->type
!= AUTH_NONE
)
988 if (!cupsdSendHeader(con
, HTTP_UNAUTHORIZED
, NULL
))
989 return (cupsdCloseClient(con
));
992 if (!strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") &&
993 con
->http
.tls
== NULL
)
997 * Do encryption stuff...
1000 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
))
1001 return (cupsdCloseClient(con
));
1003 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1004 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1005 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1006 httpPrintf(HTTP(con
), "\r\n");
1008 encrypt_client(con
);
1010 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
))
1011 return (cupsdCloseClient(con
));
1012 #endif /* HAVE_SSL */
1015 if (!cupsdSendHeader(con
, HTTP_OK
, NULL
))
1016 return (cupsdCloseClient(con
));
1018 httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n");
1019 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1020 httpPrintf(HTTP(con
), "\r\n");
1022 else if (!is_path_absolute(con
->uri
))
1025 * Protect against malicious users!
1028 if (!cupsdSendError(con
, HTTP_FORBIDDEN
))
1029 return (cupsdCloseClient(con
));
1033 if (!strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") &&
1034 con
->http
.tls
== NULL
)
1038 * Do encryption stuff...
1041 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
))
1042 return (cupsdCloseClient(con
));
1044 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1045 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1046 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1047 httpPrintf(HTTP(con
), "\r\n");
1049 encrypt_client(con
);
1051 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
))
1052 return (cupsdCloseClient(con
));
1053 #endif /* HAVE_SSL */
1056 if ((status
= cupsdIsAuthorized(con
, NULL
)) != HTTP_OK
)
1058 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1059 "cupsdReadClient: Unauthorized request for %s...\n",
1061 cupsdSendError(con
, status
);
1062 return (cupsdCloseClient(con
));
1065 if (con
->http
.expect
&&
1066 (con
->operation
== HTTP_POST
|| con
->operation
== HTTP_PUT
))
1068 if (con
->http
.expect
== HTTP_CONTINUE
)
1071 * Send 100-continue header...
1074 if (!cupsdSendHeader(con
, HTTP_CONTINUE
, NULL
))
1075 return (cupsdCloseClient(con
));
1080 * Send 417-expectation-failed header...
1083 if (!cupsdSendHeader(con
, HTTP_EXPECTATION_FAILED
, NULL
))
1084 return (cupsdCloseClient(con
));
1086 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1087 httpPrintf(HTTP(con
), "\r\n");
1091 switch (con
->http
.state
)
1093 case HTTP_GET_SEND
:
1094 if (!strncmp(con
->uri
, "/printers/", 10) &&
1095 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1098 * Send PPD file - get the real printer name since printer
1099 * names are not case sensitive but filenames can be...
1102 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1104 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1105 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1108 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
1109 return (cupsdCloseClient(con
));
1115 if ((!strncmp(con
->uri
, "/admin", 6) &&
1116 strncmp(con
->uri
, "/admin/conf/", 12) &&
1117 strncmp(con
->uri
, "/admin/log/", 11)) ||
1118 !strncmp(con
->uri
, "/printers", 9) ||
1119 !strncmp(con
->uri
, "/classes", 8) ||
1120 !strncmp(con
->uri
, "/help", 5) ||
1121 !strncmp(con
->uri
, "/jobs", 5))
1124 * Send CGI output...
1127 if (!strncmp(con
->uri
, "/admin", 6))
1129 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1132 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1134 else if (!strncmp(con
->uri
, "/printers", 9))
1136 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1139 if (con
->uri
[9] && con
->uri
[10])
1140 cupsdSetString(&con
->options
, con
->uri
+ 9);
1142 cupsdSetString(&con
->options
, NULL
);
1144 else if (!strncmp(con
->uri
, "/classes", 8))
1146 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1149 if (con
->uri
[8] && con
->uri
[9])
1150 cupsdSetString(&con
->options
, con
->uri
+ 8);
1152 cupsdSetString(&con
->options
, NULL
);
1154 else if (!strncmp(con
->uri
, "/jobs", 5))
1156 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1159 if (con
->uri
[5] && con
->uri
[6])
1160 cupsdSetString(&con
->options
, con
->uri
+ 5);
1162 cupsdSetString(&con
->options
, NULL
);
1166 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1169 if (con
->uri
[5] && con
->uri
[6])
1170 cupsdSetString(&con
->options
, con
->uri
+ 5);
1172 cupsdSetString(&con
->options
, NULL
);
1175 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1177 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
1178 return (cupsdCloseClient(con
));
1181 cupsdLogRequest(con
, HTTP_OK
);
1183 if (con
->http
.version
<= HTTP_1_0
)
1184 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1186 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1187 (strchr(con
->uri
+ 12, '/') ||
1188 strlen(con
->uri
) == 12)) ||
1189 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1190 (strchr(con
->uri
+ 11, '/') ||
1191 strlen(con
->uri
) == 11)))
1194 * GET can only be done to configuration files under
1198 if (!cupsdSendError(con
, HTTP_FORBIDDEN
))
1199 return (cupsdCloseClient(con
));
1209 if ((filename
= get_file(con
, &filestats
, buf
,
1210 sizeof(buf
))) == NULL
)
1212 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
1213 return (cupsdCloseClient(con
));
1218 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1220 if (is_cgi(con
, filename
, &filestats
, type
))
1223 * Note: con->command and con->options were set by
1227 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1229 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
1230 return (cupsdCloseClient(con
));
1233 cupsdLogRequest(con
, HTTP_OK
);
1235 if (con
->http
.version
<= HTTP_1_0
)
1236 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1240 if (!check_if_modified(con
, &filestats
))
1242 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
))
1243 return (cupsdCloseClient(con
));
1248 strcpy(line
, "text/plain");
1250 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1252 if (!send_file(con
, HTTP_OK
, filename
, line
, &filestats
))
1253 return (cupsdCloseClient(con
));
1258 case HTTP_POST_RECV
:
1260 * See if the POST request includes a Content-Length field, and if
1261 * so check the length against any limits that are set...
1264 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "POST %s", con
->uri
);
1265 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "CONTENT_TYPE = %s",
1266 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
1268 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1269 MaxRequestSize
> 0 &&
1270 con
->http
.data_remaining
> MaxRequestSize
)
1273 * Request too large...
1276 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1277 return (cupsdCloseClient(con
));
1281 else if (con
->http
.data_remaining
< 0)
1284 * Negative content lengths are invalid!
1287 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
))
1288 return (cupsdCloseClient(con
));
1294 * See what kind of POST request this is; for IPP requests the
1295 * content-type field will be "application/ipp"...
1298 if (!strcmp(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
],
1300 con
->request
= ippNew();
1301 else if ((!strncmp(con
->uri
, "/admin", 6) &&
1302 strncmp(con
->uri
, "/admin/conf/", 12) &&
1303 strncmp(con
->uri
, "/admin/log/", 11)) ||
1304 !strncmp(con
->uri
, "/printers", 9) ||
1305 !strncmp(con
->uri
, "/classes", 8) ||
1306 !strncmp(con
->uri
, "/help", 5) ||
1307 !strncmp(con
->uri
, "/jobs", 5))
1313 if (!strncmp(con
->uri
, "/admin", 6))
1315 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1318 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1320 else if (!strncmp(con
->uri
, "/printers", 9))
1322 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1325 if (con
->uri
[9] && con
->uri
[10])
1326 cupsdSetString(&con
->options
, con
->uri
+ 9);
1328 cupsdSetString(&con
->options
, NULL
);
1330 else if (!strncmp(con
->uri
, "/classes", 8))
1332 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1335 if (con
->uri
[8] && con
->uri
[9])
1336 cupsdSetString(&con
->options
, con
->uri
+ 8);
1338 cupsdSetString(&con
->options
, NULL
);
1340 else if (!strncmp(con
->uri
, "/jobs", 5))
1342 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1345 if (con
->uri
[5] && con
->uri
[6])
1346 cupsdSetString(&con
->options
, con
->uri
+ 5);
1348 cupsdSetString(&con
->options
, NULL
);
1352 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1355 if (con
->uri
[5] && con
->uri
[6])
1356 cupsdSetString(&con
->options
, con
->uri
+ 5);
1358 cupsdSetString(&con
->options
, NULL
);
1361 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1362 "cupsdReadClient: %d command=\"%s\", "
1364 con
->http
.fd
, con
->command
, con
->options
);
1366 if (con
->http
.version
<= HTTP_1_0
)
1367 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1375 if ((filename
= get_file(con
, &filestats
, buf
,
1376 sizeof(buf
))) == NULL
)
1378 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
1379 return (cupsdCloseClient(con
));
1384 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1386 if (!is_cgi(con
, filename
, &filestats
, type
))
1389 * Only POST to CGI's...
1392 if (!cupsdSendError(con
, HTTP_UNAUTHORIZED
))
1393 return (cupsdCloseClient(con
));
1398 case HTTP_PUT_RECV
:
1400 * Validate the resource name...
1403 if (strncmp(con
->uri
, "/admin/conf/", 12) ||
1404 strchr(con
->uri
+ 12, '/') ||
1405 strlen(con
->uri
) == 12)
1408 * PUT can only be done to configuration files under
1412 if (!cupsdSendError(con
, HTTP_FORBIDDEN
))
1413 return (cupsdCloseClient(con
));
1419 * See if the PUT request includes a Content-Length field, and if
1420 * so check the length against any limits that are set...
1423 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "PUT %s", con
->uri
);
1424 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "CONTENT_TYPE = %s",
1425 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
1427 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1428 MaxRequestSize
> 0 &&
1429 con
->http
.data_remaining
> MaxRequestSize
)
1432 * Request too large...
1435 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1436 return (cupsdCloseClient(con
));
1440 else if (con
->http
.data_remaining
< 0)
1443 * Negative content lengths are invalid!
1446 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
))
1447 return (cupsdCloseClient(con
));
1453 * Open a temporary file to hold the request...
1456 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
1458 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1460 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1461 "cupsdReadClient: %d REQUEST %s=%d", con
->http
.fd
,
1462 con
->filename
, con
->file
);
1466 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1467 return (cupsdCloseClient(con
));
1470 fchmod(con
->file
, 0640);
1471 fchown(con
->file
, RunUser
, Group
);
1472 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1477 cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
);
1478 return (cupsdCloseClient(con
));
1481 if (!strncmp(con
->uri
, "/printers/", 10) &&
1482 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1485 * Send PPD file - get the real printer name since printer
1486 * names are not case sensitive but filenames can be...
1489 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1491 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1492 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1495 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
1496 return (cupsdCloseClient(con
));
1502 if ((!strncmp(con
->uri
, "/admin", 6) &&
1503 strncmp(con
->uri
, "/admin/conf/", 12) &&
1504 strncmp(con
->uri
, "/admin/log/", 11)) ||
1505 !strncmp(con
->uri
, "/printers", 9) ||
1506 !strncmp(con
->uri
, "/classes", 8) ||
1507 !strncmp(con
->uri
, "/help", 5) ||
1508 !strncmp(con
->uri
, "/jobs", 5))
1514 if (!cupsdSendHeader(con
, HTTP_OK
, "text/html"))
1515 return (cupsdCloseClient(con
));
1517 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1518 return (cupsdCloseClient(con
));
1520 cupsdLogRequest(con
, HTTP_OK
);
1522 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1523 (strchr(con
->uri
+ 12, '/') ||
1524 strlen(con
->uri
) == 12)) ||
1525 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1526 (strchr(con
->uri
+ 11, '/') ||
1527 strlen(con
->uri
) == 11)))
1530 * HEAD can only be done to configuration files under
1534 if (!cupsdSendError(con
, HTTP_FORBIDDEN
))
1535 return (cupsdCloseClient(con
));
1539 else if ((filename
= get_file(con
, &filestats
, buf
,
1540 sizeof(buf
))) == NULL
)
1542 if (!cupsdSendHeader(con
, HTTP_NOT_FOUND
, "text/html"))
1543 return (cupsdCloseClient(con
));
1545 cupsdLogRequest(con
, HTTP_NOT_FOUND
);
1547 else if (!check_if_modified(con
, &filestats
))
1549 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
))
1550 return (cupsdCloseClient(con
));
1552 cupsdLogRequest(con
, HTTP_NOT_MODIFIED
);
1560 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1562 strcpy(line
, "text/plain");
1564 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1566 if (!cupsdSendHeader(con
, HTTP_OK
, line
))
1567 return (cupsdCloseClient(con
));
1569 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
1570 httpGetDateString(filestats
.st_mtime
)) < 0)
1571 return (cupsdCloseClient(con
));
1573 if (httpPrintf(HTTP(con
), "Content-Length: %lu\r\n",
1574 (unsigned long)filestats
.st_size
) < 0)
1575 return (cupsdCloseClient(con
));
1577 cupsdLogRequest(con
, HTTP_OK
);
1580 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1581 return (cupsdCloseClient(con
));
1583 con
->http
.state
= HTTP_WAITING
;
1587 break; /* Anti-compiler-warning-code */
1593 * Handle any incoming data...
1596 switch (con
->http
.state
)
1598 case HTTP_PUT_RECV
:
1599 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1600 "cupsdReadClient: %d con->data_encoding=HTTP_ENCODE_%s, "
1601 "con->data_remaining=" CUPS_LLFMT
", con->file=%d",
1603 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
?
1604 "CHUNKED" : "LENGTH",
1605 CUPS_LLCAST con
->http
.data_remaining
, con
->file
);
1607 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
1608 return (cupsdCloseClient(con
));
1611 con
->bytes
+= bytes
;
1613 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1614 "cupsdReadClient: %d writing %d bytes to %d",
1615 con
->http
.fd
, bytes
, con
->file
);
1617 if (write(con
->file
, line
, bytes
) < bytes
)
1619 cupsdLogMessage(CUPSD_LOG_ERROR
,
1620 "cupsdReadClient: Unable to write %d bytes to %s: %s",
1621 bytes
, con
->filename
, strerror(errno
));
1623 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1624 "cupsdReadClient: Closing data file %d...",
1629 unlink(con
->filename
);
1630 cupsdClearString(&con
->filename
);
1632 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1633 return (cupsdCloseClient(con
));
1637 if (con
->http
.state
== HTTP_WAITING
)
1640 * End of file, see how big it is...
1643 fstat(con
->file
, &filestats
);
1645 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1646 "cupsdReadClient: %d Closing data file %d, size="
1648 con
->http
.fd
, con
->file
,
1649 CUPS_LLCAST filestats
.st_size
);
1654 if (filestats
.st_size
> MaxRequestSize
&&
1658 * Request is too big; remove it and send an error...
1661 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1662 "cupsdReadClient: %d Removing temp file %s",
1663 con
->http
.fd
, con
->filename
);
1664 unlink(con
->filename
);
1665 cupsdClearString(&con
->filename
);
1667 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1668 return (cupsdCloseClient(con
));
1672 * Install the configuration file...
1675 status
= install_conf_file(con
);
1678 * Return the status to the client...
1681 if (!cupsdSendError(con
, status
))
1682 return (cupsdCloseClient(con
));
1686 case HTTP_POST_RECV
:
1687 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1688 "cupsdReadClient: %d con->data_encoding=HTTP_ENCODE_"
1689 "%s, con->data_remaining=" CUPS_LLFMT
", con->file=%d",
1691 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
?
1692 "CHUNKED" : "LENGTH",
1693 CUPS_LLCAST con
->http
.data_remaining
, con
->file
);
1695 if (con
->request
!= NULL
)
1698 * Grab any request data from the connection...
1701 if ((ipp_state
= ippRead(&(con
->http
), con
->request
)) == IPP_ERROR
)
1703 cupsdLogMessage(CUPSD_LOG_ERROR
,
1704 "cupsdReadClient: %d IPP Read Error!",
1707 cupsdSendError(con
, HTTP_BAD_REQUEST
);
1708 return (cupsdCloseClient(con
));
1710 else if (ipp_state
!= IPP_DATA
)
1712 if (con
->http
.state
== HTTP_POST_SEND
)
1714 cupsdSendError(con
, HTTP_BAD_REQUEST
);
1715 return (cupsdCloseClient(con
));
1721 con
->bytes
+= ippLength(con
->request
);
1724 if (con
->file
< 0 && con
->http
.state
!= HTTP_POST_SEND
)
1727 * Create a file as needed for the request data...
1730 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
, request_id
++);
1731 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1733 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdReadClient: %d REQUEST %s=%d", con
->http
.fd
,
1734 con
->filename
, con
->file
);
1738 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1739 return (cupsdCloseClient(con
));
1742 fchmod(con
->file
, 0640);
1743 fchown(con
->file
, RunUser
, Group
);
1744 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1747 if (con
->http
.state
!= HTTP_POST_SEND
)
1749 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
1750 return (cupsdCloseClient(con
));
1753 con
->bytes
+= bytes
;
1755 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1756 "cupsdReadClient: %d writing %d bytes to %d",
1757 con
->http
.fd
, bytes
, con
->file
);
1759 if (write(con
->file
, line
, bytes
) < bytes
)
1761 cupsdLogMessage(CUPSD_LOG_ERROR
,
1762 "cupsdReadClient: Unable to write %d bytes to %s: %s",
1763 bytes
, con
->filename
, strerror(errno
));
1765 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1766 "cupsdReadClient: Closing file %d...",
1771 unlink(con
->filename
);
1772 cupsdClearString(&con
->filename
);
1774 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1775 return (cupsdCloseClient(con
));
1778 else if (con
->http
.state
== HTTP_POST_RECV
)
1779 return (1); /* ??? */
1780 else if (con
->http
.state
!= HTTP_POST_SEND
)
1781 return (cupsdCloseClient(con
));
1784 if (con
->http
.state
== HTTP_POST_SEND
)
1788 fstat(con
->file
, &filestats
);
1790 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1791 "cupsdReadClient: %d Closing data file %d, "
1792 "size=" CUPS_LLFMT
".",
1793 con
->http
.fd
, con
->file
,
1794 CUPS_LLCAST filestats
.st_size
);
1799 if (filestats
.st_size
> MaxRequestSize
&&
1803 * Request is too big; remove it and send an error...
1806 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1807 "cupsdReadClient: %d Removing temp file %s",
1808 con
->http
.fd
, con
->filename
);
1809 unlink(con
->filename
);
1810 cupsdClearString(&con
->filename
);
1815 * Delete any IPP request data...
1818 ippDelete(con
->request
);
1819 con
->request
= NULL
;
1822 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
))
1823 return (cupsdCloseClient(con
));
1828 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1830 if (!cupsdSendError(con
, HTTP_NOT_FOUND
))
1831 return (cupsdCloseClient(con
));
1834 cupsdLogRequest(con
, HTTP_OK
);
1839 return (cupsdProcessIPPRequest(con
));
1844 break; /* Anti-compiler-warning-code */
1847 if (!con
->http
.keep_alive
&& con
->http
.state
== HTTP_WAITING
)
1848 return (cupsdCloseClient(con
));
1855 * 'cupsdSendCommand()' - Send output from a command via HTTP.
1858 int /* O - 1 on success, 0 on failure */
1860 cupsd_client_t
*con
, /* I - Client connection */
1861 char *command
, /* I - Command to run */
1862 char *options
, /* I - Command-line options */
1863 int root
) /* I - Run as root? */
1865 int fd
; /* Standard input file descriptor */
1869 fd
= open(con
->filename
, O_RDONLY
);
1871 fd
= open("/dev/null", O_RDONLY
);
1875 cupsdLogMessage(CUPSD_LOG_ERROR
,
1876 "cupsdSendCommand: %d Unable to open \"%s\" for reading: %s",
1877 con
->http
.fd
, con
->filename
? con
->filename
: "/dev/null",
1882 fcntl(fd
, F_SETFD
, fcntl(fd
, F_GETFD
) | FD_CLOEXEC
);
1884 con
->pipe_pid
= pipe_command(con
, fd
, &(con
->file
), command
, options
, root
);
1888 cupsdLogMessage(CUPSD_LOG_INFO
, "Started \"%s\" (pid=%d)", command
,
1891 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendCommand: %d file=%d",
1892 con
->http
.fd
, con
->file
);
1894 if (con
->pipe_pid
== 0)
1897 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1899 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1900 "cupsdSendCommand: Adding fd %d to InputSet...", con
->file
);
1901 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1902 "cupsdSendCommand: Adding fd %d to OutputSet...",
1905 FD_SET(con
->file
, InputSet
);
1906 FD_SET(con
->http
.fd
, OutputSet
);
1908 con
->sent_header
= 0;
1909 con
->file_ready
= 0;
1910 con
->got_fields
= 0;
1918 * 'cupsdSendError()' - Send an error message via HTTP.
1921 int /* O - 1 if successful, 0 otherwise */
1922 cupsdSendError(cupsd_client_t
*con
, /* I - Connection */
1923 http_status_t code
) /* I - Error code */
1927 * Force client to upgrade for authentication if that is how the
1928 * server is configured...
1931 if (code
== HTTP_UNAUTHORIZED
&&
1932 DefaultEncryption
== HTTP_ENCRYPT_REQUIRED
&&
1933 strcasecmp(con
->http
.hostname
, "localhost") &&
1936 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1937 "cupsdSendError: Encryption before authentication!");
1938 code
= HTTP_UPGRADE_REQUIRED
;
1940 #endif /* HAVE_SSL */
1943 * Put the request in the access_log file...
1946 cupsdLogRequest(con
, code
);
1948 cupsdLogMessage(CUPSD_LOG_DEBUG
, "cupsdSendError: %d code=%d (%s)",
1949 con
->http
.fd
, code
, httpStatus(code
));
1952 * To work around bugs in some proxies, don't use Keep-Alive for some
1956 if (code
>= HTTP_BAD_REQUEST
)
1957 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1960 * Send an error message back to the client. If the error code is a
1961 * 400 or 500 series, make sure the message contains some text, too!
1964 if (!cupsdSendHeader(con
, code
, NULL
))
1968 if (code
== HTTP_UPGRADE_REQUIRED
)
1969 if (httpPrintf(HTTP(con
), "Connection: Upgrade\r\n") < 0)
1972 if (httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n") < 0)
1974 #endif /* HAVE_SSL */
1976 if ((con
->http
.version
>= HTTP_1_1
&& !con
->http
.keep_alive
) ||
1977 (code
>= HTTP_BAD_REQUEST
&& code
!= HTTP_UPGRADE_REQUIRED
))
1979 if (httpPrintf(HTTP(con
), "Connection: close\r\n") < 0)
1983 if (code
>= HTTP_BAD_REQUEST
)
1986 * Send a human-readable error message.
1989 char message
[1024]; /* Message for user */
1990 const char *text
; /* Status-specific text */
1992 if (code
== HTTP_UNAUTHORIZED
)
1993 text
= _cupsLangString(con
->language
,
1994 _("Enter your username and password or the "
1995 "root username and password to access this "
1997 else if (code
== HTTP_UPGRADE_REQUIRED
)
1998 text
= _cupsLangString(con
->language
,
1999 _("You must use a https: URL to access this "
2004 snprintf(message
, sizeof(message
),
2005 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" "
2006 "\"http://www.w3.org/TR/REC-html40/loose.dtd\">\n"
2009 "\t<META HTTP-EQUIV=\"Content-Type\" "
2010 "CONTENT=\"text/html; charset=utf-8\">\n"
2011 "\t<TITLE>%d %s</TITLE>\n"
2012 "\t<LINK REL=\"STYLESHEET\" TYPE=\"text/css\" "
2013 "HREF=\"/cups.css\">\n"
2020 code
, httpStatus(code
), code
, httpStatus(code
), text
);
2022 if (httpPrintf(HTTP(con
), "Content-Type: text/html; charset=utf-8\r\n") < 0)
2024 if (httpPrintf(HTTP(con
), "Content-Length: %d\r\n",
2025 (int)strlen(message
)) < 0)
2027 if (httpPrintf(HTTP(con
), "\r\n") < 0)
2029 if (httpPrintf(HTTP(con
), "%s", message
) < 0)
2032 else if (httpPrintf(HTTP(con
), "\r\n") < 0)
2035 con
->http
.state
= HTTP_WAITING
;
2042 * 'cupsdSendHeader()' - Send an HTTP request.
2045 int /* O - 1 on success, 0 on failure */
2046 cupsdSendHeader(cupsd_client_t
*con
, /* I - Client to send to */
2047 http_status_t code
, /* I - HTTP status code */
2048 char *type
) /* I - MIME type of document */
2051 * Send the HTTP status header...
2054 if (httpPrintf(HTTP(con
), "HTTP/%d.%d %d %s\r\n", con
->http
.version
/ 100,
2055 con
->http
.version
% 100, code
, httpStatus(code
)) < 0)
2058 if (code
== HTTP_CONTINUE
)
2061 * 100-continue doesn't send any headers...
2064 if (httpPrintf(HTTP(con
), "\r\n") < 0)
2070 if (httpPrintf(HTTP(con
), "Date: %s\r\n", httpGetDateString(time(NULL
))) < 0)
2073 if (httpPrintf(HTTP(con
), "Server: %s\r\n", ServerHeader
) < 0)
2075 if (con
->http
.keep_alive
&& con
->http
.version
>= HTTP_1_0
)
2077 if (httpPrintf(HTTP(con
), "Connection: Keep-Alive\r\n") < 0)
2079 if (httpPrintf(HTTP(con
), "Keep-Alive: timeout=%d\r\n",
2080 KeepAliveTimeout
) < 0)
2083 if (code
== HTTP_METHOD_NOT_ALLOWED
)
2084 if (httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST\r\n") < 0)
2087 if (code
== HTTP_UNAUTHORIZED
)
2089 int auth_type
; /* Authentication type */
2092 if (!con
->best
|| con
->best
->type
== AUTH_NONE
)
2093 auth_type
= DefaultAuthType
;
2095 auth_type
= con
->best
->type
;
2097 if (auth_type
!= AUTH_DIGEST
)
2099 if (httpPrintf(HTTP(con
),
2100 "WWW-Authenticate: Basic realm=\"CUPS\"\r\n") < 0)
2105 if (httpPrintf(HTTP(con
),
2106 "WWW-Authenticate: Digest realm=\"CUPS\", nonce=\"%s\"\r\n",
2107 con
->http
.hostname
) < 0)
2112 if (con
->language
&& strcmp(con
->language
->language
, "C"))
2114 if (httpPrintf(HTTP(con
), "Content-Language: %s\r\n",
2115 con
->language
->language
) < 0)
2121 if (!strcmp(type
, "text/html"))
2123 if (httpPrintf(HTTP(con
),
2124 "Content-Type: text/html; charset=utf-8\r\n") < 0)
2127 else if (httpPrintf(HTTP(con
), "Content-Type: %s\r\n", type
) < 0)
2136 * 'cupsdUpdateCGI()' - Read status messages from CGI scripts and programs.
2140 cupsdUpdateCGI(void)
2142 char *ptr
, /* Pointer to end of line in buffer */
2143 message
[1024]; /* Pointer to message text */
2144 int loglevel
; /* Log level for message */
2147 while ((ptr
= cupsdStatBufUpdate(CGIStatusBuffer
, &loglevel
,
2148 message
, sizeof(message
))) != NULL
)
2149 if (!strchr(CGIStatusBuffer
->buffer
, '\n'))
2152 if (ptr
== NULL
&& errno
)
2155 * Fatal error on pipe - should never happen!
2158 cupsdLogMessage(CUPSD_LOG_CRIT
,
2159 "cupsdUpdateCGI: error reading from CGI error pipe - %s",
2166 * 'cupsdWriteClient()' - Write data to a client as needed.
2169 int /* O - 1 if success, 0 if fail */
2170 cupsdWriteClient(cupsd_client_t
*con
) /* I - Client connection */
2172 int bytes
; /* Number of bytes written */
2173 char buf
[16385]; /* Data buffer */
2174 char *bufptr
; /* Pointer into buffer */
2175 ipp_state_t ipp_state
; /* IPP state value */
2179 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2180 "cupsdWriteClient(con=%p) %d response=%p, file=%d "
2181 "pipe_pid=%d state=%d",
2182 con
, con
->http
.fd
, con
->response
, con
->file
, con
->pipe_pid
,
2186 if (con
->http
.state
!= HTTP_GET_SEND
&&
2187 con
->http
.state
!= HTTP_POST_SEND
)
2190 if (con
->response
!= NULL
)
2192 ipp_state
= ippWrite(&(con
->http
), con
->response
);
2193 bytes
= ipp_state
!= IPP_ERROR
&& ipp_state
!= IPP_DATA
;
2195 else if ((bytes
= read(con
->file
, buf
, sizeof(buf
) - 1)) > 0)
2197 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2198 "cupsdWriteClient: Read %d bytes from file %d...",
2201 if (con
->pipe_pid
&& !con
->got_fields
)
2204 * Inspect the data for Content-Type and other fields.
2209 for (bufptr
= buf
; !con
->got_fields
&& *bufptr
; bufptr
++)
2210 if (*bufptr
== '\n')
2213 * Send line to client...
2216 if (bufptr
> buf
&& bufptr
[-1] == '\r')
2220 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "Script header: %s", buf
);
2222 if (!con
->sent_header
)
2225 * Handle redirection and CGI status codes...
2228 if (!strncasecmp(buf
, "Location:", 9))
2229 cupsdSendHeader(con
, HTTP_SEE_OTHER
, NULL
);
2230 else if (!strncasecmp(buf
, "Status:", 7))
2231 cupsdSendError(con
, atoi(buf
+ 7));
2234 cupsdSendHeader(con
, HTTP_OK
, NULL
);
2236 if (con
->http
.version
== HTTP_1_1
)
2238 con
->http
.data_encoding
= HTTP_ENCODE_CHUNKED
;
2240 if (httpPrintf(HTTP(con
), "Transfer-Encoding: chunked\r\n") < 0)
2245 con
->sent_header
= 1;
2248 if (strncasecmp(buf
, "Status:", 7))
2249 httpPrintf(HTTP(con
), "%s\r\n", buf
);
2251 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdWriteClient: %d %s",
2258 bytes
-= (bufptr
- buf
);
2259 memmove(buf
, bufptr
, bytes
+ 1);
2263 * See if the line was empty...
2266 if (con
->field_col
== 0)
2267 con
->got_fields
= 1;
2271 else if (*bufptr
!= '\r')
2274 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2275 "cupsdWriteClient: %d bytes=%d, got_fields=%d",
2276 con
->http
.fd
, bytes
, con
->got_fields
);
2278 if (bytes
> 0 && !con
->got_fields
)
2281 * Remaining text needs to go out...
2284 httpPrintf(HTTP(con
), "%s", buf
);
2286 con
->http
.activity
= time(NULL
);
2289 else if (bytes
== 0)
2290 con
->http
.activity
= time(NULL
);
2295 if (httpWrite2(HTTP(con
), buf
, bytes
) < 0)
2297 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2298 "cupsdWriteClient: %d Write of %d bytes failed!",
2299 con
->http
.fd
, bytes
);
2301 cupsdCloseClient(con
);
2305 con
->bytes
+= bytes
;
2307 if (con
->http
.state
== HTTP_WAITING
)
2314 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdWriteClient: %d bytes < 0",
2317 cupsdLogRequest(con
, HTTP_OK
);
2319 httpFlushWrite(HTTP(con
));
2321 if (con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
)
2323 if (httpPrintf(HTTP(con
), "0\r\n\r\n") < 0)
2325 cupsdCloseClient(con
);
2330 con
->http
.state
= HTTP_WAITING
;
2332 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2333 "cupsdWriteClient: Removing fd %d from OutputSet...",
2336 FD_CLR(con
->http
.fd
, OutputSet
);
2340 if (FD_ISSET(con
->file
, InputSet
))
2342 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2343 "cupsdWriteClient: Removing fd %d from InputSet...",
2345 FD_CLR(con
->file
, InputSet
);
2349 cupsdEndProcess(con
->pipe_pid
, 0);
2351 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2352 "cupsdWriteClient: %d Closing data file %d.",
2353 con
->http
.fd
, con
->file
);
2362 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2363 "cupsdWriteClient: %d Removing temp file %s",
2364 con
->http
.fd
, con
->filename
);
2365 unlink(con
->filename
);
2366 cupsdClearString(&con
->filename
);
2369 if (con
->request
!= NULL
)
2371 ippDelete(con
->request
);
2372 con
->request
= NULL
;
2375 if (con
->response
!= NULL
)
2377 ippDelete(con
->response
);
2378 con
->response
= NULL
;
2381 cupsdClearString(&con
->command
);
2382 cupsdClearString(&con
->options
);
2384 if (!con
->http
.keep_alive
)
2386 cupsdCloseClient(con
);
2392 con
->file_ready
= 0;
2394 if (con
->pipe_pid
&& !FD_ISSET(con
->file
, InputSet
))
2396 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2397 "cupsdWriteClient: Adding fd %d to InputSet...",
2399 FD_SET(con
->file
, InputSet
);
2403 con
->http
.activity
= time(NULL
);
2410 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
2413 static int /* O - 1 if modified since */
2415 cupsd_client_t
*con
, /* I - Client connection */
2416 struct stat
*filestats
) /* I - File information */
2418 char *ptr
; /* Pointer into field */
2419 time_t date
; /* Time/date value */
2420 off_t size
; /* Size/length value */
2425 ptr
= con
->http
.fields
[HTTP_FIELD_IF_MODIFIED_SINCE
];
2430 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2431 "check_if_modified: %d If-Modified-Since=\"%s\"",
2434 while (*ptr
!= '\0')
2436 while (isspace(*ptr
) || *ptr
== ';')
2439 if (strncasecmp(ptr
, "length=", 7) == 0)
2442 size
= strtoll(ptr
, NULL
, 10);
2444 while (isdigit(*ptr
))
2447 else if (isalpha(*ptr
))
2449 date
= httpGetDateTime(ptr
);
2450 while (*ptr
!= '\0' && *ptr
!= ';')
2455 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2456 "check_if_modified: %d sizes=" CUPS_LLFMT
","
2457 CUPS_LLFMT
" dates=%d,%d",
2458 con
->http
.fd
, CUPS_LLCAST size
,
2459 CUPS_LLCAST filestats
->st_size
, (int)date
,
2460 (int)filestats
->st_mtime
);
2462 return ((size
!= filestats
->st_size
&& size
!= 0) ||
2463 (date
< filestats
->st_mtime
&& date
!= 0) ||
2464 (size
== 0 && date
== 0));
2469 * 'encrypt_client()' - Enable encryption for the client...
2472 static int /* O - 1 on success, 0 on error */
2473 encrypt_client(cupsd_client_t
*con
) /* I - Client to encrypt */
2476 SSL_CTX
*context
; /* Context for encryption */
2477 SSL
*conn
; /* Connection for encryption */
2478 unsigned long error
; /* Error code */
2482 * Create the SSL context and accept the connection...
2485 context
= SSL_CTX_new(SSLv23_server_method());
2487 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
2488 SSL_CTX_use_PrivateKey_file(context
, ServerKey
, SSL_FILETYPE_PEM
);
2489 SSL_CTX_use_certificate_file(context
, ServerCertificate
, SSL_FILETYPE_PEM
);
2491 conn
= SSL_new(context
);
2493 SSL_set_fd(conn
, con
->http
.fd
);
2494 if (SSL_accept(conn
) != 1)
2496 cupsdLogMessage(CUPSD_LOG_ERROR
,
2497 "encrypt_client: Unable to encrypt connection from %s!",
2498 con
->http
.hostname
);
2500 while ((error
= ERR_get_error()) != 0)
2501 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s",
2502 ERR_error_string(error
, NULL
));
2504 SSL_CTX_free(context
);
2509 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2510 "encrypt_client: %d Connection from %s now encrypted.",
2511 con
->http
.fd
, con
->http
.hostname
);
2513 con
->http
.tls
= conn
;
2516 #elif defined(HAVE_GNUTLS)
2517 http_tls_t
*conn
; /* TLS session object */
2518 int error
; /* Error code */
2519 gnutls_certificate_server_credentials
*credentials
;
2520 /* TLS credentials */
2524 * Verify that we have a certificate...
2527 if (access(ServerKey
, 0) || access(ServerCertificate
, 0))
2530 * Nope, make a self-signed certificate...
2537 * Create the SSL object and perform the SSL handshake...
2540 conn
= (http_tls_t
*)malloc(sizeof(gnutls_session
));
2545 credentials
= (gnutls_certificate_server_credentials
*)
2546 malloc(sizeof(gnutls_certificate_server_credentials
));
2547 if (credentials
== NULL
)
2549 cupsdLogMessage(CUPSD_LOG_ERROR
,
2550 "encrypt_client: Unable to encrypt connection from %s!",
2551 con
->http
.hostname
);
2552 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s", strerror(errno
));
2558 gnutls_certificate_allocate_credentials(credentials
);
2559 gnutls_certificate_set_x509_key_file(*credentials
, ServerCertificate
,
2560 ServerKey
, GNUTLS_X509_FMT_PEM
);
2562 gnutls_init(&(conn
->session
), GNUTLS_SERVER
);
2563 gnutls_set_default_priority(conn
->session
);
2564 gnutls_credentials_set(conn
->session
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
2565 gnutls_transport_set_ptr(conn
->session
,
2566 (gnutls_transport_ptr
)((long)con
->http
.fd
));
2568 error
= gnutls_handshake(conn
->session
);
2570 if (error
!= GNUTLS_E_SUCCESS
)
2572 cupsdLogMessage(CUPSD_LOG_ERROR
,
2573 "encrypt_client: Unable to encrypt connection from %s!",
2574 con
->http
.hostname
);
2575 cupsdLogMessage(CUPSD_LOG_ERROR
, "encrypt_client: %s",
2576 gnutls_strerror(error
));
2578 gnutls_deinit(conn
->session
);
2579 gnutls_certificate_free_credentials(*credentials
);
2585 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2586 "encrypt_client: %d Connection from %s now encrypted.",
2587 con
->http
.fd
, con
->http
.hostname
);
2589 conn
->credentials
= credentials
;
2590 con
->http
.tls
= conn
;
2593 #elif defined(HAVE_CDSASSL)
2594 OSStatus error
; /* Error info */
2595 SSLContextRef conn
; /* New connection */
2596 CFArrayRef certificatesArray
; /* Array containing certificates */
2597 int allowExpired
; /* Allow expired certificates? */
2598 int allowAnyRoot
; /* Allow any root certificate? */
2602 error
= SSLNewContext(true, &conn
);
2606 certificatesArray
= get_cdsa_server_certs();
2608 if (!certificatesArray
)
2610 cupsdLogMessage(CUPSD_LOG_ERROR
,
2611 "EncryptClient: Could not find signing key in keychain "
2612 "\"%s\"", ServerCertificate
);
2613 error
= errSSLBadCert
; /* errSSLBadConfiguration is a better choice, but not available on 10.2.x */
2617 error
= SSLSetIOFuncs(conn
, _httpReadCDSA
, _httpWriteCDSA
);
2620 error
= SSLSetProtocolVersion(conn
, kSSLProtocol3
);
2623 error
= SSLSetConnection(conn
, (SSLConnectionRef
)con
->http
.fd
);
2626 error
= SSLSetPeerDomainName(conn
, ServerName
, strlen(ServerName
) + 1);
2628 /* have to do these options before setting server certs */
2629 if (!error
&& allowExpired
)
2630 error
= SSLSetAllowsExpiredCerts(conn
, true);
2632 if (!error
&& allowAnyRoot
)
2633 error
= SSLSetAllowsAnyRoot(conn
, true);
2636 error
= SSLSetCertificate(conn
, certificatesArray
);
2638 if (certificatesArray
)
2640 CFRelease(certificatesArray
);
2641 certificatesArray
= NULL
;
2647 * Perform SSL/TLS handshake
2650 while ((error
= SSLHandshake(conn
)) == errSSLWouldBlock
)
2656 cupsdLogMessage(CUPSD_LOG_ERROR
,
2657 "encrypt_client: Unable to encrypt connection from %s!",
2658 con
->http
.hostname
);
2660 cupsdLogMessage(CUPSD_LOG_ERROR
,
2661 "encrypt_client: CDSA error code is %d", (int)error
);
2663 con
->http
.error
= error
;
2664 con
->http
.status
= HTTP_ERROR
;
2667 SSLDisposeContext(conn
);
2672 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2673 "encrypt_client: %d Connection from %s now encrypted.",
2674 con
->http
.fd
, con
->http
.hostname
);
2676 con
->http
.tls
= conn
;
2681 #endif /* HAVE_LIBSSL */
2687 * 'get_cdsa_server_certs()' - Convert a keychain name into the CFArrayRef
2688 * required by SSLSetCertificate.
2690 * For now we assumes that there is exactly one SecIdentity in the
2691 * keychain - i.e. there is exactly one matching cert/private key pair.
2692 * In the future we will search a keychain for a SecIdentity matching a
2693 * specific criteria. We also skip the operation of adding additional
2694 * non-signing certs from the keychain to the CFArrayRef.
2696 * To create a self-signed certificate for testing use the certtool.
2697 * Executing the following as root will do it:
2699 * certtool c k=/Library/Keychains/System.keychain
2702 static CFArrayRef
/* O - Array of certificates */
2703 get_cdsa_server_certs(void)
2705 OSStatus err
; /* Error info */
2706 SecKeychainRef kcRef
; /* Keychain reference */
2707 SecIdentitySearchRef srchRef
; /* Search reference */
2708 SecIdentityRef identity
; /* Identity */
2709 CFArrayRef ca
; /* Certificate array */
2716 err
= SecKeychainOpen(ServerCertificate
, &kcRef
);
2719 cupsdLogMessage(CUPSD_LOG_ERROR
, "Cannot open keychain \"%s\", error %d.",
2720 ServerCertificate
, (int)err
);
2724 * Search for "any" identity matching specified key use;
2725 * in this app, we expect there to be exactly one.
2728 err
= SecIdentitySearchCreate(kcRef
, CSSM_KEYUSE_SIGN
, &srchRef
);
2731 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2732 "Cannot find signing key in keychain \"%s\", error %d",
2733 ServerCertificate
, (int)err
);
2736 err
= SecIdentitySearchCopyNext(srchRef
, &identity
);
2739 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2740 "Cannot find signing key in keychain \"%s\", error %d",
2741 ServerCertificate
, (int)err
);
2744 if (CFGetTypeID(identity
) != SecIdentityGetTypeID())
2745 cupsdLogMessage(CUPSD_LOG_ERROR
,
2746 "SecIdentitySearchCopyNext CFTypeID failure!");
2750 * Found one. Place it in a CFArray.
2751 * TBD: snag other (non-identity) certs from keychain and add them
2755 ca
= CFArrayCreate(NULL
, (const void **)&identity
, 1, &kCFTypeArrayCallBacks
);
2758 cupsdLogMessage(CUPSD_LOG_ERROR
, "CFArrayCreate error");
2761 CFRelease(identity
);
2772 #endif /* HAVE_CDSASSL */
2776 * 'get_file()' - Get a filename and state info.
2779 static char * /* O - Real filename */
2780 get_file(cupsd_client_t
*con
, /* I - Client connection */
2781 struct stat
*filestats
, /* O - File information */
2782 char *filename
, /* IO - Filename buffer */
2783 int len
) /* I - Buffer length */
2785 int status
; /* Status of filesystem calls */
2786 char *ptr
; /* Pointer info filename */
2787 int plen
; /* Remaining length after pointer */
2791 * Need to add DocumentRoot global...
2794 if (!strncmp(con
->uri
, "/ppd/", 5))
2795 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
);
2796 else if (!strncmp(con
->uri
, "/admin/conf/", 12))
2797 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
+ 11);
2798 else if (!strncmp(con
->uri
, "/admin/log/", 11))
2800 if (!strcmp(con
->uri
+ 11, "access_log") && AccessLog
[0] == '/')
2801 strlcpy(filename
, AccessLog
, len
);
2802 else if (!strcmp(con
->uri
+ 11, "error_log") && ErrorLog
[0] == '/')
2803 strlcpy(filename
, ErrorLog
, len
);
2804 else if (!strcmp(con
->uri
+ 11, "page_log") && PageLog
[0] == '/')
2805 strlcpy(filename
, PageLog
, len
);
2809 else if (con
->language
!= NULL
)
2810 snprintf(filename
, len
, "%s/%s%s", DocumentRoot
, con
->language
->language
,
2813 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
2815 if ((ptr
= strchr(filename
, '?')) != NULL
)
2819 * Grab the status for this language; if there isn't a language-specific file
2820 * then fallback to the default one...
2823 if ((status
= stat(filename
, filestats
)) != 0 && con
->language
!= NULL
)
2826 * Drop the language prefix and try the current directory...
2829 if (strncmp(con
->uri
, "/ppd/", 5) &&
2830 strncmp(con
->uri
, "/admin/conf/", 12) &&
2831 strncmp(con
->uri
, "/admin/log/", 11))
2833 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
2835 if ((ptr
= strchr(filename
, '?')) != NULL
)
2838 status
= stat(filename
, filestats
);
2843 * If we're found a directory, get the index.html file instead...
2846 if (!status
&& S_ISDIR(filestats
->st_mode
))
2848 if (filename
[strlen(filename
) - 1] != '/')
2849 strlcat(filename
, "/", len
);
2851 ptr
= filename
+ strlen(filename
);
2852 plen
= len
- (ptr
- filename
);
2854 strlcpy(ptr
, "index.html", plen
);
2855 status
= stat(filename
, filestats
);
2860 strlcpy(ptr
, "index.class", plen
);
2861 status
= stat(filename
, filestats
);
2863 #endif /* HAVE_JAVA */
2868 strlcpy(ptr
, "index.pl", plen
);
2869 status
= stat(filename
, filestats
);
2871 #endif /* HAVE_PERL */
2876 strlcpy(ptr
, "index.php", plen
);
2877 status
= stat(filename
, filestats
);
2879 #endif /* HAVE_PHP */
2884 strlcpy(ptr
, "index.pyc", plen
);
2885 status
= stat(filename
, filestats
);
2890 strlcpy(ptr
, "index.py", plen
);
2891 status
= stat(filename
, filestats
);
2893 #endif /* HAVE_PYTHON */
2896 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "get_file: %d filename=%s size=%d",
2897 con
->http
.fd
, filename
,
2898 status
? -1 : (int)filestats
->st_size
);
2901 con
->http
.data_remaining
= (int)filestats
->st_size
;
2911 * 'install_conf_file()' - Install a configuration file.
2914 static http_status_t
/* O - Status */
2915 install_conf_file(cupsd_client_t
*con
) /* I - Connection */
2917 cups_file_t
*in
, /* Input file */
2918 *out
; /* Output file */
2919 char buffer
[1024]; /* Copy buffer */
2920 int bytes
; /* Number of bytes */
2921 char conffile
[1024], /* Configuration filename */
2922 newfile
[1024], /* New config filename */
2923 oldfile
[1024]; /* Old config filename */
2924 struct stat confinfo
; /* Config file info */
2928 * First construct the filenames...
2931 snprintf(conffile
, sizeof(conffile
), "%s%s", ServerRoot
, con
->uri
+ 11);
2932 snprintf(newfile
, sizeof(newfile
), "%s%s.N", ServerRoot
, con
->uri
+ 11);
2933 snprintf(oldfile
, sizeof(oldfile
), "%s%s.O", ServerRoot
, con
->uri
+ 11);
2935 cupsdLogMessage(CUPSD_LOG_INFO
, "Installing config file \"%s\"...", conffile
);
2938 * Get the owner, group, and permissions of the configuration file.
2939 * If it doesn't exist, assign it to the User and Group in the
2940 * cupsd.conf file with mode 0640 permissions.
2943 if (stat(conffile
, &confinfo
))
2945 confinfo
.st_uid
= User
;
2946 confinfo
.st_gid
= Group
;
2947 confinfo
.st_mode
= ConfigFilePerm
;
2951 * Open the request file and new config file...
2954 if ((in
= cupsFileOpen(con
->filename
, "rb")) == NULL
)
2956 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open request file \"%s\" - %s",
2957 con
->filename
, strerror(errno
));
2958 return (HTTP_SERVER_ERROR
);
2961 if ((out
= cupsFileOpen(newfile
, "wb")) == NULL
)
2964 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open config file \"%s\" - %s",
2965 newfile
, strerror(errno
));
2966 return (HTTP_SERVER_ERROR
);
2969 fchmod(cupsFileNumber(out
), confinfo
.st_mode
);
2970 fchown(cupsFileNumber(out
), confinfo
.st_uid
, confinfo
.st_gid
);
2973 * Copy from the request to the new config file...
2976 while ((bytes
= cupsFileRead(in
, buffer
, sizeof(buffer
))) > 0)
2977 if (cupsFileWrite(out
, buffer
, bytes
) < bytes
)
2979 cupsdLogMessage(CUPSD_LOG_ERROR
,
2980 "Unable to copy to config file \"%s\" - %s",
2981 newfile
, strerror(errno
));
2987 return (HTTP_SERVER_ERROR
);
2991 * Close the files...
2995 if (cupsFileClose(out
))
2997 cupsdLogMessage(CUPSD_LOG_ERROR
,
2998 "Error file closing config file \"%s\" - %s",
2999 newfile
, strerror(errno
));
3003 return (HTTP_SERVER_ERROR
);
3007 * Remove the request file...
3010 unlink(con
->filename
);
3011 cupsdClearString(&con
->filename
);
3014 * Unlink the old backup, rename the current config file to the backup
3015 * filename, and rename the new config file to the config file name...
3018 if (unlink(oldfile
))
3019 if (errno
!= ENOENT
)
3021 cupsdLogMessage(CUPSD_LOG_ERROR
,
3022 "Unable to remove backup config file \"%s\" - %s",
3023 oldfile
, strerror(errno
));
3027 return (HTTP_SERVER_ERROR
);
3030 if (rename(conffile
, oldfile
))
3031 if (errno
!= ENOENT
)
3033 cupsdLogMessage(CUPSD_LOG_ERROR
,
3034 "Unable to rename old config file \"%s\" - %s",
3035 conffile
, strerror(errno
));
3039 return (HTTP_SERVER_ERROR
);
3042 if (rename(newfile
, conffile
))
3044 cupsdLogMessage(CUPSD_LOG_ERROR
,
3045 "Unable to rename new config file \"%s\" - %s",
3046 newfile
, strerror(errno
));
3048 rename(oldfile
, conffile
);
3051 return (HTTP_SERVER_ERROR
);
3055 * If the cupsd.conf file was updated, set the NeedReload flag...
3058 if (!strcmp(con
->uri
, "/admin/conf/cupsd.conf"))
3059 NeedReload
= RELOAD_CUPSD
;
3061 NeedReload
= RELOAD_ALL
;
3063 ReloadTime
= time(NULL
);
3066 * Return that the file was created successfully...
3069 return (HTTP_CREATED
);
3074 * 'is_cgi()' - Is the resource a CGI script/program?
3077 static int /* O - 1 = CGI, 0 = file */
3078 is_cgi(cupsd_client_t
*con
, /* I - Client connection */
3079 const char *filename
, /* I - Real filename */
3080 struct stat
*filestats
, /* I - File information */
3081 mime_type_t
*type
) /* I - MIME type */
3083 const char *options
; /* Options on URL */
3086 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3087 "is_cgi(con=%p, filename=\"%s\", filestats=%p, type=%s/%s)\n",
3088 con
, filename
, filestats
, type
? type
->super
: "unknown",
3089 type
? type
->type
: "unknown");
3092 * Get the options, if any...
3095 if ((options
= strchr(con
->uri
, '?')) != NULL
)
3099 * Check for known types...
3102 if (!type
|| strcasecmp(type
->super
, "application"))
3104 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "is_cgi: Returning 0...");
3108 if (!strcasecmp(type
->type
, "x-httpd-cgi") &&
3109 (filestats
->st_mode
& 0111))
3112 * "application/x-httpd-cgi" is a CGI script.
3115 cupsdSetString(&con
->command
, filename
);
3117 filename
= strrchr(filename
, '/') + 1; /* Filename always absolute */
3119 cupsdSetString(&con
->options
, options
);
3121 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3122 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3123 con
->command
, con
->options
);
3128 else if (!strcasecmp(type
->type
, "x-httpd-java"))
3131 * "application/x-httpd-java" is a Java servlet.
3134 cupsdSetString(&con
->command
, CUPS_JAVA
);
3137 cupsdSetStringf(&con
->options
, "%s %s", filename
, options
);
3139 cupsdSetString(&con
->options
, filename
);
3141 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3142 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3143 con
->command
, con
->options
);
3147 #endif /* HAVE_JAVA */
3149 else if (!strcasecmp(type
->type
, "x-httpd-perl"))
3152 * "application/x-httpd-perl" is a Perl page.
3155 cupsdSetString(&con
->command
, CUPS_PERL
);
3158 cupsdSetStringf(&con
->options
, "%s %s", filename
, options
);
3160 cupsdSetString(&con
->options
, filename
);
3162 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3163 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3164 con
->command
, con
->options
);
3168 #endif /* HAVE_PERL */
3170 else if (!strcasecmp(type
->type
, "x-httpd-php"))
3173 * "application/x-httpd-php" is a PHP page.
3176 cupsdSetString(&con
->command
, CUPS_PHP
);
3179 cupsdSetStringf(&con
->options
, "%s %s", filename
, options
);
3181 cupsdSetString(&con
->options
, filename
);
3183 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3184 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3185 con
->command
, con
->options
);
3189 #endif /* HAVE_PHP */
3191 else if (!strcasecmp(type
->type
, "x-httpd-python"))
3194 * "application/x-httpd-python" is a Python page.
3197 cupsdSetString(&con
->command
, CUPS_PYTHON
);
3200 cupsdSetStringf(&con
->options
, "%s %s", filename
, options
);
3202 cupsdSetString(&con
->options
, filename
);
3204 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3205 "is_cgi: Returning 1 with command=\"%s\" and options=\"%s\"",
3206 con
->command
, con
->options
);
3210 #endif /* HAVE_PYTHON */
3212 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "is_cgi: Returning 0...");
3219 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
3222 static int /* O - 0 if relative, 1 if absolute */
3223 is_path_absolute(const char *path
) /* I - Input path */
3226 * Check for a leading slash...
3233 * Check for "/.." in the path...
3236 while ((path
= strstr(path
, "/..")) != NULL
)
3238 if (!path
[3] || path
[3] == '/')
3245 * If we haven't found any relative paths, return 1 indicating an
3255 * 'make_certificate()' - Make a self-signed SSL/TLS certificate.
3259 make_certificate(void)
3261 gnutls_x509_crt crt
; /* Self-signed certificate */
3262 gnutls_x509_privkey key
; /* Encryption key */
3263 cups_lang_t
*language
; /* Default language info */
3264 cups_file_t
*fp
; /* Key/cert file */
3265 unsigned char buffer
[8192]; /* Buffer for x509 data */
3266 size_t bytes
; /* Number of bytes of data */
3267 unsigned char serial
[4]; /* Serial number buffer */
3268 time_t curtime
; /* Current time */
3269 int result
; /* Result of GNU TLS calls */
3273 * Create the encryption key...
3276 cupsdLogMessage(CUPSD_LOG_INFO
, "Generating server key...");
3278 gnutls_x509_privkey_init(&key
);
3279 gnutls_x509_privkey_generate(key
, GNUTLS_PK_RSA
, 2048, 0);
3285 bytes
= sizeof(buffer
);
3287 if ((result
= gnutls_x509_privkey_export(key
, GNUTLS_X509_FMT_PEM
,
3288 buffer
, &bytes
)) < 0)
3290 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to export server key - %s",
3291 gnutls_strerror(result
));
3292 gnutls_x509_privkey_deinit(key
);
3295 else if ((fp
= cupsFileOpen(ServerKey
, "w")) != NULL
)
3297 cupsFileWrite(fp
, (char *)buffer
, bytes
);
3300 cupsdLogMessage(CUPSD_LOG_INFO
, "Created server key file \"%s\"...",
3305 cupsdLogMessage(CUPSD_LOG_ERROR
,
3306 "Unable to create server key file \"%s\" - %s",
3307 ServerKey
, strerror(errno
));
3308 gnutls_x509_privkey_deinit(key
);
3313 * Create the self-signed certificate...
3316 cupsdLogMessage(CUPSD_LOG_INFO
, "Generating self-signed certificate...");
3318 language
= cupsLangDefault();
3319 curtime
= time(NULL
);
3320 serial
[0] = curtime
>> 24;
3321 serial
[1] = curtime
>> 16;
3322 serial
[2] = curtime
>> 8;
3323 serial
[3] = curtime
;
3325 gnutls_x509_crt_init(&crt
);
3326 if (strlen(language
->language
) == 5)
3327 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
3328 language
->language
+ 3, 2);
3330 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COUNTRY_NAME
, 0,
3332 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_COMMON_NAME
, 0,
3333 ServerName
, strlen(ServerName
));
3334 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATION_NAME
, 0,
3335 ServerName
, strlen(ServerName
));
3336 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_ORGANIZATIONAL_UNIT_NAME
,
3338 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_STATE_OR_PROVINCE_NAME
, 0,
3340 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_X520_LOCALITY_NAME
, 0,
3342 gnutls_x509_crt_set_dn_by_oid(crt
, GNUTLS_OID_PKCS9_EMAIL
, 0,
3343 ServerAdmin
, strlen(ServerAdmin
));
3344 gnutls_x509_crt_set_key(crt
, key
);
3345 gnutls_x509_crt_set_serial(crt
, serial
, sizeof(serial
));
3346 gnutls_x509_crt_set_activation_time(crt
, curtime
);
3347 gnutls_x509_crt_set_expiration_time(crt
, curtime
+ 10 * 365 * 86400);
3348 gnutls_x509_crt_set_ca_status(crt
, 0);
3349 gnutls_x509_crt_set_subject_alternative_name(crt
, GNUTLS_SAN_DNSNAME
,
3351 gnutls_x509_crt_set_key_purpose_oid(crt
, GNUTLS_KP_TLS_WWW_SERVER
, 0);
3352 gnutls_x509_crt_set_key_usage(crt
, GNUTLS_KEY_KEY_ENCIPHERMENT
);
3353 gnutls_x509_crt_set_version(crt
, 3);
3355 bytes
= sizeof(buffer
);
3356 if (gnutls_x509_crt_get_key_id(crt
, 0, buffer
, &bytes
) >= 0)
3357 gnutls_x509_crt_set_subject_key_id(crt
, buffer
, bytes
);
3359 gnutls_x509_crt_sign(crt
, crt
, key
);
3365 bytes
= sizeof(buffer
);
3366 if ((result
= gnutls_x509_crt_export(crt
, GNUTLS_X509_FMT_PEM
,
3367 buffer
, &bytes
)) < 0)
3368 cupsdLogMessage(CUPSD_LOG_ERROR
,
3369 "Unable to export server certificate - %s",
3370 gnutls_strerror(result
));
3371 else if ((fp
= cupsFileOpen(ServerCertificate
, "w")) != NULL
)
3373 cupsFileWrite(fp
, (char *)buffer
, bytes
);
3376 cupsdLogMessage(CUPSD_LOG_INFO
,
3377 "Created 10-year server certificate file \"%s\"...",
3381 cupsdLogMessage(CUPSD_LOG_ERROR
,
3382 "Unable to create server certificate file \"%s\" - %s",
3383 ServerCertificate
, strerror(errno
));
3389 gnutls_x509_crt_deinit(crt
);
3390 gnutls_x509_privkey_deinit(key
);
3392 #endif /* HAVE_GNUTLS */
3396 * 'pipe_command()' - Pipe the output of a command to the remote client.
3399 static int /* O - Process ID */
3400 pipe_command(cupsd_client_t
*con
, /* I - Client connection */
3401 int infile
, /* I - Standard input for command */
3402 int *outfile
, /* O - Standard output for command */
3403 char *command
, /* I - Command to run */
3404 char *options
, /* I - Options for command */
3405 int root
) /* I - Run as root? */
3407 int i
; /* Looping var */
3408 int pid
; /* Process ID */
3409 char *commptr
, /* Command string pointer */
3410 commch
; /* Command string character */
3411 char *uriptr
; /* URI string pointer */
3412 int fds
[2]; /* Pipe FDs */
3413 int argc
; /* Number of arguments */
3414 int envc
; /* Number of environment variables */
3415 char argbuf
[10240], /* Argument buffer */
3416 *argv
[100], /* Argument strings */
3417 *envp
[MAX_ENV
+ 17]; /* Environment variables */
3418 char content_length
[1024], /* CONTENT_LENGTH environment variable */
3419 content_type
[1024], /* CONTENT_TYPE environment variable */
3420 http_cookie
[32768], /* HTTP_COOKIE environment variable */
3421 http_user_agent
[1024], /* HTTP_USER_AGENT environment variable */
3422 lang
[1024], /* LANG environment variable */
3423 path_info
[1024], /* PATH_INFO environment variable */
3424 *query_string
, /* QUERY_STRING env variable */
3425 remote_addr
[1024], /* REMOTE_ADDR environment variable */
3426 remote_host
[1024], /* REMOTE_HOST environment variable */
3427 remote_user
[1024], /* REMOTE_USER environment variable */
3428 script_name
[1024], /* SCRIPT_NAME environment variable */
3429 server_name
[1024], /* SERVER_NAME environment variable */
3430 server_port
[1024]; /* SERVER_PORT environment variable */
3434 * Parse a copy of the options string, which is of the form:
3436 * argument+argument+argument
3437 * ?argument+argument+argument
3438 * param=value¶m=value
3439 * ?param=value¶m=value
3440 * /name?argument+argument+argument
3441 * /name?param=value¶m=value
3443 * If the string contains an "=" character after the initial name,
3444 * then we treat it as a HTTP GET form request and make a copy of
3445 * the remaining string for the environment variable.
3447 * The string is always parsed out as command-line arguments, to
3448 * be consistent with Apache...
3451 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3452 "pipe_command: command=\"%s\", options=\"%s\"",
3456 query_string
= NULL
;
3459 strlcpy(argbuf
, options
, sizeof(argbuf
));
3463 if (argbuf
[0] == '/')
3466 * Found some trailing path information, set PATH_INFO...
3469 if ((commptr
= strchr(argbuf
, '?')) == NULL
)
3470 commptr
= argbuf
+ strlen(argbuf
);
3474 snprintf(path_info
, sizeof(path_info
), "PATH_INFO=%s", argbuf
);
3480 path_info
[0] = '\0';
3483 if (*commptr
== '?' && con
->operation
== HTTP_GET
)
3486 cupsdSetStringf(&query_string
, "QUERY_STRING=%s", commptr
);
3493 argv
[argc
++] = commptr
;
3495 for (; *commptr
&& argc
< 99; commptr
++)
3498 * Break arguments whenever we see a + or space...
3501 if (*commptr
== ' ' || *commptr
== '+')
3503 while (*commptr
== ' ' || *commptr
== '+')
3507 * If we don't have a blank string, save it as another argument...
3512 argv
[argc
] = commptr
;
3518 else if (*commptr
== '%' && isxdigit(commptr
[1] & 255) &&
3519 isxdigit(commptr
[2] & 255))
3522 * Convert the %xx notation to the individual character.
3525 if (commptr
[1] >= '0' && commptr
[1] <= '9')
3526 *commptr
= (commptr
[1] - '0') << 4;
3528 *commptr
= (tolower(commptr
[1]) - 'a' + 10) << 4;
3530 if (commptr
[2] >= '0' && commptr
[2] <= '9')
3531 *commptr
|= commptr
[2] - '0';
3533 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
3535 _cups_strcpy(commptr
+ 1, commptr
+ 3);
3538 * Check for a %00 and break if that is the case...
3550 * Setup the environment variables as needed...
3554 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF-8", con
->language
->language
);
3556 strcpy(lang
, "LANG=C");
3558 strcpy(remote_addr
, "REMOTE_ADDR=");
3559 httpAddrString(con
->http
.hostaddr
, remote_addr
+ 12,
3560 sizeof(remote_addr
) - 12);
3562 snprintf(remote_host
, sizeof(remote_host
), "REMOTE_HOST=%s",
3563 con
->http
.hostname
);
3565 snprintf(script_name
, sizeof(script_name
), "SCRIPT_NAME=%s", con
->uri
);
3566 if ((uriptr
= strchr(script_name
, '?')) != NULL
)
3569 sprintf(server_port
, "SERVER_PORT=%d", con
->serverport
);
3571 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
3574 envc
= cupsdLoadEnv(envp
, (int)(sizeof(envp
) / sizeof(envp
[0])));
3576 envp
[envc
++] = lang
;
3577 envp
[envc
++] = "REDIRECT_STATUS=1";
3578 envp
[envc
++] = server_name
;
3579 envp
[envc
++] = server_port
;
3580 envp
[envc
++] = remote_addr
;
3581 envp
[envc
++] = remote_host
;
3582 envp
[envc
++] = script_name
;
3585 envp
[envc
++] = path_info
;
3587 if (con
->username
[0])
3589 snprintf(remote_user
, sizeof(remote_user
), "REMOTE_USER=%s", con
->username
);
3591 envp
[envc
++] = remote_user
;
3594 if (con
->http
.version
== HTTP_1_1
)
3595 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.1";
3596 else if (con
->http
.version
== HTTP_1_0
)
3597 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.0";
3599 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/0.9";
3601 if (con
->http
.cookie
)
3603 snprintf(http_cookie
, sizeof(http_cookie
), "HTTP_COOKIE=%s",
3605 envp
[envc
++] = http_cookie
;
3608 if (con
->http
.fields
[HTTP_FIELD_USER_AGENT
][0])
3610 snprintf(http_user_agent
, sizeof(http_user_agent
), "HTTP_USER_AGENT=%s",
3611 con
->http
.fields
[HTTP_FIELD_USER_AGENT
]);
3612 envp
[envc
++] = http_user_agent
;
3615 if (con
->operation
== HTTP_GET
)
3617 for (i
= 0; i
< argc
; i
++)
3618 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "argv[%d] = \"%s\"", i
, argv
[i
]);
3620 envp
[envc
++] = "REQUEST_METHOD=GET";
3625 * Add GET form variables after ?...
3628 envp
[envc
++] = query_string
;
3633 sprintf(content_length
, "CONTENT_LENGTH=" CUPS_LLFMT
,
3634 CUPS_LLCAST con
->bytes
);
3635 snprintf(content_type
, sizeof(content_type
), "CONTENT_TYPE=%s",
3636 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
3638 envp
[envc
++] = "REQUEST_METHOD=POST";
3639 envp
[envc
++] = content_length
;
3640 envp
[envc
++] = content_type
;
3644 * Tell the CGI if we are using encryption...
3647 if (con
->http
.encryption
== HTTP_ENCRYPT_ALWAYS
)
3648 envp
[envc
++] = "HTTPS=ON";
3651 * Terminate the environment array...
3656 if (LogLevel
== CUPSD_LOG_DEBUG2
)
3658 for (i
= 0; i
< argc
; i
++)
3659 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3660 "pipe_command: argv[%d] = \"%s\"", i
, argv
[i
]);
3661 for (i
= 0; i
< envc
; i
++)
3662 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3663 "pipe_command: envp[%d] = \"%s\"", i
, envp
[i
]);
3667 * Create a pipe for the output...
3670 if (cupsdOpenPipe(fds
))
3672 cupsdClearString(&query_string
);
3674 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to create pipes for CGI %s - %s",
3675 argv
[0], strerror(errno
));
3680 * Then execute the command...
3683 if (cupsdStartProcess(command
, argv
, envp
, infile
, fds
[1], CGIPipes
[1],
3684 -1, root
, &pid
) < 0)
3687 * Error - can't fork!
3690 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to fork for CGI %s - %s", argv
[0],
3693 cupsdClosePipe(fds
);
3699 * Fork successful - return the PID...
3702 if (con
->username
[0])
3703 cupsdAddCert(pid
, con
->username
);
3705 cupsdLogMessage(CUPSD_LOG_DEBUG
, "CGI %s started - PID = %d", command
, pid
);
3711 cupsdClearString(&query_string
);
3718 * 'send_file()' - Send a file via HTTP.
3721 static int /* O - 0 on failure, 1 on success */
3722 send_file(cupsd_client_t
*con
, /* I - Client connection */
3723 http_status_t code
, /* I - HTTP status */
3724 char *filename
, /* I - Filename */
3725 char *type
, /* I - File type */
3726 struct stat
*filestats
) /* O - File information */
3728 con
->file
= open(filename
, O_RDONLY
);
3730 cupsdLogMessage(CUPSD_LOG_DEBUG
, "send_file: %d file=%d", con
->http
.fd
,
3736 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
3740 if (!cupsdSendHeader(con
, code
, type
))
3743 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
3744 httpGetDateString(filestats
->st_mtime
)) < 0)
3746 if (httpPrintf(HTTP(con
), "Content-Length: " CUPS_LLFMT
"\r\n",
3747 CUPS_LLCAST filestats
->st_size
) < 0)
3749 if (httpPrintf(HTTP(con
), "\r\n") < 0)
3752 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
3753 con
->http
.data_remaining
= filestats
->st_size
;
3755 if (con
->http
.data_remaining
<= INT_MAX
)
3756 con
->http
._data_remaining
= con
->http
.data_remaining
;
3758 con
->http
._data_remaining
= INT_MAX
;
3760 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3761 "send_file: Adding fd %d to OutputSet...", con
->http
.fd
);
3763 FD_SET(con
->http
.fd
, OutputSet
);
3770 * End of "$Id: client.c 5305 2006-03-18 03:05:12Z mike $".