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_cupsd_conf() - 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_cupsd_conf(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;
184 con
->http
.mode
= _HTTP_MODE_SERVER
;
187 * Accept the client and get the remote address...
190 addrlen
= sizeof(http_addr_t
);
192 if ((con
->http
.fd
= accept(lis
->fd
, (struct sockaddr
*)con
->http
.hostaddr
,
195 if (errno
== ENFILE
|| errno
== EMFILE
)
196 cupsdPauseListening();
198 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to accept client connection - %s.",
206 * Save the connected port number...
209 _httpAddrSetPort(con
->http
.hostaddr
, httpAddrPort(&(lis
->address
)));
213 * Convert IPv4 over IPv6 addresses (::ffff:n.n.n.n) to IPv4 forms we
214 * can more easily use...
217 if (lis
->address
.addr
.sa_family
== AF_INET6
&&
218 con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[0] == 0 &&
219 con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[1] == 0 &&
220 ntohl(con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[2]) == 0xffff)
221 con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[2] = 0;
222 #endif /* AF_INET6 */
225 * Check the number of clients on the same address...
228 for (count
= 0, tempcon
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
230 tempcon
= (cupsd_client_t
*)cupsArrayNext(Clients
))
231 if (httpAddrEqual(tempcon
->http
.hostaddr
, con
->http
.hostaddr
))
234 if (count
>= MaxClientsPerHost
)
238 if (count
>= MaxClientsPerHost
)
240 if ((time(NULL
) - last_dos
) >= 60)
242 last_dos
= time(NULL
);
243 cupsdLogMessage(CUPSD_LOG_WARN
,
244 "Possible DoS attack - more than %d clients connecting "
247 httpAddrString(con
->http
.hostaddr
, con
->http
.hostname
,
248 sizeof(con
->http
.hostname
)));
252 closesocket(con
->http
.fd
);
262 * Get the hostname or format the IP address as needed...
265 if (httpAddrLocalhost(con
->http
.hostaddr
))
268 * Map accesses from the loopback interface to "localhost"...
271 strlcpy(con
->http
.hostname
, "localhost", sizeof(con
->http
.hostname
));
272 hostname
= con
->http
.hostname
;
277 * Map accesses from the same host to the server name.
281 hostname
= httpAddrLookup(con
->http
.hostaddr
, con
->http
.hostname
,
282 sizeof(con
->http
.hostname
));
286 httpAddrString(con
->http
.hostaddr
, con
->http
.hostname
,
287 sizeof(con
->http
.hostname
));
291 if (hostname
== NULL
&& HostNameLookups
== 2)
294 * Can't have an unresolved IP address with double-lookups enabled...
298 closesocket(con
->http
.fd
);
303 cupsdLogMessage(CUPSD_LOG_WARN
,
304 "Name lookup failed - connection from %s closed!",
311 if (HostNameLookups
== 2)
314 * Do double lookups as needed...
317 if ((addrlist
= httpAddrGetList(con
->http
.hostname
, AF_UNSPEC
, NULL
))
321 * See if the hostname maps to the same IP address...
324 for (addr
= addrlist
; addr
; addr
= addr
->next
)
325 if (httpAddrEqual(con
->http
.hostaddr
, &(addr
->addr
)))
331 httpAddrFreeList(addrlist
);
336 * Can't have a hostname that doesn't resolve to the same IP address
337 * with double-lookups enabled...
341 closesocket(con
->http
.fd
);
346 cupsdLogMessage(CUPSD_LOG_WARN
,
347 "IP lookup failed - connection from %s closed!",
356 * See if the connection is denied by TCP wrappers...
359 request_init(&wrap_req
, RQ_DAEMON
, "cupsd", RQ_FILE
, con
->http
.fd
, NULL
);
362 if (!hosts_access(&wrap_req
))
365 closesocket(con
->http
.fd
);
370 cupsdLogMessage(CUPSD_LOG_WARN
,
371 "Connection from %s refused by /etc/hosts.allow and "
372 "/etc/hosts.deny rules.", con
->http
.hostname
);
376 #endif /* HAVE_TCPD_H */
379 if (con
->http
.hostaddr
->addr
.sa_family
== AF_LOCAL
)
380 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[Client %d] Accepted from %s (Domain)",
381 con
->http
.fd
, con
->http
.hostname
);
383 #endif /* AF_LOCAL */
384 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[Client %d] Accepted from %s:%d (IPv%d)",
385 con
->http
.fd
, con
->http
.hostname
,
386 httpAddrPort(con
->http
.hostaddr
),
387 _httpAddrFamily(con
->http
.hostaddr
) == AF_INET
? 4 : 6);
390 * Get the local address the client connected to...
393 addrlen
= sizeof(temp
);
394 if (getsockname(con
->http
.fd
, (struct sockaddr
*)&temp
, &addrlen
))
396 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to get local address - %s",
399 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
400 con
->serverport
= LocalPort
;
403 else if (_httpAddrFamily(&temp
) == AF_LOCAL
)
405 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
406 con
->serverport
= LocalPort
;
408 #endif /* AF_LOCAL */
411 if (httpAddrLocalhost(&temp
))
412 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
413 else if (HostNameLookups
|| RemotePort
)
414 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
416 httpAddrString(&temp
, con
->servername
, sizeof(con
->servername
));
418 con
->serverport
= httpAddrPort(&(lis
->address
));
422 * Add the connection to the array of active clients...
425 cupsArrayAdd(Clients
, con
);
428 * Using TCP_NODELAY improves responsiveness, especially on systems with a slow
429 * loopback interface. Since we write large buffers when sending print files
430 * and requests there shouldn't be any performance penalty for this...
434 setsockopt(con
->http
.fd
, IPPROTO_TCP
, TCP_NODELAY
, &val
, sizeof(val
));
437 * Close this file on all execs...
440 fcntl(con
->http
.fd
, F_SETFD
, fcntl(con
->http
.fd
, F_GETFD
) | FD_CLOEXEC
);
443 * Add the socket to the server select.
446 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
449 * Temporarily suspend accept()'s until we lose a client...
452 if (cupsArrayCount(Clients
) == MaxClients
)
453 cupsdPauseListening();
457 * See if we are connecting on a secure port...
460 if (lis
->encryption
== HTTP_ENCRYPT_ALWAYS
)
463 * https connection; go secure...
466 con
->http
.encryption
= HTTP_ENCRYPT_ALWAYS
;
468 if (!cupsdStartTLS(con
))
469 cupsdCloseClient(con
);
473 #endif /* HAVE_SSL */
478 * 'cupsdCloseAllClients()' - Close all remote clients immediately.
482 cupsdCloseAllClients(void)
484 cupsd_client_t
*con
; /* Current client */
487 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdCloseAllClients() Clients=%d",
488 cupsArrayCount(Clients
));
490 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
492 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
493 if (cupsdCloseClient(con
))
494 cupsdCloseClient(con
);
499 * 'cupsdCloseClient()' - Close a remote client.
502 int /* O - 1 if partial close, 0 if fully closed */
503 cupsdCloseClient(cupsd_client_t
*con
) /* I - Client to close */
505 int partial
; /* Do partial close for SSL? */
507 #elif defined(HAVE_GNUTLS)
508 # elif defined(HAVE_CDSASSL)
509 #endif /* HAVE_LIBSSL */
512 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[Client %d] Closing connection.",
516 * Flush pending writes before closing...
519 httpFlushWrite(HTTP(con
));
525 * Shutdown encryption as needed...
534 #endif /* HAVE_SSL */
536 if (con
->pipe_pid
!= 0)
539 * Stop any CGI process...
542 cupsdEndProcess(con
->pipe_pid
, 1);
548 cupsdRemoveSelect(con
->file
);
555 * Close the socket and clear the file from the input set for select()...
558 if (con
->http
.fd
>= 0)
560 cupsArrayRemove(ActiveClients
, con
);
566 * Only do a partial close so that the encrypted client gets everything.
569 shutdown(con
->http
.fd
, 0);
570 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
575 * Shut the socket down fully...
578 cupsdRemoveSelect(con
->http
.fd
);
590 if (con
->http
.input_set
)
591 free(con
->http
.input_set
);
593 httpClearCookie(HTTP(con
));
594 httpClearFields(HTTP(con
));
596 cupsdClearString(&con
->filename
);
597 cupsdClearString(&con
->command
);
598 cupsdClearString(&con
->options
);
599 cupsdClearString(&con
->query_string
);
603 ippDelete(con
->request
);
609 ippDelete(con
->response
);
610 con
->response
= NULL
;
615 cupsLangFree(con
->language
);
616 con
->language
= NULL
;
619 #ifdef HAVE_AUTHORIZATION_H
622 AuthorizationFree(con
->authref
, kAuthorizationFlagDefaults
);
625 #endif /* HAVE_AUTHORIZATION_H */
628 * Re-enable new client connections if we are going back under the
632 if (cupsArrayCount(Clients
) == MaxClients
)
633 cupsdResumeListening();
636 * Compact the list of clients as necessary...
639 cupsArrayRemove(Clients
, con
);
649 * 'cupsdFlushHeader()' - Flush the header fields to the client.
652 int /* I - Bytes written or -1 on error */
653 cupsdFlushHeader(cupsd_client_t
*con
) /* I - Client to flush to */
655 int bytes
= httpFlushWrite(HTTP(con
));
657 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
664 * 'cupsdReadClient()' - Read data from a client.
668 cupsdReadClient(cupsd_client_t
*con
) /* I - Client to read from */
670 char line
[32768], /* Line from client... */
671 operation
[64], /* Operation code from socket */
672 version
[64], /* HTTP version number string */
673 locale
[64], /* Locale */
674 *ptr
; /* Pointer into strings */
675 int major
, minor
; /* HTTP version numbers */
676 http_status_t status
; /* Transfer status */
677 ipp_state_t ipp_state
; /* State of IPP transfer */
678 int bytes
; /* Number of bytes to POST */
679 char *filename
; /* Name of file for GET/HEAD */
680 char buf
[1024]; /* Buffer for real filename */
681 struct stat filestats
; /* File information */
682 mime_type_t
*type
; /* MIME type of file */
683 cupsd_printer_t
*p
; /* Printer */
684 static unsigned request_id
= 0; /* Request ID for temp files */
687 status
= HTTP_CONTINUE
;
689 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
690 "[Client %d] cupsdReadClient "
694 "data_encoding=HTTP_ENCODING_%s, "
695 "data_remaining=" CUPS_LLFMT
", "
698 con
->http
.fd
, con
->http
.error
, con
->http
.used
,
699 http_states
[con
->http
.state
+ 1],
700 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
?
701 "CHUNKED" : "LENGTH",
702 CUPS_LLCAST con
->http
.data_remaining
,
704 con
->request
? ipp_states
[con
->request
->state
] : "",
711 * Automatically check for a SSL/TLS handshake...
716 if (recv(con
->http
.fd
, buf
, 1, MSG_PEEK
) == 1 &&
717 (!buf
[0] || !strchr("DGHOPT", buf
[0])))
720 * Encrypt this connection...
723 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
724 "[Client %d] Saw first byte %02X, auto-negotiating "
725 "SSL/TLS session.", con
->http
.fd
, buf
[0] & 255);
727 if (!cupsdStartTLS(con
))
728 cupsdCloseClient(con
);
733 #endif /* HAVE_SSL */
735 switch (con
->http
.state
)
739 * See if we've received a request line...
742 if (httpGets(line
, sizeof(line
) - 1, HTTP(con
)) == NULL
)
744 if (con
->http
.error
&& con
->http
.error
!= EPIPE
)
745 cupsdLogMessage(CUPSD_LOG_DEBUG
,
746 "[Client %d] HTTP_WAITING Closing for error %d "
747 "(%s)", con
->http
.fd
, con
->http
.error
,
748 strerror(con
->http
.error
));
750 cupsdLogMessage(CUPSD_LOG_DEBUG
,
751 "[Client %d] HTTP_WAITING Closing on EOF",
754 cupsdCloseClient(con
);
759 * Ignore blank request lines...
766 * Clear other state variables...
769 httpClearFields(HTTP(con
));
771 con
->http
.activity
= time(NULL
);
772 con
->http
.version
= HTTP_1_0
;
773 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
774 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
775 con
->http
.data_remaining
= 0;
776 con
->http
._data_remaining
= 0;
777 con
->operation
= HTTP_WAITING
;
782 con
->username
[0] = '\0';
783 con
->password
[0] = '\0';
786 cupsdClearString(&con
->command
);
787 cupsdClearString(&con
->options
);
788 cupsdClearString(&con
->query_string
);
792 ippDelete(con
->request
);
798 ippDelete(con
->response
);
799 con
->response
= NULL
;
804 cupsLangFree(con
->language
);
805 con
->language
= NULL
;
811 #endif /* HAVE_GSSAPI */
814 * Grab the request line...
817 switch (sscanf(line
, "%63s%1023s%63s", operation
, con
->uri
, version
))
822 cupsdLogMessage(CUPSD_LOG_ERROR
,
823 "[Client %d] Bad request line \"%s\" from %s.",
825 _httpEncodeURI(buf
, line
, sizeof(buf
)),
827 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
828 cupsdCloseClient(con
);
832 con
->http
.version
= HTTP_0_9
;
835 if (sscanf(version
, "HTTP/%d.%d", &major
, &minor
) != 2)
837 cupsdLogMessage(CUPSD_LOG_ERROR
,
838 "[Client %d] Bad request line \"%s\" from %s.",
840 _httpEncodeURI(buf
, line
, sizeof(buf
)),
842 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
843 cupsdCloseClient(con
);
849 con
->http
.version
= (http_version_t
)(major
* 100 + minor
);
850 if (con
->http
.version
== HTTP_1_1
&& KeepAlive
)
851 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
853 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
857 cupsdLogMessage(CUPSD_LOG_ERROR
,
858 "[Client %d] Unsupported request line \"%s\" "
859 "from %s.", con
->http
.fd
,
860 _httpEncodeURI(buf
, line
, sizeof(buf
)),
862 cupsdSendError(con
, HTTP_NOT_SUPPORTED
, CUPSD_AUTH_NONE
);
863 cupsdCloseClient(con
);
870 * Handle full URLs in the request line...
873 if (strcmp(con
->uri
, "*"))
875 char scheme
[HTTP_MAX_URI
], /* Method/scheme */
876 userpass
[HTTP_MAX_URI
], /* Username:password */
877 hostname
[HTTP_MAX_URI
], /* Hostname */
878 resource
[HTTP_MAX_URI
]; /* Resource path */
879 int port
; /* Port number */
883 * Separate the URI into its components...
886 httpSeparateURI(HTTP_URI_CODING_MOST
, con
->uri
,
887 scheme
, sizeof(scheme
),
888 userpass
, sizeof(userpass
),
889 hostname
, sizeof(hostname
), &port
,
890 resource
, sizeof(resource
));
893 * Only allow URIs with the servername, localhost, or an IP
897 if (strcmp(scheme
, "file") &&
898 _cups_strcasecmp(hostname
, ServerName
) &&
899 _cups_strcasecmp(hostname
, "localhost") &&
900 !isdigit(hostname
[0]) && hostname
[0] != '[')
903 * Nope, we don't do proxies...
906 cupsdLogMessage(CUPSD_LOG_ERROR
,
907 "[Client %d] Bad URI \"%s\" in request.",
908 con
->http
.fd
, con
->uri
);
909 cupsdSendError(con
, HTTP_METHOD_NOT_ALLOWED
, CUPSD_AUTH_NONE
);
910 cupsdCloseClient(con
);
915 * Copy the resource portion back into the URI; both resource and
916 * con->uri are HTTP_MAX_URI bytes in size...
919 strlcpy(con
->uri
, resource
, sizeof(con
->uri
));
923 * Process the request...
926 if (!strcmp(operation
, "GET"))
927 con
->http
.state
= HTTP_GET
;
928 else if (!strcmp(operation
, "PUT"))
929 con
->http
.state
= HTTP_PUT
;
930 else if (!strcmp(operation
, "POST"))
931 con
->http
.state
= HTTP_POST
;
932 else if (!strcmp(operation
, "DELETE"))
933 con
->http
.state
= HTTP_DELETE
;
934 else if (!strcmp(operation
, "TRACE"))
935 con
->http
.state
= HTTP_TRACE
;
936 else if (!strcmp(operation
, "OPTIONS"))
937 con
->http
.state
= HTTP_OPTIONS
;
938 else if (!strcmp(operation
, "HEAD"))
939 con
->http
.state
= HTTP_HEAD
;
942 cupsdLogMessage(CUPSD_LOG_ERROR
,
943 "[Client %d] Bad operation \"%s\".", con
->http
.fd
,
945 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
946 cupsdCloseClient(con
);
950 gettimeofday(&(con
->start
), NULL
);
951 con
->operation
= con
->http
.state
;
953 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[Client %d] %s %s HTTP/%d.%d",
954 con
->http
.fd
, operation
, con
->uri
,
955 con
->http
.version
/ 100, con
->http
.version
% 100);
957 con
->http
.status
= HTTP_OK
;
959 if (!cupsArrayFind(ActiveClients
, con
))
961 cupsArrayAdd(ActiveClients
, con
);
973 * Parse incoming parameters until the status changes...
976 while ((status
= httpUpdate(HTTP(con
))) == HTTP_CONTINUE
)
977 if (!data_ready(con
))
980 if (status
!= HTTP_OK
&& status
!= HTTP_CONTINUE
)
982 if (con
->http
.error
&& con
->http
.error
!= EPIPE
)
983 cupsdLogMessage(CUPSD_LOG_DEBUG
,
984 "[Client %d] Closing for error %d (%s) while "
986 con
->http
.fd
, con
->http
.error
,
987 strerror(con
->http
.error
));
989 cupsdLogMessage(CUPSD_LOG_DEBUG
,
990 "[Client %d] Closing on EOF while reading headers.",
993 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
994 cupsdCloseClient(con
);
1000 if (!data_ready(con
) && recv(con
->http
.fd
, buf
, 1, MSG_PEEK
) < 1)
1003 * Connection closed...
1006 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1007 "[Client %d] Closing on EOF", con
->http
.fd
);
1008 cupsdCloseClient(con
);
1011 break; /* Anti-compiler-warning-code */
1015 * Handle new transfers...
1018 if (status
== HTTP_OK
)
1020 if (con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
][0])
1023 * Figure out the locale from the Accept-Language and Content-Type
1027 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
],
1031 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
],
1035 if ((ptr
= strstr(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
],
1036 "charset=")) != NULL
)
1039 * Combine language and charset, and trim any extra params in the
1043 snprintf(locale
, sizeof(locale
), "%s.%s",
1044 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ptr
+ 8);
1046 if ((ptr
= strchr(locale
, ',')) != NULL
)
1050 snprintf(locale
, sizeof(locale
), "%s.UTF-8",
1051 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
]);
1053 con
->language
= cupsLangGet(locale
);
1056 con
->language
= cupsLangGet(DefaultLocale
);
1058 cupsdAuthorize(con
);
1060 if (!_cups_strncasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
],
1061 "Keep-Alive", 10) && KeepAlive
)
1062 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
1063 else if (!_cups_strncasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
],
1065 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1067 if (!con
->http
.fields
[HTTP_FIELD_HOST
][0] &&
1068 con
->http
.version
>= HTTP_1_1
)
1071 * HTTP/1.1 and higher require the "Host:" field...
1074 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1076 cupsdLogMessage(CUPSD_LOG_ERROR
,
1077 "[Client %d] Missing Host: field in request.",
1079 cupsdCloseClient(con
);
1083 else if (!valid_host(con
))
1086 * Access to localhost must use "localhost" or the corresponding IPv4
1087 * or IPv6 values in the Host: field.
1090 cupsdLogMessage(CUPSD_LOG_ERROR
,
1091 "[Client %d] Request from \"%s\" using invalid Host: "
1092 "field \"%s\"", con
->http
.fd
, con
->http
.hostname
,
1093 con
->http
.fields
[HTTP_FIELD_HOST
]);
1095 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1097 cupsdCloseClient(con
);
1101 else if (con
->operation
== HTTP_OPTIONS
)
1104 * Do OPTIONS command...
1107 if (con
->best
&& con
->best
->type
!= CUPSD_AUTH_NONE
)
1109 if (!cupsdSendHeader(con
, HTTP_UNAUTHORIZED
, NULL
, CUPSD_AUTH_NONE
))
1111 cupsdCloseClient(con
);
1116 if (!_cups_strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") &&
1117 con
->http
.tls
== NULL
)
1121 * Do encryption stuff...
1124 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
, CUPSD_AUTH_NONE
))
1126 cupsdCloseClient(con
);
1130 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1131 httpPrintf(HTTP(con
), "Upgrade: TLS/1.2,TLS/1.1,TLS/1.0\r\n");
1132 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1133 httpPrintf(HTTP(con
), "\r\n");
1135 if (cupsdFlushHeader(con
) < 0)
1137 cupsdCloseClient(con
);
1141 if (!cupsdStartTLS(con
))
1143 cupsdCloseClient(con
);
1147 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
1149 cupsdCloseClient(con
);
1152 #endif /* HAVE_SSL */
1155 if (!cupsdSendHeader(con
, HTTP_OK
, NULL
, CUPSD_AUTH_NONE
))
1157 cupsdCloseClient(con
);
1161 httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n");
1162 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1163 httpPrintf(HTTP(con
), "\r\n");
1165 if (cupsdFlushHeader(con
) < 0)
1167 cupsdCloseClient(con
);
1171 else if (!is_path_absolute(con
->uri
))
1174 * Protect against malicious users!
1177 cupsdLogMessage(CUPSD_LOG_ERROR
,
1178 "[Client %d] Request for non-absolute resource \"%s\".",
1179 con
->http
.fd
, con
->uri
);
1181 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1183 cupsdCloseClient(con
);
1189 if (!_cups_strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
],
1190 "Upgrade") && con
->http
.tls
== NULL
)
1194 * Do encryption stuff...
1197 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
,
1200 cupsdCloseClient(con
);
1204 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1205 httpPrintf(HTTP(con
), "Upgrade: TLS/1.2,TLS/1.1,TLS/1.0\r\n");
1206 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1207 httpPrintf(HTTP(con
), "\r\n");
1209 if (cupsdFlushHeader(con
) < 0)
1211 cupsdCloseClient(con
);
1215 if (!cupsdStartTLS(con
))
1217 cupsdCloseClient(con
);
1221 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
1223 cupsdCloseClient(con
);
1226 #endif /* HAVE_SSL */
1229 if ((status
= cupsdIsAuthorized(con
, NULL
)) != HTTP_OK
)
1231 cupsdSendError(con
, status
, CUPSD_AUTH_NONE
);
1232 cupsdCloseClient(con
);
1236 if (con
->http
.expect
&&
1237 (con
->operation
== HTTP_POST
|| con
->operation
== HTTP_PUT
))
1239 if (con
->http
.expect
== HTTP_CONTINUE
)
1242 * Send 100-continue header...
1245 if (!cupsdSendHeader(con
, HTTP_CONTINUE
, NULL
, CUPSD_AUTH_NONE
))
1247 cupsdCloseClient(con
);
1254 * Send 417-expectation-failed header...
1257 if (!cupsdSendHeader(con
, HTTP_EXPECTATION_FAILED
, NULL
,
1260 cupsdCloseClient(con
);
1264 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1265 httpPrintf(HTTP(con
), "\r\n");
1267 if (cupsdFlushHeader(con
) < 0)
1269 cupsdCloseClient(con
);
1275 switch (con
->http
.state
)
1277 case HTTP_GET_SEND
:
1278 if (!strncmp(con
->uri
, "/printers/", 10) &&
1279 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1282 * Send PPD file - get the real printer name since printer
1283 * names are not case sensitive but filenames can be...
1286 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1288 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1289 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1292 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1294 cupsdCloseClient(con
);
1301 else if ((!strncmp(con
->uri
, "/printers/", 10) ||
1302 !strncmp(con
->uri
, "/classes/", 9)) &&
1303 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".png"))
1306 * Send icon file - get the real queue name since queue names are
1307 * not case sensitive but filenames can be...
1310 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".png" */
1312 if (!strncmp(con
->uri
, "/printers/", 10))
1313 p
= cupsdFindPrinter(con
->uri
+ 10);
1315 p
= cupsdFindClass(con
->uri
+ 9);
1318 snprintf(con
->uri
, sizeof(con
->uri
), "/icons/%s.png", p
->name
);
1321 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1323 cupsdCloseClient(con
);
1330 else if (!WebInterface
)
1333 * Web interface is disabled. Show an appropriate message...
1336 if (!cupsdSendError(con
, HTTP_WEBIF_DISABLED
, CUPSD_AUTH_NONE
))
1338 cupsdCloseClient(con
);
1345 if ((!strncmp(con
->uri
, "/admin", 6) &&
1346 strncmp(con
->uri
, "/admin/conf/", 12) &&
1347 strncmp(con
->uri
, "/admin/log/", 11)) ||
1348 !strncmp(con
->uri
, "/printers", 9) ||
1349 !strncmp(con
->uri
, "/classes", 8) ||
1350 !strncmp(con
->uri
, "/help", 5) ||
1351 !strncmp(con
->uri
, "/jobs", 5))
1354 * Send CGI output...
1357 if (!strncmp(con
->uri
, "/admin", 6))
1359 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1362 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1364 else if (!strncmp(con
->uri
, "/printers", 9))
1366 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1369 if (con
->uri
[9] && con
->uri
[10])
1370 cupsdSetString(&con
->options
, con
->uri
+ 9);
1372 cupsdSetString(&con
->options
, NULL
);
1374 else if (!strncmp(con
->uri
, "/classes", 8))
1376 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1379 if (con
->uri
[8] && con
->uri
[9])
1380 cupsdSetString(&con
->options
, con
->uri
+ 8);
1382 cupsdSetString(&con
->options
, NULL
);
1384 else if (!strncmp(con
->uri
, "/jobs", 5))
1386 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1389 if (con
->uri
[5] && con
->uri
[6])
1390 cupsdSetString(&con
->options
, con
->uri
+ 5);
1392 cupsdSetString(&con
->options
, NULL
);
1396 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1399 if (con
->uri
[5] && con
->uri
[6])
1400 cupsdSetString(&con
->options
, con
->uri
+ 5);
1402 cupsdSetString(&con
->options
, NULL
);
1405 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1407 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1409 cupsdCloseClient(con
);
1414 cupsdLogRequest(con
, HTTP_OK
);
1416 if (con
->http
.version
<= HTTP_1_0
)
1417 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1419 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1420 (strchr(con
->uri
+ 12, '/') ||
1421 strlen(con
->uri
) == 12)) ||
1422 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1423 (strchr(con
->uri
+ 11, '/') ||
1424 strlen(con
->uri
) == 11)))
1427 * GET can only be done to configuration files directly under
1431 cupsdLogMessage(CUPSD_LOG_ERROR
,
1432 "Request for subdirectory \"%s\"!", con
->uri
);
1434 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1436 cupsdCloseClient(con
);
1448 if ((filename
= get_file(con
, &filestats
, buf
,
1449 sizeof(buf
))) == NULL
)
1451 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1453 cupsdCloseClient(con
);
1460 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1462 if (is_cgi(con
, filename
, &filestats
, type
))
1465 * Note: con->command and con->options were set by
1469 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1471 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1473 cupsdCloseClient(con
);
1478 cupsdLogRequest(con
, HTTP_OK
);
1480 if (con
->http
.version
<= HTTP_1_0
)
1481 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1485 if (!check_if_modified(con
, &filestats
))
1487 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1489 cupsdCloseClient(con
);
1496 strlcpy(line
, "text/plain", sizeof(line
));
1498 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1500 if (!write_file(con
, HTTP_OK
, filename
, line
, &filestats
))
1502 cupsdCloseClient(con
);
1509 case HTTP_POST_RECV
:
1511 * See if the POST request includes a Content-Length field, and if
1512 * so check the length against any limits that are set...
1515 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1516 MaxRequestSize
> 0 &&
1517 con
->http
.data_remaining
> MaxRequestSize
)
1520 * Request too large...
1523 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1525 cupsdCloseClient(con
);
1531 else if (con
->http
.data_remaining
< 0 ||
1532 (!con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1533 con
->http
.data_encoding
== HTTP_ENCODE_LENGTH
))
1536 * Negative content lengths are invalid!
1539 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1541 cupsdCloseClient(con
);
1549 * See what kind of POST request this is; for IPP requests the
1550 * content-type field will be "application/ipp"...
1553 if (!strcmp(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
],
1555 con
->request
= ippNew();
1556 else if (!WebInterface
)
1559 * Web interface is disabled. Show an appropriate message...
1562 if (!cupsdSendError(con
, HTTP_WEBIF_DISABLED
, CUPSD_AUTH_NONE
))
1564 cupsdCloseClient(con
);
1570 else if ((!strncmp(con
->uri
, "/admin", 6) &&
1571 strncmp(con
->uri
, "/admin/conf/", 12) &&
1572 strncmp(con
->uri
, "/admin/log/", 11)) ||
1573 !strncmp(con
->uri
, "/printers", 9) ||
1574 !strncmp(con
->uri
, "/classes", 8) ||
1575 !strncmp(con
->uri
, "/help", 5) ||
1576 !strncmp(con
->uri
, "/jobs", 5))
1582 if (!strncmp(con
->uri
, "/admin", 6))
1584 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1587 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1589 else if (!strncmp(con
->uri
, "/printers", 9))
1591 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1594 if (con
->uri
[9] && con
->uri
[10])
1595 cupsdSetString(&con
->options
, con
->uri
+ 9);
1597 cupsdSetString(&con
->options
, NULL
);
1599 else if (!strncmp(con
->uri
, "/classes", 8))
1601 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1604 if (con
->uri
[8] && con
->uri
[9])
1605 cupsdSetString(&con
->options
, con
->uri
+ 8);
1607 cupsdSetString(&con
->options
, NULL
);
1609 else if (!strncmp(con
->uri
, "/jobs", 5))
1611 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1614 if (con
->uri
[5] && con
->uri
[6])
1615 cupsdSetString(&con
->options
, con
->uri
+ 5);
1617 cupsdSetString(&con
->options
, NULL
);
1621 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1624 if (con
->uri
[5] && con
->uri
[6])
1625 cupsdSetString(&con
->options
, con
->uri
+ 5);
1627 cupsdSetString(&con
->options
, NULL
);
1630 if (con
->http
.version
<= HTTP_1_0
)
1631 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1639 if ((filename
= get_file(con
, &filestats
, buf
,
1640 sizeof(buf
))) == NULL
)
1642 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1644 cupsdCloseClient(con
);
1651 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1653 if (!is_cgi(con
, filename
, &filestats
, type
))
1656 * Only POST to CGI's...
1659 if (!cupsdSendError(con
, HTTP_UNAUTHORIZED
, CUPSD_AUTH_NONE
))
1661 cupsdCloseClient(con
);
1668 case HTTP_PUT_RECV
:
1670 * Validate the resource name...
1673 if (strcmp(con
->uri
, "/admin/conf/cupsd.conf"))
1676 * PUT can only be done to the cupsd.conf file...
1679 cupsdLogMessage(CUPSD_LOG_ERROR
,
1680 "[Client %d] Disallowed PUT request for \"%s\".",
1681 con
->http
.fd
, con
->uri
);
1683 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1685 cupsdCloseClient(con
);
1693 * See if the PUT request includes a Content-Length field, and if
1694 * so check the length against any limits that are set...
1697 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1698 MaxRequestSize
> 0 &&
1699 con
->http
.data_remaining
> MaxRequestSize
)
1702 * Request too large...
1705 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1707 cupsdCloseClient(con
);
1713 else if (con
->http
.data_remaining
< 0)
1716 * Negative content lengths are invalid!
1719 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1721 cupsdCloseClient(con
);
1729 * Open a temporary file to hold the request...
1732 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
1734 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1738 cupsdLogMessage(CUPSD_LOG_ERROR
,
1739 "[Client %d] Unable to create request file "
1740 "\"%s\": %s", con
->http
.fd
, con
->filename
,
1743 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1745 cupsdCloseClient(con
);
1750 fchmod(con
->file
, 0640);
1751 fchown(con
->file
, RunUser
, Group
);
1752 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1757 cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
);
1758 cupsdCloseClient(con
);
1762 if (!strncmp(con
->uri
, "/printers/", 10) &&
1763 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1766 * Send PPD file - get the real printer name since printer
1767 * names are not case sensitive but filenames can be...
1770 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1772 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1773 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1776 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1778 cupsdCloseClient(con
);
1785 else if (!strncmp(con
->uri
, "/printers/", 10) &&
1786 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".png"))
1789 * Send PNG file - get the real printer name since printer
1790 * names are not case sensitive but filenames can be...
1793 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1795 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1796 snprintf(con
->uri
, sizeof(con
->uri
), "/icons/%s.png", p
->name
);
1799 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1801 cupsdCloseClient(con
);
1808 else if (!WebInterface
)
1810 if (!cupsdSendHeader(con
, HTTP_OK
, line
, CUPSD_AUTH_NONE
))
1812 cupsdCloseClient(con
);
1816 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1818 cupsdCloseClient(con
);
1822 if (cupsdFlushHeader(con
) < 0)
1824 cupsdCloseClient(con
);
1828 con
->http
.state
= HTTP_STATE_WAITING
;
1829 DEBUG_puts("cupsdReadClient: Set state to HTTP_STATE_WAITING "
1834 if ((!strncmp(con
->uri
, "/admin", 6) &&
1835 strncmp(con
->uri
, "/admin/conf/", 12) &&
1836 strncmp(con
->uri
, "/admin/log/", 11)) ||
1837 !strncmp(con
->uri
, "/printers", 9) ||
1838 !strncmp(con
->uri
, "/classes", 8) ||
1839 !strncmp(con
->uri
, "/help", 5) ||
1840 !strncmp(con
->uri
, "/jobs", 5))
1846 if (!cupsdSendHeader(con
, HTTP_OK
, "text/html", CUPSD_AUTH_NONE
))
1848 cupsdCloseClient(con
);
1852 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1854 cupsdCloseClient(con
);
1858 if (cupsdFlushHeader(con
) < 0)
1860 cupsdCloseClient(con
);
1864 cupsdLogRequest(con
, HTTP_OK
);
1866 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1867 (strchr(con
->uri
+ 12, '/') ||
1868 strlen(con
->uri
) == 12)) ||
1869 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1870 (strchr(con
->uri
+ 11, '/') ||
1871 strlen(con
->uri
) == 11)))
1874 * HEAD can only be done to configuration files under
1878 cupsdLogMessage(CUPSD_LOG_ERROR
,
1879 "[Client %d] Request for subdirectory \"%s\".",
1880 con
->http
.fd
, con
->uri
);
1882 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1884 cupsdCloseClient(con
);
1890 else if ((filename
= get_file(con
, &filestats
, buf
,
1891 sizeof(buf
))) == NULL
)
1893 if (!cupsdSendHeader(con
, HTTP_NOT_FOUND
, "text/html",
1896 cupsdCloseClient(con
);
1900 cupsdLogRequest(con
, HTTP_NOT_FOUND
);
1902 else if (!check_if_modified(con
, &filestats
))
1904 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1906 cupsdCloseClient(con
);
1910 cupsdLogRequest(con
, HTTP_NOT_MODIFIED
);
1918 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1920 strlcpy(line
, "text/plain", sizeof(line
));
1922 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1924 if (!cupsdSendHeader(con
, HTTP_OK
, line
, CUPSD_AUTH_NONE
))
1926 cupsdCloseClient(con
);
1930 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
1931 httpGetDateString(filestats
.st_mtime
)) < 0)
1933 cupsdCloseClient(con
);
1937 if (httpPrintf(HTTP(con
), "Content-Length: %lu\r\n",
1938 (unsigned long)filestats
.st_size
) < 0)
1940 cupsdCloseClient(con
);
1944 cupsdLogRequest(con
, HTTP_OK
);
1947 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1949 cupsdCloseClient(con
);
1953 if (cupsdFlushHeader(con
) < 0)
1955 cupsdCloseClient(con
);
1959 con
->http
.state
= HTTP_STATE_WAITING
;
1960 DEBUG_puts("cupsdReadClient: Set state to HTTP_STATE_WAITING "
1965 break; /* Anti-compiler-warning-code */
1971 * Handle any incoming data...
1974 switch (con
->http
.state
)
1976 case HTTP_PUT_RECV
:
1979 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
1981 if (con
->http
.error
&& con
->http
.error
!= EPIPE
)
1982 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1983 "[Client %d] HTTP_PUT_RECV Closing for error "
1984 "%d (%s)", con
->http
.fd
, con
->http
.error
,
1985 strerror(con
->http
.error
));
1987 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1988 "[Client %d] HTTP_PUT_RECV Closing on EOF",
1991 cupsdCloseClient(con
);
1996 con
->bytes
+= bytes
;
1998 if (write(con
->file
, line
, bytes
) < bytes
)
2000 cupsdLogMessage(CUPSD_LOG_ERROR
,
2001 "[Client %d] Unable to write %d bytes to "
2002 "\"%s\": %s", con
->http
.fd
, bytes
, con
->filename
,
2007 unlink(con
->filename
);
2008 cupsdClearString(&con
->filename
);
2010 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2012 cupsdCloseClient(con
);
2018 while (con
->http
.state
== HTTP_PUT_RECV
&& data_ready(con
));
2020 if (con
->http
.state
== HTTP_WAITING
)
2023 * End of file, see how big it is...
2026 fstat(con
->file
, &filestats
);
2031 if (filestats
.st_size
> MaxRequestSize
&&
2035 * Request is too big; remove it and send an error...
2038 unlink(con
->filename
);
2039 cupsdClearString(&con
->filename
);
2041 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2043 cupsdCloseClient(con
);
2049 * Install the configuration file...
2052 status
= install_cupsd_conf(con
);
2055 * Return the status to the client...
2058 if (!cupsdSendError(con
, status
, CUPSD_AUTH_NONE
))
2060 cupsdCloseClient(con
);
2066 case HTTP_POST_RECV
:
2069 if (con
->request
&& con
->file
< 0)
2072 * Grab any request data from the connection...
2075 if ((ipp_state
= ippRead(&(con
->http
), con
->request
)) == IPP_ERROR
)
2077 cupsdLogMessage(CUPSD_LOG_ERROR
,
2078 "[Client %d] IPP read error: %s", con
->http
.fd
,
2079 cupsLastErrorString());
2081 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
2082 cupsdCloseClient(con
);
2085 else if (ipp_state
!= IPP_DATA
)
2087 if (con
->http
.state
== HTTP_POST_SEND
)
2089 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
2090 cupsdCloseClient(con
);
2098 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[Client %d] %d.%d %s %d",
2099 con
->http
.fd
, con
->request
->request
.op
.version
[0],
2100 con
->request
->request
.op
.version
[1],
2101 ippOpString(con
->request
->request
.op
.operation_id
),
2102 con
->request
->request
.op
.request_id
);
2103 con
->bytes
+= ippLength(con
->request
);
2107 if (con
->file
< 0 && con
->http
.state
!= HTTP_POST_SEND
)
2110 * Create a file as needed for the request data...
2113 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
2115 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
2119 cupsdLogMessage(CUPSD_LOG_ERROR
,
2120 "[Client %d] Unable to create request file "
2121 "\"%s\": %s", con
->http
.fd
, con
->filename
,
2124 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2126 cupsdCloseClient(con
);
2131 fchmod(con
->file
, 0640);
2132 fchown(con
->file
, RunUser
, Group
);
2133 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2136 if (con
->http
.state
!= HTTP_POST_SEND
)
2138 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
2140 if (con
->http
.error
&& con
->http
.error
!= EPIPE
)
2141 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2142 "[Client %d] HTTP_POST_SEND Closing for "
2143 "error %d (%s)", con
->http
.fd
, con
->http
.error
,
2144 strerror(con
->http
.error
));
2146 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2147 "[Client %d] HTTP_POST_SEND Closing on EOF",
2150 cupsdCloseClient(con
);
2155 con
->bytes
+= bytes
;
2157 if (write(con
->file
, line
, bytes
) < bytes
)
2159 cupsdLogMessage(CUPSD_LOG_ERROR
,
2160 "[Client %d] Unable to write %d bytes to "
2161 "\"%s\": %s", con
->http
.fd
, bytes
,
2162 con
->filename
, strerror(errno
));
2166 unlink(con
->filename
);
2167 cupsdClearString(&con
->filename
);
2169 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
,
2172 cupsdCloseClient(con
);
2177 else if (con
->http
.state
== HTTP_POST_RECV
)
2179 else if (con
->http
.state
!= HTTP_POST_SEND
)
2181 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2182 "[Client %d] Closing on unexpected state %s.",
2183 con
->http
.fd
, http_states
[con
->http
.state
+ 1]);
2184 cupsdCloseClient(con
);
2189 while (con
->http
.state
== HTTP_POST_RECV
&& data_ready(con
));
2191 if (con
->http
.state
== HTTP_POST_SEND
)
2195 fstat(con
->file
, &filestats
);
2200 if (filestats
.st_size
> MaxRequestSize
&&
2204 * Request is too big; remove it and send an error...
2207 unlink(con
->filename
);
2208 cupsdClearString(&con
->filename
);
2213 * Delete any IPP request data...
2216 ippDelete(con
->request
);
2217 con
->request
= NULL
;
2220 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2222 cupsdCloseClient(con
);
2226 else if (filestats
.st_size
== 0)
2229 * Don't allow empty file...
2232 unlink(con
->filename
);
2233 cupsdClearString(&con
->filename
);
2238 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
2240 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
2242 cupsdCloseClient(con
);
2247 cupsdLogRequest(con
, HTTP_OK
);
2253 cupsdProcessIPPRequest(con
);
2257 unlink(con
->filename
);
2258 cupsdClearString(&con
->filename
);
2267 break; /* Anti-compiler-warning-code */
2270 if (con
->http
.state
== HTTP_WAITING
)
2272 if (!con
->http
.keep_alive
)
2274 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2275 "[Client %d] Closing because Keep-Alive disabled",
2277 cupsdCloseClient(con
);
2281 cupsArrayRemove(ActiveClients
, con
);
2282 cupsdSetBusyState();
2289 * 'cupsdSendCommand()' - Send output from a command via HTTP.
2292 int /* O - 1 on success, 0 on failure */
2294 cupsd_client_t
*con
, /* I - Client connection */
2295 char *command
, /* I - Command to run */
2296 char *options
, /* I - Command-line options */
2297 int root
) /* I - Run as root? */
2299 int fd
; /* Standard input file descriptor */
2304 fd
= open(con
->filename
, O_RDONLY
);
2308 cupsdLogMessage(CUPSD_LOG_ERROR
,
2309 "[Client %d] Unable to open \"%s\" for reading: %s",
2310 con
->http
.fd
, con
->filename
? con
->filename
: "/dev/null",
2315 fcntl(fd
, F_SETFD
, fcntl(fd
, F_GETFD
) | FD_CLOEXEC
);
2320 con
->pipe_pid
= pipe_command(con
, fd
, &(con
->file
), command
, options
, root
);
2325 cupsdLogMessage(CUPSD_LOG_INFO
, "[Client %d] Started \"%s\" (pid=%d)",
2326 con
->http
.fd
, command
, con
->pipe_pid
);
2328 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[Client %d] file=%d", con
->http
.fd
,
2331 if (con
->pipe_pid
== 0)
2334 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2336 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2338 con
->sent_header
= 0;
2339 con
->file_ready
= 0;
2340 con
->got_fields
= 0;
2341 con
->header_used
= 0;
2348 * 'cupsdSendError()' - Send an error message via HTTP.
2351 int /* O - 1 if successful, 0 otherwise */
2352 cupsdSendError(cupsd_client_t
*con
, /* I - Connection */
2353 http_status_t code
, /* I - Error code */
2354 int auth_type
)/* I - Authentication type */
2356 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2357 "[Client %d] cupsdSendError code=%d, auth_type=%d",
2358 con
->http
.fd
, code
, auth_type
);
2362 * Force client to upgrade for authentication if that is how the
2363 * server is configured...
2366 if (code
== HTTP_UNAUTHORIZED
&&
2367 DefaultEncryption
== HTTP_ENCRYPT_REQUIRED
&&
2368 _cups_strcasecmp(con
->http
.hostname
, "localhost") &&
2371 code
= HTTP_UPGRADE_REQUIRED
;
2373 #endif /* HAVE_SSL */
2376 * Put the request in the access_log file...
2379 cupsdLogRequest(con
, code
);
2382 * To work around bugs in some proxies, don't use Keep-Alive for some
2385 * Kerberos authentication doesn't work without Keep-Alive, so
2386 * never disable it in that case.
2389 if (code
>= HTTP_BAD_REQUEST
&& con
->http
.auth_type
!= CUPSD_AUTH_NEGOTIATE
)
2390 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
2393 * Send an error message back to the client. If the error code is a
2394 * 400 or 500 series, make sure the message contains some text, too!
2397 if (!cupsdSendHeader(con
, code
, NULL
, auth_type
))
2401 if (code
== HTTP_UPGRADE_REQUIRED
)
2402 if (httpPrintf(HTTP(con
), "Connection: Upgrade\r\n") < 0)
2405 if (httpPrintf(HTTP(con
), "Upgrade: TLS/1.2,TLS/1.1,TLS/1.0\r\n") < 0)
2407 #endif /* HAVE_SSL */
2409 if (con
->http
.version
>= HTTP_1_1
&&
2410 con
->http
.keep_alive
== HTTP_KEEPALIVE_OFF
)
2412 if (httpPrintf(HTTP(con
), "Connection: close\r\n") < 0)
2416 if (code
>= HTTP_BAD_REQUEST
)
2419 * Send a human-readable error message.
2422 char message
[4096], /* Message for user */
2423 urltext
[1024], /* URL redirection text */
2424 redirect
[1024]; /* Redirection link */
2425 const char *text
; /* Status-specific text */
2430 if (code
== HTTP_UNAUTHORIZED
)
2431 text
= _cupsLangString(con
->language
,
2432 _("Enter your username and password or the "
2433 "root username and password to access this "
2434 "page. If you are using Kerberos authentication, "
2435 "make sure you have a valid Kerberos ticket."));
2436 else if (code
== HTTP_UPGRADE_REQUIRED
)
2440 snprintf(urltext
, sizeof(urltext
),
2441 _cupsLangString(con
->language
,
2442 _("You must access this page using the URL "
2443 "<A HREF=\"https://%s:%d%s\">"
2444 "https://%s:%d%s</A>.")),
2445 con
->servername
, con
->serverport
, con
->uri
,
2446 con
->servername
, con
->serverport
, con
->uri
);
2448 snprintf(redirect
, sizeof(redirect
),
2449 "<META HTTP-EQUIV=\"Refresh\" "
2450 "CONTENT=\"3;URL=https://%s:%d%s\">\n",
2451 con
->servername
, con
->serverport
, con
->uri
);
2453 else if (code
== HTTP_WEBIF_DISABLED
)
2454 text
= _cupsLangString(con
->language
,
2455 _("The web interface is currently disabled. Run "
2456 "\"cupsctl WebInterface=yes\" to enable it."));
2460 snprintf(message
, sizeof(message
),
2461 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" "
2462 "\"http://www.w3.org/TR/html4/loose.dtd\">\n"
2465 "\t<META HTTP-EQUIV=\"Content-Type\" "
2466 "CONTENT=\"text/html; charset=utf-8\">\n"
2467 "\t<TITLE>%s - " CUPS_SVERSION
"</TITLE>\n"
2468 "\t<LINK REL=\"STYLESHEET\" TYPE=\"text/css\" "
2469 "HREF=\"/cups.css\">\n"
2477 httpStatus(code
), redirect
, httpStatus(code
), text
);
2479 if (httpPrintf(HTTP(con
), "Content-Type: text/html; charset=utf-8\r\n") < 0)
2481 if (httpPrintf(HTTP(con
), "Content-Length: %d\r\n",
2482 (int)strlen(message
)) < 0)
2484 if (httpPrintf(HTTP(con
), "\r\n") < 0)
2486 if (httpPrintf(HTTP(con
), "%s", message
) < 0)
2489 else if (httpPrintf(HTTP(con
), "\r\n") < 0)
2492 if (cupsdFlushHeader(con
) < 0)
2495 con
->http
.state
= HTTP_STATE_WAITING
;
2497 DEBUG_puts("cupsdSendError: Set state to HTTP_STATE_WAITING.");
2504 * 'cupsdSendHeader()' - Send an HTTP request.
2507 int /* O - 1 on success, 0 on failure */
2509 cupsd_client_t
*con
, /* I - Client to send to */
2510 http_status_t code
, /* I - HTTP status code */
2511 char *type
, /* I - MIME type of document */
2512 int auth_type
) /* I - Type of authentication */
2514 char auth_str
[1024]; /* Authorization string */
2518 * Send the HTTP status header...
2521 if (code
== HTTP_CONTINUE
)
2524 * 100-continue doesn't send any headers...
2527 return (httpPrintf(HTTP(con
), "HTTP/%d.%d 100 Continue\r\n\r\n",
2528 con
->http
.version
/ 100, con
->http
.version
% 100) > 0);
2530 else if (code
== HTTP_WEBIF_DISABLED
)
2533 * Treat our special "web interface is disabled" status as "200 OK" for web
2540 httpFlushWrite(HTTP(con
));
2542 con
->http
.data_encoding
= HTTP_ENCODE_FIELDS
;
2544 if (httpPrintf(HTTP(con
), "HTTP/%d.%d %d %s\r\n", con
->http
.version
/ 100,
2545 con
->http
.version
% 100, code
, httpStatus(code
)) < 0)
2547 if (httpPrintf(HTTP(con
), "Date: %s\r\n", httpGetDateString(time(NULL
))) < 0)
2550 if (httpPrintf(HTTP(con
), "Server: %s\r\n", ServerHeader
) < 0)
2552 if (con
->http
.keep_alive
&& con
->http
.version
>= HTTP_1_0
)
2554 if (httpPrintf(HTTP(con
), "Connection: Keep-Alive\r\n") < 0)
2556 if (httpPrintf(HTTP(con
), "Keep-Alive: timeout=%d\r\n",
2557 KeepAliveTimeout
) < 0)
2560 if (code
== HTTP_METHOD_NOT_ALLOWED
)
2561 if (httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n") < 0)
2564 if (code
== HTTP_UNAUTHORIZED
)
2566 if (auth_type
== CUPSD_AUTH_NONE
)
2568 if (!con
->best
|| con
->best
->type
<= CUPSD_AUTH_NONE
)
2569 auth_type
= cupsdDefaultAuthType();
2571 auth_type
= con
->best
->type
;
2576 if (auth_type
== CUPSD_AUTH_BASIC
|| auth_type
== CUPSD_AUTH_BASICDIGEST
)
2577 strlcpy(auth_str
, "Basic realm=\"CUPS\"", sizeof(auth_str
));
2578 else if (auth_type
== CUPSD_AUTH_DIGEST
)
2579 snprintf(auth_str
, sizeof(auth_str
), "Digest realm=\"CUPS\", nonce=\"%s\"",
2580 con
->http
.hostname
);
2582 else if (auth_type
== CUPSD_AUTH_NEGOTIATE
)
2585 if (_httpAddrFamily(con
->http
.hostaddr
) == AF_LOCAL
)
2586 strlcpy(auth_str
, "Basic realm=\"CUPS\"", sizeof(auth_str
));
2588 # endif /* AF_LOCAL */
2589 strlcpy(auth_str
, "Negotiate", sizeof(auth_str
));
2591 #endif /* HAVE_GSSAPI */
2593 if (con
->best
&& auth_type
!= CUPSD_AUTH_NEGOTIATE
&&
2594 !_cups_strcasecmp(con
->http
.hostname
, "localhost"))
2597 * Add a "trc" (try root certification) parameter for local non-Kerberos
2598 * requests when the request requires system group membership - then the
2599 * client knows the root certificate can/should be used.
2601 * Also, for OS X we also look for @AUTHKEY and add an "authkey"
2602 * parameter as needed...
2605 char *name
, /* Current user name */
2606 *auth_key
; /* Auth key buffer */
2607 size_t auth_size
; /* Size of remaining buffer */
2609 auth_key
= auth_str
+ strlen(auth_str
);
2610 auth_size
= sizeof(auth_str
) - (auth_key
- auth_str
);
2612 for (name
= (char *)cupsArrayFirst(con
->best
->names
);
2614 name
= (char *)cupsArrayNext(con
->best
->names
))
2616 #ifdef HAVE_AUTHORIZATION_H
2617 if (!_cups_strncasecmp(name
, "@AUTHKEY(", 9))
2619 snprintf(auth_key
, auth_size
, ", authkey=\"%s\"", name
+ 9);
2620 /* end parenthesis is stripped in conf.c */
2624 #endif /* HAVE_AUTHORIZATION_H */
2625 if (!_cups_strcasecmp(name
, "@SYSTEM"))
2627 #ifdef HAVE_AUTHORIZATION_H
2628 if (SystemGroupAuthKey
)
2629 snprintf(auth_key
, auth_size
,
2631 SystemGroupAuthKey
);
2634 strlcpy(auth_key
, ", trc=\"y\"", auth_size
);
2635 #endif /* HAVE_AUTHORIZATION_H */
2643 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2644 "[Client %d] WWW-Authenticate: %s", con
->http
.fd
,
2647 if (httpPrintf(HTTP(con
), "WWW-Authenticate: %s\r\n", auth_str
) < 0)
2652 if (con
->language
&& strcmp(con
->language
->language
, "C"))
2654 if (httpPrintf(HTTP(con
), "Content-Language: %s\r\n",
2655 con
->language
->language
) < 0)
2661 if (!strcmp(type
, "text/html"))
2663 if (httpPrintf(HTTP(con
),
2664 "Content-Type: text/html; charset=utf-8\r\n") < 0)
2667 else if (httpPrintf(HTTP(con
), "Content-Type: %s\r\n", type
) < 0)
2676 * 'cupsdUpdateCGI()' - Read status messages from CGI scripts and programs.
2680 cupsdUpdateCGI(void)
2682 char *ptr
, /* Pointer to end of line in buffer */
2683 message
[1024]; /* Pointer to message text */
2684 int loglevel
; /* Log level for message */
2687 while ((ptr
= cupsdStatBufUpdate(CGIStatusBuffer
, &loglevel
,
2688 message
, sizeof(message
))) != NULL
)
2690 if (loglevel
== CUPSD_LOG_INFO
)
2691 cupsdLogMessage(CUPSD_LOG_INFO
, "%s", message
);
2693 if (!strchr(CGIStatusBuffer
->buffer
, '\n'))
2697 if (ptr
== NULL
&& !CGIStatusBuffer
->bufused
)
2700 * Fatal error on pipe - should never happen!
2703 cupsdLogMessage(CUPSD_LOG_CRIT
,
2704 "cupsdUpdateCGI: error reading from CGI error pipe - %s",
2711 * 'cupsdWriteClient()' - Write data to a client as needed.
2715 cupsdWriteClient(cupsd_client_t
*con
) /* I - Client connection */
2717 int bytes
, /* Number of bytes written */
2718 field_col
; /* Current column */
2719 char *bufptr
, /* Pointer into buffer */
2720 *bufend
; /* Pointer to end of buffer */
2721 ipp_state_t ipp_state
; /* IPP state value */
2724 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2725 "[Client %d] cupsdWriteClient "
2729 "data_encoding=HTTP_ENCODE_%s, "
2730 "data_remaining=" CUPS_LLFMT
", "
2734 con
->http
.fd
, con
->http
.error
, con
->http
.used
,
2735 http_states
[con
->http
.state
+ 1],
2736 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
?
2737 "CHUNKED" : "LENGTH",
2738 CUPS_LLCAST con
->http
.data_remaining
,
2740 con
->response
? ipp_states
[con
->response
->state
] : "",
2741 con
->pipe_pid
, con
->file
);
2743 if (con
->http
.state
!= HTTP_GET_SEND
&&
2744 con
->http
.state
!= HTTP_POST_SEND
)
2747 * If we get called in the wrong state, then something went wrong with the
2748 * connection and we need to shut it down...
2751 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2752 "[Client %d] Closing on unexpected HTTP state %s.",
2753 con
->http
.fd
, http_states
[con
->http
.state
+ 1]);
2754 cupsdCloseClient(con
);
2761 * Make sure we select on the CGI output...
2764 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2766 if (!con
->file_ready
)
2769 * Try again later when there is CGI output available...
2772 cupsdRemoveSelect(con
->http
.fd
);
2776 con
->file_ready
= 0;
2779 if (con
->response
&& con
->response
->state
!= IPP_DATA
)
2781 ipp_state
= ippWrite(HTTP(con
), con
->response
);
2782 bytes
= ipp_state
!= IPP_ERROR
&&
2783 (con
->file
>= 0 || ipp_state
!= IPP_DATA
);
2785 else if ((bytes
= read(con
->file
, con
->header
+ con
->header_used
,
2786 sizeof(con
->header
) - con
->header_used
)) > 0)
2788 con
->header_used
+= bytes
;
2790 if (con
->pipe_pid
&& !con
->got_fields
)
2793 * Inspect the data for Content-Type and other fields.
2796 for (bufptr
= con
->header
, bufend
= con
->header
+ con
->header_used
,
2798 !con
->got_fields
&& bufptr
< bufend
;
2801 if (*bufptr
== '\n')
2804 * Send line to client...
2807 if (bufptr
> con
->header
&& bufptr
[-1] == '\r')
2811 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Script header: %s", con
->header
);
2813 if (!con
->sent_header
)
2816 * Handle redirection and CGI status codes...
2819 if (!_cups_strncasecmp(con
->header
, "Location:", 9))
2821 if (!cupsdSendHeader(con
, HTTP_SEE_OTHER
, NULL
, CUPSD_AUTH_NONE
))
2823 cupsdCloseClient(con
);
2827 con
->sent_header
= 2;
2829 if (httpPrintf(HTTP(con
), "Content-Length: 0\r\n") < 0)
2832 else if (!_cups_strncasecmp(con
->header
, "Status:", 7))
2834 cupsdSendError(con
, (http_status_t
)atoi(con
->header
+ 7),
2836 con
->sent_header
= 2;
2840 if (!cupsdSendHeader(con
, HTTP_OK
, NULL
, CUPSD_AUTH_NONE
))
2842 cupsdCloseClient(con
);
2846 con
->sent_header
= 1;
2848 if (con
->http
.version
== HTTP_1_1
)
2850 if (httpPrintf(HTTP(con
), "Transfer-Encoding: chunked\r\n") < 0)
2856 if (_cups_strncasecmp(con
->header
, "Status:", 7))
2857 httpPrintf(HTTP(con
), "%s\r\n", con
->header
);
2863 con
->header_used
-= bufptr
- con
->header
;
2865 if (con
->header_used
> 0)
2866 memmove(con
->header
, bufptr
, con
->header_used
);
2868 bufptr
= con
->header
- 1;
2871 * See if the line was empty...
2876 con
->got_fields
= 1;
2878 if (cupsdFlushHeader(con
) < 0)
2880 cupsdCloseClient(con
);
2884 if (con
->http
.version
== HTTP_1_1
)
2885 con
->http
.data_encoding
= HTTP_ENCODE_CHUNKED
;
2890 else if (*bufptr
!= '\r')
2894 if (!con
->got_fields
)
2896 con
->http
.activity
= time(NULL
);
2901 if (con
->header_used
> 0)
2903 if (httpWrite2(HTTP(con
), con
->header
, con
->header_used
) < 0)
2905 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2906 "[Client %d] Closing for error %d (%s)",
2907 con
->http
.fd
, con
->http
.error
,
2908 strerror(con
->http
.error
));
2909 cupsdCloseClient(con
);
2913 if (con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
)
2914 httpFlushWrite(HTTP(con
));
2916 con
->bytes
+= con
->header_used
;
2918 if (con
->http
.state
== HTTP_WAITING
)
2921 bytes
= con
->header_used
;
2923 con
->header_used
= 0;
2928 (con
->http
.state
!= HTTP_GET_SEND
&& con
->http
.state
!= HTTP_POST_SEND
))
2930 if (!con
->sent_header
&& con
->pipe_pid
)
2931 cupsdSendError(con
, HTTP_SERVER_ERROR
, CUPSD_AUTH_NONE
);
2934 cupsdLogRequest(con
, HTTP_OK
);
2936 httpFlushWrite(HTTP(con
));
2938 if (con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
&& con
->sent_header
== 1)
2940 if (httpWrite2(HTTP(con
), "", 0) < 0)
2942 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2943 "[Client %d] Closing for error %d (%s)",
2944 con
->http
.fd
, con
->http
.error
,
2945 strerror(con
->http
.error
));
2946 cupsdCloseClient(con
);
2952 con
->http
.state
= HTTP_WAITING
;
2954 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
2958 cupsdRemoveSelect(con
->file
);
2961 cupsdEndProcess(con
->pipe_pid
, 0);
2970 unlink(con
->filename
);
2971 cupsdClearString(&con
->filename
);
2976 ippDelete(con
->request
);
2977 con
->request
= NULL
;
2982 ippDelete(con
->response
);
2983 con
->response
= NULL
;
2986 cupsdClearString(&con
->command
);
2987 cupsdClearString(&con
->options
);
2988 cupsdClearString(&con
->query_string
);
2990 if (!con
->http
.keep_alive
)
2992 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2993 "[Client %d] Closing because Keep-Alive disabled.",
2995 cupsdCloseClient(con
);
3000 cupsArrayRemove(ActiveClients
, con
);
3001 cupsdSetBusyState();
3005 con
->http
.activity
= time(NULL
);
3010 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
3013 static int /* O - 1 if modified since */
3015 cupsd_client_t
*con
, /* I - Client connection */
3016 struct stat
*filestats
) /* I - File information */
3018 char *ptr
; /* Pointer into field */
3019 time_t date
; /* Time/date value */
3020 off_t size
; /* Size/length value */
3025 ptr
= con
->http
.fields
[HTTP_FIELD_IF_MODIFIED_SINCE
];
3030 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3031 "[Client %d] check_if_modified "
3032 "filestats=%p(" CUPS_LLFMT
", %d)) If-Modified-Since=\"%s\"",
3033 con
->http
.fd
, filestats
, CUPS_LLCAST filestats
->st_size
,
3034 (int)filestats
->st_mtime
, ptr
);
3036 while (*ptr
!= '\0')
3038 while (isspace(*ptr
) || *ptr
== ';')
3041 if (_cups_strncasecmp(ptr
, "length=", 7) == 0)
3044 size
= strtoll(ptr
, NULL
, 10);
3046 while (isdigit(*ptr
))
3049 else if (isalpha(*ptr
))
3051 date
= httpGetDateTime(ptr
);
3052 while (*ptr
!= '\0' && *ptr
!= ';')
3059 return ((size
!= filestats
->st_size
&& size
!= 0) ||
3060 (date
< filestats
->st_mtime
&& date
!= 0) ||
3061 (size
== 0 && date
== 0));
3066 * 'compare_clients()' - Compare two client connections.
3069 static int /* O - Result of comparison */
3070 compare_clients(cupsd_client_t
*a
, /* I - First client */
3071 cupsd_client_t
*b
, /* I - Second client */
3072 void *data
) /* I - User data (not used) */
3086 * 'data_ready()' - Check whether data is available from a client.
3089 static int /* O - 1 if data is ready, 0 otherwise */
3090 data_ready(cupsd_client_t
*con
) /* I - Client */
3092 if (con
->http
.used
> 0)
3095 else if (con
->http
.tls
)
3098 if (SSL_pending((SSL
*)(con
->http
.tls
)))
3100 # elif defined(HAVE_GNUTLS)
3101 if (gnutls_record_check_pending(con
->http
.tls
))
3103 # elif defined(HAVE_CDSASSL)
3104 size_t bytes
; /* Bytes that are available */
3106 if (!SSLGetBufferedReadSize(con
->http
.tls
, &bytes
) && bytes
> 0)
3108 # endif /* HAVE_LIBSSL */
3110 #endif /* HAVE_SSL */
3117 * 'get_file()' - Get a filename and state info.
3120 static char * /* O - Real filename */
3121 get_file(cupsd_client_t
*con
, /* I - Client connection */
3122 struct stat
*filestats
, /* O - File information */
3123 char *filename
, /* IO - Filename buffer */
3124 int len
) /* I - Buffer length */
3126 int status
; /* Status of filesystem calls */
3127 char *ptr
; /* Pointer info filename */
3128 int plen
; /* Remaining length after pointer */
3129 char language
[7]; /* Language subdirectory, if any */
3133 * Figure out the real filename...
3138 if (!strncmp(con
->uri
, "/ppd/", 5) && !strchr(con
->uri
+ 5, '/'))
3139 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
);
3140 else if (!strncmp(con
->uri
, "/icons/", 7) && !strchr(con
->uri
+ 7, '/'))
3142 snprintf(filename
, len
, "%s/%s", CacheDir
, con
->uri
+ 7);
3143 if (access(filename
, F_OK
) < 0)
3144 snprintf(filename
, len
, "%s/images/generic.png", DocumentRoot
);
3146 else if (!strncmp(con
->uri
, "/rss/", 5) && !strchr(con
->uri
+ 5, '/'))
3147 snprintf(filename
, len
, "%s/rss/%s", CacheDir
, con
->uri
+ 5);
3148 else if (!strncmp(con
->uri
, "/admin/conf/", 12))
3149 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
+ 11);
3150 else if (!strncmp(con
->uri
, "/admin/log/", 11))
3152 if (!strncmp(con
->uri
+ 11, "access_log", 10) && AccessLog
[0] == '/')
3153 strlcpy(filename
, AccessLog
, len
);
3154 else if (!strncmp(con
->uri
+ 11, "error_log", 9) && ErrorLog
[0] == '/')
3155 strlcpy(filename
, ErrorLog
, len
);
3156 else if (!strncmp(con
->uri
+ 11, "page_log", 8) && PageLog
[0] == '/')
3157 strlcpy(filename
, PageLog
, len
);
3161 else if (con
->language
)
3163 snprintf(language
, sizeof(language
), "/%s", con
->language
->language
);
3164 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3167 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3169 if ((ptr
= strchr(filename
, '?')) != NULL
)
3173 * Grab the status for this language; if there isn't a language-specific file
3174 * then fallback to the default one...
3177 if ((status
= stat(filename
, filestats
)) != 0 && language
[0] &&
3178 strncmp(con
->uri
, "/icons/", 7) &&
3179 strncmp(con
->uri
, "/ppd/", 5) &&
3180 strncmp(con
->uri
, "/rss/", 5) &&
3181 strncmp(con
->uri
, "/admin/conf/", 12) &&
3182 strncmp(con
->uri
, "/admin/log/", 11))
3185 * Drop the country code...
3189 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3191 if ((ptr
= strchr(filename
, '?')) != NULL
)
3194 if ((status
= stat(filename
, filestats
)) != 0)
3197 * Drop the language prefix and try the root directory...
3201 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3203 if ((ptr
= strchr(filename
, '?')) != NULL
)
3206 status
= stat(filename
, filestats
);
3211 * If we're found a directory, get the index.html file instead...
3214 if (!status
&& S_ISDIR(filestats
->st_mode
))
3217 * Make sure the URI ends with a slash...
3220 if (con
->uri
[strlen(con
->uri
) - 1] != '/')
3221 strlcat(con
->uri
, "/", sizeof(con
->uri
));
3224 * Find the directory index file, trying every language...
3229 if (status
&& language
[0])
3232 * Try a different language subset...
3236 language
[0] = '\0'; /* Strip country code */
3238 language
[0] = '\0'; /* Strip language */
3242 * Look for the index file...
3245 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3247 if ((ptr
= strchr(filename
, '?')) != NULL
)
3250 ptr
= filename
+ strlen(filename
);
3251 plen
= len
- (ptr
- filename
);
3253 strlcpy(ptr
, "index.html", plen
);
3254 status
= stat(filename
, filestats
);
3259 strlcpy(ptr
, "index.class", plen
);
3260 status
= stat(filename
, filestats
);
3262 #endif /* HAVE_JAVA */
3267 strlcpy(ptr
, "index.pl", plen
);
3268 status
= stat(filename
, filestats
);
3270 #endif /* HAVE_PERL */
3275 strlcpy(ptr
, "index.php", plen
);
3276 status
= stat(filename
, filestats
);
3278 #endif /* HAVE_PHP */
3283 strlcpy(ptr
, "index.pyc", plen
);
3284 status
= stat(filename
, filestats
);
3289 strlcpy(ptr
, "index.py", plen
);
3290 status
= stat(filename
, filestats
);
3292 #endif /* HAVE_PYTHON */
3295 while (status
&& language
[0]);
3298 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3299 "[Client %d] get_file filestats=%p, filename=%p, len=%d, "
3300 "returning \"%s\".", con
->http
.fd
, filestats
, filename
, len
,
3301 status
? "(null)" : filename
);
3311 * 'install_cupsd_conf()' - Install a configuration file.
3314 static http_status_t
/* O - Status */
3315 install_cupsd_conf(cupsd_client_t
*con
) /* I - Connection */
3317 char filename
[1024]; /* Configuration filename */
3318 cups_file_t
*in
, /* Input file */
3319 *out
; /* Output file */
3320 char buffer
[16384]; /* Copy buffer */
3321 ssize_t bytes
; /* Number of bytes */
3325 * Open the request file...
3328 if ((in
= cupsFileOpen(con
->filename
, "rb")) == NULL
)
3330 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open request file \"%s\": %s",
3331 con
->filename
, strerror(errno
));
3332 return (HTTP_SERVER_ERROR
);
3336 * Open the new config file...
3339 snprintf(filename
, sizeof(filename
), "%s/cupsd.conf", ServerRoot
);
3340 if ((out
= cupsdCreateConfFile(filename
, ConfigFilePerm
)) == NULL
)
3343 return (HTTP_SERVER_ERROR
);
3346 cupsdLogMessage(CUPSD_LOG_INFO
, "Installing config file \"%s\"...", filename
);
3349 * Copy from the request to the new config file...
3352 while ((bytes
= cupsFileRead(in
, buffer
, sizeof(buffer
))) > 0)
3353 if (cupsFileWrite(out
, buffer
, bytes
) < bytes
)
3355 cupsdLogMessage(CUPSD_LOG_ERROR
,
3356 "Unable to copy to config file \"%s\": %s",
3357 filename
, strerror(errno
));
3362 snprintf(filename
, sizeof(filename
), "%s%s.N", ServerRoot
, con
->uri
+ 11);
3363 cupsdRemoveFile(filename
);
3365 return (HTTP_SERVER_ERROR
);
3369 * Close the files...
3374 if (cupsdCloseCreatedConfFile(out
, filename
))
3375 return (HTTP_SERVER_ERROR
);
3378 * Remove the request file...
3381 cupsdRemoveFile(con
->filename
);
3382 cupsdClearString(&con
->filename
);
3385 * Set the NeedReload flag...
3388 NeedReload
= RELOAD_CUPSD
;
3389 ReloadTime
= time(NULL
);
3392 * Return that the file was created successfully...
3395 return (HTTP_CREATED
);
3400 * 'is_cgi()' - Is the resource a CGI script/program?
3403 static int /* O - 1 = CGI, 0 = file */
3404 is_cgi(cupsd_client_t
*con
, /* I - Client connection */
3405 const char *filename
, /* I - Real filename */
3406 struct stat
*filestats
, /* I - File information */
3407 mime_type_t
*type
) /* I - MIME type */
3409 const char *options
; /* Options on URL */
3413 * Get the options, if any...
3416 if ((options
= strchr(con
->uri
, '?')) != NULL
)
3419 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", options
);
3423 * Check for known types...
3426 if (!type
|| _cups_strcasecmp(type
->super
, "application"))
3428 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3429 "[Client %d] is_cgi filename=\"%s\", filestats=%p, "
3430 "type=%s/%s, returning 0", con
->http
.fd
, filename
,
3431 filestats
, type
? type
->super
: "unknown",
3432 type
? type
->type
: "unknown");
3436 if (!_cups_strcasecmp(type
->type
, "x-httpd-cgi") &&
3437 (filestats
->st_mode
& 0111))
3440 * "application/x-httpd-cgi" is a CGI script.
3443 cupsdSetString(&con
->command
, filename
);
3446 cupsdSetStringf(&con
->options
, " %s", options
);
3448 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3449 "[Client %d] is_cgi filename=\"%s\", filestats=%p, "
3450 "type=%s/%s, returning 1", con
->http
.fd
, filename
,
3451 filestats
, type
->super
, type
->type
);
3455 else if (!_cups_strcasecmp(type
->type
, "x-httpd-java"))
3458 * "application/x-httpd-java" is a Java servlet.
3461 cupsdSetString(&con
->command
, CUPS_JAVA
);
3464 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3466 cupsdSetStringf(&con
->options
, " %s", filename
);
3468 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3469 "[Client %d] is_cgi filename=\"%s\", filestats=%p, "
3470 "type=%s/%s, returning 1", con
->http
.fd
, filename
,
3471 filestats
, type
->super
, type
->type
);
3474 #endif /* HAVE_JAVA */
3476 else if (!_cups_strcasecmp(type
->type
, "x-httpd-perl"))
3479 * "application/x-httpd-perl" is a Perl page.
3482 cupsdSetString(&con
->command
, CUPS_PERL
);
3485 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3487 cupsdSetStringf(&con
->options
, " %s", filename
);
3489 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3490 "[Client %d] is_cgi filename=\"%s\", filestats=%p, "
3491 "type=%s/%s, returning 1", con
->http
.fd
, filename
,
3492 filestats
, type
->super
, type
->type
);
3495 #endif /* HAVE_PERL */
3497 else if (!_cups_strcasecmp(type
->type
, "x-httpd-php"))
3500 * "application/x-httpd-php" is a PHP page.
3503 cupsdSetString(&con
->command
, CUPS_PHP
);
3506 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3508 cupsdSetStringf(&con
->options
, " %s", filename
);
3510 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3511 "[Client %d] is_cgi filename=\"%s\", filestats=%p, "
3512 "type=%s/%s, returning 1", con
->http
.fd
, filename
,
3513 filestats
, type
->super
, type
->type
);
3516 #endif /* HAVE_PHP */
3518 else if (!_cups_strcasecmp(type
->type
, "x-httpd-python"))
3521 * "application/x-httpd-python" is a Python page.
3524 cupsdSetString(&con
->command
, CUPS_PYTHON
);
3527 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3529 cupsdSetStringf(&con
->options
, " %s", filename
);
3531 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3532 "[Client %d] is_cgi filename=\"%s\", filestats=%p, "
3533 "type=%s/%s, returning 1", con
->http
.fd
, filename
,
3534 filestats
, type
->super
, type
->type
);
3537 #endif /* HAVE_PYTHON */
3539 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3540 "[Client %d] is_cgi filename=\"%s\", filestats=%p, "
3541 "type=%s/%s, returning 0", con
->http
.fd
, filename
,
3542 filestats
, type
->super
, type
->type
);
3548 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
3551 static int /* O - 0 if relative, 1 if absolute */
3552 is_path_absolute(const char *path
) /* I - Input path */
3555 * Check for a leading slash...
3562 * Check for "/.." in the path...
3565 while ((path
= strstr(path
, "/..")) != NULL
)
3567 if (!path
[3] || path
[3] == '/')
3574 * If we haven't found any relative paths, return 1 indicating an
3583 * 'pipe_command()' - Pipe the output of a command to the remote client.
3586 static int /* O - Process ID */
3587 pipe_command(cupsd_client_t
*con
, /* I - Client connection */
3588 int infile
, /* I - Standard input for command */
3589 int *outfile
, /* O - Standard output for command */
3590 char *command
, /* I - Command to run */
3591 char *options
, /* I - Options for command */
3592 int root
) /* I - Run as root? */
3594 int i
; /* Looping var */
3595 int pid
; /* Process ID */
3596 char *commptr
, /* Command string pointer */
3597 commch
; /* Command string character */
3598 char *uriptr
; /* URI string pointer */
3599 int fds
[2]; /* Pipe FDs */
3600 int argc
; /* Number of arguments */
3601 int envc
; /* Number of environment variables */
3602 char argbuf
[10240], /* Argument buffer */
3603 *argv
[100], /* Argument strings */
3604 *envp
[MAX_ENV
+ 20]; /* Environment variables */
3605 char auth_type
[256], /* AUTH_TYPE environment variable */
3606 content_length
[1024], /* CONTENT_LENGTH environment variable */
3607 content_type
[1024], /* CONTENT_TYPE environment variable */
3608 http_cookie
[32768], /* HTTP_COOKIE environment variable */
3609 http_referer
[1024], /* HTTP_REFERER environment variable */
3610 http_user_agent
[1024], /* HTTP_USER_AGENT environment variable */
3611 lang
[1024], /* LANG environment variable */
3612 path_info
[1024], /* PATH_INFO environment variable */
3613 remote_addr
[1024], /* REMOTE_ADDR environment variable */
3614 remote_host
[1024], /* REMOTE_HOST environment variable */
3615 remote_user
[1024], /* REMOTE_USER environment variable */
3616 script_filename
[1024], /* SCRIPT_FILENAME environment variable */
3617 script_name
[1024], /* SCRIPT_NAME environment variable */
3618 server_name
[1024], /* SERVER_NAME environment variable */
3619 server_port
[1024]; /* SERVER_PORT environment variable */
3620 ipp_attribute_t
*attr
; /* attributes-natural-language attribute */
3621 void *ccache
= NULL
; /* Kerberos credentials */
3625 * Parse a copy of the options string, which is of the form:
3627 * argument+argument+argument
3628 * ?argument+argument+argument
3629 * param=value¶m=value
3630 * ?param=value¶m=value
3631 * /name?argument+argument+argument
3632 * /name?param=value¶m=value
3634 * If the string contains an "=" character after the initial name,
3635 * then we treat it as a HTTP GET form request and make a copy of
3636 * the remaining string for the environment variable.
3638 * The string is always parsed out as command-line arguments, to
3639 * be consistent with Apache...
3642 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3643 "[Client %d] pipe_command infile=%d, outfile=%p, "
3644 "command=\"%s\", options=\"%s\", root=%d",
3645 con
->http
.fd
, infile
, outfile
, command
,
3646 options
? options
: "(null)", root
);
3653 if (*commptr
== ' ')
3655 strlcpy(argbuf
, commptr
, sizeof(argbuf
));
3660 if (argbuf
[0] == '/')
3663 * Found some trailing path information, set PATH_INFO...
3666 if ((commptr
= strchr(argbuf
, '?')) == NULL
)
3667 commptr
= argbuf
+ strlen(argbuf
);
3671 snprintf(path_info
, sizeof(path_info
), "PATH_INFO=%s", argbuf
);
3677 path_info
[0] = '\0';
3679 if (*commptr
== ' ')
3683 if (*commptr
== '?' && con
->operation
== HTTP_GET
&& !con
->query_string
)
3686 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", commptr
);
3693 argv
[argc
++] = commptr
;
3695 for (; *commptr
&& argc
< 99; commptr
++)
3698 * Break arguments whenever we see a + or space...
3701 if (*commptr
== ' ' || *commptr
== '+')
3703 while (*commptr
== ' ' || *commptr
== '+')
3707 * If we don't have a blank string, save it as another argument...
3712 argv
[argc
] = commptr
;
3718 else if (*commptr
== '%' && isxdigit(commptr
[1] & 255) &&
3719 isxdigit(commptr
[2] & 255))
3722 * Convert the %xx notation to the individual character.
3725 if (commptr
[1] >= '0' && commptr
[1] <= '9')
3726 *commptr
= (commptr
[1] - '0') << 4;
3728 *commptr
= (tolower(commptr
[1]) - 'a' + 10) << 4;
3730 if (commptr
[2] >= '0' && commptr
[2] <= '9')
3731 *commptr
|= commptr
[2] - '0';
3733 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
3735 _cups_strcpy(commptr
+ 1, commptr
+ 3);
3738 * Check for a %00 and break if that is the case...
3750 * Setup the environment variables as needed...
3753 if (con
->username
[0])
3755 snprintf(auth_type
, sizeof(auth_type
), "AUTH_TYPE=%s",
3756 httpGetField(HTTP(con
), HTTP_FIELD_AUTHORIZATION
));
3758 if ((uriptr
= strchr(auth_type
+ 10, ' ')) != NULL
)
3762 auth_type
[0] = '\0';
3765 (attr
= ippFindAttribute(con
->request
, "attributes-natural-language",
3766 IPP_TAG_LANGUAGE
)) != NULL
)
3768 switch (strlen(attr
->values
[0].string
.text
))
3772 * This is an unknown or badly formatted language code; use
3773 * the POSIX locale...
3776 strlcpy(lang
, "LANG=C", sizeof(lang
));
3781 * Just the language code (ll)...
3784 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8",
3785 attr
->values
[0].string
.text
);
3790 * Language and country code (ll-cc)...
3793 snprintf(lang
, sizeof(lang
), "LANG=%c%c_%c%c.UTF8",
3794 attr
->values
[0].string
.text
[0],
3795 attr
->values
[0].string
.text
[1],
3796 toupper(attr
->values
[0].string
.text
[3] & 255),
3797 toupper(attr
->values
[0].string
.text
[4] & 255));
3801 else if (con
->language
)
3802 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8", con
->language
->language
);
3804 strlcpy(lang
, "LANG=C", sizeof(lang
));
3806 strlcpy(remote_addr
, "REMOTE_ADDR=", sizeof(remote_addr
));
3807 httpAddrString(con
->http
.hostaddr
, remote_addr
+ 12,
3808 sizeof(remote_addr
) - 12);
3810 snprintf(remote_host
, sizeof(remote_host
), "REMOTE_HOST=%s",
3811 con
->http
.hostname
);
3813 snprintf(script_name
, sizeof(script_name
), "SCRIPT_NAME=%s", con
->uri
);
3814 if ((uriptr
= strchr(script_name
, '?')) != NULL
)
3817 snprintf(script_filename
, sizeof(script_filename
), "SCRIPT_FILENAME=%s%s",
3818 DocumentRoot
, script_name
+ 12);
3820 sprintf(server_port
, "SERVER_PORT=%d", con
->serverport
);
3822 if (con
->http
.fields
[HTTP_FIELD_HOST
][0])
3824 char *nameptr
; /* Pointer to ":port" */
3826 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
3827 con
->http
.fields
[HTTP_FIELD_HOST
]);
3828 if ((nameptr
= strrchr(server_name
, ':')) != NULL
&& !strchr(nameptr
, ']'))
3829 *nameptr
= '\0'; /* Strip trailing ":port" */
3832 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
3835 envc
= cupsdLoadEnv(envp
, (int)(sizeof(envp
) / sizeof(envp
[0])));
3838 envp
[envc
++] = auth_type
;
3840 envp
[envc
++] = lang
;
3841 envp
[envc
++] = "REDIRECT_STATUS=1";
3842 envp
[envc
++] = "GATEWAY_INTERFACE=CGI/1.1";
3843 envp
[envc
++] = server_name
;
3844 envp
[envc
++] = server_port
;
3845 envp
[envc
++] = remote_addr
;
3846 envp
[envc
++] = remote_host
;
3847 envp
[envc
++] = script_name
;
3848 envp
[envc
++] = script_filename
;
3851 envp
[envc
++] = path_info
;
3853 if (con
->username
[0])
3855 snprintf(remote_user
, sizeof(remote_user
), "REMOTE_USER=%s", con
->username
);
3857 envp
[envc
++] = remote_user
;
3860 if (con
->http
.version
== HTTP_1_1
)
3861 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.1";
3862 else if (con
->http
.version
== HTTP_1_0
)
3863 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.0";
3865 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/0.9";
3867 if (con
->http
.cookie
)
3869 snprintf(http_cookie
, sizeof(http_cookie
), "HTTP_COOKIE=%s",
3871 envp
[envc
++] = http_cookie
;
3874 if (con
->http
.fields
[HTTP_FIELD_USER_AGENT
][0])
3876 snprintf(http_user_agent
, sizeof(http_user_agent
), "HTTP_USER_AGENT=%s",
3877 con
->http
.fields
[HTTP_FIELD_USER_AGENT
]);
3878 envp
[envc
++] = http_user_agent
;
3881 if (con
->http
.fields
[HTTP_FIELD_REFERER
][0])
3883 snprintf(http_referer
, sizeof(http_referer
), "HTTP_REFERER=%s",
3884 con
->http
.fields
[HTTP_FIELD_REFERER
]);
3885 envp
[envc
++] = http_referer
;
3888 if (con
->operation
== HTTP_GET
)
3890 envp
[envc
++] = "REQUEST_METHOD=GET";
3892 if (con
->query_string
)
3895 * Add GET form variables after ?...
3898 envp
[envc
++] = con
->query_string
;
3901 envp
[envc
++] = "QUERY_STRING=";
3905 sprintf(content_length
, "CONTENT_LENGTH=" CUPS_LLFMT
,
3906 CUPS_LLCAST con
->bytes
);
3907 snprintf(content_type
, sizeof(content_type
), "CONTENT_TYPE=%s",
3908 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
3910 envp
[envc
++] = "REQUEST_METHOD=POST";
3911 envp
[envc
++] = content_length
;
3912 envp
[envc
++] = content_type
;
3916 * Tell the CGI if we are using encryption...
3920 envp
[envc
++] = "HTTPS=ON";
3923 * Terminate the environment array...
3928 if (LogLevel
>= CUPSD_LOG_DEBUG
)
3930 for (i
= 0; i
< argc
; i
++)
3931 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3932 "[CGI] argv[%d] = \"%s\"", i
, argv
[i
]);
3933 for (i
= 0; i
< envc
; i
++)
3934 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3935 "[CGI] envp[%d] = \"%s\"", i
, envp
[i
]);
3939 * Create a pipe for the output...
3942 if (cupsdOpenPipe(fds
))
3944 cupsdLogMessage(CUPSD_LOG_ERROR
, "[CGI] Unable to create pipe for %s - %s",
3945 argv
[0], strerror(errno
));
3950 * Then execute the command...
3953 if (cupsdStartProcess(command
, argv
, envp
, infile
, fds
[1], CGIPipes
[1],
3954 -1, -1, root
, DefaultProfile
, NULL
, &pid
) < 0)
3957 * Error - can't fork!
3960 cupsdLogMessage(CUPSD_LOG_ERROR
, "[CGI] Unable to start %s - %s", argv
[0],
3963 cupsdClosePipe(fds
);
3969 * Fork successful - return the PID...
3972 if (con
->username
[0])
3973 cupsdAddCert(pid
, con
->username
, ccache
);
3975 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[CGI] Started %s (PID %d)", command
, pid
);
3986 * 'valid_host()' - Is the Host: field valid?
3989 static int /* O - 1 if valid, 0 if not */
3990 valid_host(cupsd_client_t
*con
) /* I - Client connection */
3992 cupsd_alias_t
*a
; /* Current alias */
3993 cupsd_netif_t
*netif
; /* Current network interface */
3994 const char *host
, /* Host field */
3995 *end
; /* End character */
3998 host
= con
->http
.fields
[HTTP_FIELD_HOST
];
4000 if (httpAddrLocalhost(con
->http
.hostaddr
))
4003 * Only allow "localhost" or the equivalent IPv4 or IPv6 numerical
4004 * addresses when accessing CUPS via the loopback interface...
4007 return (!_cups_strcasecmp(host
, "localhost") ||
4008 !_cups_strncasecmp(host
, "localhost:", 10) ||
4009 !_cups_strcasecmp(host
, "localhost.") ||
4010 !_cups_strncasecmp(host
, "localhost.:", 11) ||
4012 !_cups_strcasecmp(host
, "localhost.localdomain") ||
4013 !_cups_strncasecmp(host
, "localhost.localdomain:", 22) ||
4014 #endif /* __linux */
4015 !strcmp(host
, "127.0.0.1") ||
4016 !strncmp(host
, "127.0.0.1:", 10) ||
4017 !strcmp(host
, "[::1]") ||
4018 !strncmp(host
, "[::1]:", 6));
4021 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
4023 * Check if the hostname is something.local (Bonjour); if so, allow it.
4026 if ((end
= strrchr(host
, '.')) != NULL
&& end
> host
&&
4027 (!end
[1] || end
[1] == ':'))
4030 * "." on end, work back to second-to-last "."...
4032 for (end
--; end
> host
&& *end
!= '.'; end
--);
4035 if (end
&& (!_cups_strcasecmp(end
, ".local") ||
4036 !_cups_strncasecmp(end
, ".local:", 7) ||
4037 !_cups_strcasecmp(end
, ".local.") ||
4038 !_cups_strncasecmp(end
, ".local.:", 8)))
4040 #endif /* HAVE_DNSSD || HAVE_AVAHI */
4043 * Check if the hostname is an IP address...
4046 if (isdigit(*host
& 255) || *host
== '[')
4049 * Possible IPv4/IPv6 address...
4052 char temp
[1024], /* Temporary string */
4053 *ptr
; /* Pointer into temporary string */
4054 http_addrlist_t
*addrlist
; /* List of addresses */
4057 strlcpy(temp
, host
, sizeof(temp
));
4058 if ((ptr
= strrchr(temp
, ':')) != NULL
&& !strchr(ptr
, ']'))
4059 *ptr
= '\0'; /* Strip :port from host value */
4061 if ((addrlist
= httpAddrGetList(temp
, AF_UNSPEC
, NULL
)) != NULL
)
4064 * Good IPv4/IPv6 address...
4067 httpAddrFreeList(addrlist
);
4073 * Check for (alias) name matches...
4076 for (a
= (cupsd_alias_t
*)cupsArrayFirst(ServerAlias
);
4078 a
= (cupsd_alias_t
*)cupsArrayNext(ServerAlias
))
4081 * "ServerAlias *" allows all host values through...
4084 if (!strcmp(a
->name
, "*"))
4087 if (!_cups_strncasecmp(host
, a
->name
, a
->namelen
))
4090 * Prefix matches; check the character at the end - it must be ":", ".",
4094 end
= host
+ a
->namelen
;
4096 if (!*end
|| *end
== ':' || (*end
== '.' && (!end
[1] || end
[1] == ':')))
4101 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
4102 for (a
= (cupsd_alias_t
*)cupsArrayFirst(DNSSDAlias
);
4104 a
= (cupsd_alias_t
*)cupsArrayNext(DNSSDAlias
))
4107 * "ServerAlias *" allows all host values through...
4110 if (!strcmp(a
->name
, "*"))
4113 if (!_cups_strncasecmp(host
, a
->name
, a
->namelen
))
4116 * Prefix matches; check the character at the end - it must be ":", ".",
4120 end
= host
+ a
->namelen
;
4122 if (!*end
|| *end
== ':' || (*end
== '.' && (!end
[1] || end
[1] == ':')))
4126 #endif /* HAVE_DNSSD || HAVE_AVAHI */
4129 * Check for interface hostname matches...
4132 for (netif
= (cupsd_netif_t
*)cupsArrayFirst(NetIFList
);
4134 netif
= (cupsd_netif_t
*)cupsArrayNext(NetIFList
))
4136 if (!_cups_strncasecmp(host
, netif
->hostname
, netif
->hostlen
))
4139 * Prefix matches; check the character at the end - it must be ":", ".",
4143 end
= host
+ netif
->hostlen
;
4145 if (!*end
|| *end
== ':' || (*end
== '.' && (!end
[1] || end
[1] == ':')))
4155 * 'write_file()' - Send a file via HTTP.
4158 static int /* O - 0 on failure, 1 on success */
4159 write_file(cupsd_client_t
*con
, /* I - Client connection */
4160 http_status_t code
, /* I - HTTP status */
4161 char *filename
, /* I - Filename */
4162 char *type
, /* I - File type */
4163 struct stat
*filestats
) /* O - File information */
4165 con
->file
= open(filename
, O_RDONLY
);
4167 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4168 "[Client %d] write_file code=%d, filename=\"%s\" (%d), "
4169 "type=\"%s\", filestats=%p", con
->http
.fd
,
4170 code
, filename
, con
->file
, type
? type
: "(null)", filestats
);
4175 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
4179 if (!cupsdSendHeader(con
, code
, type
, CUPSD_AUTH_NONE
))
4182 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
4183 httpGetDateString(filestats
->st_mtime
)) < 0)
4185 if (httpPrintf(HTTP(con
), "Content-Length: " CUPS_LLFMT
"\r\n",
4186 CUPS_LLCAST filestats
->st_size
) < 0)
4188 if (httpPrintf(HTTP(con
), "\r\n") < 0)
4191 if (cupsdFlushHeader(con
) < 0)
4194 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
4195 con
->http
.data_remaining
= filestats
->st_size
;
4197 if (con
->http
.data_remaining
<= INT_MAX
)
4198 con
->http
._data_remaining
= con
->http
.data_remaining
;
4200 con
->http
._data_remaining
= INT_MAX
;
4202 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
,
4203 (cupsd_selfunc_t
)cupsdWriteClient
, con
);
4210 * 'write_pipe()' - Flag that data is available on the CGI pipe.
4214 write_pipe(cupsd_client_t
*con
) /* I - Client connection */
4216 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4217 "[Client %d] write_pipe CGI output on fd %d",
4218 con
->http
.fd
, con
->file
);
4220 con
->file_ready
= 1;
4222 cupsdRemoveSelect(con
->file
);
4223 cupsdAddSelect(con
->http
.fd
, NULL
, (cupsd_selfunc_t
)cupsdWriteClient
, con
);
4228 * End of "$Id: client.c 7950 2008-09-17 00:21:59Z mike $".