2 * "$Id: client.c 7950 2008-09-17 00:21:59Z mike $"
4 * Client routines for the CUPS scheduler.
6 * Copyright 2007-2012 by Apple Inc.
7 * Copyright 1997-2007 by Easy Software Products, all rights reserved.
9 * This file contains Kerberos support code, copyright 2006 by
12 * These coded instructions, statements, and computer programs are the
13 * property of Apple Inc. and are protected by Federal copyright
14 * law. Distribution and use rights are outlined in the file "LICENSE.txt"
15 * which should have been included with this file. If this file is
16 * file is missing or damaged, see the license at "http://www.cups.org/".
20 * cupsdAcceptClient() - Accept a new client.
21 * cupsdCloseAllClients() - Close all remote clients immediately.
22 * cupsdCloseClient() - Close a remote client.
23 * cupsdFlushHeader() - Flush the header fields to the client.
24 * cupsdReadClient() - Read data from a client.
25 * cupsdSendCommand() - Send output from a command via HTTP.
26 * cupsdSendError() - Send an error message via HTTP.
27 * cupsdSendHeader() - Send an HTTP request.
28 * cupsdUpdateCGI() - Read status messages from CGI scripts and
30 * cupsdWriteClient() - Write data to a client as needed.
31 * check_if_modified() - Decode an "If-Modified-Since" line.
32 * compare_clients() - Compare two client connections.
33 * data_ready() - Check whether data is available from a client.
34 * get_file() - Get a filename and state info.
35 * install_conf_file() - Install a configuration file.
36 * is_cgi() - Is the resource a CGI script/program?
37 * is_path_absolute() - Is a path absolute and free of relative elements
39 * pipe_command() - Pipe the output of a command to the remote
41 * valid_host() - Is the Host: field valid?
42 * write_file() - Send a file via HTTP.
43 * write_pipe() - Flag that data is available on the CGI pipe.
47 * Include necessary headers...
54 #endif /* HAVE_TCPD_H */
61 static const char * const http_states
[] =
62 { /* HTTP state strings */
67 "HTTP_STATE_GET_SEND",
70 "HTTP_STATE_POST_RECV",
71 "HTTP_STATE_POST_SEND",
73 "HTTP_STATE_PUT_RECV",
78 "HTTP_STATE_UNKNOWN_METHOD",
79 "HTTP_STATE_UNKNOWN_VERSION"
81 static const char * const ipp_states
[] =
82 { /* IPP state strings */
94 static int check_if_modified(cupsd_client_t
*con
,
95 struct stat
*filestats
);
96 static int compare_clients(cupsd_client_t
*a
, cupsd_client_t
*b
,
98 static int data_ready(cupsd_client_t
*con
);
99 static char *get_file(cupsd_client_t
*con
, struct stat
*filestats
,
100 char *filename
, int len
);
101 static http_status_t
install_conf_file(cupsd_client_t
*con
);
102 static int is_cgi(cupsd_client_t
*con
, const char *filename
,
103 struct stat
*filestats
, mime_type_t
*type
);
104 static int is_path_absolute(const char *path
);
105 static int pipe_command(cupsd_client_t
*con
, int infile
, int *outfile
,
106 char *command
, char *options
, int root
);
107 static int valid_host(cupsd_client_t
*con
);
108 static int write_file(cupsd_client_t
*con
, http_status_t code
,
109 char *filename
, char *type
,
110 struct stat
*filestats
);
111 static void write_pipe(cupsd_client_t
*con
);
115 * 'cupsdAcceptClient()' - Accept a new client.
119 cupsdAcceptClient(cupsd_listener_t
*lis
)/* I - Listener socket */
121 int count
; /* Count of connections on a host */
122 int val
; /* Parameter value */
123 cupsd_client_t
*con
, /* New client pointer */
124 *tempcon
; /* Temporary client pointer */
125 http_addrlist_t
*addrlist
, /* List of adddresses for host */
126 *addr
; /* Current address */
127 socklen_t addrlen
; /* Length of address */
128 char *hostname
; /* Hostname for address */
129 http_addr_t temp
; /* Temporary address variable */
130 static time_t last_dos
= 0; /* Time of last DoS attack */
132 struct request_info wrap_req
; /* TCP wrappers request information */
133 #endif /* HAVE_TCPD_H */
136 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
137 "cupsdAcceptClient(lis=%p(%d)) Clients=%d",
138 lis
, lis
->fd
, cupsArrayCount(Clients
));
141 * Make sure we don't have a full set of clients already...
144 if (cupsArrayCount(Clients
) == MaxClients
)
148 * Get a pointer to the next available client...
152 Clients
= cupsArrayNew(NULL
, NULL
);
156 cupsdLogMessage(CUPSD_LOG_ERROR
,
157 "Unable to allocate memory for clients array!");
158 cupsdPauseListening();
163 ActiveClients
= cupsArrayNew((cups_array_func_t
)compare_clients
, NULL
);
167 cupsdLogMessage(CUPSD_LOG_ERROR
,
168 "Unable to allocate memory for active clients array!");
169 cupsdPauseListening();
173 if ((con
= calloc(1, sizeof(cupsd_client_t
))) == NULL
)
175 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to allocate memory for client!");
176 cupsdPauseListening();
181 con
->http
.activity
= time(NULL
);
182 con
->http
.hostaddr
= &(con
->clientaddr
);
183 con
->http
.wait_value
= 10000;
186 * Accept the client and get the remote address...
189 addrlen
= sizeof(http_addr_t
);
191 if ((con
->http
.fd
= accept(lis
->fd
, (struct sockaddr
*)con
->http
.hostaddr
,
194 if (errno
== ENFILE
|| errno
== EMFILE
)
195 cupsdPauseListening();
197 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to accept client connection - %s.",
205 * Save the connected port number...
208 _httpAddrSetPort(con
->http
.hostaddr
, httpAddrPort(&(lis
->address
)));
212 * Convert IPv4 over IPv6 addresses (::ffff:n.n.n.n) to IPv4 forms we
213 * can more easily use...
216 if (lis
->address
.addr
.sa_family
== AF_INET6
&&
217 con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[0] == 0 &&
218 con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[1] == 0 &&
219 ntohl(con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[2]) == 0xffff)
220 con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[2] = 0;
221 #endif /* AF_INET6 */
224 * Check the number of clients on the same address...
227 for (count
= 0, tempcon
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
229 tempcon
= (cupsd_client_t
*)cupsArrayNext(Clients
))
230 if (httpAddrEqual(tempcon
->http
.hostaddr
, con
->http
.hostaddr
))
233 if (count
>= MaxClientsPerHost
)
237 if (count
>= MaxClientsPerHost
)
239 if ((time(NULL
) - last_dos
) >= 60)
241 last_dos
= time(NULL
);
242 cupsdLogMessage(CUPSD_LOG_WARN
,
243 "Possible DoS attack - more than %d clients connecting "
246 httpAddrString(con
->http
.hostaddr
, con
->http
.hostname
,
247 sizeof(con
->http
.hostname
)));
251 closesocket(con
->http
.fd
);
261 * Get the hostname or format the IP address as needed...
264 if (httpAddrLocalhost(con
->http
.hostaddr
))
267 * Map accesses from the loopback interface to "localhost"...
270 strlcpy(con
->http
.hostname
, "localhost", sizeof(con
->http
.hostname
));
271 hostname
= con
->http
.hostname
;
276 * Map accesses from the same host to the server name.
280 hostname
= httpAddrLookup(con
->http
.hostaddr
, con
->http
.hostname
,
281 sizeof(con
->http
.hostname
));
285 httpAddrString(con
->http
.hostaddr
, con
->http
.hostname
,
286 sizeof(con
->http
.hostname
));
290 if (hostname
== NULL
&& HostNameLookups
== 2)
293 * Can't have an unresolved IP address with double-lookups enabled...
297 closesocket(con
->http
.fd
);
302 cupsdLogMessage(CUPSD_LOG_WARN
,
303 "Name lookup failed - connection from %s closed!",
310 if (HostNameLookups
== 2)
313 * Do double lookups as needed...
316 if ((addrlist
= httpAddrGetList(con
->http
.hostname
, AF_UNSPEC
, NULL
))
320 * See if the hostname maps to the same IP address...
323 for (addr
= addrlist
; addr
; addr
= addr
->next
)
324 if (httpAddrEqual(con
->http
.hostaddr
, &(addr
->addr
)))
330 httpAddrFreeList(addrlist
);
335 * Can't have a hostname that doesn't resolve to the same IP address
336 * with double-lookups enabled...
340 closesocket(con
->http
.fd
);
345 cupsdLogMessage(CUPSD_LOG_WARN
,
346 "IP lookup failed - connection from %s closed!",
355 * See if the connection is denied by TCP wrappers...
358 request_init(&wrap_req
, RQ_DAEMON
, "cupsd", RQ_FILE
, con
->http
.fd
, NULL
);
361 if (!hosts_access(&wrap_req
))
364 closesocket(con
->http
.fd
);
369 cupsdLogMessage(CUPSD_LOG_WARN
,
370 "Connection from %s refused by /etc/hosts.allow and "
371 "/etc/hosts.deny rules.", con
->http
.hostname
);
375 #endif /* HAVE_TCPD_H */
378 if (con
->http
.hostaddr
->addr
.sa_family
== AF_LOCAL
)
379 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[Client %d] Accepted from %s (Domain)",
380 con
->http
.fd
, con
->http
.hostname
);
382 #endif /* AF_LOCAL */
383 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[Client %d] Accepted from %s:%d (IPv%d)",
384 con
->http
.fd
, con
->http
.hostname
,
385 httpAddrPort(con
->http
.hostaddr
),
386 _httpAddrFamily(con
->http
.hostaddr
) == AF_INET
? 4 : 6);
389 * Get the local address the client connected to...
392 addrlen
= sizeof(temp
);
393 if (getsockname(con
->http
.fd
, (struct sockaddr
*)&temp
, &addrlen
))
395 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to get local address - %s",
398 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
399 con
->serverport
= LocalPort
;
402 else if (_httpAddrFamily(&temp
) == AF_LOCAL
)
404 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
405 con
->serverport
= LocalPort
;
407 #endif /* AF_LOCAL */
410 if (httpAddrLocalhost(&temp
))
411 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
412 else if (HostNameLookups
|| RemotePort
)
413 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
415 httpAddrString(&temp
, con
->servername
, sizeof(con
->servername
));
417 con
->serverport
= httpAddrPort(&(lis
->address
));
421 * Add the connection to the array of active clients...
424 cupsArrayAdd(Clients
, con
);
427 * Using TCP_NODELAY improves responsiveness, especially on systems with a slow
428 * loopback interface. Since we write large buffers when sending print files
429 * and requests there shouldn't be any performance penalty for this...
433 setsockopt(con
->http
.fd
, IPPROTO_TCP
, TCP_NODELAY
, &val
, sizeof(val
));
436 * Close this file on all execs...
439 fcntl(con
->http
.fd
, F_SETFD
, fcntl(con
->http
.fd
, F_GETFD
) | FD_CLOEXEC
);
442 * Add the socket to the server select.
445 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
448 * Temporarily suspend accept()'s until we lose a client...
451 if (cupsArrayCount(Clients
) == MaxClients
)
452 cupsdPauseListening();
456 * See if we are connecting on a secure port...
459 if (lis
->encryption
== HTTP_ENCRYPT_ALWAYS
)
462 * https connection; go secure...
465 con
->http
.encryption
= HTTP_ENCRYPT_ALWAYS
;
467 if (!cupsdStartTLS(con
))
468 cupsdCloseClient(con
);
472 #endif /* HAVE_SSL */
477 * 'cupsdCloseAllClients()' - Close all remote clients immediately.
481 cupsdCloseAllClients(void)
483 cupsd_client_t
*con
; /* Current client */
486 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdCloseAllClients() Clients=%d",
487 cupsArrayCount(Clients
));
489 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
491 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
492 if (cupsdCloseClient(con
))
493 cupsdCloseClient(con
);
498 * 'cupsdCloseClient()' - Close a remote client.
501 int /* O - 1 if partial close, 0 if fully closed */
502 cupsdCloseClient(cupsd_client_t
*con
) /* I - Client to close */
504 int partial
; /* Do partial close for SSL? */
506 #elif defined(HAVE_GNUTLS)
507 # elif defined(HAVE_CDSASSL)
508 #endif /* HAVE_LIBSSL */
511 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[Client %d] Closing connection.",
515 * Flush pending writes before closing...
518 httpFlushWrite(HTTP(con
));
524 * Shutdown encryption as needed...
533 #endif /* HAVE_SSL */
535 if (con
->pipe_pid
!= 0)
538 * Stop any CGI process...
541 cupsdEndProcess(con
->pipe_pid
, 1);
547 cupsdRemoveSelect(con
->file
);
554 * Close the socket and clear the file from the input set for select()...
557 if (con
->http
.fd
>= 0)
559 cupsArrayRemove(ActiveClients
, con
);
565 * Only do a partial close so that the encrypted client gets everything.
568 shutdown(con
->http
.fd
, 0);
569 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
574 * Shut the socket down fully...
577 cupsdRemoveSelect(con
->http
.fd
);
589 if (con
->http
.input_set
)
590 free(con
->http
.input_set
);
592 httpClearCookie(HTTP(con
));
593 httpClearFields(HTTP(con
));
595 cupsdClearString(&con
->filename
);
596 cupsdClearString(&con
->command
);
597 cupsdClearString(&con
->options
);
598 cupsdClearString(&con
->query_string
);
602 ippDelete(con
->request
);
608 ippDelete(con
->response
);
609 con
->response
= NULL
;
614 cupsLangFree(con
->language
);
615 con
->language
= NULL
;
618 #ifdef HAVE_AUTHORIZATION_H
621 AuthorizationFree(con
->authref
, kAuthorizationFlagDefaults
);
624 #endif /* HAVE_AUTHORIZATION_H */
627 * Re-enable new client connections if we are going back under the
631 if (cupsArrayCount(Clients
) == MaxClients
)
632 cupsdResumeListening();
635 * Compact the list of clients as necessary...
638 cupsArrayRemove(Clients
, con
);
648 * 'cupsdFlushHeader()' - Flush the header fields to the client.
651 int /* I - Bytes written or -1 on error */
652 cupsdFlushHeader(cupsd_client_t
*con
) /* I - Client to flush to */
654 int bytes
= httpFlushWrite(HTTP(con
));
656 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
663 * 'cupsdReadClient()' - Read data from a client.
667 cupsdReadClient(cupsd_client_t
*con
) /* I - Client to read from */
669 char line
[32768], /* Line from client... */
670 operation
[64], /* Operation code from socket */
671 version
[64], /* HTTP version number string */
672 locale
[64], /* Locale */
673 *ptr
; /* Pointer into strings */
674 int major
, minor
; /* HTTP version numbers */
675 http_status_t status
; /* Transfer status */
676 ipp_state_t ipp_state
; /* State of IPP transfer */
677 int bytes
; /* Number of bytes to POST */
678 char *filename
; /* Name of file for GET/HEAD */
679 char buf
[1024]; /* Buffer for real filename */
680 struct stat filestats
; /* File information */
681 mime_type_t
*type
; /* MIME type of file */
682 cupsd_printer_t
*p
; /* Printer */
683 static unsigned request_id
= 0; /* Request ID for temp files */
686 status
= HTTP_CONTINUE
;
688 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
689 "[Client %d] cupsdReadClient "
693 "data_encoding=HTTP_ENCODING_%s, "
694 "data_remaining=" CUPS_LLFMT
", "
697 con
->http
.fd
, con
->http
.error
, con
->http
.used
,
698 http_states
[con
->http
.state
+ 1],
699 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
?
700 "CHUNKED" : "LENGTH",
701 CUPS_LLCAST con
->http
.data_remaining
,
703 con
->request
? ipp_states
[con
->request
->state
] : "",
710 * Automatically check for a SSL/TLS handshake...
715 if (recv(con
->http
.fd
, buf
, 1, MSG_PEEK
) == 1 &&
716 (!buf
[0] || !strchr("DGHOPT", buf
[0])))
719 * Encrypt this connection...
722 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
723 "[Client %d] Saw first byte %02X, auto-negotiating "
724 "SSL/TLS session.", con
->http
.fd
, buf
[0] & 255);
726 if (!cupsdStartTLS(con
))
727 cupsdCloseClient(con
);
732 #endif /* HAVE_SSL */
734 switch (con
->http
.state
)
738 * See if we've received a request line...
741 if (httpGets(line
, sizeof(line
) - 1, HTTP(con
)) == NULL
)
743 if (con
->http
.error
&& con
->http
.error
!= EPIPE
)
744 cupsdLogMessage(CUPSD_LOG_DEBUG
,
745 "[Client %d] HTTP_WAITING Closing for error %d "
746 "(%s)", con
->http
.fd
, con
->http
.error
,
747 strerror(con
->http
.error
));
749 cupsdLogMessage(CUPSD_LOG_DEBUG
,
750 "[Client %d] HTTP_WAITING Closing on EOF",
753 cupsdCloseClient(con
);
758 * Ignore blank request lines...
765 * Clear other state variables...
768 httpClearFields(HTTP(con
));
770 con
->http
.activity
= time(NULL
);
771 con
->http
.version
= HTTP_1_0
;
772 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
773 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
774 con
->http
.data_remaining
= 0;
775 con
->http
._data_remaining
= 0;
776 con
->operation
= HTTP_WAITING
;
781 con
->username
[0] = '\0';
782 con
->password
[0] = '\0';
785 cupsdClearString(&con
->command
);
786 cupsdClearString(&con
->options
);
787 cupsdClearString(&con
->query_string
);
791 ippDelete(con
->request
);
797 ippDelete(con
->response
);
798 con
->response
= NULL
;
803 cupsLangFree(con
->language
);
804 con
->language
= NULL
;
810 #endif /* HAVE_GSSAPI */
813 * Grab the request line...
816 switch (sscanf(line
, "%63s%1023s%63s", operation
, con
->uri
, version
))
821 cupsdLogMessage(CUPSD_LOG_ERROR
,
822 "[Client %d] Bad request line \"%s\" from %s.",
824 _httpEncodeURI(buf
, line
, sizeof(buf
)),
826 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
827 cupsdCloseClient(con
);
831 con
->http
.version
= HTTP_0_9
;
834 if (sscanf(version
, "HTTP/%d.%d", &major
, &minor
) != 2)
836 cupsdLogMessage(CUPSD_LOG_ERROR
,
837 "[Client %d] Bad request line \"%s\" from %s.",
839 _httpEncodeURI(buf
, line
, sizeof(buf
)),
841 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
842 cupsdCloseClient(con
);
848 con
->http
.version
= (http_version_t
)(major
* 100 + minor
);
849 if (con
->http
.version
== HTTP_1_1
&& KeepAlive
)
850 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
852 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
856 cupsdLogMessage(CUPSD_LOG_ERROR
,
857 "[Client %d] Unsupported request line \"%s\" "
858 "from %s.", con
->http
.fd
,
859 _httpEncodeURI(buf
, line
, sizeof(buf
)),
861 cupsdSendError(con
, HTTP_NOT_SUPPORTED
, CUPSD_AUTH_NONE
);
862 cupsdCloseClient(con
);
869 * Handle full URLs in the request line...
872 if (strcmp(con
->uri
, "*"))
874 char scheme
[HTTP_MAX_URI
], /* Method/scheme */
875 userpass
[HTTP_MAX_URI
], /* Username:password */
876 hostname
[HTTP_MAX_URI
], /* Hostname */
877 resource
[HTTP_MAX_URI
]; /* Resource path */
878 int port
; /* Port number */
882 * Separate the URI into its components...
885 httpSeparateURI(HTTP_URI_CODING_MOST
, con
->uri
,
886 scheme
, sizeof(scheme
),
887 userpass
, sizeof(userpass
),
888 hostname
, sizeof(hostname
), &port
,
889 resource
, sizeof(resource
));
892 * Only allow URIs with the servername, localhost, or an IP
896 if (strcmp(scheme
, "file") &&
897 _cups_strcasecmp(hostname
, ServerName
) &&
898 _cups_strcasecmp(hostname
, "localhost") &&
899 !isdigit(hostname
[0]) && hostname
[0] != '[')
902 * Nope, we don't do proxies...
905 cupsdLogMessage(CUPSD_LOG_ERROR
,
906 "[Client %d] Bad URI \"%s\" in request.",
907 con
->http
.fd
, con
->uri
);
908 cupsdSendError(con
, HTTP_METHOD_NOT_ALLOWED
, CUPSD_AUTH_NONE
);
909 cupsdCloseClient(con
);
914 * Copy the resource portion back into the URI; both resource and
915 * con->uri are HTTP_MAX_URI bytes in size...
918 strlcpy(con
->uri
, resource
, sizeof(con
->uri
));
922 * Process the request...
925 if (!strcmp(operation
, "GET"))
926 con
->http
.state
= HTTP_GET
;
927 else if (!strcmp(operation
, "PUT"))
928 con
->http
.state
= HTTP_PUT
;
929 else if (!strcmp(operation
, "POST"))
930 con
->http
.state
= HTTP_POST
;
931 else if (!strcmp(operation
, "DELETE"))
932 con
->http
.state
= HTTP_DELETE
;
933 else if (!strcmp(operation
, "TRACE"))
934 con
->http
.state
= HTTP_TRACE
;
935 else if (!strcmp(operation
, "OPTIONS"))
936 con
->http
.state
= HTTP_OPTIONS
;
937 else if (!strcmp(operation
, "HEAD"))
938 con
->http
.state
= HTTP_HEAD
;
941 cupsdLogMessage(CUPSD_LOG_ERROR
,
942 "[Client %d] Bad operation \"%s\".", con
->http
.fd
,
944 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
945 cupsdCloseClient(con
);
949 gettimeofday(&(con
->start
), NULL
);
950 con
->operation
= con
->http
.state
;
952 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[Client %d] %s %s HTTP/%d.%d",
953 con
->http
.fd
, operation
, con
->uri
,
954 con
->http
.version
/ 100, con
->http
.version
% 100);
956 con
->http
.status
= HTTP_OK
;
958 if (!cupsArrayFind(ActiveClients
, con
))
960 cupsArrayAdd(ActiveClients
, con
);
972 * Parse incoming parameters until the status changes...
975 while ((status
= httpUpdate(HTTP(con
))) == HTTP_CONTINUE
)
976 if (!data_ready(con
))
979 if (status
!= HTTP_OK
&& status
!= HTTP_CONTINUE
)
981 if (con
->http
.error
&& con
->http
.error
!= EPIPE
)
982 cupsdLogMessage(CUPSD_LOG_DEBUG
,
983 "[Client %d] Closing for error %d (%s) while "
985 con
->http
.fd
, con
->http
.error
,
986 strerror(con
->http
.error
));
988 cupsdLogMessage(CUPSD_LOG_DEBUG
,
989 "[Client %d] Closing on EOF while reading headers.",
992 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
993 cupsdCloseClient(con
);
999 if (!data_ready(con
) && recv(con
->http
.fd
, buf
, 1, MSG_PEEK
) < 1)
1002 * Connection closed...
1005 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1006 "[Client %d] Closing on EOF", con
->http
.fd
);
1007 cupsdCloseClient(con
);
1010 break; /* Anti-compiler-warning-code */
1014 * Handle new transfers...
1017 if (status
== HTTP_OK
)
1019 if (con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
][0])
1022 * Figure out the locale from the Accept-Language and Content-Type
1026 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
],
1030 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
],
1034 if ((ptr
= strstr(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
],
1035 "charset=")) != NULL
)
1038 * Combine language and charset, and trim any extra params in the
1042 snprintf(locale
, sizeof(locale
), "%s.%s",
1043 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ptr
+ 8);
1045 if ((ptr
= strchr(locale
, ',')) != NULL
)
1049 snprintf(locale
, sizeof(locale
), "%s.UTF-8",
1050 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
]);
1052 con
->language
= cupsLangGet(locale
);
1055 con
->language
= cupsLangGet(DefaultLocale
);
1057 cupsdAuthorize(con
);
1059 if (!_cups_strncasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
],
1060 "Keep-Alive", 10) && KeepAlive
)
1061 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
1062 else if (!_cups_strncasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
],
1064 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1066 if (!con
->http
.fields
[HTTP_FIELD_HOST
][0] &&
1067 con
->http
.version
>= HTTP_1_1
)
1070 * HTTP/1.1 and higher require the "Host:" field...
1073 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1075 cupsdLogMessage(CUPSD_LOG_ERROR
,
1076 "[Client %d] Missing Host: field in request.",
1078 cupsdCloseClient(con
);
1082 else if (!valid_host(con
))
1085 * Access to localhost must use "localhost" or the corresponding IPv4
1086 * or IPv6 values in the Host: field.
1089 cupsdLogMessage(CUPSD_LOG_ERROR
,
1090 "[Client %d] Request from \"%s\" using invalid Host: "
1091 "field \"%s\"", con
->http
.fd
, con
->http
.hostname
,
1092 con
->http
.fields
[HTTP_FIELD_HOST
]);
1094 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1096 cupsdCloseClient(con
);
1100 else if (con
->operation
== HTTP_OPTIONS
)
1103 * Do OPTIONS command...
1106 if (con
->best
&& con
->best
->type
!= CUPSD_AUTH_NONE
)
1108 if (!cupsdSendHeader(con
, HTTP_UNAUTHORIZED
, NULL
, CUPSD_AUTH_NONE
))
1110 cupsdCloseClient(con
);
1115 if (!_cups_strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") &&
1116 con
->http
.tls
== NULL
)
1120 * Do encryption stuff...
1123 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
, CUPSD_AUTH_NONE
))
1125 cupsdCloseClient(con
);
1129 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1130 httpPrintf(HTTP(con
), "Upgrade: TLS/1.2,TLS/1.1,TLS/1.0\r\n");
1131 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1132 httpPrintf(HTTP(con
), "\r\n");
1134 if (cupsdFlushHeader(con
) < 0)
1136 cupsdCloseClient(con
);
1140 if (!cupsdStartTLS(con
))
1142 cupsdCloseClient(con
);
1146 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
1148 cupsdCloseClient(con
);
1151 #endif /* HAVE_SSL */
1154 if (!cupsdSendHeader(con
, HTTP_OK
, NULL
, CUPSD_AUTH_NONE
))
1156 cupsdCloseClient(con
);
1160 httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n");
1161 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1162 httpPrintf(HTTP(con
), "\r\n");
1164 if (cupsdFlushHeader(con
) < 0)
1166 cupsdCloseClient(con
);
1170 else if (!is_path_absolute(con
->uri
))
1173 * Protect against malicious users!
1176 cupsdLogMessage(CUPSD_LOG_ERROR
,
1177 "[Client %d] Request for non-absolute resource \"%s\".",
1178 con
->http
.fd
, con
->uri
);
1180 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1182 cupsdCloseClient(con
);
1188 if (!_cups_strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
],
1189 "Upgrade") && con
->http
.tls
== NULL
)
1193 * Do encryption stuff...
1196 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
,
1199 cupsdCloseClient(con
);
1203 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1204 httpPrintf(HTTP(con
), "Upgrade: TLS/1.2,TLS/1.1,TLS/1.0\r\n");
1205 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1206 httpPrintf(HTTP(con
), "\r\n");
1208 if (cupsdFlushHeader(con
) < 0)
1210 cupsdCloseClient(con
);
1214 if (!cupsdStartTLS(con
))
1216 cupsdCloseClient(con
);
1220 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
1222 cupsdCloseClient(con
);
1225 #endif /* HAVE_SSL */
1228 if ((status
= cupsdIsAuthorized(con
, NULL
)) != HTTP_OK
)
1230 cupsdSendError(con
, status
, CUPSD_AUTH_NONE
);
1231 cupsdCloseClient(con
);
1235 if (con
->http
.expect
&&
1236 (con
->operation
== HTTP_POST
|| con
->operation
== HTTP_PUT
))
1238 if (con
->http
.expect
== HTTP_CONTINUE
)
1241 * Send 100-continue header...
1244 if (!cupsdSendHeader(con
, HTTP_CONTINUE
, NULL
, CUPSD_AUTH_NONE
))
1246 cupsdCloseClient(con
);
1253 * Send 417-expectation-failed header...
1256 if (!cupsdSendHeader(con
, HTTP_EXPECTATION_FAILED
, NULL
,
1259 cupsdCloseClient(con
);
1263 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1264 httpPrintf(HTTP(con
), "\r\n");
1266 if (cupsdFlushHeader(con
) < 0)
1268 cupsdCloseClient(con
);
1274 switch (con
->http
.state
)
1276 case HTTP_GET_SEND
:
1277 if (!strncmp(con
->uri
, "/printers/", 10) &&
1278 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1281 * Send PPD file - get the real printer name since printer
1282 * names are not case sensitive but filenames can be...
1285 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1287 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1288 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1291 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1293 cupsdCloseClient(con
);
1300 else if ((!strncmp(con
->uri
, "/printers/", 10) ||
1301 !strncmp(con
->uri
, "/classes/", 9)) &&
1302 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".png"))
1305 * Send icon file - get the real queue name since queue names are
1306 * not case sensitive but filenames can be...
1309 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".png" */
1311 if (!strncmp(con
->uri
, "/printers/", 10))
1312 p
= cupsdFindPrinter(con
->uri
+ 10);
1314 p
= cupsdFindClass(con
->uri
+ 9);
1317 snprintf(con
->uri
, sizeof(con
->uri
), "/icons/%s.png", p
->name
);
1320 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1322 cupsdCloseClient(con
);
1329 else if (!WebInterface
)
1332 * Web interface is disabled. Show an appropriate message...
1335 if (!cupsdSendError(con
, HTTP_WEBIF_DISABLED
, CUPSD_AUTH_NONE
))
1337 cupsdCloseClient(con
);
1344 if ((!strncmp(con
->uri
, "/admin", 6) &&
1345 strncmp(con
->uri
, "/admin/conf/", 12) &&
1346 strncmp(con
->uri
, "/admin/log/", 11)) ||
1347 !strncmp(con
->uri
, "/printers", 9) ||
1348 !strncmp(con
->uri
, "/classes", 8) ||
1349 !strncmp(con
->uri
, "/help", 5) ||
1350 !strncmp(con
->uri
, "/jobs", 5))
1353 * Send CGI output...
1356 if (!strncmp(con
->uri
, "/admin", 6))
1358 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1361 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1363 else if (!strncmp(con
->uri
, "/printers", 9))
1365 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1368 if (con
->uri
[9] && con
->uri
[10])
1369 cupsdSetString(&con
->options
, con
->uri
+ 9);
1371 cupsdSetString(&con
->options
, NULL
);
1373 else if (!strncmp(con
->uri
, "/classes", 8))
1375 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1378 if (con
->uri
[8] && con
->uri
[9])
1379 cupsdSetString(&con
->options
, con
->uri
+ 8);
1381 cupsdSetString(&con
->options
, NULL
);
1383 else if (!strncmp(con
->uri
, "/jobs", 5))
1385 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1388 if (con
->uri
[5] && con
->uri
[6])
1389 cupsdSetString(&con
->options
, con
->uri
+ 5);
1391 cupsdSetString(&con
->options
, NULL
);
1395 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1398 if (con
->uri
[5] && con
->uri
[6])
1399 cupsdSetString(&con
->options
, con
->uri
+ 5);
1401 cupsdSetString(&con
->options
, NULL
);
1404 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1406 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1408 cupsdCloseClient(con
);
1413 cupsdLogRequest(con
, HTTP_OK
);
1415 if (con
->http
.version
<= HTTP_1_0
)
1416 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1418 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1419 (strchr(con
->uri
+ 12, '/') ||
1420 strlen(con
->uri
) == 12)) ||
1421 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1422 (strchr(con
->uri
+ 11, '/') ||
1423 strlen(con
->uri
) == 11)))
1426 * GET can only be done to configuration files directly under
1430 cupsdLogMessage(CUPSD_LOG_ERROR
,
1431 "Request for subdirectory \"%s\"!", con
->uri
);
1433 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1435 cupsdCloseClient(con
);
1447 if ((filename
= get_file(con
, &filestats
, buf
,
1448 sizeof(buf
))) == NULL
)
1450 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1452 cupsdCloseClient(con
);
1459 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1461 if (is_cgi(con
, filename
, &filestats
, type
))
1464 * Note: con->command and con->options were set by
1468 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1470 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1472 cupsdCloseClient(con
);
1477 cupsdLogRequest(con
, HTTP_OK
);
1479 if (con
->http
.version
<= HTTP_1_0
)
1480 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1484 if (!check_if_modified(con
, &filestats
))
1486 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1488 cupsdCloseClient(con
);
1495 strlcpy(line
, "text/plain", sizeof(line
));
1497 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1499 if (!write_file(con
, HTTP_OK
, filename
, line
, &filestats
))
1501 cupsdCloseClient(con
);
1508 case HTTP_POST_RECV
:
1510 * See if the POST request includes a Content-Length field, and if
1511 * so check the length against any limits that are set...
1514 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1515 MaxRequestSize
> 0 &&
1516 con
->http
.data_remaining
> MaxRequestSize
)
1519 * Request too large...
1522 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1524 cupsdCloseClient(con
);
1530 else if (con
->http
.data_remaining
< 0 ||
1531 (!con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1532 con
->http
.data_encoding
== HTTP_ENCODE_LENGTH
))
1535 * Negative content lengths are invalid!
1538 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1540 cupsdCloseClient(con
);
1548 * See what kind of POST request this is; for IPP requests the
1549 * content-type field will be "application/ipp"...
1552 if (!strcmp(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
],
1554 con
->request
= ippNew();
1555 else if (!WebInterface
)
1558 * Web interface is disabled. Show an appropriate message...
1561 if (!cupsdSendError(con
, HTTP_WEBIF_DISABLED
, CUPSD_AUTH_NONE
))
1563 cupsdCloseClient(con
);
1569 else if ((!strncmp(con
->uri
, "/admin", 6) &&
1570 strncmp(con
->uri
, "/admin/conf/", 12) &&
1571 strncmp(con
->uri
, "/admin/log/", 11)) ||
1572 !strncmp(con
->uri
, "/printers", 9) ||
1573 !strncmp(con
->uri
, "/classes", 8) ||
1574 !strncmp(con
->uri
, "/help", 5) ||
1575 !strncmp(con
->uri
, "/jobs", 5))
1581 if (!strncmp(con
->uri
, "/admin", 6))
1583 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1586 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1588 else if (!strncmp(con
->uri
, "/printers", 9))
1590 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1593 if (con
->uri
[9] && con
->uri
[10])
1594 cupsdSetString(&con
->options
, con
->uri
+ 9);
1596 cupsdSetString(&con
->options
, NULL
);
1598 else if (!strncmp(con
->uri
, "/classes", 8))
1600 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1603 if (con
->uri
[8] && con
->uri
[9])
1604 cupsdSetString(&con
->options
, con
->uri
+ 8);
1606 cupsdSetString(&con
->options
, NULL
);
1608 else if (!strncmp(con
->uri
, "/jobs", 5))
1610 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1613 if (con
->uri
[5] && con
->uri
[6])
1614 cupsdSetString(&con
->options
, con
->uri
+ 5);
1616 cupsdSetString(&con
->options
, NULL
);
1620 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1623 if (con
->uri
[5] && con
->uri
[6])
1624 cupsdSetString(&con
->options
, con
->uri
+ 5);
1626 cupsdSetString(&con
->options
, NULL
);
1629 if (con
->http
.version
<= HTTP_1_0
)
1630 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1638 if ((filename
= get_file(con
, &filestats
, buf
,
1639 sizeof(buf
))) == NULL
)
1641 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1643 cupsdCloseClient(con
);
1650 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1652 if (!is_cgi(con
, filename
, &filestats
, type
))
1655 * Only POST to CGI's...
1658 if (!cupsdSendError(con
, HTTP_UNAUTHORIZED
, CUPSD_AUTH_NONE
))
1660 cupsdCloseClient(con
);
1667 case HTTP_PUT_RECV
:
1669 * Validate the resource name...
1672 if (strncmp(con
->uri
, "/admin/conf/", 12) ||
1673 strchr(con
->uri
+ 12, '/') ||
1674 strlen(con
->uri
) == 12)
1677 * PUT can only be done to configuration files under
1681 cupsdLogMessage(CUPSD_LOG_ERROR
,
1682 "[Client %d] Request for subdirectory \"%s\".",
1683 con
->http
.fd
, con
->uri
);
1685 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1687 cupsdCloseClient(con
);
1695 * See if the PUT request includes a Content-Length field, and if
1696 * so check the length against any limits that are set...
1699 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1700 MaxRequestSize
> 0 &&
1701 con
->http
.data_remaining
> MaxRequestSize
)
1704 * Request too large...
1707 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1709 cupsdCloseClient(con
);
1715 else if (con
->http
.data_remaining
< 0)
1718 * Negative content lengths are invalid!
1721 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1723 cupsdCloseClient(con
);
1731 * Open a temporary file to hold the request...
1734 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
1736 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1740 cupsdLogMessage(CUPSD_LOG_ERROR
,
1741 "[Client %d] Unable to create request file "
1742 "\"%s\": %s", con
->http
.fd
, con
->filename
,
1745 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1747 cupsdCloseClient(con
);
1752 fchmod(con
->file
, 0640);
1753 fchown(con
->file
, RunUser
, Group
);
1754 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1759 cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
);
1760 cupsdCloseClient(con
);
1764 if (!strncmp(con
->uri
, "/printers/", 10) &&
1765 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1768 * Send PPD file - get the real printer name since printer
1769 * names are not case sensitive but filenames can be...
1772 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1774 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1775 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1778 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1780 cupsdCloseClient(con
);
1787 else if (!strncmp(con
->uri
, "/printers/", 10) &&
1788 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".png"))
1791 * Send PNG file - get the real printer name since printer
1792 * names are not case sensitive but filenames can be...
1795 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1797 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1798 snprintf(con
->uri
, sizeof(con
->uri
), "/icons/%s.png", p
->name
);
1801 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1803 cupsdCloseClient(con
);
1810 else if (!WebInterface
)
1812 if (!cupsdSendHeader(con
, HTTP_OK
, line
, CUPSD_AUTH_NONE
))
1814 cupsdCloseClient(con
);
1818 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1820 cupsdCloseClient(con
);
1824 if (cupsdFlushHeader(con
) < 0)
1826 cupsdCloseClient(con
);
1830 con
->http
.state
= HTTP_STATE_WAITING
;
1831 DEBUG_puts("cupsdReadClient: Set state to HTTP_STATE_WAITING "
1836 if ((!strncmp(con
->uri
, "/admin", 6) &&
1837 strncmp(con
->uri
, "/admin/conf/", 12) &&
1838 strncmp(con
->uri
, "/admin/log/", 11)) ||
1839 !strncmp(con
->uri
, "/printers", 9) ||
1840 !strncmp(con
->uri
, "/classes", 8) ||
1841 !strncmp(con
->uri
, "/help", 5) ||
1842 !strncmp(con
->uri
, "/jobs", 5))
1848 if (!cupsdSendHeader(con
, HTTP_OK
, "text/html", CUPSD_AUTH_NONE
))
1850 cupsdCloseClient(con
);
1854 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1856 cupsdCloseClient(con
);
1860 if (cupsdFlushHeader(con
) < 0)
1862 cupsdCloseClient(con
);
1866 cupsdLogRequest(con
, HTTP_OK
);
1868 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1869 (strchr(con
->uri
+ 12, '/') ||
1870 strlen(con
->uri
) == 12)) ||
1871 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1872 (strchr(con
->uri
+ 11, '/') ||
1873 strlen(con
->uri
) == 11)))
1876 * HEAD can only be done to configuration files under
1880 cupsdLogMessage(CUPSD_LOG_ERROR
,
1881 "[Client %d] Request for subdirectory \"%s\".",
1882 con
->http
.fd
, con
->uri
);
1884 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1886 cupsdCloseClient(con
);
1892 else if ((filename
= get_file(con
, &filestats
, buf
,
1893 sizeof(buf
))) == NULL
)
1895 if (!cupsdSendHeader(con
, HTTP_NOT_FOUND
, "text/html",
1898 cupsdCloseClient(con
);
1902 cupsdLogRequest(con
, HTTP_NOT_FOUND
);
1904 else if (!check_if_modified(con
, &filestats
))
1906 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1908 cupsdCloseClient(con
);
1912 cupsdLogRequest(con
, HTTP_NOT_MODIFIED
);
1920 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1922 strlcpy(line
, "text/plain", sizeof(line
));
1924 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1926 if (!cupsdSendHeader(con
, HTTP_OK
, line
, CUPSD_AUTH_NONE
))
1928 cupsdCloseClient(con
);
1932 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
1933 httpGetDateString(filestats
.st_mtime
)) < 0)
1935 cupsdCloseClient(con
);
1939 if (httpPrintf(HTTP(con
), "Content-Length: %lu\r\n",
1940 (unsigned long)filestats
.st_size
) < 0)
1942 cupsdCloseClient(con
);
1946 cupsdLogRequest(con
, HTTP_OK
);
1949 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1951 cupsdCloseClient(con
);
1955 if (cupsdFlushHeader(con
) < 0)
1957 cupsdCloseClient(con
);
1961 con
->http
.state
= HTTP_STATE_WAITING
;
1962 DEBUG_puts("cupsdReadClient: Set state to HTTP_STATE_WAITING "
1967 break; /* Anti-compiler-warning-code */
1973 * Handle any incoming data...
1976 switch (con
->http
.state
)
1978 case HTTP_PUT_RECV
:
1981 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
1983 if (con
->http
.error
&& con
->http
.error
!= EPIPE
)
1984 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1985 "[Client %d] HTTP_PUT_RECV Closing for error "
1986 "%d (%s)", con
->http
.fd
, con
->http
.error
,
1987 strerror(con
->http
.error
));
1989 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1990 "[Client %d] HTTP_PUT_RECV Closing on EOF",
1993 cupsdCloseClient(con
);
1998 con
->bytes
+= bytes
;
2000 if (write(con
->file
, line
, bytes
) < bytes
)
2002 cupsdLogMessage(CUPSD_LOG_ERROR
,
2003 "[Client %d] Unable to write %d bytes to "
2004 "\"%s\": %s", con
->http
.fd
, bytes
, con
->filename
,
2009 unlink(con
->filename
);
2010 cupsdClearString(&con
->filename
);
2012 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2014 cupsdCloseClient(con
);
2020 while (con
->http
.state
== HTTP_PUT_RECV
&& data_ready(con
));
2022 if (con
->http
.state
== HTTP_WAITING
)
2025 * End of file, see how big it is...
2028 fstat(con
->file
, &filestats
);
2033 if (filestats
.st_size
> MaxRequestSize
&&
2037 * Request is too big; remove it and send an error...
2040 unlink(con
->filename
);
2041 cupsdClearString(&con
->filename
);
2043 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2045 cupsdCloseClient(con
);
2051 * Install the configuration file...
2054 status
= install_conf_file(con
);
2057 * Return the status to the client...
2060 if (!cupsdSendError(con
, status
, CUPSD_AUTH_NONE
))
2062 cupsdCloseClient(con
);
2068 case HTTP_POST_RECV
:
2071 if (con
->request
&& con
->file
< 0)
2074 * Grab any request data from the connection...
2077 if ((ipp_state
= ippRead(&(con
->http
), con
->request
)) == IPP_ERROR
)
2079 cupsdLogMessage(CUPSD_LOG_ERROR
,
2080 "[Client %d] IPP read error: %s", con
->http
.fd
,
2081 cupsLastErrorString());
2083 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
2084 cupsdCloseClient(con
);
2087 else if (ipp_state
!= IPP_DATA
)
2089 if (con
->http
.state
== HTTP_POST_SEND
)
2091 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
2092 cupsdCloseClient(con
);
2100 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[Client %d] %d.%d %s %d",
2101 con
->http
.fd
, con
->request
->request
.op
.version
[0],
2102 con
->request
->request
.op
.version
[1],
2103 ippOpString(con
->request
->request
.op
.operation_id
),
2104 con
->request
->request
.op
.request_id
);
2105 con
->bytes
+= ippLength(con
->request
);
2109 if (con
->file
< 0 && con
->http
.state
!= HTTP_POST_SEND
)
2112 * Create a file as needed for the request data...
2115 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
2117 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
2121 cupsdLogMessage(CUPSD_LOG_ERROR
,
2122 "[Client %d] Unable to create request file "
2123 "\"%s\": %s", con
->http
.fd
, con
->filename
,
2126 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2128 cupsdCloseClient(con
);
2133 fchmod(con
->file
, 0640);
2134 fchown(con
->file
, RunUser
, Group
);
2135 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2138 if (con
->http
.state
!= HTTP_POST_SEND
)
2140 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
2142 if (con
->http
.error
&& con
->http
.error
!= EPIPE
)
2143 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2144 "[Client %d] HTTP_POST_SEND Closing for "
2145 "error %d (%s)", con
->http
.fd
, con
->http
.error
,
2146 strerror(con
->http
.error
));
2148 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2149 "[Client %d] HTTP_POST_SEND Closing on EOF",
2152 cupsdCloseClient(con
);
2157 con
->bytes
+= bytes
;
2159 if (write(con
->file
, line
, bytes
) < bytes
)
2161 cupsdLogMessage(CUPSD_LOG_ERROR
,
2162 "[Client %d] Unable to write %d bytes to "
2163 "\"%s\": %s", con
->http
.fd
, bytes
,
2164 con
->filename
, strerror(errno
));
2168 unlink(con
->filename
);
2169 cupsdClearString(&con
->filename
);
2171 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
,
2174 cupsdCloseClient(con
);
2179 else if (con
->http
.state
== HTTP_POST_RECV
)
2181 else if (con
->http
.state
!= HTTP_POST_SEND
)
2183 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2184 "[Client %d] Closing on unexpected state %s.",
2185 con
->http
.fd
, http_states
[con
->http
.state
+ 1]);
2186 cupsdCloseClient(con
);
2191 while (con
->http
.state
== HTTP_POST_RECV
&& data_ready(con
));
2193 if (con
->http
.state
== HTTP_POST_SEND
)
2197 fstat(con
->file
, &filestats
);
2202 if (filestats
.st_size
> MaxRequestSize
&&
2206 * Request is too big; remove it and send an error...
2209 unlink(con
->filename
);
2210 cupsdClearString(&con
->filename
);
2215 * Delete any IPP request data...
2218 ippDelete(con
->request
);
2219 con
->request
= NULL
;
2222 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2224 cupsdCloseClient(con
);
2228 else if (filestats
.st_size
== 0)
2231 * Don't allow empty file...
2234 unlink(con
->filename
);
2235 cupsdClearString(&con
->filename
);
2240 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
2242 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
2244 cupsdCloseClient(con
);
2249 cupsdLogRequest(con
, HTTP_OK
);
2255 cupsdProcessIPPRequest(con
);
2259 unlink(con
->filename
);
2260 cupsdClearString(&con
->filename
);
2269 break; /* Anti-compiler-warning-code */
2272 if (con
->http
.state
== HTTP_WAITING
)
2274 if (!con
->http
.keep_alive
)
2276 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2277 "[Client %d] Closing because Keep-Alive disabled",
2279 cupsdCloseClient(con
);
2283 cupsArrayRemove(ActiveClients
, con
);
2284 cupsdSetBusyState();
2291 * 'cupsdSendCommand()' - Send output from a command via HTTP.
2294 int /* O - 1 on success, 0 on failure */
2296 cupsd_client_t
*con
, /* I - Client connection */
2297 char *command
, /* I - Command to run */
2298 char *options
, /* I - Command-line options */
2299 int root
) /* I - Run as root? */
2301 int fd
; /* Standard input file descriptor */
2306 fd
= open(con
->filename
, O_RDONLY
);
2310 cupsdLogMessage(CUPSD_LOG_ERROR
,
2311 "[Client %d] Unable to open \"%s\" for reading: %s",
2312 con
->http
.fd
, con
->filename
? con
->filename
: "/dev/null",
2317 fcntl(fd
, F_SETFD
, fcntl(fd
, F_GETFD
) | FD_CLOEXEC
);
2322 con
->pipe_pid
= pipe_command(con
, fd
, &(con
->file
), command
, options
, root
);
2327 cupsdLogMessage(CUPSD_LOG_INFO
, "[Client %d] Started \"%s\" (pid=%d)",
2328 con
->http
.fd
, command
, con
->pipe_pid
);
2330 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[Client %d] file=%d", con
->http
.fd
,
2333 if (con
->pipe_pid
== 0)
2336 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2338 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2340 con
->sent_header
= 0;
2341 con
->file_ready
= 0;
2342 con
->got_fields
= 0;
2343 con
->header_used
= 0;
2350 * 'cupsdSendError()' - Send an error message via HTTP.
2353 int /* O - 1 if successful, 0 otherwise */
2354 cupsdSendError(cupsd_client_t
*con
, /* I - Connection */
2355 http_status_t code
, /* I - Error code */
2356 int auth_type
)/* I - Authentication type */
2358 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2359 "[Client %d] cupsdSendError code=%d, auth_type=%d",
2360 con
->http
.fd
, code
, auth_type
);
2364 * Force client to upgrade for authentication if that is how the
2365 * server is configured...
2368 if (code
== HTTP_UNAUTHORIZED
&&
2369 DefaultEncryption
== HTTP_ENCRYPT_REQUIRED
&&
2370 _cups_strcasecmp(con
->http
.hostname
, "localhost") &&
2373 code
= HTTP_UPGRADE_REQUIRED
;
2375 #endif /* HAVE_SSL */
2378 * Put the request in the access_log file...
2381 cupsdLogRequest(con
, code
);
2384 * To work around bugs in some proxies, don't use Keep-Alive for some
2387 * Kerberos authentication doesn't work without Keep-Alive, so
2388 * never disable it in that case.
2391 if (code
>= HTTP_BAD_REQUEST
&& con
->http
.auth_type
!= CUPSD_AUTH_NEGOTIATE
)
2392 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
2395 * Send an error message back to the client. If the error code is a
2396 * 400 or 500 series, make sure the message contains some text, too!
2399 if (!cupsdSendHeader(con
, code
, NULL
, auth_type
))
2403 if (code
== HTTP_UPGRADE_REQUIRED
)
2404 if (httpPrintf(HTTP(con
), "Connection: Upgrade\r\n") < 0)
2407 if (httpPrintf(HTTP(con
), "Upgrade: TLS/1.2,TLS/1.1,TLS/1.0\r\n") < 0)
2409 #endif /* HAVE_SSL */
2411 if (con
->http
.version
>= HTTP_1_1
&&
2412 con
->http
.keep_alive
== HTTP_KEEPALIVE_OFF
)
2414 if (httpPrintf(HTTP(con
), "Connection: close\r\n") < 0)
2418 if (code
>= HTTP_BAD_REQUEST
)
2421 * Send a human-readable error message.
2424 char message
[4096], /* Message for user */
2425 urltext
[1024], /* URL redirection text */
2426 redirect
[1024]; /* Redirection link */
2427 const char *text
; /* Status-specific text */
2432 if (code
== HTTP_UNAUTHORIZED
)
2433 text
= _cupsLangString(con
->language
,
2434 _("Enter your username and password or the "
2435 "root username and password to access this "
2436 "page. If you are using Kerberos authentication, "
2437 "make sure you have a valid Kerberos ticket."));
2438 else if (code
== HTTP_UPGRADE_REQUIRED
)
2442 snprintf(urltext
, sizeof(urltext
),
2443 _cupsLangString(con
->language
,
2444 _("You must access this page using the URL "
2445 "<A HREF=\"https://%s:%d%s\">"
2446 "https://%s:%d%s</A>.")),
2447 con
->servername
, con
->serverport
, con
->uri
,
2448 con
->servername
, con
->serverport
, con
->uri
);
2450 snprintf(redirect
, sizeof(redirect
),
2451 "<META HTTP-EQUIV=\"Refresh\" "
2452 "CONTENT=\"3;URL=https://%s:%d%s\">\n",
2453 con
->servername
, con
->serverport
, con
->uri
);
2455 else if (code
== HTTP_WEBIF_DISABLED
)
2456 text
= _cupsLangString(con
->language
,
2457 _("The web interface is currently disabled. Run "
2458 "\"cupsctl WebInterface=yes\" to enable it."));
2462 snprintf(message
, sizeof(message
),
2463 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" "
2464 "\"http://www.w3.org/TR/html4/loose.dtd\">\n"
2467 "\t<META HTTP-EQUIV=\"Content-Type\" "
2468 "CONTENT=\"text/html; charset=utf-8\">\n"
2469 "\t<TITLE>%s - " CUPS_SVERSION
"</TITLE>\n"
2470 "\t<LINK REL=\"STYLESHEET\" TYPE=\"text/css\" "
2471 "HREF=\"/cups.css\">\n"
2479 httpStatus(code
), redirect
, httpStatus(code
), text
);
2481 if (httpPrintf(HTTP(con
), "Content-Type: text/html; charset=utf-8\r\n") < 0)
2483 if (httpPrintf(HTTP(con
), "Content-Length: %d\r\n",
2484 (int)strlen(message
)) < 0)
2486 if (httpPrintf(HTTP(con
), "\r\n") < 0)
2488 if (httpPrintf(HTTP(con
), "%s", message
) < 0)
2491 else if (httpPrintf(HTTP(con
), "\r\n") < 0)
2494 if (cupsdFlushHeader(con
) < 0)
2497 con
->http
.state
= HTTP_STATE_WAITING
;
2499 DEBUG_puts("cupsdSendError: Set state to HTTP_STATE_WAITING.");
2506 * 'cupsdSendHeader()' - Send an HTTP request.
2509 int /* O - 1 on success, 0 on failure */
2511 cupsd_client_t
*con
, /* I - Client to send to */
2512 http_status_t code
, /* I - HTTP status code */
2513 char *type
, /* I - MIME type of document */
2514 int auth_type
) /* I - Type of authentication */
2516 char auth_str
[1024]; /* Authorization string */
2520 * Send the HTTP status header...
2523 if (code
== HTTP_CONTINUE
)
2526 * 100-continue doesn't send any headers...
2529 return (httpPrintf(HTTP(con
), "HTTP/%d.%d 100 Continue\r\n\r\n",
2530 con
->http
.version
/ 100, con
->http
.version
% 100) > 0);
2532 else if (code
== HTTP_WEBIF_DISABLED
)
2535 * Treat our special "web interface is disabled" status as "200 OK" for web
2542 httpFlushWrite(HTTP(con
));
2544 con
->http
.data_encoding
= HTTP_ENCODE_FIELDS
;
2546 if (httpPrintf(HTTP(con
), "HTTP/%d.%d %d %s\r\n", con
->http
.version
/ 100,
2547 con
->http
.version
% 100, code
, httpStatus(code
)) < 0)
2549 if (httpPrintf(HTTP(con
), "Date: %s\r\n", httpGetDateString(time(NULL
))) < 0)
2552 if (httpPrintf(HTTP(con
), "Server: %s\r\n", ServerHeader
) < 0)
2554 if (con
->http
.keep_alive
&& con
->http
.version
>= HTTP_1_0
)
2556 if (httpPrintf(HTTP(con
), "Connection: Keep-Alive\r\n") < 0)
2558 if (httpPrintf(HTTP(con
), "Keep-Alive: timeout=%d\r\n",
2559 KeepAliveTimeout
) < 0)
2562 if (code
== HTTP_METHOD_NOT_ALLOWED
)
2563 if (httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n") < 0)
2566 if (code
== HTTP_UNAUTHORIZED
)
2568 if (auth_type
== CUPSD_AUTH_NONE
)
2570 if (!con
->best
|| con
->best
->type
<= CUPSD_AUTH_NONE
)
2571 auth_type
= cupsdDefaultAuthType();
2573 auth_type
= con
->best
->type
;
2578 if (auth_type
== CUPSD_AUTH_BASIC
|| auth_type
== CUPSD_AUTH_BASICDIGEST
)
2579 strlcpy(auth_str
, "Basic realm=\"CUPS\"", sizeof(auth_str
));
2580 else if (auth_type
== CUPSD_AUTH_DIGEST
)
2581 snprintf(auth_str
, sizeof(auth_str
), "Digest realm=\"CUPS\", nonce=\"%s\"",
2582 con
->http
.hostname
);
2584 else if (auth_type
== CUPSD_AUTH_NEGOTIATE
)
2587 if (_httpAddrFamily(con
->http
.hostaddr
) == AF_LOCAL
)
2588 strlcpy(auth_str
, "Basic realm=\"CUPS\"", sizeof(auth_str
));
2590 # endif /* AF_LOCAL */
2591 strlcpy(auth_str
, "Negotiate", sizeof(auth_str
));
2593 #endif /* HAVE_GSSAPI */
2595 if (con
->best
&& auth_type
!= CUPSD_AUTH_NEGOTIATE
&&
2596 !_cups_strcasecmp(con
->http
.hostname
, "localhost"))
2599 * Add a "trc" (try root certification) parameter for local non-Kerberos
2600 * requests when the request requires system group membership - then the
2601 * client knows the root certificate can/should be used.
2603 * Also, for OS X we also look for @AUTHKEY and add an "authkey"
2604 * parameter as needed...
2607 char *name
, /* Current user name */
2608 *auth_key
; /* Auth key buffer */
2609 size_t auth_size
; /* Size of remaining buffer */
2611 auth_key
= auth_str
+ strlen(auth_str
);
2612 auth_size
= sizeof(auth_str
) - (auth_key
- auth_str
);
2614 for (name
= (char *)cupsArrayFirst(con
->best
->names
);
2616 name
= (char *)cupsArrayNext(con
->best
->names
))
2618 #ifdef HAVE_AUTHORIZATION_H
2619 if (!_cups_strncasecmp(name
, "@AUTHKEY(", 9))
2621 snprintf(auth_key
, auth_size
, ", authkey=\"%s\"", name
+ 9);
2622 /* end parenthesis is stripped in conf.c */
2626 #endif /* HAVE_AUTHORIZATION_H */
2627 if (!_cups_strcasecmp(name
, "@SYSTEM"))
2629 #ifdef HAVE_AUTHORIZATION_H
2630 if (SystemGroupAuthKey
)
2631 snprintf(auth_key
, auth_size
,
2633 SystemGroupAuthKey
);
2636 strlcpy(auth_key
, ", trc=\"y\"", auth_size
);
2637 #endif /* HAVE_AUTHORIZATION_H */
2645 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2646 "[Client %d] WWW-Authenticate: %s", con
->http
.fd
,
2649 if (httpPrintf(HTTP(con
), "WWW-Authenticate: %s\r\n", auth_str
) < 0)
2654 if (con
->language
&& strcmp(con
->language
->language
, "C"))
2656 if (httpPrintf(HTTP(con
), "Content-Language: %s\r\n",
2657 con
->language
->language
) < 0)
2663 if (!strcmp(type
, "text/html"))
2665 if (httpPrintf(HTTP(con
),
2666 "Content-Type: text/html; charset=utf-8\r\n") < 0)
2669 else if (httpPrintf(HTTP(con
), "Content-Type: %s\r\n", type
) < 0)
2678 * 'cupsdUpdateCGI()' - Read status messages from CGI scripts and programs.
2682 cupsdUpdateCGI(void)
2684 char *ptr
, /* Pointer to end of line in buffer */
2685 message
[1024]; /* Pointer to message text */
2686 int loglevel
; /* Log level for message */
2689 while ((ptr
= cupsdStatBufUpdate(CGIStatusBuffer
, &loglevel
,
2690 message
, sizeof(message
))) != NULL
)
2692 if (loglevel
== CUPSD_LOG_INFO
)
2693 cupsdLogMessage(CUPSD_LOG_INFO
, "%s", message
);
2695 if (!strchr(CGIStatusBuffer
->buffer
, '\n'))
2699 if (ptr
== NULL
&& !CGIStatusBuffer
->bufused
)
2702 * Fatal error on pipe - should never happen!
2705 cupsdLogMessage(CUPSD_LOG_CRIT
,
2706 "cupsdUpdateCGI: error reading from CGI error pipe - %s",
2713 * 'cupsdWriteClient()' - Write data to a client as needed.
2717 cupsdWriteClient(cupsd_client_t
*con
) /* I - Client connection */
2719 int bytes
, /* Number of bytes written */
2720 field_col
; /* Current column */
2721 char *bufptr
, /* Pointer into buffer */
2722 *bufend
; /* Pointer to end of buffer */
2723 ipp_state_t ipp_state
; /* IPP state value */
2726 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2727 "[Client %d] cupsdWriteClient "
2731 "data_encoding=HTTP_ENCODE_%s, "
2732 "data_remaining=" CUPS_LLFMT
", "
2736 con
->http
.fd
, con
->http
.error
, con
->http
.used
,
2737 http_states
[con
->http
.state
+ 1],
2738 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
?
2739 "CHUNKED" : "LENGTH",
2740 CUPS_LLCAST con
->http
.data_remaining
,
2742 con
->response
? ipp_states
[con
->response
->state
] : "",
2743 con
->pipe_pid
, con
->file
);
2745 if (con
->http
.state
!= HTTP_GET_SEND
&&
2746 con
->http
.state
!= HTTP_POST_SEND
)
2749 * If we get called in the wrong state, then something went wrong with the
2750 * connection and we need to shut it down...
2753 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2754 "[Client %d] Closing on unexpected HTTP state %s.",
2755 con
->http
.fd
, http_states
[con
->http
.state
+ 1]);
2756 cupsdCloseClient(con
);
2763 * Make sure we select on the CGI output...
2766 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2768 if (!con
->file_ready
)
2771 * Try again later when there is CGI output available...
2774 cupsdRemoveSelect(con
->http
.fd
);
2778 con
->file_ready
= 0;
2781 if (con
->response
&& con
->response
->state
!= IPP_DATA
)
2783 ipp_state
= ippWrite(HTTP(con
), con
->response
);
2784 bytes
= ipp_state
!= IPP_ERROR
&&
2785 (con
->file
>= 0 || ipp_state
!= IPP_DATA
);
2787 else if ((bytes
= read(con
->file
, con
->header
+ con
->header_used
,
2788 sizeof(con
->header
) - con
->header_used
)) > 0)
2790 con
->header_used
+= bytes
;
2792 if (con
->pipe_pid
&& !con
->got_fields
)
2795 * Inspect the data for Content-Type and other fields.
2798 for (bufptr
= con
->header
, bufend
= con
->header
+ con
->header_used
,
2800 !con
->got_fields
&& bufptr
< bufend
;
2803 if (*bufptr
== '\n')
2806 * Send line to client...
2809 if (bufptr
> con
->header
&& bufptr
[-1] == '\r')
2813 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Script header: %s", con
->header
);
2815 if (!con
->sent_header
)
2818 * Handle redirection and CGI status codes...
2821 if (!_cups_strncasecmp(con
->header
, "Location:", 9))
2823 if (!cupsdSendHeader(con
, HTTP_SEE_OTHER
, NULL
, CUPSD_AUTH_NONE
))
2825 cupsdCloseClient(con
);
2829 con
->sent_header
= 2;
2831 if (httpPrintf(HTTP(con
), "Content-Length: 0\r\n") < 0)
2834 else if (!_cups_strncasecmp(con
->header
, "Status:", 7))
2836 cupsdSendError(con
, (http_status_t
)atoi(con
->header
+ 7),
2838 con
->sent_header
= 2;
2842 if (!cupsdSendHeader(con
, HTTP_OK
, NULL
, CUPSD_AUTH_NONE
))
2844 cupsdCloseClient(con
);
2848 con
->sent_header
= 1;
2850 if (con
->http
.version
== HTTP_1_1
)
2852 if (httpPrintf(HTTP(con
), "Transfer-Encoding: chunked\r\n") < 0)
2858 if (_cups_strncasecmp(con
->header
, "Status:", 7))
2859 httpPrintf(HTTP(con
), "%s\r\n", con
->header
);
2865 con
->header_used
-= bufptr
- con
->header
;
2867 if (con
->header_used
> 0)
2868 memmove(con
->header
, bufptr
, con
->header_used
);
2870 bufptr
= con
->header
- 1;
2873 * See if the line was empty...
2878 con
->got_fields
= 1;
2880 if (cupsdFlushHeader(con
) < 0)
2882 cupsdCloseClient(con
);
2886 if (con
->http
.version
== HTTP_1_1
)
2887 con
->http
.data_encoding
= HTTP_ENCODE_CHUNKED
;
2892 else if (*bufptr
!= '\r')
2896 if (!con
->got_fields
)
2898 con
->http
.activity
= time(NULL
);
2903 if (con
->header_used
> 0)
2905 if (httpWrite2(HTTP(con
), con
->header
, con
->header_used
) < 0)
2907 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2908 "[Client %d] Closing for error %d (%s)",
2909 con
->http
.fd
, con
->http
.error
,
2910 strerror(con
->http
.error
));
2911 cupsdCloseClient(con
);
2915 if (con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
)
2916 httpFlushWrite(HTTP(con
));
2918 con
->bytes
+= con
->header_used
;
2920 if (con
->http
.state
== HTTP_WAITING
)
2923 bytes
= con
->header_used
;
2925 con
->header_used
= 0;
2930 (con
->http
.state
!= HTTP_GET_SEND
&& con
->http
.state
!= HTTP_POST_SEND
))
2932 if (!con
->sent_header
&& con
->pipe_pid
)
2933 cupsdSendError(con
, HTTP_SERVER_ERROR
, CUPSD_AUTH_NONE
);
2936 cupsdLogRequest(con
, HTTP_OK
);
2938 httpFlushWrite(HTTP(con
));
2940 if (con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
&& con
->sent_header
== 1)
2942 if (httpWrite2(HTTP(con
), "", 0) < 0)
2944 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2945 "[Client %d] Closing for error %d (%s)",
2946 con
->http
.fd
, con
->http
.error
,
2947 strerror(con
->http
.error
));
2948 cupsdCloseClient(con
);
2954 con
->http
.state
= HTTP_WAITING
;
2956 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
2960 cupsdRemoveSelect(con
->file
);
2963 cupsdEndProcess(con
->pipe_pid
, 0);
2972 unlink(con
->filename
);
2973 cupsdClearString(&con
->filename
);
2978 ippDelete(con
->request
);
2979 con
->request
= NULL
;
2984 ippDelete(con
->response
);
2985 con
->response
= NULL
;
2988 cupsdClearString(&con
->command
);
2989 cupsdClearString(&con
->options
);
2990 cupsdClearString(&con
->query_string
);
2992 if (!con
->http
.keep_alive
)
2994 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2995 "[Client %d] Closing because Keep-Alive disabled.",
2997 cupsdCloseClient(con
);
3002 cupsArrayRemove(ActiveClients
, con
);
3003 cupsdSetBusyState();
3007 con
->http
.activity
= time(NULL
);
3012 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
3015 static int /* O - 1 if modified since */
3017 cupsd_client_t
*con
, /* I - Client connection */
3018 struct stat
*filestats
) /* I - File information */
3020 char *ptr
; /* Pointer into field */
3021 time_t date
; /* Time/date value */
3022 off_t size
; /* Size/length value */
3027 ptr
= con
->http
.fields
[HTTP_FIELD_IF_MODIFIED_SINCE
];
3032 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3033 "[Client %d] check_if_modified "
3034 "filestats=%p(" CUPS_LLFMT
", %d)) If-Modified-Since=\"%s\"",
3035 con
->http
.fd
, filestats
, CUPS_LLCAST filestats
->st_size
,
3036 (int)filestats
->st_mtime
, ptr
);
3038 while (*ptr
!= '\0')
3040 while (isspace(*ptr
) || *ptr
== ';')
3043 if (_cups_strncasecmp(ptr
, "length=", 7) == 0)
3046 size
= strtoll(ptr
, NULL
, 10);
3048 while (isdigit(*ptr
))
3051 else if (isalpha(*ptr
))
3053 date
= httpGetDateTime(ptr
);
3054 while (*ptr
!= '\0' && *ptr
!= ';')
3061 return ((size
!= filestats
->st_size
&& size
!= 0) ||
3062 (date
< filestats
->st_mtime
&& date
!= 0) ||
3063 (size
== 0 && date
== 0));
3068 * 'compare_clients()' - Compare two client connections.
3071 static int /* O - Result of comparison */
3072 compare_clients(cupsd_client_t
*a
, /* I - First client */
3073 cupsd_client_t
*b
, /* I - Second client */
3074 void *data
) /* I - User data (not used) */
3088 * 'data_ready()' - Check whether data is available from a client.
3091 static int /* O - 1 if data is ready, 0 otherwise */
3092 data_ready(cupsd_client_t
*con
) /* I - Client */
3094 if (con
->http
.used
> 0)
3097 else if (con
->http
.tls
)
3100 if (SSL_pending((SSL
*)(con
->http
.tls
)))
3102 # elif defined(HAVE_GNUTLS)
3103 if (gnutls_record_check_pending(con
->http
.tls
))
3105 # elif defined(HAVE_CDSASSL)
3106 size_t bytes
; /* Bytes that are available */
3108 if (!SSLGetBufferedReadSize(con
->http
.tls
, &bytes
) && bytes
> 0)
3110 # endif /* HAVE_LIBSSL */
3112 #endif /* HAVE_SSL */
3119 * 'get_file()' - Get a filename and state info.
3122 static char * /* O - Real filename */
3123 get_file(cupsd_client_t
*con
, /* I - Client connection */
3124 struct stat
*filestats
, /* O - File information */
3125 char *filename
, /* IO - Filename buffer */
3126 int len
) /* I - Buffer length */
3128 int status
; /* Status of filesystem calls */
3129 char *ptr
; /* Pointer info filename */
3130 int plen
; /* Remaining length after pointer */
3131 char language
[7]; /* Language subdirectory, if any */
3135 * Figure out the real filename...
3140 if (!strncmp(con
->uri
, "/ppd/", 5) && !strchr(con
->uri
+ 5, '/'))
3141 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
);
3142 else if (!strncmp(con
->uri
, "/icons/", 7) && !strchr(con
->uri
+ 7, '/'))
3144 snprintf(filename
, len
, "%s/%s", CacheDir
, con
->uri
+ 7);
3145 if (access(filename
, F_OK
) < 0)
3146 snprintf(filename
, len
, "%s/images/generic.png", DocumentRoot
);
3148 else if (!strncmp(con
->uri
, "/rss/", 5) && !strchr(con
->uri
+ 5, '/'))
3149 snprintf(filename
, len
, "%s/rss/%s", CacheDir
, con
->uri
+ 5);
3150 else if (!strncmp(con
->uri
, "/admin/conf/", 12))
3151 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
+ 11);
3152 else if (!strncmp(con
->uri
, "/admin/log/", 11))
3154 if (!strncmp(con
->uri
+ 11, "access_log", 10) && AccessLog
[0] == '/')
3155 strlcpy(filename
, AccessLog
, len
);
3156 else if (!strncmp(con
->uri
+ 11, "error_log", 9) && ErrorLog
[0] == '/')
3157 strlcpy(filename
, ErrorLog
, len
);
3158 else if (!strncmp(con
->uri
+ 11, "page_log", 8) && PageLog
[0] == '/')
3159 strlcpy(filename
, PageLog
, len
);
3163 else if (con
->language
)
3165 snprintf(language
, sizeof(language
), "/%s", con
->language
->language
);
3166 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3169 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3171 if ((ptr
= strchr(filename
, '?')) != NULL
)
3175 * Grab the status for this language; if there isn't a language-specific file
3176 * then fallback to the default one...
3179 if ((status
= stat(filename
, filestats
)) != 0 && language
[0] &&
3180 strncmp(con
->uri
, "/icons/", 7) &&
3181 strncmp(con
->uri
, "/ppd/", 5) &&
3182 strncmp(con
->uri
, "/rss/", 5) &&
3183 strncmp(con
->uri
, "/admin/conf/", 12) &&
3184 strncmp(con
->uri
, "/admin/log/", 11))
3187 * Drop the country code...
3191 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3193 if ((ptr
= strchr(filename
, '?')) != NULL
)
3196 if ((status
= stat(filename
, filestats
)) != 0)
3199 * Drop the language prefix and try the root directory...
3203 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3205 if ((ptr
= strchr(filename
, '?')) != NULL
)
3208 status
= stat(filename
, filestats
);
3213 * If we're found a directory, get the index.html file instead...
3216 if (!status
&& S_ISDIR(filestats
->st_mode
))
3219 * Make sure the URI ends with a slash...
3222 if (con
->uri
[strlen(con
->uri
) - 1] != '/')
3223 strlcat(con
->uri
, "/", sizeof(con
->uri
));
3226 * Find the directory index file, trying every language...
3231 if (status
&& language
[0])
3234 * Try a different language subset...
3238 language
[0] = '\0'; /* Strip country code */
3240 language
[0] = '\0'; /* Strip language */
3244 * Look for the index file...
3247 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3249 if ((ptr
= strchr(filename
, '?')) != NULL
)
3252 ptr
= filename
+ strlen(filename
);
3253 plen
= len
- (ptr
- filename
);
3255 strlcpy(ptr
, "index.html", plen
);
3256 status
= stat(filename
, filestats
);
3261 strlcpy(ptr
, "index.class", plen
);
3262 status
= stat(filename
, filestats
);
3264 #endif /* HAVE_JAVA */
3269 strlcpy(ptr
, "index.pl", plen
);
3270 status
= stat(filename
, filestats
);
3272 #endif /* HAVE_PERL */
3277 strlcpy(ptr
, "index.php", plen
);
3278 status
= stat(filename
, filestats
);
3280 #endif /* HAVE_PHP */
3285 strlcpy(ptr
, "index.pyc", plen
);
3286 status
= stat(filename
, filestats
);
3291 strlcpy(ptr
, "index.py", plen
);
3292 status
= stat(filename
, filestats
);
3294 #endif /* HAVE_PYTHON */
3297 while (status
&& language
[0]);
3300 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3301 "[Client %d] get_file filestats=%p, filename=%p, len=%d, "
3302 "returning \"%s\".", con
->http
.fd
, filestats
, filename
, len
,
3303 status
? "(null)" : filename
);
3313 * 'install_conf_file()' - Install a configuration file.
3316 static http_status_t
/* O - Status */
3317 install_conf_file(cupsd_client_t
*con
) /* I - Connection */
3319 char filename
[1024]; /* Configuration filename */
3320 mode_t mode
; /* Permissions */
3321 cups_file_t
*in
, /* Input file */
3322 *out
; /* Output file */
3323 char buffer
[16384]; /* Copy buffer */
3324 ssize_t bytes
; /* Number of bytes */
3328 * Open the request file...
3331 if ((in
= cupsFileOpen(con
->filename
, "rb")) == NULL
)
3333 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open request file \"%s\": %s",
3334 con
->filename
, strerror(errno
));
3335 return (HTTP_SERVER_ERROR
);
3339 * Open the new config file...
3342 snprintf(filename
, sizeof(filename
), "%s%s", ServerRoot
, con
->uri
+ 11);
3343 if (!strcmp(con
->uri
, "/admin/conf/printers.conf"))
3344 mode
= ConfigFilePerm
& 0600;
3346 mode
= ConfigFilePerm
;
3348 if ((out
= cupsdCreateConfFile(filename
, mode
)) == NULL
)
3351 return (HTTP_SERVER_ERROR
);
3354 cupsdLogMessage(CUPSD_LOG_INFO
, "Installing config file \"%s\"...", filename
);
3357 * Copy from the request to the new config file...
3360 while ((bytes
= cupsFileRead(in
, buffer
, sizeof(buffer
))) > 0)
3361 if (cupsFileWrite(out
, buffer
, bytes
) < bytes
)
3363 cupsdLogMessage(CUPSD_LOG_ERROR
,
3364 "Unable to copy to config file \"%s\": %s",
3365 filename
, strerror(errno
));
3370 snprintf(filename
, sizeof(filename
), "%s%s.N", ServerRoot
, con
->uri
+ 11);
3371 cupsdRemoveFile(filename
);
3373 return (HTTP_SERVER_ERROR
);
3377 * Close the files...
3382 if (cupsdCloseCreatedConfFile(out
, filename
))
3383 return (HTTP_SERVER_ERROR
);
3386 * Remove the request file...
3389 cupsdRemoveFile(con
->filename
);
3390 cupsdClearString(&con
->filename
);
3393 * If the cupsd.conf file was updated, set the NeedReload flag...
3396 if (!strcmp(con
->uri
, "/admin/conf/cupsd.conf"))
3397 NeedReload
= RELOAD_CUPSD
;
3399 NeedReload
= RELOAD_ALL
;
3401 ReloadTime
= time(NULL
);
3404 * Return that the file was created successfully...
3407 return (HTTP_CREATED
);
3412 * 'is_cgi()' - Is the resource a CGI script/program?
3415 static int /* O - 1 = CGI, 0 = file */
3416 is_cgi(cupsd_client_t
*con
, /* I - Client connection */
3417 const char *filename
, /* I - Real filename */
3418 struct stat
*filestats
, /* I - File information */
3419 mime_type_t
*type
) /* I - MIME type */
3421 const char *options
; /* Options on URL */
3425 * Get the options, if any...
3428 if ((options
= strchr(con
->uri
, '?')) != NULL
)
3431 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", options
);
3435 * Check for known types...
3438 if (!type
|| _cups_strcasecmp(type
->super
, "application"))
3440 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3441 "[Client %d] is_cgi filename=\"%s\", filestats=%p, "
3442 "type=%s/%s, returning 0", con
->http
.fd
, filename
,
3443 filestats
, type
? type
->super
: "unknown",
3444 type
? type
->type
: "unknown");
3448 if (!_cups_strcasecmp(type
->type
, "x-httpd-cgi") &&
3449 (filestats
->st_mode
& 0111))
3452 * "application/x-httpd-cgi" is a CGI script.
3455 cupsdSetString(&con
->command
, filename
);
3458 cupsdSetStringf(&con
->options
, " %s", options
);
3460 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3461 "[Client %d] is_cgi filename=\"%s\", filestats=%p, "
3462 "type=%s/%s, returning 1", con
->http
.fd
, filename
,
3463 filestats
, type
->super
, type
->type
);
3467 else if (!_cups_strcasecmp(type
->type
, "x-httpd-java"))
3470 * "application/x-httpd-java" is a Java servlet.
3473 cupsdSetString(&con
->command
, CUPS_JAVA
);
3476 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3478 cupsdSetStringf(&con
->options
, " %s", filename
);
3480 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3481 "[Client %d] is_cgi filename=\"%s\", filestats=%p, "
3482 "type=%s/%s, returning 1", con
->http
.fd
, filename
,
3483 filestats
, type
->super
, type
->type
);
3486 #endif /* HAVE_JAVA */
3488 else if (!_cups_strcasecmp(type
->type
, "x-httpd-perl"))
3491 * "application/x-httpd-perl" is a Perl page.
3494 cupsdSetString(&con
->command
, CUPS_PERL
);
3497 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3499 cupsdSetStringf(&con
->options
, " %s", filename
);
3501 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3502 "[Client %d] is_cgi filename=\"%s\", filestats=%p, "
3503 "type=%s/%s, returning 1", con
->http
.fd
, filename
,
3504 filestats
, type
->super
, type
->type
);
3507 #endif /* HAVE_PERL */
3509 else if (!_cups_strcasecmp(type
->type
, "x-httpd-php"))
3512 * "application/x-httpd-php" is a PHP page.
3515 cupsdSetString(&con
->command
, CUPS_PHP
);
3518 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3520 cupsdSetStringf(&con
->options
, " %s", filename
);
3522 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3523 "[Client %d] is_cgi filename=\"%s\", filestats=%p, "
3524 "type=%s/%s, returning 1", con
->http
.fd
, filename
,
3525 filestats
, type
->super
, type
->type
);
3528 #endif /* HAVE_PHP */
3530 else if (!_cups_strcasecmp(type
->type
, "x-httpd-python"))
3533 * "application/x-httpd-python" is a Python page.
3536 cupsdSetString(&con
->command
, CUPS_PYTHON
);
3539 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3541 cupsdSetStringf(&con
->options
, " %s", filename
);
3543 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3544 "[Client %d] is_cgi filename=\"%s\", filestats=%p, "
3545 "type=%s/%s, returning 1", con
->http
.fd
, filename
,
3546 filestats
, type
->super
, type
->type
);
3549 #endif /* HAVE_PYTHON */
3551 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3552 "[Client %d] is_cgi filename=\"%s\", filestats=%p, "
3553 "type=%s/%s, returning 0", con
->http
.fd
, filename
,
3554 filestats
, type
->super
, type
->type
);
3560 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
3563 static int /* O - 0 if relative, 1 if absolute */
3564 is_path_absolute(const char *path
) /* I - Input path */
3567 * Check for a leading slash...
3574 * Check for "/.." in the path...
3577 while ((path
= strstr(path
, "/..")) != NULL
)
3579 if (!path
[3] || path
[3] == '/')
3586 * If we haven't found any relative paths, return 1 indicating an
3595 * 'pipe_command()' - Pipe the output of a command to the remote client.
3598 static int /* O - Process ID */
3599 pipe_command(cupsd_client_t
*con
, /* I - Client connection */
3600 int infile
, /* I - Standard input for command */
3601 int *outfile
, /* O - Standard output for command */
3602 char *command
, /* I - Command to run */
3603 char *options
, /* I - Options for command */
3604 int root
) /* I - Run as root? */
3606 int i
; /* Looping var */
3607 int pid
; /* Process ID */
3608 char *commptr
, /* Command string pointer */
3609 commch
; /* Command string character */
3610 char *uriptr
; /* URI string pointer */
3611 int fds
[2]; /* Pipe FDs */
3612 int argc
; /* Number of arguments */
3613 int envc
; /* Number of environment variables */
3614 char argbuf
[10240], /* Argument buffer */
3615 *argv
[100], /* Argument strings */
3616 *envp
[MAX_ENV
+ 20]; /* Environment variables */
3617 char auth_type
[256], /* AUTH_TYPE environment variable */
3618 content_length
[1024], /* CONTENT_LENGTH environment variable */
3619 content_type
[1024], /* CONTENT_TYPE environment variable */
3620 http_cookie
[32768], /* HTTP_COOKIE environment variable */
3621 http_referer
[1024], /* HTTP_REFERER environment variable */
3622 http_user_agent
[1024], /* HTTP_USER_AGENT environment variable */
3623 lang
[1024], /* LANG environment variable */
3624 path_info
[1024], /* PATH_INFO environment variable */
3625 remote_addr
[1024], /* REMOTE_ADDR environment variable */
3626 remote_host
[1024], /* REMOTE_HOST environment variable */
3627 remote_user
[1024], /* REMOTE_USER environment variable */
3628 script_filename
[1024], /* SCRIPT_FILENAME environment variable */
3629 script_name
[1024], /* SCRIPT_NAME environment variable */
3630 server_name
[1024], /* SERVER_NAME environment variable */
3631 server_port
[1024]; /* SERVER_PORT environment variable */
3632 ipp_attribute_t
*attr
; /* attributes-natural-language attribute */
3633 void *ccache
= NULL
; /* Kerberos credentials */
3637 * Parse a copy of the options string, which is of the form:
3639 * argument+argument+argument
3640 * ?argument+argument+argument
3641 * param=value¶m=value
3642 * ?param=value¶m=value
3643 * /name?argument+argument+argument
3644 * /name?param=value¶m=value
3646 * If the string contains an "=" character after the initial name,
3647 * then we treat it as a HTTP GET form request and make a copy of
3648 * the remaining string for the environment variable.
3650 * The string is always parsed out as command-line arguments, to
3651 * be consistent with Apache...
3654 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3655 "[Client %d] pipe_command infile=%d, outfile=%p, "
3656 "command=\"%s\", options=\"%s\", root=%d",
3657 con
->http
.fd
, infile
, outfile
, command
,
3658 options
? options
: "(null)", root
);
3665 if (*commptr
== ' ')
3667 strlcpy(argbuf
, commptr
, sizeof(argbuf
));
3672 if (argbuf
[0] == '/')
3675 * Found some trailing path information, set PATH_INFO...
3678 if ((commptr
= strchr(argbuf
, '?')) == NULL
)
3679 commptr
= argbuf
+ strlen(argbuf
);
3683 snprintf(path_info
, sizeof(path_info
), "PATH_INFO=%s", argbuf
);
3689 path_info
[0] = '\0';
3691 if (*commptr
== ' ')
3695 if (*commptr
== '?' && con
->operation
== HTTP_GET
&& !con
->query_string
)
3698 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", commptr
);
3705 argv
[argc
++] = commptr
;
3707 for (; *commptr
&& argc
< 99; commptr
++)
3710 * Break arguments whenever we see a + or space...
3713 if (*commptr
== ' ' || *commptr
== '+')
3715 while (*commptr
== ' ' || *commptr
== '+')
3719 * If we don't have a blank string, save it as another argument...
3724 argv
[argc
] = commptr
;
3730 else if (*commptr
== '%' && isxdigit(commptr
[1] & 255) &&
3731 isxdigit(commptr
[2] & 255))
3734 * Convert the %xx notation to the individual character.
3737 if (commptr
[1] >= '0' && commptr
[1] <= '9')
3738 *commptr
= (commptr
[1] - '0') << 4;
3740 *commptr
= (tolower(commptr
[1]) - 'a' + 10) << 4;
3742 if (commptr
[2] >= '0' && commptr
[2] <= '9')
3743 *commptr
|= commptr
[2] - '0';
3745 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
3747 _cups_strcpy(commptr
+ 1, commptr
+ 3);
3750 * Check for a %00 and break if that is the case...
3762 * Setup the environment variables as needed...
3765 if (con
->username
[0])
3767 snprintf(auth_type
, sizeof(auth_type
), "AUTH_TYPE=%s",
3768 httpGetField(HTTP(con
), HTTP_FIELD_AUTHORIZATION
));
3770 if ((uriptr
= strchr(auth_type
+ 10, ' ')) != NULL
)
3774 auth_type
[0] = '\0';
3777 (attr
= ippFindAttribute(con
->request
, "attributes-natural-language",
3778 IPP_TAG_LANGUAGE
)) != NULL
)
3780 switch (strlen(attr
->values
[0].string
.text
))
3784 * This is an unknown or badly formatted language code; use
3785 * the POSIX locale...
3788 strlcpy(lang
, "LANG=C", sizeof(lang
));
3793 * Just the language code (ll)...
3796 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8",
3797 attr
->values
[0].string
.text
);
3802 * Language and country code (ll-cc)...
3805 snprintf(lang
, sizeof(lang
), "LANG=%c%c_%c%c.UTF8",
3806 attr
->values
[0].string
.text
[0],
3807 attr
->values
[0].string
.text
[1],
3808 toupper(attr
->values
[0].string
.text
[3] & 255),
3809 toupper(attr
->values
[0].string
.text
[4] & 255));
3813 else if (con
->language
)
3814 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8", con
->language
->language
);
3816 strlcpy(lang
, "LANG=C", sizeof(lang
));
3818 strlcpy(remote_addr
, "REMOTE_ADDR=", sizeof(remote_addr
));
3819 httpAddrString(con
->http
.hostaddr
, remote_addr
+ 12,
3820 sizeof(remote_addr
) - 12);
3822 snprintf(remote_host
, sizeof(remote_host
), "REMOTE_HOST=%s",
3823 con
->http
.hostname
);
3825 snprintf(script_name
, sizeof(script_name
), "SCRIPT_NAME=%s", con
->uri
);
3826 if ((uriptr
= strchr(script_name
, '?')) != NULL
)
3829 snprintf(script_filename
, sizeof(script_filename
), "SCRIPT_FILENAME=%s%s",
3830 DocumentRoot
, script_name
+ 12);
3832 sprintf(server_port
, "SERVER_PORT=%d", con
->serverport
);
3834 if (con
->http
.fields
[HTTP_FIELD_HOST
][0])
3836 char *nameptr
; /* Pointer to ":port" */
3838 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
3839 con
->http
.fields
[HTTP_FIELD_HOST
]);
3840 if ((nameptr
= strrchr(server_name
, ':')) != NULL
&& !strchr(nameptr
, ']'))
3841 *nameptr
= '\0'; /* Strip trailing ":port" */
3844 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
3847 envc
= cupsdLoadEnv(envp
, (int)(sizeof(envp
) / sizeof(envp
[0])));
3850 envp
[envc
++] = auth_type
;
3852 envp
[envc
++] = lang
;
3853 envp
[envc
++] = "REDIRECT_STATUS=1";
3854 envp
[envc
++] = "GATEWAY_INTERFACE=CGI/1.1";
3855 envp
[envc
++] = server_name
;
3856 envp
[envc
++] = server_port
;
3857 envp
[envc
++] = remote_addr
;
3858 envp
[envc
++] = remote_host
;
3859 envp
[envc
++] = script_name
;
3860 envp
[envc
++] = script_filename
;
3863 envp
[envc
++] = path_info
;
3865 if (con
->username
[0])
3867 snprintf(remote_user
, sizeof(remote_user
), "REMOTE_USER=%s", con
->username
);
3869 envp
[envc
++] = remote_user
;
3872 if (con
->http
.version
== HTTP_1_1
)
3873 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.1";
3874 else if (con
->http
.version
== HTTP_1_0
)
3875 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.0";
3877 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/0.9";
3879 if (con
->http
.cookie
)
3881 snprintf(http_cookie
, sizeof(http_cookie
), "HTTP_COOKIE=%s",
3883 envp
[envc
++] = http_cookie
;
3886 if (con
->http
.fields
[HTTP_FIELD_USER_AGENT
][0])
3888 snprintf(http_user_agent
, sizeof(http_user_agent
), "HTTP_USER_AGENT=%s",
3889 con
->http
.fields
[HTTP_FIELD_USER_AGENT
]);
3890 envp
[envc
++] = http_user_agent
;
3893 if (con
->http
.fields
[HTTP_FIELD_REFERER
][0])
3895 snprintf(http_referer
, sizeof(http_referer
), "HTTP_REFERER=%s",
3896 con
->http
.fields
[HTTP_FIELD_REFERER
]);
3897 envp
[envc
++] = http_referer
;
3900 if (con
->operation
== HTTP_GET
)
3902 envp
[envc
++] = "REQUEST_METHOD=GET";
3904 if (con
->query_string
)
3907 * Add GET form variables after ?...
3910 envp
[envc
++] = con
->query_string
;
3913 envp
[envc
++] = "QUERY_STRING=";
3917 sprintf(content_length
, "CONTENT_LENGTH=" CUPS_LLFMT
,
3918 CUPS_LLCAST con
->bytes
);
3919 snprintf(content_type
, sizeof(content_type
), "CONTENT_TYPE=%s",
3920 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
3922 envp
[envc
++] = "REQUEST_METHOD=POST";
3923 envp
[envc
++] = content_length
;
3924 envp
[envc
++] = content_type
;
3928 * Tell the CGI if we are using encryption...
3932 envp
[envc
++] = "HTTPS=ON";
3935 * Terminate the environment array...
3940 if (LogLevel
>= CUPSD_LOG_DEBUG
)
3942 for (i
= 0; i
< argc
; i
++)
3943 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3944 "[CGI] argv[%d] = \"%s\"", i
, argv
[i
]);
3945 for (i
= 0; i
< envc
; i
++)
3946 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3947 "[CGI] envp[%d] = \"%s\"", i
, envp
[i
]);
3951 * Create a pipe for the output...
3954 if (cupsdOpenPipe(fds
))
3956 cupsdLogMessage(CUPSD_LOG_ERROR
, "[CGI] Unable to create pipe for %s - %s",
3957 argv
[0], strerror(errno
));
3962 * Then execute the command...
3965 if (cupsdStartProcess(command
, argv
, envp
, infile
, fds
[1], CGIPipes
[1],
3966 -1, -1, root
, DefaultProfile
, NULL
, &pid
) < 0)
3969 * Error - can't fork!
3972 cupsdLogMessage(CUPSD_LOG_ERROR
, "[CGI] Unable to start %s - %s", argv
[0],
3975 cupsdClosePipe(fds
);
3981 * Fork successful - return the PID...
3984 if (con
->username
[0])
3985 cupsdAddCert(pid
, con
->username
, ccache
);
3987 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[CGI] Started %s (PID %d)", command
, pid
);
3998 * 'valid_host()' - Is the Host: field valid?
4001 static int /* O - 1 if valid, 0 if not */
4002 valid_host(cupsd_client_t
*con
) /* I - Client connection */
4004 cupsd_alias_t
*a
; /* Current alias */
4005 cupsd_netif_t
*netif
; /* Current network interface */
4006 const char *host
, /* Host field */
4007 *end
; /* End character */
4010 host
= con
->http
.fields
[HTTP_FIELD_HOST
];
4012 if (httpAddrLocalhost(con
->http
.hostaddr
))
4015 * Only allow "localhost" or the equivalent IPv4 or IPv6 numerical
4016 * addresses when accessing CUPS via the loopback interface...
4019 return (!_cups_strcasecmp(host
, "localhost") ||
4020 !_cups_strncasecmp(host
, "localhost:", 10) ||
4021 !_cups_strcasecmp(host
, "localhost.") ||
4022 !_cups_strncasecmp(host
, "localhost.:", 11) ||
4024 !_cups_strcasecmp(host
, "localhost.localdomain") ||
4025 !_cups_strncasecmp(host
, "localhost.localdomain:", 22) ||
4026 #endif /* __linux */
4027 !strcmp(host
, "127.0.0.1") ||
4028 !strncmp(host
, "127.0.0.1:", 10) ||
4029 !strcmp(host
, "[::1]") ||
4030 !strncmp(host
, "[::1]:", 6));
4033 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
4035 * Check if the hostname is something.local (Bonjour); if so, allow it.
4038 if ((end
= strrchr(host
, '.')) != NULL
&& end
> host
&&
4039 (!end
[1] || end
[1] == ':'))
4042 * "." on end, work back to second-to-last "."...
4044 for (end
--; end
> host
&& *end
!= '.'; end
--);
4047 if (end
&& (!_cups_strcasecmp(end
, ".local") ||
4048 !_cups_strncasecmp(end
, ".local:", 7) ||
4049 !_cups_strcasecmp(end
, ".local.") ||
4050 !_cups_strncasecmp(end
, ".local.:", 8)))
4052 #endif /* HAVE_DNSSD || HAVE_AVAHI */
4055 * Check if the hostname is an IP address...
4058 if (isdigit(*host
& 255) || *host
== '[')
4061 * Possible IPv4/IPv6 address...
4064 char temp
[1024], /* Temporary string */
4065 *ptr
; /* Pointer into temporary string */
4066 http_addrlist_t
*addrlist
; /* List of addresses */
4069 strlcpy(temp
, host
, sizeof(temp
));
4070 if ((ptr
= strrchr(temp
, ':')) != NULL
&& !strchr(ptr
, ']'))
4071 *ptr
= '\0'; /* Strip :port from host value */
4073 if ((addrlist
= httpAddrGetList(temp
, AF_UNSPEC
, NULL
)) != NULL
)
4076 * Good IPv4/IPv6 address...
4079 httpAddrFreeList(addrlist
);
4085 * Check for (alias) name matches...
4088 for (a
= (cupsd_alias_t
*)cupsArrayFirst(ServerAlias
);
4090 a
= (cupsd_alias_t
*)cupsArrayNext(ServerAlias
))
4093 * "ServerAlias *" allows all host values through...
4096 if (!strcmp(a
->name
, "*"))
4099 if (!_cups_strncasecmp(host
, a
->name
, a
->namelen
))
4102 * Prefix matches; check the character at the end - it must be ":", ".",
4106 end
= host
+ a
->namelen
;
4108 if (!*end
|| *end
== ':' || (*end
== '.' && (!end
[1] || end
[1] == ':')))
4113 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
4114 for (a
= (cupsd_alias_t
*)cupsArrayFirst(DNSSDAlias
);
4116 a
= (cupsd_alias_t
*)cupsArrayNext(DNSSDAlias
))
4119 * "ServerAlias *" allows all host values through...
4122 if (!strcmp(a
->name
, "*"))
4125 if (!_cups_strncasecmp(host
, a
->name
, a
->namelen
))
4128 * Prefix matches; check the character at the end - it must be ":", ".",
4132 end
= host
+ a
->namelen
;
4134 if (!*end
|| *end
== ':' || (*end
== '.' && (!end
[1] || end
[1] == ':')))
4138 #endif /* HAVE_DNSSD || HAVE_AVAHI */
4141 * Check for interface hostname matches...
4144 for (netif
= (cupsd_netif_t
*)cupsArrayFirst(NetIFList
);
4146 netif
= (cupsd_netif_t
*)cupsArrayNext(NetIFList
))
4148 if (!_cups_strncasecmp(host
, netif
->hostname
, netif
->hostlen
))
4151 * Prefix matches; check the character at the end - it must be ":", ".",
4155 end
= host
+ netif
->hostlen
;
4157 if (!*end
|| *end
== ':' || (*end
== '.' && (!end
[1] || end
[1] == ':')))
4167 * 'write_file()' - Send a file via HTTP.
4170 static int /* O - 0 on failure, 1 on success */
4171 write_file(cupsd_client_t
*con
, /* I - Client connection */
4172 http_status_t code
, /* I - HTTP status */
4173 char *filename
, /* I - Filename */
4174 char *type
, /* I - File type */
4175 struct stat
*filestats
) /* O - File information */
4177 con
->file
= open(filename
, O_RDONLY
);
4179 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4180 "[Client %d] write_file code=%d, filename=\"%s\" (%d), "
4181 "type=\"%s\", filestats=%p", con
->http
.fd
,
4182 code
, filename
, con
->file
, type
? type
: "(null)", filestats
);
4187 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
4191 if (!cupsdSendHeader(con
, code
, type
, CUPSD_AUTH_NONE
))
4194 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
4195 httpGetDateString(filestats
->st_mtime
)) < 0)
4197 if (httpPrintf(HTTP(con
), "Content-Length: " CUPS_LLFMT
"\r\n",
4198 CUPS_LLCAST filestats
->st_size
) < 0)
4200 if (httpPrintf(HTTP(con
), "\r\n") < 0)
4203 if (cupsdFlushHeader(con
) < 0)
4206 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
4207 con
->http
.data_remaining
= filestats
->st_size
;
4209 if (con
->http
.data_remaining
<= INT_MAX
)
4210 con
->http
._data_remaining
= con
->http
.data_remaining
;
4212 con
->http
._data_remaining
= INT_MAX
;
4214 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
,
4215 (cupsd_selfunc_t
)cupsdWriteClient
, con
);
4222 * 'write_pipe()' - Flag that data is available on the CGI pipe.
4226 write_pipe(cupsd_client_t
*con
) /* I - Client connection */
4228 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4229 "[Client %d] write_pipe CGI output on fd %d",
4230 con
->http
.fd
, con
->file
);
4232 con
->file_ready
= 1;
4234 cupsdRemoveSelect(con
->file
);
4235 cupsdAddSelect(con
->http
.fd
, NULL
, (cupsd_selfunc_t
)cupsdWriteClient
, con
);
4240 * End of "$Id: client.c 7950 2008-09-17 00:21:59Z mike $".