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 */
78 static const char * const ipp_states
[] =
79 { /* IPP state strings */
91 static int check_if_modified(cupsd_client_t
*con
,
92 struct stat
*filestats
);
93 static int compare_clients(cupsd_client_t
*a
, cupsd_client_t
*b
,
95 static int data_ready(cupsd_client_t
*con
);
96 static char *get_file(cupsd_client_t
*con
, struct stat
*filestats
,
97 char *filename
, int len
);
98 static http_status_t
install_conf_file(cupsd_client_t
*con
);
99 static int is_cgi(cupsd_client_t
*con
, const char *filename
,
100 struct stat
*filestats
, mime_type_t
*type
);
101 static int is_path_absolute(const char *path
);
102 static int pipe_command(cupsd_client_t
*con
, int infile
, int *outfile
,
103 char *command
, char *options
, int root
);
104 static int valid_host(cupsd_client_t
*con
);
105 static int write_file(cupsd_client_t
*con
, http_status_t code
,
106 char *filename
, char *type
,
107 struct stat
*filestats
);
108 static void write_pipe(cupsd_client_t
*con
);
112 * 'cupsdAcceptClient()' - Accept a new client.
116 cupsdAcceptClient(cupsd_listener_t
*lis
)/* I - Listener socket */
118 int count
; /* Count of connections on a host */
119 int val
; /* Parameter value */
120 cupsd_client_t
*con
, /* New client pointer */
121 *tempcon
; /* Temporary client pointer */
122 http_addrlist_t
*addrlist
, /* List of adddresses for host */
123 *addr
; /* Current address */
124 socklen_t addrlen
; /* Length of address */
125 char *hostname
; /* Hostname for address */
126 http_addr_t temp
; /* Temporary address variable */
127 static time_t last_dos
= 0; /* Time of last DoS attack */
129 struct request_info wrap_req
; /* TCP wrappers request information */
130 #endif /* HAVE_TCPD_H */
133 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
134 "cupsdAcceptClient(lis=%p(%d)) Clients=%d",
135 lis
, lis
->fd
, cupsArrayCount(Clients
));
138 * Make sure we don't have a full set of clients already...
141 if (cupsArrayCount(Clients
) == MaxClients
)
145 * Get a pointer to the next available client...
149 Clients
= cupsArrayNew(NULL
, NULL
);
153 cupsdLogMessage(CUPSD_LOG_ERROR
,
154 "Unable to allocate memory for clients array!");
155 cupsdPauseListening();
160 ActiveClients
= cupsArrayNew((cups_array_func_t
)compare_clients
, NULL
);
164 cupsdLogMessage(CUPSD_LOG_ERROR
,
165 "Unable to allocate memory for active clients array!");
166 cupsdPauseListening();
170 if ((con
= calloc(1, sizeof(cupsd_client_t
))) == NULL
)
172 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to allocate memory for client!");
173 cupsdPauseListening();
178 con
->http
.activity
= time(NULL
);
179 con
->http
.hostaddr
= &(con
->clientaddr
);
180 con
->http
.wait_value
= 10000;
183 * Accept the client and get the remote address...
186 addrlen
= sizeof(http_addr_t
);
188 if ((con
->http
.fd
= accept(lis
->fd
, (struct sockaddr
*)con
->http
.hostaddr
,
191 if (errno
== ENFILE
|| errno
== EMFILE
)
192 cupsdPauseListening();
194 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to accept client connection - %s.",
202 * Save the connected port number...
205 _httpAddrSetPort(con
->http
.hostaddr
, _httpAddrPort(&(lis
->address
)));
209 * Convert IPv4 over IPv6 addresses (::ffff:n.n.n.n) to IPv4 forms we
210 * can more easily use...
213 if (lis
->address
.addr
.sa_family
== AF_INET6
&&
214 con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[0] == 0 &&
215 con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[1] == 0 &&
216 ntohl(con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[2]) == 0xffff)
217 con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[2] = 0;
218 #endif /* AF_INET6 */
221 * Check the number of clients on the same address...
224 for (count
= 0, tempcon
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
226 tempcon
= (cupsd_client_t
*)cupsArrayNext(Clients
))
227 if (httpAddrEqual(tempcon
->http
.hostaddr
, con
->http
.hostaddr
))
230 if (count
>= MaxClientsPerHost
)
234 if (count
>= MaxClientsPerHost
)
236 if ((time(NULL
) - last_dos
) >= 60)
238 last_dos
= time(NULL
);
239 cupsdLogMessage(CUPSD_LOG_WARN
,
240 "Possible DoS attack - more than %d clients connecting "
243 httpAddrString(con
->http
.hostaddr
, con
->http
.hostname
,
244 sizeof(con
->http
.hostname
)));
248 closesocket(con
->http
.fd
);
258 * Get the hostname or format the IP address as needed...
261 if (httpAddrLocalhost(con
->http
.hostaddr
))
264 * Map accesses from the loopback interface to "localhost"...
267 strlcpy(con
->http
.hostname
, "localhost", sizeof(con
->http
.hostname
));
268 hostname
= con
->http
.hostname
;
273 * Map accesses from the same host to the server name.
277 hostname
= httpAddrLookup(con
->http
.hostaddr
, con
->http
.hostname
,
278 sizeof(con
->http
.hostname
));
282 httpAddrString(con
->http
.hostaddr
, con
->http
.hostname
,
283 sizeof(con
->http
.hostname
));
287 if (hostname
== NULL
&& HostNameLookups
== 2)
290 * Can't have an unresolved IP address with double-lookups enabled...
294 closesocket(con
->http
.fd
);
299 cupsdLogMessage(CUPSD_LOG_WARN
,
300 "Name lookup failed - connection from %s closed!",
307 if (HostNameLookups
== 2)
310 * Do double lookups as needed...
313 if ((addrlist
= httpAddrGetList(con
->http
.hostname
, AF_UNSPEC
, NULL
))
317 * See if the hostname maps to the same IP address...
320 for (addr
= addrlist
; addr
; addr
= addr
->next
)
321 if (httpAddrEqual(con
->http
.hostaddr
, &(addr
->addr
)))
327 httpAddrFreeList(addrlist
);
332 * Can't have a hostname that doesn't resolve to the same IP address
333 * with double-lookups enabled...
337 closesocket(con
->http
.fd
);
342 cupsdLogMessage(CUPSD_LOG_WARN
,
343 "IP lookup failed - connection from %s closed!",
352 * See if the connection is denied by TCP wrappers...
355 request_init(&wrap_req
, RQ_DAEMON
, "cupsd", RQ_FILE
, con
->http
.fd
, NULL
);
358 if (!hosts_access(&wrap_req
))
361 closesocket(con
->http
.fd
);
366 cupsdLogMessage(CUPSD_LOG_WARN
,
367 "Connection from %s refused by /etc/hosts.allow and "
368 "/etc/hosts.deny rules.", con
->http
.hostname
);
372 #endif /* HAVE_TCPD_H */
375 if (con
->http
.hostaddr
->addr
.sa_family
== AF_LOCAL
)
376 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[Client %d] Accepted from %s (Domain)",
377 con
->http
.fd
, con
->http
.hostname
);
379 #endif /* AF_LOCAL */
380 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[Client %d] Accepted from %s:%d (IPv%d)",
381 con
->http
.fd
, con
->http
.hostname
,
382 _httpAddrPort(con
->http
.hostaddr
),
383 _httpAddrFamily(con
->http
.hostaddr
) == AF_INET
? 4 : 6);
386 * Get the local address the client connected to...
389 addrlen
= sizeof(temp
);
390 if (getsockname(con
->http
.fd
, (struct sockaddr
*)&temp
, &addrlen
))
392 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to get local address - %s",
395 strcpy(con
->servername
, "localhost");
396 con
->serverport
= LocalPort
;
399 else if (_httpAddrFamily(&temp
) == AF_LOCAL
)
401 strcpy(con
->servername
, "localhost");
402 con
->serverport
= LocalPort
;
404 #endif /* AF_LOCAL */
407 if (httpAddrLocalhost(&temp
))
408 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
409 else if (HostNameLookups
|| RemotePort
)
410 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
412 httpAddrString(&temp
, con
->servername
, sizeof(con
->servername
));
414 con
->serverport
= _httpAddrPort(&(lis
->address
));
418 * Add the connection to the array of active clients...
421 cupsArrayAdd(Clients
, con
);
424 * Using TCP_NODELAY improves responsiveness, especially on systems with a slow
425 * loopback interface. Since we write large buffers when sending print files
426 * and requests there shouldn't be any performance penalty for this...
430 setsockopt(con
->http
.fd
, IPPROTO_TCP
, TCP_NODELAY
, &val
, sizeof(val
));
433 * Close this file on all execs...
436 fcntl(con
->http
.fd
, F_SETFD
, fcntl(con
->http
.fd
, F_GETFD
) | FD_CLOEXEC
);
439 * Add the socket to the server select.
442 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
445 * Temporarily suspend accept()'s until we lose a client...
448 if (cupsArrayCount(Clients
) == MaxClients
)
449 cupsdPauseListening();
453 * See if we are connecting on a secure port...
456 if (lis
->encryption
== HTTP_ENCRYPT_ALWAYS
)
459 * https connection; go secure...
462 con
->http
.encryption
= HTTP_ENCRYPT_ALWAYS
;
464 if (!cupsdStartTLS(con
))
465 cupsdCloseClient(con
);
469 #endif /* HAVE_SSL */
474 * 'cupsdCloseAllClients()' - Close all remote clients immediately.
478 cupsdCloseAllClients(void)
480 cupsd_client_t
*con
; /* Current client */
483 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdCloseAllClients() Clients=%d",
484 cupsArrayCount(Clients
));
486 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
488 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
489 if (cupsdCloseClient(con
))
490 cupsdCloseClient(con
);
495 * 'cupsdCloseClient()' - Close a remote client.
498 int /* O - 1 if partial close, 0 if fully closed */
499 cupsdCloseClient(cupsd_client_t
*con
) /* I - Client to close */
501 int partial
; /* Do partial close for SSL? */
503 #elif defined(HAVE_GNUTLS)
504 # elif defined(HAVE_CDSASSL)
505 #endif /* HAVE_LIBSSL */
508 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[Client %d] Closing connection.",
512 * Flush pending writes before closing...
515 httpFlushWrite(HTTP(con
));
521 * Shutdown encryption as needed...
530 #endif /* HAVE_SSL */
532 if (con
->pipe_pid
!= 0)
535 * Stop any CGI process...
538 cupsdEndProcess(con
->pipe_pid
, 1);
544 cupsdRemoveSelect(con
->file
);
551 * Close the socket and clear the file from the input set for select()...
554 if (con
->http
.fd
>= 0)
556 cupsArrayRemove(ActiveClients
, con
);
562 * Only do a partial close so that the encrypted client gets everything.
565 shutdown(con
->http
.fd
, 0);
566 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
571 * Shut the socket down fully...
574 cupsdRemoveSelect(con
->http
.fd
);
586 if (con
->http
.input_set
)
587 free(con
->http
.input_set
);
589 httpClearCookie(HTTP(con
));
590 httpClearFields(HTTP(con
));
592 cupsdClearString(&con
->filename
);
593 cupsdClearString(&con
->command
);
594 cupsdClearString(&con
->options
);
595 cupsdClearString(&con
->query_string
);
599 ippDelete(con
->request
);
605 ippDelete(con
->response
);
606 con
->response
= NULL
;
611 cupsLangFree(con
->language
);
612 con
->language
= NULL
;
615 #ifdef HAVE_AUTHORIZATION_H
618 AuthorizationFree(con
->authref
, kAuthorizationFlagDefaults
);
621 #endif /* HAVE_AUTHORIZATION_H */
624 * Re-enable new client connections if we are going back under the
628 if (cupsArrayCount(Clients
) == MaxClients
)
629 cupsdResumeListening();
632 * Compact the list of clients as necessary...
635 cupsArrayRemove(Clients
, con
);
645 * 'cupsdFlushHeader()' - Flush the header fields to the client.
648 int /* I - Bytes written or -1 on error */
649 cupsdFlushHeader(cupsd_client_t
*con
) /* I - Client to flush to */
651 int bytes
= httpFlushWrite(HTTP(con
));
653 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
660 * 'cupsdReadClient()' - Read data from a client.
664 cupsdReadClient(cupsd_client_t
*con
) /* I - Client to read from */
666 char line
[32768], /* Line from client... */
667 operation
[64], /* Operation code from socket */
668 version
[64], /* HTTP version number string */
669 locale
[64], /* Locale */
670 *ptr
; /* Pointer into strings */
671 int major
, minor
; /* HTTP version numbers */
672 http_status_t status
; /* Transfer status */
673 ipp_state_t ipp_state
; /* State of IPP transfer */
674 int bytes
; /* Number of bytes to POST */
675 char *filename
; /* Name of file for GET/HEAD */
676 char buf
[1024]; /* Buffer for real filename */
677 struct stat filestats
; /* File information */
678 mime_type_t
*type
; /* MIME type of file */
679 cupsd_printer_t
*p
; /* Printer */
680 static unsigned request_id
= 0; /* Request ID for temp files */
683 status
= HTTP_CONTINUE
;
685 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
686 "[Client %d] cupsdReadClient "
690 "data_encoding=HTTP_ENCODE_%s, "
691 "data_remaining=" CUPS_LLFMT
", "
694 con
->http
.fd
, con
->http
.error
, con
->http
.used
,
695 http_states
[con
->http
.state
],
696 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
?
697 "CHUNKED" : "LENGTH",
698 CUPS_LLCAST con
->http
.data_remaining
,
700 con
->request
? ipp_states
[con
->request
->state
] : "",
707 * Automatically check for a SSL/TLS handshake...
712 if (recv(con
->http
.fd
, buf
, 1, MSG_PEEK
) == 1 &&
713 (!buf
[0] || !strchr("DGHOPT", buf
[0])))
716 * Encrypt this connection...
719 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
720 "[Client %d] Saw first byte %02X, auto-negotiating "
721 "SSL/TLS session.", con
->http
.fd
, buf
[0] & 255);
723 if (!cupsdStartTLS(con
))
724 cupsdCloseClient(con
);
729 #endif /* HAVE_SSL */
731 switch (con
->http
.state
)
735 * See if we've received a request line...
738 if (httpGets(line
, sizeof(line
) - 1, HTTP(con
)) == NULL
)
740 if (con
->http
.error
&& con
->http
.error
!= EPIPE
)
741 cupsdLogMessage(CUPSD_LOG_DEBUG
,
742 "[Client %d] HTTP_WAITING Closing for error %d "
743 "(%s)", con
->http
.fd
, con
->http
.error
,
744 strerror(con
->http
.error
));
746 cupsdLogMessage(CUPSD_LOG_DEBUG
,
747 "[Client %d] HTTP_WAITING Closing on EOF",
750 cupsdCloseClient(con
);
755 * Ignore blank request lines...
762 * Clear other state variables...
765 httpClearFields(HTTP(con
));
767 con
->http
.activity
= time(NULL
);
768 con
->http
.version
= HTTP_1_0
;
769 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
770 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
771 con
->http
.data_remaining
= 0;
772 con
->http
._data_remaining
= 0;
773 con
->operation
= HTTP_WAITING
;
778 con
->username
[0] = '\0';
779 con
->password
[0] = '\0';
782 cupsdClearString(&con
->command
);
783 cupsdClearString(&con
->options
);
784 cupsdClearString(&con
->query_string
);
788 ippDelete(con
->request
);
794 ippDelete(con
->response
);
795 con
->response
= NULL
;
800 cupsLangFree(con
->language
);
801 con
->language
= NULL
;
807 #endif /* HAVE_GSSAPI */
810 * Grab the request line...
813 switch (sscanf(line
, "%63s%1023s%63s", operation
, con
->uri
, version
))
818 cupsdLogMessage(CUPSD_LOG_ERROR
,
819 "[Client %d] Bad request line \"%s\" from %s.",
821 _httpEncodeURI(buf
, line
, sizeof(buf
)),
823 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
824 cupsdCloseClient(con
);
828 con
->http
.version
= HTTP_0_9
;
831 if (sscanf(version
, "HTTP/%d.%d", &major
, &minor
) != 2)
833 cupsdLogMessage(CUPSD_LOG_ERROR
,
834 "[Client %d] Bad request line \"%s\" from %s.",
836 _httpEncodeURI(buf
, line
, sizeof(buf
)),
838 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
839 cupsdCloseClient(con
);
845 con
->http
.version
= (http_version_t
)(major
* 100 + minor
);
846 if (con
->http
.version
== HTTP_1_1
&& KeepAlive
)
847 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
849 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
853 cupsdLogMessage(CUPSD_LOG_ERROR
,
854 "[Client %d] Unsupported request line \"%s\" "
855 "from %s.", con
->http
.fd
,
856 _httpEncodeURI(buf
, line
, sizeof(buf
)),
858 cupsdSendError(con
, HTTP_NOT_SUPPORTED
, CUPSD_AUTH_NONE
);
859 cupsdCloseClient(con
);
866 * Handle full URLs in the request line...
869 if (strcmp(con
->uri
, "*"))
871 char scheme
[HTTP_MAX_URI
], /* Method/scheme */
872 userpass
[HTTP_MAX_URI
], /* Username:password */
873 hostname
[HTTP_MAX_URI
], /* Hostname */
874 resource
[HTTP_MAX_URI
]; /* Resource path */
875 int port
; /* Port number */
879 * Separate the URI into its components...
882 httpSeparateURI(HTTP_URI_CODING_MOST
, con
->uri
,
883 scheme
, sizeof(scheme
),
884 userpass
, sizeof(userpass
),
885 hostname
, sizeof(hostname
), &port
,
886 resource
, sizeof(resource
));
889 * Only allow URIs with the servername, localhost, or an IP
893 if (strcmp(scheme
, "file") &&
894 _cups_strcasecmp(hostname
, ServerName
) &&
895 _cups_strcasecmp(hostname
, "localhost") &&
896 !isdigit(hostname
[0]) && hostname
[0] != '[')
899 * Nope, we don't do proxies...
902 cupsdLogMessage(CUPSD_LOG_ERROR
,
903 "[Client %d] Bad URI \"%s\" in request.",
904 con
->http
.fd
, con
->uri
);
905 cupsdSendError(con
, HTTP_METHOD_NOT_ALLOWED
, CUPSD_AUTH_NONE
);
906 cupsdCloseClient(con
);
911 * Copy the resource portion back into the URI; both resource and
912 * con->uri are HTTP_MAX_URI bytes in size...
915 strcpy(con
->uri
, resource
);
919 * Process the request...
922 if (!strcmp(operation
, "GET"))
923 con
->http
.state
= HTTP_GET
;
924 else if (!strcmp(operation
, "PUT"))
925 con
->http
.state
= HTTP_PUT
;
926 else if (!strcmp(operation
, "POST"))
927 con
->http
.state
= HTTP_POST
;
928 else if (!strcmp(operation
, "DELETE"))
929 con
->http
.state
= HTTP_DELETE
;
930 else if (!strcmp(operation
, "TRACE"))
931 con
->http
.state
= HTTP_TRACE
;
932 else if (!strcmp(operation
, "OPTIONS"))
933 con
->http
.state
= HTTP_OPTIONS
;
934 else if (!strcmp(operation
, "HEAD"))
935 con
->http
.state
= HTTP_HEAD
;
938 cupsdLogMessage(CUPSD_LOG_ERROR
,
939 "[Client %d] Bad operation \"%s\".", con
->http
.fd
,
941 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
942 cupsdCloseClient(con
);
946 gettimeofday(&(con
->start
), NULL
);
947 con
->operation
= con
->http
.state
;
949 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[Client %d] %s %s HTTP/%d.%d",
950 con
->http
.fd
, operation
, con
->uri
,
951 con
->http
.version
/ 100, con
->http
.version
% 100);
953 con
->http
.status
= HTTP_OK
;
955 if (!cupsArrayFind(ActiveClients
, con
))
957 cupsArrayAdd(ActiveClients
, con
);
969 * Parse incoming parameters until the status changes...
972 while ((status
= httpUpdate(HTTP(con
))) == HTTP_CONTINUE
)
973 if (!data_ready(con
))
976 if (status
!= HTTP_OK
&& status
!= HTTP_CONTINUE
)
978 if (con
->http
.error
&& con
->http
.error
!= EPIPE
)
979 cupsdLogMessage(CUPSD_LOG_DEBUG
,
980 "[Client %d] Closing for error %d (%s) while "
982 con
->http
.fd
, con
->http
.error
,
983 strerror(con
->http
.error
));
985 cupsdLogMessage(CUPSD_LOG_DEBUG
,
986 "[Client %d] Closing on EOF while reading headers.",
989 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
990 cupsdCloseClient(con
);
996 if (!data_ready(con
) && recv(con
->http
.fd
, buf
, 1, MSG_PEEK
) < 1)
999 * Connection closed...
1002 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1003 "[Client %d] Closing on EOF", con
->http
.fd
);
1004 cupsdCloseClient(con
);
1007 break; /* Anti-compiler-warning-code */
1011 * Handle new transfers...
1014 if (status
== HTTP_OK
)
1016 if (con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
][0])
1019 * Figure out the locale from the Accept-Language and Content-Type
1023 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
],
1027 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
],
1031 if ((ptr
= strstr(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
],
1032 "charset=")) != NULL
)
1035 * Combine language and charset, and trim any extra params in the
1039 snprintf(locale
, sizeof(locale
), "%s.%s",
1040 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ptr
+ 8);
1042 if ((ptr
= strchr(locale
, ',')) != NULL
)
1046 snprintf(locale
, sizeof(locale
), "%s.UTF-8",
1047 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
]);
1049 con
->language
= cupsLangGet(locale
);
1052 con
->language
= cupsLangGet(DefaultLocale
);
1054 cupsdAuthorize(con
);
1056 if (!_cups_strncasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
],
1057 "Keep-Alive", 10) && KeepAlive
)
1058 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
1059 else if (!_cups_strncasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
],
1061 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1063 if (!con
->http
.fields
[HTTP_FIELD_HOST
][0] &&
1064 con
->http
.version
>= HTTP_1_1
)
1067 * HTTP/1.1 and higher require the "Host:" field...
1070 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1072 cupsdLogMessage(CUPSD_LOG_ERROR
,
1073 "[Client %d] Missing Host: field in request.",
1075 cupsdCloseClient(con
);
1079 else if (!valid_host(con
))
1082 * Access to localhost must use "localhost" or the corresponding IPv4
1083 * or IPv6 values in the Host: field.
1086 cupsdLogMessage(CUPSD_LOG_ERROR
,
1087 "[Client %d] Request from \"%s\" using invalid Host: "
1088 "field \"%s\"", con
->http
.fd
, con
->http
.hostname
,
1089 con
->http
.fields
[HTTP_FIELD_HOST
]);
1091 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1093 cupsdCloseClient(con
);
1097 else if (con
->operation
== HTTP_OPTIONS
)
1100 * Do OPTIONS command...
1103 if (con
->best
&& con
->best
->type
!= CUPSD_AUTH_NONE
)
1105 if (!cupsdSendHeader(con
, HTTP_UNAUTHORIZED
, NULL
, CUPSD_AUTH_NONE
))
1107 cupsdCloseClient(con
);
1112 if (!_cups_strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") &&
1113 con
->http
.tls
== NULL
)
1117 * Do encryption stuff...
1120 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
, CUPSD_AUTH_NONE
))
1122 cupsdCloseClient(con
);
1126 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1127 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1128 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1129 httpPrintf(HTTP(con
), "\r\n");
1131 if (cupsdFlushHeader(con
) < 0)
1133 cupsdCloseClient(con
);
1137 if (!cupsdStartTLS(con
))
1139 cupsdCloseClient(con
);
1143 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
1145 cupsdCloseClient(con
);
1148 #endif /* HAVE_SSL */
1151 if (!cupsdSendHeader(con
, HTTP_OK
, NULL
, CUPSD_AUTH_NONE
))
1153 cupsdCloseClient(con
);
1157 httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n");
1158 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1159 httpPrintf(HTTP(con
), "\r\n");
1161 if (cupsdFlushHeader(con
) < 0)
1163 cupsdCloseClient(con
);
1167 else if (!is_path_absolute(con
->uri
))
1170 * Protect against malicious users!
1173 cupsdLogMessage(CUPSD_LOG_ERROR
,
1174 "[Client %d] Request for non-absolute resource \"%s\".",
1175 con
->http
.fd
, con
->uri
);
1177 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1179 cupsdCloseClient(con
);
1185 if (!_cups_strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
],
1186 "Upgrade") && con
->http
.tls
== NULL
)
1190 * Do encryption stuff...
1193 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
,
1196 cupsdCloseClient(con
);
1200 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1201 httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n");
1202 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1203 httpPrintf(HTTP(con
), "\r\n");
1205 if (cupsdFlushHeader(con
) < 0)
1207 cupsdCloseClient(con
);
1211 if (!cupsdStartTLS(con
))
1213 cupsdCloseClient(con
);
1217 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
1219 cupsdCloseClient(con
);
1222 #endif /* HAVE_SSL */
1225 if ((status
= cupsdIsAuthorized(con
, NULL
)) != HTTP_OK
)
1227 cupsdSendError(con
, status
, CUPSD_AUTH_NONE
);
1228 cupsdCloseClient(con
);
1232 if (con
->http
.expect
&&
1233 (con
->operation
== HTTP_POST
|| con
->operation
== HTTP_PUT
))
1235 if (con
->http
.expect
== HTTP_CONTINUE
)
1238 * Send 100-continue header...
1241 if (!cupsdSendHeader(con
, HTTP_CONTINUE
, NULL
, CUPSD_AUTH_NONE
))
1243 cupsdCloseClient(con
);
1250 * Send 417-expectation-failed header...
1253 if (!cupsdSendHeader(con
, HTTP_EXPECTATION_FAILED
, NULL
,
1256 cupsdCloseClient(con
);
1260 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1261 httpPrintf(HTTP(con
), "\r\n");
1263 if (cupsdFlushHeader(con
) < 0)
1265 cupsdCloseClient(con
);
1271 switch (con
->http
.state
)
1273 case HTTP_GET_SEND
:
1274 if (!strncmp(con
->uri
, "/printers/", 10) &&
1275 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1278 * Send PPD file - get the real printer name since printer
1279 * names are not case sensitive but filenames can be...
1282 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1284 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1285 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1288 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1290 cupsdCloseClient(con
);
1297 else if ((!strncmp(con
->uri
, "/printers/", 10) ||
1298 !strncmp(con
->uri
, "/classes/", 9)) &&
1299 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".png"))
1302 * Send icon file - get the real queue name since queue names are
1303 * not case sensitive but filenames can be...
1306 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".png" */
1308 if (!strncmp(con
->uri
, "/printers/", 10))
1309 p
= cupsdFindPrinter(con
->uri
+ 10);
1311 p
= cupsdFindClass(con
->uri
+ 9);
1314 snprintf(con
->uri
, sizeof(con
->uri
), "/icons/%s.png", p
->name
);
1317 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1319 cupsdCloseClient(con
);
1326 else if (!WebInterface
)
1329 * Web interface is disabled. Show an appropriate message...
1332 if (!cupsdSendError(con
, HTTP_WEBIF_DISABLED
, CUPSD_AUTH_NONE
))
1334 cupsdCloseClient(con
);
1341 if ((!strncmp(con
->uri
, "/admin", 6) &&
1342 strncmp(con
->uri
, "/admin/conf/", 12) &&
1343 strncmp(con
->uri
, "/admin/log/", 11)) ||
1344 !strncmp(con
->uri
, "/printers", 9) ||
1345 !strncmp(con
->uri
, "/classes", 8) ||
1346 !strncmp(con
->uri
, "/help", 5) ||
1347 !strncmp(con
->uri
, "/jobs", 5))
1350 * Send CGI output...
1353 if (!strncmp(con
->uri
, "/admin", 6))
1355 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1358 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1360 else if (!strncmp(con
->uri
, "/printers", 9))
1362 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1365 if (con
->uri
[9] && con
->uri
[10])
1366 cupsdSetString(&con
->options
, con
->uri
+ 9);
1368 cupsdSetString(&con
->options
, NULL
);
1370 else if (!strncmp(con
->uri
, "/classes", 8))
1372 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1375 if (con
->uri
[8] && con
->uri
[9])
1376 cupsdSetString(&con
->options
, con
->uri
+ 8);
1378 cupsdSetString(&con
->options
, NULL
);
1380 else if (!strncmp(con
->uri
, "/jobs", 5))
1382 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1385 if (con
->uri
[5] && con
->uri
[6])
1386 cupsdSetString(&con
->options
, con
->uri
+ 5);
1388 cupsdSetString(&con
->options
, NULL
);
1392 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1395 if (con
->uri
[5] && con
->uri
[6])
1396 cupsdSetString(&con
->options
, con
->uri
+ 5);
1398 cupsdSetString(&con
->options
, NULL
);
1401 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1403 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1405 cupsdCloseClient(con
);
1410 cupsdLogRequest(con
, HTTP_OK
);
1412 if (con
->http
.version
<= HTTP_1_0
)
1413 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1415 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1416 (strchr(con
->uri
+ 12, '/') ||
1417 strlen(con
->uri
) == 12)) ||
1418 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1419 (strchr(con
->uri
+ 11, '/') ||
1420 strlen(con
->uri
) == 11)))
1423 * GET can only be done to configuration files directly under
1427 cupsdLogMessage(CUPSD_LOG_ERROR
,
1428 "Request for subdirectory \"%s\"!", con
->uri
);
1430 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1432 cupsdCloseClient(con
);
1444 if ((filename
= get_file(con
, &filestats
, buf
,
1445 sizeof(buf
))) == NULL
)
1447 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1449 cupsdCloseClient(con
);
1456 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1458 if (is_cgi(con
, filename
, &filestats
, type
))
1461 * Note: con->command and con->options were set by
1465 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1467 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1469 cupsdCloseClient(con
);
1474 cupsdLogRequest(con
, HTTP_OK
);
1476 if (con
->http
.version
<= HTTP_1_0
)
1477 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1481 if (!check_if_modified(con
, &filestats
))
1483 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1485 cupsdCloseClient(con
);
1492 strcpy(line
, "text/plain");
1494 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1496 if (!write_file(con
, HTTP_OK
, filename
, line
, &filestats
))
1498 cupsdCloseClient(con
);
1505 case HTTP_POST_RECV
:
1507 * See if the POST request includes a Content-Length field, and if
1508 * so check the length against any limits that are set...
1511 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1512 MaxRequestSize
> 0 &&
1513 con
->http
.data_remaining
> MaxRequestSize
)
1516 * Request too large...
1519 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1521 cupsdCloseClient(con
);
1527 else if (con
->http
.data_remaining
< 0 ||
1528 (!con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1529 con
->http
.data_encoding
== HTTP_ENCODE_LENGTH
))
1532 * Negative content lengths are invalid!
1535 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1537 cupsdCloseClient(con
);
1545 * See what kind of POST request this is; for IPP requests the
1546 * content-type field will be "application/ipp"...
1549 if (!strcmp(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
],
1551 con
->request
= ippNew();
1552 else if (!WebInterface
)
1555 * Web interface is disabled. Show an appropriate message...
1558 if (!cupsdSendError(con
, HTTP_WEBIF_DISABLED
, CUPSD_AUTH_NONE
))
1560 cupsdCloseClient(con
);
1566 else if ((!strncmp(con
->uri
, "/admin", 6) &&
1567 strncmp(con
->uri
, "/admin/conf/", 12) &&
1568 strncmp(con
->uri
, "/admin/log/", 11)) ||
1569 !strncmp(con
->uri
, "/printers", 9) ||
1570 !strncmp(con
->uri
, "/classes", 8) ||
1571 !strncmp(con
->uri
, "/help", 5) ||
1572 !strncmp(con
->uri
, "/jobs", 5))
1578 if (!strncmp(con
->uri
, "/admin", 6))
1580 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1583 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1585 else if (!strncmp(con
->uri
, "/printers", 9))
1587 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1590 if (con
->uri
[9] && con
->uri
[10])
1591 cupsdSetString(&con
->options
, con
->uri
+ 9);
1593 cupsdSetString(&con
->options
, NULL
);
1595 else if (!strncmp(con
->uri
, "/classes", 8))
1597 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1600 if (con
->uri
[8] && con
->uri
[9])
1601 cupsdSetString(&con
->options
, con
->uri
+ 8);
1603 cupsdSetString(&con
->options
, NULL
);
1605 else if (!strncmp(con
->uri
, "/jobs", 5))
1607 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1610 if (con
->uri
[5] && con
->uri
[6])
1611 cupsdSetString(&con
->options
, con
->uri
+ 5);
1613 cupsdSetString(&con
->options
, NULL
);
1617 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1620 if (con
->uri
[5] && con
->uri
[6])
1621 cupsdSetString(&con
->options
, con
->uri
+ 5);
1623 cupsdSetString(&con
->options
, NULL
);
1626 if (con
->http
.version
<= HTTP_1_0
)
1627 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1635 if ((filename
= get_file(con
, &filestats
, buf
,
1636 sizeof(buf
))) == NULL
)
1638 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1640 cupsdCloseClient(con
);
1647 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1649 if (!is_cgi(con
, filename
, &filestats
, type
))
1652 * Only POST to CGI's...
1655 if (!cupsdSendError(con
, HTTP_UNAUTHORIZED
, CUPSD_AUTH_NONE
))
1657 cupsdCloseClient(con
);
1664 case HTTP_PUT_RECV
:
1666 * Validate the resource name...
1669 if (strncmp(con
->uri
, "/admin/conf/", 12) ||
1670 strchr(con
->uri
+ 12, '/') ||
1671 strlen(con
->uri
) == 12)
1674 * PUT can only be done to configuration files under
1678 cupsdLogMessage(CUPSD_LOG_ERROR
,
1679 "[Client %d] Request for subdirectory \"%s\".",
1680 con
->http
.fd
, con
->uri
);
1682 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1684 cupsdCloseClient(con
);
1692 * See if the PUT request includes a Content-Length field, and if
1693 * so check the length against any limits that are set...
1696 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1697 MaxRequestSize
> 0 &&
1698 con
->http
.data_remaining
> MaxRequestSize
)
1701 * Request too large...
1704 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1706 cupsdCloseClient(con
);
1712 else if (con
->http
.data_remaining
< 0)
1715 * Negative content lengths are invalid!
1718 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1720 cupsdCloseClient(con
);
1728 * Open a temporary file to hold the request...
1731 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
1733 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1737 cupsdLogMessage(CUPSD_LOG_ERROR
,
1738 "[Client %d] Unable to create request file "
1739 "\"%s\": %s", con
->http
.fd
, con
->filename
,
1742 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1744 cupsdCloseClient(con
);
1749 fchmod(con
->file
, 0640);
1750 fchown(con
->file
, RunUser
, Group
);
1751 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1756 cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
);
1757 cupsdCloseClient(con
);
1761 if (!strncmp(con
->uri
, "/printers/", 10) &&
1762 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1765 * Send PPD file - get the real printer name since printer
1766 * names are not case sensitive but filenames can be...
1769 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1771 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1772 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1775 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1777 cupsdCloseClient(con
);
1784 else if (!strncmp(con
->uri
, "/printers/", 10) &&
1785 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".png"))
1788 * Send PNG file - get the real printer name since printer
1789 * names are not case sensitive but filenames can be...
1792 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1794 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1795 snprintf(con
->uri
, sizeof(con
->uri
), "/icons/%s.png", p
->name
);
1798 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1800 cupsdCloseClient(con
);
1807 else if (!WebInterface
)
1809 if (!cupsdSendHeader(con
, HTTP_OK
, line
, CUPSD_AUTH_NONE
))
1811 cupsdCloseClient(con
);
1815 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1817 cupsdCloseClient(con
);
1821 if (cupsdFlushHeader(con
) < 0)
1823 cupsdCloseClient(con
);
1827 con
->http
.state
= HTTP_WAITING
;
1831 if ((!strncmp(con
->uri
, "/admin", 6) &&
1832 strncmp(con
->uri
, "/admin/conf/", 12) &&
1833 strncmp(con
->uri
, "/admin/log/", 11)) ||
1834 !strncmp(con
->uri
, "/printers", 9) ||
1835 !strncmp(con
->uri
, "/classes", 8) ||
1836 !strncmp(con
->uri
, "/help", 5) ||
1837 !strncmp(con
->uri
, "/jobs", 5))
1843 if (!cupsdSendHeader(con
, HTTP_OK
, "text/html", CUPSD_AUTH_NONE
))
1845 cupsdCloseClient(con
);
1849 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1851 cupsdCloseClient(con
);
1855 if (cupsdFlushHeader(con
) < 0)
1857 cupsdCloseClient(con
);
1861 cupsdLogRequest(con
, HTTP_OK
);
1863 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1864 (strchr(con
->uri
+ 12, '/') ||
1865 strlen(con
->uri
) == 12)) ||
1866 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1867 (strchr(con
->uri
+ 11, '/') ||
1868 strlen(con
->uri
) == 11)))
1871 * HEAD can only be done to configuration files under
1875 cupsdLogMessage(CUPSD_LOG_ERROR
,
1876 "[Client %d] Request for subdirectory \"%s\".",
1877 con
->http
.fd
, con
->uri
);
1879 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1881 cupsdCloseClient(con
);
1887 else if ((filename
= get_file(con
, &filestats
, buf
,
1888 sizeof(buf
))) == NULL
)
1890 if (!cupsdSendHeader(con
, HTTP_NOT_FOUND
, "text/html",
1893 cupsdCloseClient(con
);
1897 cupsdLogRequest(con
, HTTP_NOT_FOUND
);
1899 else if (!check_if_modified(con
, &filestats
))
1901 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1903 cupsdCloseClient(con
);
1907 cupsdLogRequest(con
, HTTP_NOT_MODIFIED
);
1915 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1917 strcpy(line
, "text/plain");
1919 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1921 if (!cupsdSendHeader(con
, HTTP_OK
, line
, CUPSD_AUTH_NONE
))
1923 cupsdCloseClient(con
);
1927 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
1928 httpGetDateString(filestats
.st_mtime
)) < 0)
1930 cupsdCloseClient(con
);
1934 if (httpPrintf(HTTP(con
), "Content-Length: %lu\r\n",
1935 (unsigned long)filestats
.st_size
) < 0)
1937 cupsdCloseClient(con
);
1941 cupsdLogRequest(con
, HTTP_OK
);
1944 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1946 cupsdCloseClient(con
);
1950 if (cupsdFlushHeader(con
) < 0)
1952 cupsdCloseClient(con
);
1956 con
->http
.state
= HTTP_WAITING
;
1960 break; /* Anti-compiler-warning-code */
1966 * Handle any incoming data...
1969 switch (con
->http
.state
)
1971 case HTTP_PUT_RECV
:
1974 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
1976 if (con
->http
.error
&& con
->http
.error
!= EPIPE
)
1977 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1978 "[Client %d] HTTP_PUT_RECV Closing for error "
1979 "%d (%s)", con
->http
.fd
, con
->http
.error
,
1980 strerror(con
->http
.error
));
1982 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1983 "[Client %d] HTTP_PUT_RECV Closing on EOF",
1986 cupsdCloseClient(con
);
1991 con
->bytes
+= bytes
;
1993 if (write(con
->file
, line
, bytes
) < bytes
)
1995 cupsdLogMessage(CUPSD_LOG_ERROR
,
1996 "[Client %d] Unable to write %d bytes to "
1997 "\"%s\": %s", con
->http
.fd
, bytes
, con
->filename
,
2002 unlink(con
->filename
);
2003 cupsdClearString(&con
->filename
);
2005 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2007 cupsdCloseClient(con
);
2013 while (con
->http
.state
== HTTP_PUT_RECV
&& data_ready(con
));
2015 if (con
->http
.state
== HTTP_WAITING
)
2018 * End of file, see how big it is...
2021 fstat(con
->file
, &filestats
);
2026 if (filestats
.st_size
> MaxRequestSize
&&
2030 * Request is too big; remove it and send an error...
2033 unlink(con
->filename
);
2034 cupsdClearString(&con
->filename
);
2036 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2038 cupsdCloseClient(con
);
2044 * Install the configuration file...
2047 status
= install_conf_file(con
);
2050 * Return the status to the client...
2053 if (!cupsdSendError(con
, status
, CUPSD_AUTH_NONE
))
2055 cupsdCloseClient(con
);
2061 case HTTP_POST_RECV
:
2064 if (con
->request
&& con
->file
< 0)
2067 * Grab any request data from the connection...
2070 if ((ipp_state
= ippRead(&(con
->http
), con
->request
)) == IPP_ERROR
)
2072 cupsdLogMessage(CUPSD_LOG_ERROR
,
2073 "[Client %d] IPP read error: %s", con
->http
.fd
,
2074 cupsLastErrorString());
2076 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
2077 cupsdCloseClient(con
);
2080 else if (ipp_state
!= IPP_DATA
)
2082 if (con
->http
.state
== HTTP_POST_SEND
)
2084 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
2085 cupsdCloseClient(con
);
2093 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[Client %d] %d.%d %s %d",
2094 con
->http
.fd
, con
->request
->request
.op
.version
[0],
2095 con
->request
->request
.op
.version
[1],
2096 ippOpString(con
->request
->request
.op
.operation_id
),
2097 con
->request
->request
.op
.request_id
);
2098 con
->bytes
+= ippLength(con
->request
);
2102 if (con
->file
< 0 && con
->http
.state
!= HTTP_POST_SEND
)
2105 * Create a file as needed for the request data...
2108 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
2110 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
2114 cupsdLogMessage(CUPSD_LOG_ERROR
,
2115 "[Client %d] Unable to create request file "
2116 "\"%s\": %s", con
->http
.fd
, con
->filename
,
2119 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2121 cupsdCloseClient(con
);
2126 fchmod(con
->file
, 0640);
2127 fchown(con
->file
, RunUser
, Group
);
2128 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2131 if (con
->http
.state
!= HTTP_POST_SEND
)
2133 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
2135 if (con
->http
.error
&& con
->http
.error
!= EPIPE
)
2136 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2137 "[Client %d] HTTP_POST_SEND Closing for "
2138 "error %d (%s)", con
->http
.fd
, con
->http
.error
,
2139 strerror(con
->http
.error
));
2141 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2142 "[Client %d] HTTP_POST_SEND Closing on EOF",
2145 cupsdCloseClient(con
);
2150 con
->bytes
+= bytes
;
2152 if (write(con
->file
, line
, bytes
) < bytes
)
2154 cupsdLogMessage(CUPSD_LOG_ERROR
,
2155 "[Client %d] Unable to write %d bytes to "
2156 "\"%s\": %s", con
->http
.fd
, bytes
,
2157 con
->filename
, strerror(errno
));
2161 unlink(con
->filename
);
2162 cupsdClearString(&con
->filename
);
2164 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
,
2167 cupsdCloseClient(con
);
2172 else if (con
->http
.state
== HTTP_POST_RECV
)
2174 else if (con
->http
.state
!= HTTP_POST_SEND
)
2176 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2177 "[Client %d] Closing on unexpected state %s.",
2178 con
->http
.fd
, http_states
[con
->http
.state
]);
2179 cupsdCloseClient(con
);
2184 while (con
->http
.state
== HTTP_POST_RECV
&& data_ready(con
));
2186 if (con
->http
.state
== HTTP_POST_SEND
)
2190 fstat(con
->file
, &filestats
);
2195 if (filestats
.st_size
> MaxRequestSize
&&
2199 * Request is too big; remove it and send an error...
2202 unlink(con
->filename
);
2203 cupsdClearString(&con
->filename
);
2208 * Delete any IPP request data...
2211 ippDelete(con
->request
);
2212 con
->request
= NULL
;
2215 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2217 cupsdCloseClient(con
);
2221 else if (filestats
.st_size
== 0)
2224 * Don't allow empty file...
2227 unlink(con
->filename
);
2228 cupsdClearString(&con
->filename
);
2233 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
2235 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
2237 cupsdCloseClient(con
);
2242 cupsdLogRequest(con
, HTTP_OK
);
2248 cupsdProcessIPPRequest(con
);
2252 unlink(con
->filename
);
2253 cupsdClearString(&con
->filename
);
2262 break; /* Anti-compiler-warning-code */
2265 if (con
->http
.state
== HTTP_WAITING
)
2267 if (!con
->http
.keep_alive
)
2269 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2270 "[Client %d] Closing because Keep-Alive disabled",
2272 cupsdCloseClient(con
);
2276 cupsArrayRemove(ActiveClients
, con
);
2277 cupsdSetBusyState();
2284 * 'cupsdSendCommand()' - Send output from a command via HTTP.
2287 int /* O - 1 on success, 0 on failure */
2289 cupsd_client_t
*con
, /* I - Client connection */
2290 char *command
, /* I - Command to run */
2291 char *options
, /* I - Command-line options */
2292 int root
) /* I - Run as root? */
2294 int fd
; /* Standard input file descriptor */
2299 fd
= open(con
->filename
, O_RDONLY
);
2303 cupsdLogMessage(CUPSD_LOG_ERROR
,
2304 "[Client %d] Unable to open \"%s\" for reading: %s",
2305 con
->http
.fd
, con
->filename
? con
->filename
: "/dev/null",
2310 fcntl(fd
, F_SETFD
, fcntl(fd
, F_GETFD
) | FD_CLOEXEC
);
2315 con
->pipe_pid
= pipe_command(con
, fd
, &(con
->file
), command
, options
, root
);
2320 cupsdLogMessage(CUPSD_LOG_INFO
, "[Client %d] Started \"%s\" (pid=%d)",
2321 con
->http
.fd
, command
, con
->pipe_pid
);
2323 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[Client %d] file=%d", con
->http
.fd
,
2326 if (con
->pipe_pid
== 0)
2329 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2331 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2333 con
->sent_header
= 0;
2334 con
->file_ready
= 0;
2335 con
->got_fields
= 0;
2336 con
->header_used
= 0;
2343 * 'cupsdSendError()' - Send an error message via HTTP.
2346 int /* O - 1 if successful, 0 otherwise */
2347 cupsdSendError(cupsd_client_t
*con
, /* I - Connection */
2348 http_status_t code
, /* I - Error code */
2349 int auth_type
)/* I - Authentication type */
2351 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2352 "[Client %d] cupsdSendError code=%d, auth_type=%d",
2353 con
->http
.fd
, code
, auth_type
);
2357 * Force client to upgrade for authentication if that is how the
2358 * server is configured...
2361 if (code
== HTTP_UNAUTHORIZED
&&
2362 DefaultEncryption
== HTTP_ENCRYPT_REQUIRED
&&
2363 _cups_strcasecmp(con
->http
.hostname
, "localhost") &&
2366 code
= HTTP_UPGRADE_REQUIRED
;
2368 #endif /* HAVE_SSL */
2371 * Put the request in the access_log file...
2374 cupsdLogRequest(con
, code
);
2377 * To work around bugs in some proxies, don't use Keep-Alive for some
2380 * Kerberos authentication doesn't work without Keep-Alive, so
2381 * never disable it in that case.
2384 if (code
>= HTTP_BAD_REQUEST
&& con
->http
.auth_type
!= CUPSD_AUTH_NEGOTIATE
)
2385 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
2388 * Send an error message back to the client. If the error code is a
2389 * 400 or 500 series, make sure the message contains some text, too!
2392 if (!cupsdSendHeader(con
, code
, NULL
, auth_type
))
2396 if (code
== HTTP_UPGRADE_REQUIRED
)
2397 if (httpPrintf(HTTP(con
), "Connection: Upgrade\r\n") < 0)
2400 if (httpPrintf(HTTP(con
), "Upgrade: TLS/1.0,HTTP/1.1\r\n") < 0)
2402 #endif /* HAVE_SSL */
2404 if (con
->http
.version
>= HTTP_1_1
&&
2405 con
->http
.keep_alive
== HTTP_KEEPALIVE_OFF
)
2407 if (httpPrintf(HTTP(con
), "Connection: close\r\n") < 0)
2411 if (code
>= HTTP_BAD_REQUEST
)
2414 * Send a human-readable error message.
2417 char message
[4096], /* Message for user */
2418 urltext
[1024], /* URL redirection text */
2419 redirect
[1024]; /* Redirection link */
2420 const char *text
; /* Status-specific text */
2425 if (code
== HTTP_UNAUTHORIZED
)
2426 text
= _cupsLangString(con
->language
,
2427 _("Enter your username and password or the "
2428 "root username and password to access this "
2429 "page. If you are using Kerberos authentication, "
2430 "make sure you have a valid Kerberos ticket."));
2431 else if (code
== HTTP_UPGRADE_REQUIRED
)
2435 snprintf(urltext
, sizeof(urltext
),
2436 _cupsLangString(con
->language
,
2437 _("You must access this page using the URL "
2438 "<A HREF=\"https://%s:%d%s\">"
2439 "https://%s:%d%s</A>.")),
2440 con
->servername
, con
->serverport
, con
->uri
,
2441 con
->servername
, con
->serverport
, con
->uri
);
2443 snprintf(redirect
, sizeof(redirect
),
2444 "<META HTTP-EQUIV=\"Refresh\" "
2445 "CONTENT=\"3;URL=https://%s:%d%s\">\n",
2446 con
->servername
, con
->serverport
, con
->uri
);
2448 else if (code
== HTTP_WEBIF_DISABLED
)
2449 text
= _cupsLangString(con
->language
,
2450 _("The web interface is currently disabled. Run "
2451 "\"cupsctl WebInterface=yes\" to enable it."));
2455 snprintf(message
, sizeof(message
),
2456 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" "
2457 "\"http://www.w3.org/TR/html4/loose.dtd\">\n"
2460 "\t<META HTTP-EQUIV=\"Content-Type\" "
2461 "CONTENT=\"text/html; charset=utf-8\">\n"
2462 "\t<TITLE>%s - " CUPS_SVERSION
"</TITLE>\n"
2463 "\t<LINK REL=\"STYLESHEET\" TYPE=\"text/css\" "
2464 "HREF=\"/cups.css\">\n"
2472 httpStatus(code
), redirect
, httpStatus(code
), text
);
2474 if (httpPrintf(HTTP(con
), "Content-Type: text/html; charset=utf-8\r\n") < 0)
2476 if (httpPrintf(HTTP(con
), "Content-Length: %d\r\n",
2477 (int)strlen(message
)) < 0)
2479 if (httpPrintf(HTTP(con
), "\r\n") < 0)
2481 if (httpPrintf(HTTP(con
), "%s", message
) < 0)
2484 else if (httpPrintf(HTTP(con
), "\r\n") < 0)
2487 if (cupsdFlushHeader(con
) < 0)
2490 con
->http
.state
= HTTP_WAITING
;
2497 * 'cupsdSendHeader()' - Send an HTTP request.
2500 int /* O - 1 on success, 0 on failure */
2502 cupsd_client_t
*con
, /* I - Client to send to */
2503 http_status_t code
, /* I - HTTP status code */
2504 char *type
, /* I - MIME type of document */
2505 int auth_type
) /* I - Type of authentication */
2507 char auth_str
[1024]; /* Authorization string */
2511 * Send the HTTP status header...
2514 if (code
== HTTP_CONTINUE
)
2517 * 100-continue doesn't send any headers...
2520 return (httpPrintf(HTTP(con
), "HTTP/%d.%d 100 Continue\r\n\r\n",
2521 con
->http
.version
/ 100, con
->http
.version
% 100) > 0);
2523 else if (code
== HTTP_WEBIF_DISABLED
)
2526 * Treat our special "web interface is disabled" status as "200 OK" for web
2533 httpFlushWrite(HTTP(con
));
2535 con
->http
.data_encoding
= HTTP_ENCODE_FIELDS
;
2537 if (httpPrintf(HTTP(con
), "HTTP/%d.%d %d %s\r\n", con
->http
.version
/ 100,
2538 con
->http
.version
% 100, code
, httpStatus(code
)) < 0)
2540 if (httpPrintf(HTTP(con
), "Date: %s\r\n", httpGetDateString(time(NULL
))) < 0)
2543 if (httpPrintf(HTTP(con
), "Server: %s\r\n", ServerHeader
) < 0)
2545 if (con
->http
.keep_alive
&& con
->http
.version
>= HTTP_1_0
)
2547 if (httpPrintf(HTTP(con
), "Connection: Keep-Alive\r\n") < 0)
2549 if (httpPrintf(HTTP(con
), "Keep-Alive: timeout=%d\r\n",
2550 KeepAliveTimeout
) < 0)
2553 if (code
== HTTP_METHOD_NOT_ALLOWED
)
2554 if (httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n") < 0)
2557 if (code
== HTTP_UNAUTHORIZED
)
2559 if (auth_type
== CUPSD_AUTH_NONE
)
2561 if (!con
->best
|| con
->best
->type
<= CUPSD_AUTH_NONE
)
2562 auth_type
= cupsdDefaultAuthType();
2564 auth_type
= con
->best
->type
;
2569 if (auth_type
== CUPSD_AUTH_BASIC
|| auth_type
== CUPSD_AUTH_BASICDIGEST
)
2570 strlcpy(auth_str
, "Basic realm=\"CUPS\"", sizeof(auth_str
));
2571 else if (auth_type
== CUPSD_AUTH_DIGEST
)
2572 snprintf(auth_str
, sizeof(auth_str
), "Digest realm=\"CUPS\", nonce=\"%s\"",
2573 con
->http
.hostname
);
2575 else if (auth_type
== CUPSD_AUTH_NEGOTIATE
)
2578 if (_httpAddrFamily(con
->http
.hostaddr
) == AF_LOCAL
)
2579 strlcpy(auth_str
, "Basic realm=\"CUPS\"", sizeof(auth_str
));
2581 # endif /* AF_LOCAL */
2582 strlcpy(auth_str
, "Negotiate", sizeof(auth_str
));
2584 #endif /* HAVE_GSSAPI */
2586 if (con
->best
&& auth_type
!= CUPSD_AUTH_NEGOTIATE
&&
2587 !_cups_strcasecmp(con
->http
.hostname
, "localhost"))
2590 * Add a "trc" (try root certification) parameter for local non-Kerberos
2591 * requests when the request requires system group membership - then the
2592 * client knows the root certificate can/should be used.
2594 * Also, for OS X we also look for @AUTHKEY and add an "authkey"
2595 * parameter as needed...
2598 char *name
, /* Current user name */
2599 *auth_key
; /* Auth key buffer */
2600 size_t auth_size
; /* Size of remaining buffer */
2602 auth_key
= auth_str
+ strlen(auth_str
);
2603 auth_size
= sizeof(auth_str
) - (auth_key
- auth_str
);
2605 for (name
= (char *)cupsArrayFirst(con
->best
->names
);
2607 name
= (char *)cupsArrayNext(con
->best
->names
))
2609 #ifdef HAVE_AUTHORIZATION_H
2610 if (!_cups_strncasecmp(name
, "@AUTHKEY(", 9))
2612 snprintf(auth_key
, auth_size
, ", authkey=\"%s\"", name
+ 9);
2613 /* end parenthesis is stripped in conf.c */
2617 #endif /* HAVE_AUTHORIZATION_H */
2618 if (!_cups_strcasecmp(name
, "@SYSTEM"))
2620 #ifdef HAVE_AUTHORIZATION_H
2621 if (SystemGroupAuthKey
)
2622 snprintf(auth_key
, auth_size
,
2624 SystemGroupAuthKey
);
2627 strlcpy(auth_key
, ", trc=\"y\"", auth_size
);
2628 #endif /* HAVE_AUTHORIZATION_H */
2636 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2637 "[Client %d] WWW-Authenticate: %s", con
->http
.fd
,
2640 if (httpPrintf(HTTP(con
), "WWW-Authenticate: %s\r\n", auth_str
) < 0)
2645 if (con
->language
&& strcmp(con
->language
->language
, "C"))
2647 if (httpPrintf(HTTP(con
), "Content-Language: %s\r\n",
2648 con
->language
->language
) < 0)
2654 if (!strcmp(type
, "text/html"))
2656 if (httpPrintf(HTTP(con
),
2657 "Content-Type: text/html; charset=utf-8\r\n") < 0)
2660 else if (httpPrintf(HTTP(con
), "Content-Type: %s\r\n", type
) < 0)
2669 * 'cupsdUpdateCGI()' - Read status messages from CGI scripts and programs.
2673 cupsdUpdateCGI(void)
2675 char *ptr
, /* Pointer to end of line in buffer */
2676 message
[1024]; /* Pointer to message text */
2677 int loglevel
; /* Log level for message */
2680 while ((ptr
= cupsdStatBufUpdate(CGIStatusBuffer
, &loglevel
,
2681 message
, sizeof(message
))) != NULL
)
2683 if (loglevel
== CUPSD_LOG_INFO
)
2684 cupsdLogMessage(CUPSD_LOG_INFO
, "%s", message
);
2686 if (!strchr(CGIStatusBuffer
->buffer
, '\n'))
2690 if (ptr
== NULL
&& !CGIStatusBuffer
->bufused
)
2693 * Fatal error on pipe - should never happen!
2696 cupsdLogMessage(CUPSD_LOG_CRIT
,
2697 "cupsdUpdateCGI: error reading from CGI error pipe - %s",
2704 * 'cupsdWriteClient()' - Write data to a client as needed.
2708 cupsdWriteClient(cupsd_client_t
*con
) /* I - Client connection */
2710 int bytes
, /* Number of bytes written */
2711 field_col
; /* Current column */
2712 char *bufptr
, /* Pointer into buffer */
2713 *bufend
; /* Pointer to end of buffer */
2714 ipp_state_t ipp_state
; /* IPP state value */
2717 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2718 "[Client %d] cupsdWriteClient "
2722 "data_encoding=HTTP_ENCODE_%s, "
2723 "data_remaining=" CUPS_LLFMT
", "
2727 con
->http
.fd
, con
->http
.error
, con
->http
.used
,
2728 http_states
[con
->http
.state
],
2729 con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
?
2730 "CHUNKED" : "LENGTH",
2731 CUPS_LLCAST con
->http
.data_remaining
,
2733 con
->response
? ipp_states
[con
->response
->state
] : "",
2734 con
->pipe_pid
, con
->file
);
2736 if (con
->http
.state
!= HTTP_GET_SEND
&&
2737 con
->http
.state
!= HTTP_POST_SEND
)
2740 * If we get called in the wrong state, then something went wrong with the
2741 * connection and we need to shut it down...
2744 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2745 "[Client %d] Closing on unexpected HTTP state %s.",
2746 con
->http
.fd
, http_states
[con
->http
.state
]);
2747 cupsdCloseClient(con
);
2754 * Make sure we select on the CGI output...
2757 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2759 if (!con
->file_ready
)
2762 * Try again later when there is CGI output available...
2765 cupsdRemoveSelect(con
->http
.fd
);
2769 con
->file_ready
= 0;
2772 if (con
->response
&& con
->response
->state
!= IPP_DATA
)
2774 ipp_state
= ippWrite(HTTP(con
), con
->response
);
2775 bytes
= ipp_state
!= IPP_ERROR
&&
2776 (con
->file
>= 0 || ipp_state
!= IPP_DATA
);
2778 else if ((bytes
= read(con
->file
, con
->header
+ con
->header_used
,
2779 sizeof(con
->header
) - con
->header_used
)) > 0)
2781 con
->header_used
+= bytes
;
2783 if (con
->pipe_pid
&& !con
->got_fields
)
2786 * Inspect the data for Content-Type and other fields.
2789 for (bufptr
= con
->header
, bufend
= con
->header
+ con
->header_used
,
2791 !con
->got_fields
&& bufptr
< bufend
;
2794 if (*bufptr
== '\n')
2797 * Send line to client...
2800 if (bufptr
> con
->header
&& bufptr
[-1] == '\r')
2804 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Script header: %s", con
->header
);
2806 if (!con
->sent_header
)
2809 * Handle redirection and CGI status codes...
2812 if (!_cups_strncasecmp(con
->header
, "Location:", 9))
2814 if (!cupsdSendHeader(con
, HTTP_SEE_OTHER
, NULL
, CUPSD_AUTH_NONE
))
2816 cupsdCloseClient(con
);
2820 con
->sent_header
= 2;
2822 if (httpPrintf(HTTP(con
), "Content-Length: 0\r\n") < 0)
2825 else if (!_cups_strncasecmp(con
->header
, "Status:", 7))
2827 cupsdSendError(con
, (http_status_t
)atoi(con
->header
+ 7),
2829 con
->sent_header
= 2;
2833 if (!cupsdSendHeader(con
, HTTP_OK
, NULL
, CUPSD_AUTH_NONE
))
2835 cupsdCloseClient(con
);
2839 con
->sent_header
= 1;
2841 if (con
->http
.version
== HTTP_1_1
)
2843 if (httpPrintf(HTTP(con
), "Transfer-Encoding: chunked\r\n") < 0)
2849 if (_cups_strncasecmp(con
->header
, "Status:", 7))
2850 httpPrintf(HTTP(con
), "%s\r\n", con
->header
);
2856 con
->header_used
-= bufptr
- con
->header
;
2858 if (con
->header_used
> 0)
2859 memmove(con
->header
, bufptr
, con
->header_used
);
2861 bufptr
= con
->header
- 1;
2864 * See if the line was empty...
2869 con
->got_fields
= 1;
2871 if (cupsdFlushHeader(con
) < 0)
2873 cupsdCloseClient(con
);
2877 if (con
->http
.version
== HTTP_1_1
)
2878 con
->http
.data_encoding
= HTTP_ENCODE_CHUNKED
;
2883 else if (*bufptr
!= '\r')
2887 if (!con
->got_fields
)
2889 con
->http
.activity
= time(NULL
);
2894 if (con
->header_used
> 0)
2896 if (httpWrite2(HTTP(con
), con
->header
, con
->header_used
) < 0)
2898 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2899 "[Client %d] Closing for error %d (%s)",
2900 con
->http
.fd
, con
->http
.error
,
2901 strerror(con
->http
.error
));
2902 cupsdCloseClient(con
);
2906 if (con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
)
2907 httpFlushWrite(HTTP(con
));
2909 con
->bytes
+= con
->header_used
;
2911 if (con
->http
.state
== HTTP_WAITING
)
2914 bytes
= con
->header_used
;
2916 con
->header_used
= 0;
2921 (con
->http
.state
!= HTTP_GET_SEND
&& con
->http
.state
!= HTTP_POST_SEND
))
2923 if (!con
->sent_header
&& con
->pipe_pid
)
2924 cupsdSendError(con
, HTTP_SERVER_ERROR
, CUPSD_AUTH_NONE
);
2927 cupsdLogRequest(con
, HTTP_OK
);
2929 httpFlushWrite(HTTP(con
));
2931 if (con
->http
.data_encoding
== HTTP_ENCODE_CHUNKED
&& con
->sent_header
== 1)
2933 if (httpWrite2(HTTP(con
), "", 0) < 0)
2935 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2936 "[Client %d] Closing for error %d (%s)",
2937 con
->http
.fd
, con
->http
.error
,
2938 strerror(con
->http
.error
));
2939 cupsdCloseClient(con
);
2945 con
->http
.state
= HTTP_WAITING
;
2947 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
2951 cupsdRemoveSelect(con
->file
);
2954 cupsdEndProcess(con
->pipe_pid
, 0);
2963 unlink(con
->filename
);
2964 cupsdClearString(&con
->filename
);
2969 ippDelete(con
->request
);
2970 con
->request
= NULL
;
2975 ippDelete(con
->response
);
2976 con
->response
= NULL
;
2979 cupsdClearString(&con
->command
);
2980 cupsdClearString(&con
->options
);
2981 cupsdClearString(&con
->query_string
);
2983 if (!con
->http
.keep_alive
)
2985 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2986 "[Client %d] Closing because Keep-Alive disabled.",
2988 cupsdCloseClient(con
);
2993 cupsArrayRemove(ActiveClients
, con
);
2994 cupsdSetBusyState();
2998 con
->http
.activity
= time(NULL
);
3003 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
3006 static int /* O - 1 if modified since */
3008 cupsd_client_t
*con
, /* I - Client connection */
3009 struct stat
*filestats
) /* I - File information */
3011 char *ptr
; /* Pointer into field */
3012 time_t date
; /* Time/date value */
3013 off_t size
; /* Size/length value */
3018 ptr
= con
->http
.fields
[HTTP_FIELD_IF_MODIFIED_SINCE
];
3023 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3024 "[Client %d] check_if_modified "
3025 "filestats=%p(" CUPS_LLFMT
", %d)) If-Modified-Since=\"%s\"",
3026 con
->http
.fd
, filestats
, CUPS_LLCAST filestats
->st_size
,
3027 (int)filestats
->st_mtime
, ptr
);
3029 while (*ptr
!= '\0')
3031 while (isspace(*ptr
) || *ptr
== ';')
3034 if (_cups_strncasecmp(ptr
, "length=", 7) == 0)
3037 size
= strtoll(ptr
, NULL
, 10);
3039 while (isdigit(*ptr
))
3042 else if (isalpha(*ptr
))
3044 date
= httpGetDateTime(ptr
);
3045 while (*ptr
!= '\0' && *ptr
!= ';')
3052 return ((size
!= filestats
->st_size
&& size
!= 0) ||
3053 (date
< filestats
->st_mtime
&& date
!= 0) ||
3054 (size
== 0 && date
== 0));
3059 * 'compare_clients()' - Compare two client connections.
3062 static int /* O - Result of comparison */
3063 compare_clients(cupsd_client_t
*a
, /* I - First client */
3064 cupsd_client_t
*b
, /* I - Second client */
3065 void *data
) /* I - User data (not used) */
3079 * 'data_ready()' - Check whether data is available from a client.
3082 static int /* O - 1 if data is ready, 0 otherwise */
3083 data_ready(cupsd_client_t
*con
) /* I - Client */
3085 if (con
->http
.used
> 0)
3088 else if (con
->http
.tls
)
3091 if (SSL_pending((SSL
*)(con
->http
.tls
)))
3093 # elif defined(HAVE_GNUTLS)
3094 if (gnutls_record_check_pending(con
->http
.tls
))
3096 # elif defined(HAVE_CDSASSL)
3097 size_t bytes
; /* Bytes that are available */
3099 if (!SSLGetBufferedReadSize(con
->http
.tls
, &bytes
) && bytes
> 0)
3101 # endif /* HAVE_LIBSSL */
3103 #endif /* HAVE_SSL */
3110 * 'get_file()' - Get a filename and state info.
3113 static char * /* O - Real filename */
3114 get_file(cupsd_client_t
*con
, /* I - Client connection */
3115 struct stat
*filestats
, /* O - File information */
3116 char *filename
, /* IO - Filename buffer */
3117 int len
) /* I - Buffer length */
3119 int status
; /* Status of filesystem calls */
3120 char *ptr
; /* Pointer info filename */
3121 int plen
; /* Remaining length after pointer */
3122 char language
[7]; /* Language subdirectory, if any */
3126 * Figure out the real filename...
3131 if (!strncmp(con
->uri
, "/ppd/", 5) && !strchr(con
->uri
+ 5, '/'))
3132 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
);
3133 else if (!strncmp(con
->uri
, "/icons/", 7) && !strchr(con
->uri
+ 7, '/'))
3135 snprintf(filename
, len
, "%s/%s", CacheDir
, con
->uri
+ 7);
3136 if (access(filename
, F_OK
) < 0)
3137 snprintf(filename
, len
, "%s/images/generic.png", DocumentRoot
);
3139 else if (!strncmp(con
->uri
, "/rss/", 5) && !strchr(con
->uri
+ 5, '/'))
3140 snprintf(filename
, len
, "%s/rss/%s", CacheDir
, con
->uri
+ 5);
3141 else if (!strncmp(con
->uri
, "/admin/conf/", 12))
3142 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
+ 11);
3143 else if (!strncmp(con
->uri
, "/admin/log/", 11))
3145 if (!strncmp(con
->uri
+ 11, "access_log", 10) && AccessLog
[0] == '/')
3146 strlcpy(filename
, AccessLog
, len
);
3147 else if (!strncmp(con
->uri
+ 11, "error_log", 9) && ErrorLog
[0] == '/')
3148 strlcpy(filename
, ErrorLog
, len
);
3149 else if (!strncmp(con
->uri
+ 11, "page_log", 8) && PageLog
[0] == '/')
3150 strlcpy(filename
, PageLog
, len
);
3154 else if (con
->language
)
3156 snprintf(language
, sizeof(language
), "/%s", con
->language
->language
);
3157 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3160 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3162 if ((ptr
= strchr(filename
, '?')) != NULL
)
3166 * Grab the status for this language; if there isn't a language-specific file
3167 * then fallback to the default one...
3170 if ((status
= stat(filename
, filestats
)) != 0 && language
[0] &&
3171 strncmp(con
->uri
, "/icons/", 7) &&
3172 strncmp(con
->uri
, "/ppd/", 5) &&
3173 strncmp(con
->uri
, "/rss/", 5) &&
3174 strncmp(con
->uri
, "/admin/conf/", 12) &&
3175 strncmp(con
->uri
, "/admin/log/", 11))
3178 * Drop the country code...
3182 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3184 if ((ptr
= strchr(filename
, '?')) != NULL
)
3187 if ((status
= stat(filename
, filestats
)) != 0)
3190 * Drop the language prefix and try the root directory...
3194 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3196 if ((ptr
= strchr(filename
, '?')) != NULL
)
3199 status
= stat(filename
, filestats
);
3204 * If we're found a directory, get the index.html file instead...
3207 if (!status
&& S_ISDIR(filestats
->st_mode
))
3210 * Make sure the URI ends with a slash...
3213 if (con
->uri
[strlen(con
->uri
) - 1] != '/')
3214 strlcat(con
->uri
, "/", sizeof(con
->uri
));
3217 * Find the directory index file, trying every language...
3222 if (status
&& language
[0])
3225 * Try a different language subset...
3229 language
[0] = '\0'; /* Strip country code */
3231 language
[0] = '\0'; /* Strip language */
3235 * Look for the index file...
3238 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3240 if ((ptr
= strchr(filename
, '?')) != NULL
)
3243 ptr
= filename
+ strlen(filename
);
3244 plen
= len
- (ptr
- filename
);
3246 strlcpy(ptr
, "index.html", plen
);
3247 status
= stat(filename
, filestats
);
3252 strlcpy(ptr
, "index.class", plen
);
3253 status
= stat(filename
, filestats
);
3255 #endif /* HAVE_JAVA */
3260 strlcpy(ptr
, "index.pl", plen
);
3261 status
= stat(filename
, filestats
);
3263 #endif /* HAVE_PERL */
3268 strlcpy(ptr
, "index.php", plen
);
3269 status
= stat(filename
, filestats
);
3271 #endif /* HAVE_PHP */
3276 strlcpy(ptr
, "index.pyc", plen
);
3277 status
= stat(filename
, filestats
);
3282 strlcpy(ptr
, "index.py", plen
);
3283 status
= stat(filename
, filestats
);
3285 #endif /* HAVE_PYTHON */
3288 while (status
&& language
[0]);
3291 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3292 "[Client %d] get_file filestats=%p, filename=%p, len=%d, "
3293 "returning \"%s\".", con
->http
.fd
, filestats
, filename
, len
,
3294 status
? "(null)" : filename
);
3304 * 'install_conf_file()' - Install a configuration file.
3307 static http_status_t
/* O - Status */
3308 install_conf_file(cupsd_client_t
*con
) /* I - Connection */
3310 char filename
[1024]; /* Configuration filename */
3311 mode_t mode
; /* Permissions */
3312 cups_file_t
*in
, /* Input file */
3313 *out
; /* Output file */
3314 char buffer
[16384]; /* Copy buffer */
3315 ssize_t bytes
; /* Number of bytes */
3319 * Open the request file...
3322 if ((in
= cupsFileOpen(con
->filename
, "rb")) == NULL
)
3324 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open request file \"%s\": %s",
3325 con
->filename
, strerror(errno
));
3326 return (HTTP_SERVER_ERROR
);
3330 * Open the new config file...
3333 snprintf(filename
, sizeof(filename
), "%s%s", ServerRoot
, con
->uri
+ 11);
3334 if (!strcmp(con
->uri
, "/admin/conf/printers.conf"))
3335 mode
= ConfigFilePerm
& 0600;
3337 mode
= ConfigFilePerm
;
3339 if ((out
= cupsdCreateConfFile(filename
, mode
)) == NULL
)
3342 return (HTTP_SERVER_ERROR
);
3345 cupsdLogMessage(CUPSD_LOG_INFO
, "Installing config file \"%s\"...", filename
);
3348 * Copy from the request to the new config file...
3351 while ((bytes
= cupsFileRead(in
, buffer
, sizeof(buffer
))) > 0)
3352 if (cupsFileWrite(out
, buffer
, bytes
) < bytes
)
3354 cupsdLogMessage(CUPSD_LOG_ERROR
,
3355 "Unable to copy to config file \"%s\": %s",
3356 filename
, strerror(errno
));
3361 snprintf(filename
, sizeof(filename
), "%s%s.N", ServerRoot
, con
->uri
+ 11);
3362 cupsdRemoveFile(filename
);
3364 return (HTTP_SERVER_ERROR
);
3368 * Close the files...
3373 if (cupsdCloseCreatedConfFile(out
, filename
))
3374 return (HTTP_SERVER_ERROR
);
3377 * Remove the request file...
3380 cupsdRemoveFile(con
->filename
);
3381 cupsdClearString(&con
->filename
);
3384 * If the cupsd.conf file was updated, set the NeedReload flag...
3387 if (!strcmp(con
->uri
, "/admin/conf/cupsd.conf"))
3388 NeedReload
= RELOAD_CUPSD
;
3390 NeedReload
= RELOAD_ALL
;
3392 ReloadTime
= time(NULL
);
3395 * Return that the file was created successfully...
3398 return (HTTP_CREATED
);
3403 * 'is_cgi()' - Is the resource a CGI script/program?
3406 static int /* O - 1 = CGI, 0 = file */
3407 is_cgi(cupsd_client_t
*con
, /* I - Client connection */
3408 const char *filename
, /* I - Real filename */
3409 struct stat
*filestats
, /* I - File information */
3410 mime_type_t
*type
) /* I - MIME type */
3412 const char *options
; /* Options on URL */
3416 * Get the options, if any...
3419 if ((options
= strchr(con
->uri
, '?')) != NULL
)
3422 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", options
);
3426 * Check for known types...
3429 if (!type
|| _cups_strcasecmp(type
->super
, "application"))
3431 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3432 "[Client %d] is_cgi filename=\"%s\", filestats=%p, "
3433 "type=%s/%s, returning 0", con
->http
.fd
, filename
,
3434 filestats
, type
? type
->super
: "unknown",
3435 type
? type
->type
: "unknown");
3439 if (!_cups_strcasecmp(type
->type
, "x-httpd-cgi") &&
3440 (filestats
->st_mode
& 0111))
3443 * "application/x-httpd-cgi" is a CGI script.
3446 cupsdSetString(&con
->command
, filename
);
3449 cupsdSetStringf(&con
->options
, " %s", options
);
3451 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3452 "[Client %d] is_cgi filename=\"%s\", filestats=%p, "
3453 "type=%s/%s, returning 1", con
->http
.fd
, filename
,
3454 filestats
, type
->super
, type
->type
);
3458 else if (!_cups_strcasecmp(type
->type
, "x-httpd-java"))
3461 * "application/x-httpd-java" is a Java servlet.
3464 cupsdSetString(&con
->command
, CUPS_JAVA
);
3467 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3469 cupsdSetStringf(&con
->options
, " %s", filename
);
3471 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3472 "[Client %d] is_cgi filename=\"%s\", filestats=%p, "
3473 "type=%s/%s, returning 1", con
->http
.fd
, filename
,
3474 filestats
, type
->super
, type
->type
);
3477 #endif /* HAVE_JAVA */
3479 else if (!_cups_strcasecmp(type
->type
, "x-httpd-perl"))
3482 * "application/x-httpd-perl" is a Perl page.
3485 cupsdSetString(&con
->command
, CUPS_PERL
);
3488 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3490 cupsdSetStringf(&con
->options
, " %s", filename
);
3492 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3493 "[Client %d] is_cgi filename=\"%s\", filestats=%p, "
3494 "type=%s/%s, returning 1", con
->http
.fd
, filename
,
3495 filestats
, type
->super
, type
->type
);
3498 #endif /* HAVE_PERL */
3500 else if (!_cups_strcasecmp(type
->type
, "x-httpd-php"))
3503 * "application/x-httpd-php" is a PHP page.
3506 cupsdSetString(&con
->command
, CUPS_PHP
);
3509 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3511 cupsdSetStringf(&con
->options
, " %s", filename
);
3513 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3514 "[Client %d] is_cgi filename=\"%s\", filestats=%p, "
3515 "type=%s/%s, returning 1", con
->http
.fd
, filename
,
3516 filestats
, type
->super
, type
->type
);
3519 #endif /* HAVE_PHP */
3521 else if (!_cups_strcasecmp(type
->type
, "x-httpd-python"))
3524 * "application/x-httpd-python" is a Python page.
3527 cupsdSetString(&con
->command
, CUPS_PYTHON
);
3530 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3532 cupsdSetStringf(&con
->options
, " %s", filename
);
3534 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3535 "[Client %d] is_cgi filename=\"%s\", filestats=%p, "
3536 "type=%s/%s, returning 1", con
->http
.fd
, filename
,
3537 filestats
, type
->super
, type
->type
);
3540 #endif /* HAVE_PYTHON */
3542 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3543 "[Client %d] is_cgi filename=\"%s\", filestats=%p, "
3544 "type=%s/%s, returning 0", con
->http
.fd
, filename
,
3545 filestats
, type
->super
, type
->type
);
3551 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
3554 static int /* O - 0 if relative, 1 if absolute */
3555 is_path_absolute(const char *path
) /* I - Input path */
3558 * Check for a leading slash...
3565 * Check for "/.." in the path...
3568 while ((path
= strstr(path
, "/..")) != NULL
)
3570 if (!path
[3] || path
[3] == '/')
3577 * If we haven't found any relative paths, return 1 indicating an
3586 * 'pipe_command()' - Pipe the output of a command to the remote client.
3589 static int /* O - Process ID */
3590 pipe_command(cupsd_client_t
*con
, /* I - Client connection */
3591 int infile
, /* I - Standard input for command */
3592 int *outfile
, /* O - Standard output for command */
3593 char *command
, /* I - Command to run */
3594 char *options
, /* I - Options for command */
3595 int root
) /* I - Run as root? */
3597 int i
; /* Looping var */
3598 int pid
; /* Process ID */
3599 char *commptr
, /* Command string pointer */
3600 commch
; /* Command string character */
3601 char *uriptr
; /* URI string pointer */
3602 int fds
[2]; /* Pipe FDs */
3603 int argc
; /* Number of arguments */
3604 int envc
; /* Number of environment variables */
3605 char argbuf
[10240], /* Argument buffer */
3606 *argv
[100], /* Argument strings */
3607 *envp
[MAX_ENV
+ 20]; /* Environment variables */
3608 char auth_type
[256], /* AUTH_TYPE environment variable */
3609 content_length
[1024], /* CONTENT_LENGTH environment variable */
3610 content_type
[1024], /* CONTENT_TYPE environment variable */
3611 http_cookie
[32768], /* HTTP_COOKIE environment variable */
3612 http_referer
[1024], /* HTTP_REFERER environment variable */
3613 http_user_agent
[1024], /* HTTP_USER_AGENT environment variable */
3614 lang
[1024], /* LANG environment variable */
3615 path_info
[1024], /* PATH_INFO environment variable */
3616 remote_addr
[1024], /* REMOTE_ADDR environment variable */
3617 remote_host
[1024], /* REMOTE_HOST environment variable */
3618 remote_user
[1024], /* REMOTE_USER environment variable */
3619 script_filename
[1024], /* SCRIPT_FILENAME environment variable */
3620 script_name
[1024], /* SCRIPT_NAME environment variable */
3621 server_name
[1024], /* SERVER_NAME environment variable */
3622 server_port
[1024]; /* SERVER_PORT environment variable */
3623 ipp_attribute_t
*attr
; /* attributes-natural-language attribute */
3624 void *ccache
= NULL
; /* Kerberos credentials */
3628 * Parse a copy of the options string, which is of the form:
3630 * argument+argument+argument
3631 * ?argument+argument+argument
3632 * param=value¶m=value
3633 * ?param=value¶m=value
3634 * /name?argument+argument+argument
3635 * /name?param=value¶m=value
3637 * If the string contains an "=" character after the initial name,
3638 * then we treat it as a HTTP GET form request and make a copy of
3639 * the remaining string for the environment variable.
3641 * The string is always parsed out as command-line arguments, to
3642 * be consistent with Apache...
3645 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3646 "[Client %d] pipe_command infile=%d, outfile=%p, "
3647 "command=\"%s\", options=\"%s\", root=%d",
3648 con
->http
.fd
, infile
, outfile
, command
,
3649 options
? options
: "(null)", root
);
3656 if (*commptr
== ' ')
3658 strlcpy(argbuf
, commptr
, sizeof(argbuf
));
3663 if (argbuf
[0] == '/')
3666 * Found some trailing path information, set PATH_INFO...
3669 if ((commptr
= strchr(argbuf
, '?')) == NULL
)
3670 commptr
= argbuf
+ strlen(argbuf
);
3674 snprintf(path_info
, sizeof(path_info
), "PATH_INFO=%s", argbuf
);
3680 path_info
[0] = '\0';
3682 if (*commptr
== ' ')
3686 if (*commptr
== '?' && con
->operation
== HTTP_GET
&& !con
->query_string
)
3689 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", commptr
);
3696 argv
[argc
++] = commptr
;
3698 for (; *commptr
&& argc
< 99; commptr
++)
3701 * Break arguments whenever we see a + or space...
3704 if (*commptr
== ' ' || *commptr
== '+')
3706 while (*commptr
== ' ' || *commptr
== '+')
3710 * If we don't have a blank string, save it as another argument...
3715 argv
[argc
] = commptr
;
3721 else if (*commptr
== '%' && isxdigit(commptr
[1] & 255) &&
3722 isxdigit(commptr
[2] & 255))
3725 * Convert the %xx notation to the individual character.
3728 if (commptr
[1] >= '0' && commptr
[1] <= '9')
3729 *commptr
= (commptr
[1] - '0') << 4;
3731 *commptr
= (tolower(commptr
[1]) - 'a' + 10) << 4;
3733 if (commptr
[2] >= '0' && commptr
[2] <= '9')
3734 *commptr
|= commptr
[2] - '0';
3736 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
3738 _cups_strcpy(commptr
+ 1, commptr
+ 3);
3741 * Check for a %00 and break if that is the case...
3753 * Setup the environment variables as needed...
3756 if (con
->username
[0])
3758 snprintf(auth_type
, sizeof(auth_type
), "AUTH_TYPE=%s",
3759 httpGetField(HTTP(con
), HTTP_FIELD_AUTHORIZATION
));
3761 if ((uriptr
= strchr(auth_type
+ 10, ' ')) != NULL
)
3765 auth_type
[0] = '\0';
3768 (attr
= ippFindAttribute(con
->request
, "attributes-natural-language",
3769 IPP_TAG_LANGUAGE
)) != NULL
)
3771 switch (strlen(attr
->values
[0].string
.text
))
3775 * This is an unknown or badly formatted language code; use
3776 * the POSIX locale...
3779 strcpy(lang
, "LANG=C");
3784 * Just the language code (ll)...
3787 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8",
3788 attr
->values
[0].string
.text
);
3793 * Language and country code (ll-cc)...
3796 snprintf(lang
, sizeof(lang
), "LANG=%c%c_%c%c.UTF8",
3797 attr
->values
[0].string
.text
[0],
3798 attr
->values
[0].string
.text
[1],
3799 toupper(attr
->values
[0].string
.text
[3] & 255),
3800 toupper(attr
->values
[0].string
.text
[4] & 255));
3804 else if (con
->language
)
3805 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8", con
->language
->language
);
3807 strcpy(lang
, "LANG=C");
3809 strcpy(remote_addr
, "REMOTE_ADDR=");
3810 httpAddrString(con
->http
.hostaddr
, remote_addr
+ 12,
3811 sizeof(remote_addr
) - 12);
3813 snprintf(remote_host
, sizeof(remote_host
), "REMOTE_HOST=%s",
3814 con
->http
.hostname
);
3816 snprintf(script_name
, sizeof(script_name
), "SCRIPT_NAME=%s", con
->uri
);
3817 if ((uriptr
= strchr(script_name
, '?')) != NULL
)
3820 snprintf(script_filename
, sizeof(script_filename
), "SCRIPT_FILENAME=%s%s",
3821 DocumentRoot
, script_name
+ 12);
3823 sprintf(server_port
, "SERVER_PORT=%d", con
->serverport
);
3825 if (con
->http
.fields
[HTTP_FIELD_HOST
][0])
3827 char *nameptr
; /* Pointer to ":port" */
3829 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
3830 con
->http
.fields
[HTTP_FIELD_HOST
]);
3831 if ((nameptr
= strrchr(server_name
, ':')) != NULL
&& !strchr(nameptr
, ']'))
3832 *nameptr
= '\0'; /* Strip trailing ":port" */
3835 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
3838 envc
= cupsdLoadEnv(envp
, (int)(sizeof(envp
) / sizeof(envp
[0])));
3841 envp
[envc
++] = auth_type
;
3843 envp
[envc
++] = lang
;
3844 envp
[envc
++] = "REDIRECT_STATUS=1";
3845 envp
[envc
++] = "GATEWAY_INTERFACE=CGI/1.1";
3846 envp
[envc
++] = server_name
;
3847 envp
[envc
++] = server_port
;
3848 envp
[envc
++] = remote_addr
;
3849 envp
[envc
++] = remote_host
;
3850 envp
[envc
++] = script_name
;
3851 envp
[envc
++] = script_filename
;
3854 envp
[envc
++] = path_info
;
3856 if (con
->username
[0])
3858 snprintf(remote_user
, sizeof(remote_user
), "REMOTE_USER=%s", con
->username
);
3860 envp
[envc
++] = remote_user
;
3863 if (con
->http
.version
== HTTP_1_1
)
3864 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.1";
3865 else if (con
->http
.version
== HTTP_1_0
)
3866 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.0";
3868 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/0.9";
3870 if (con
->http
.cookie
)
3872 snprintf(http_cookie
, sizeof(http_cookie
), "HTTP_COOKIE=%s",
3874 envp
[envc
++] = http_cookie
;
3877 if (con
->http
.fields
[HTTP_FIELD_USER_AGENT
][0])
3879 snprintf(http_user_agent
, sizeof(http_user_agent
), "HTTP_USER_AGENT=%s",
3880 con
->http
.fields
[HTTP_FIELD_USER_AGENT
]);
3881 envp
[envc
++] = http_user_agent
;
3884 if (con
->http
.fields
[HTTP_FIELD_REFERER
][0])
3886 snprintf(http_referer
, sizeof(http_referer
), "HTTP_REFERER=%s",
3887 con
->http
.fields
[HTTP_FIELD_REFERER
]);
3888 envp
[envc
++] = http_referer
;
3891 if (con
->operation
== HTTP_GET
)
3893 envp
[envc
++] = "REQUEST_METHOD=GET";
3895 if (con
->query_string
)
3898 * Add GET form variables after ?...
3901 envp
[envc
++] = con
->query_string
;
3904 envp
[envc
++] = "QUERY_STRING=";
3908 sprintf(content_length
, "CONTENT_LENGTH=" CUPS_LLFMT
,
3909 CUPS_LLCAST con
->bytes
);
3910 snprintf(content_type
, sizeof(content_type
), "CONTENT_TYPE=%s",
3911 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
3913 envp
[envc
++] = "REQUEST_METHOD=POST";
3914 envp
[envc
++] = content_length
;
3915 envp
[envc
++] = content_type
;
3919 * Tell the CGI if we are using encryption...
3923 envp
[envc
++] = "HTTPS=ON";
3926 * Terminate the environment array...
3931 if (LogLevel
>= CUPSD_LOG_DEBUG
)
3933 for (i
= 0; i
< argc
; i
++)
3934 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3935 "[CGI] argv[%d] = \"%s\"", i
, argv
[i
]);
3936 for (i
= 0; i
< envc
; i
++)
3937 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3938 "[CGI] envp[%d] = \"%s\"", i
, envp
[i
]);
3942 * Create a pipe for the output...
3945 if (cupsdOpenPipe(fds
))
3947 cupsdLogMessage(CUPSD_LOG_ERROR
, "[CGI] Unable to create pipe for %s - %s",
3948 argv
[0], strerror(errno
));
3953 * Then execute the command...
3956 if (cupsdStartProcess(command
, argv
, envp
, infile
, fds
[1], CGIPipes
[1],
3957 -1, -1, root
, DefaultProfile
, NULL
, &pid
) < 0)
3960 * Error - can't fork!
3963 cupsdLogMessage(CUPSD_LOG_ERROR
, "[CGI] Unable to start %s - %s", argv
[0],
3966 cupsdClosePipe(fds
);
3972 * Fork successful - return the PID...
3975 if (con
->username
[0])
3976 cupsdAddCert(pid
, con
->username
, ccache
);
3978 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[CGI] Started %s (PID %d)", command
, pid
);
3989 * 'valid_host()' - Is the Host: field valid?
3992 static int /* O - 1 if valid, 0 if not */
3993 valid_host(cupsd_client_t
*con
) /* I - Client connection */
3995 cupsd_alias_t
*a
; /* Current alias */
3996 cupsd_netif_t
*netif
; /* Current network interface */
3997 const char *host
, /* Host field */
3998 *end
; /* End character */
4001 host
= con
->http
.fields
[HTTP_FIELD_HOST
];
4003 if (httpAddrLocalhost(con
->http
.hostaddr
))
4006 * Only allow "localhost" or the equivalent IPv4 or IPv6 numerical
4007 * addresses when accessing CUPS via the loopback interface...
4010 return (!_cups_strcasecmp(host
, "localhost") ||
4011 !_cups_strncasecmp(host
, "localhost:", 10) ||
4012 !_cups_strcasecmp(host
, "localhost.") ||
4013 !_cups_strncasecmp(host
, "localhost.:", 11) ||
4015 !_cups_strcasecmp(host
, "localhost.localdomain") ||
4016 !_cups_strncasecmp(host
, "localhost.localdomain:", 22) ||
4017 #endif /* __linux */
4018 !strcmp(host
, "127.0.0.1") ||
4019 !strncmp(host
, "127.0.0.1:", 10) ||
4020 !strcmp(host
, "[::1]") ||
4021 !strncmp(host
, "[::1]:", 6));
4026 * Check if the hostname is something.local (Bonjour); if so, allow it.
4029 if ((end
= strrchr(host
, '.')) != NULL
&&
4030 (!_cups_strcasecmp(end
, ".local") || !_cups_strncasecmp(end
, ".local:", 7) ||
4031 !_cups_strcasecmp(end
, ".local.") || !_cups_strncasecmp(end
, ".local.:", 8)))
4033 #endif /* HAVE_DNSSD */
4036 * Check if the hostname is an IP address...
4039 if (isdigit(*host
& 255) || *host
== '[')
4042 * Possible IPv4/IPv6 address...
4045 char temp
[1024], /* Temporary string */
4046 *ptr
; /* Pointer into temporary string */
4047 http_addrlist_t
*addrlist
; /* List of addresses */
4050 strlcpy(temp
, host
, sizeof(temp
));
4051 if ((ptr
= strrchr(temp
, ':')) != NULL
&& !strchr(ptr
, ']'))
4052 *ptr
= '\0'; /* Strip :port from host value */
4054 if ((addrlist
= httpAddrGetList(temp
, AF_UNSPEC
, NULL
)) != NULL
)
4057 * Good IPv4/IPv6 address...
4060 httpAddrFreeList(addrlist
);
4066 * Check for (alias) name matches...
4069 for (a
= (cupsd_alias_t
*)cupsArrayFirst(ServerAlias
);
4071 a
= (cupsd_alias_t
*)cupsArrayNext(ServerAlias
))
4074 * "ServerAlias *" allows all host values through...
4077 if (!strcmp(a
->name
, "*"))
4080 if (!_cups_strncasecmp(host
, a
->name
, a
->namelen
))
4083 * Prefix matches; check the character at the end - it must be ":", ".",
4087 end
= host
+ a
->namelen
;
4089 if (!*end
|| *end
== ':' || (*end
== '.' && (!end
[1] || end
[1] == ':')))
4095 for (a
= (cupsd_alias_t
*)cupsArrayFirst(DNSSDAlias
);
4097 a
= (cupsd_alias_t
*)cupsArrayNext(DNSSDAlias
))
4100 * "ServerAlias *" allows all host values through...
4103 if (!strcmp(a
->name
, "*"))
4106 if (!_cups_strncasecmp(host
, a
->name
, a
->namelen
))
4109 * Prefix matches; check the character at the end - it must be ":", ".",
4113 end
= host
+ a
->namelen
;
4115 if (!*end
|| *end
== ':' || (*end
== '.' && (!end
[1] || end
[1] == ':')))
4119 #endif /* HAVE_DNSSD */
4122 * Check for interface hostname matches...
4125 for (netif
= (cupsd_netif_t
*)cupsArrayFirst(NetIFList
);
4127 netif
= (cupsd_netif_t
*)cupsArrayNext(NetIFList
))
4129 if (!_cups_strncasecmp(host
, netif
->hostname
, netif
->hostlen
))
4132 * Prefix matches; check the character at the end - it must be ":", ".",
4136 end
= host
+ netif
->hostlen
;
4138 if (!*end
|| *end
== ':' || (*end
== '.' && (!end
[1] || end
[1] == ':')))
4148 * 'write_file()' - Send a file via HTTP.
4151 static int /* O - 0 on failure, 1 on success */
4152 write_file(cupsd_client_t
*con
, /* I - Client connection */
4153 http_status_t code
, /* I - HTTP status */
4154 char *filename
, /* I - Filename */
4155 char *type
, /* I - File type */
4156 struct stat
*filestats
) /* O - File information */
4158 con
->file
= open(filename
, O_RDONLY
);
4160 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4161 "[Client %d] write_file code=%d, filename=\"%s\" (%d), "
4162 "type=\"%s\", filestats=%p", con
->http
.fd
,
4163 code
, filename
, con
->file
, type
? type
: "(null)", filestats
);
4168 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
4172 if (!cupsdSendHeader(con
, code
, type
, CUPSD_AUTH_NONE
))
4175 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
4176 httpGetDateString(filestats
->st_mtime
)) < 0)
4178 if (httpPrintf(HTTP(con
), "Content-Length: " CUPS_LLFMT
"\r\n",
4179 CUPS_LLCAST filestats
->st_size
) < 0)
4181 if (httpPrintf(HTTP(con
), "\r\n") < 0)
4184 if (cupsdFlushHeader(con
) < 0)
4187 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
4188 con
->http
.data_remaining
= filestats
->st_size
;
4190 if (con
->http
.data_remaining
<= INT_MAX
)
4191 con
->http
._data_remaining
= con
->http
.data_remaining
;
4193 con
->http
._data_remaining
= INT_MAX
;
4195 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
,
4196 (cupsd_selfunc_t
)cupsdWriteClient
, con
);
4203 * 'write_pipe()' - Flag that data is available on the CGI pipe.
4207 write_pipe(cupsd_client_t
*con
) /* I - Client connection */
4209 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4210 "[Client %d] write_pipe CGI output on fd %d",
4211 con
->http
.fd
, con
->file
);
4213 con
->file_ready
= 1;
4215 cupsdRemoveSelect(con
->file
);
4216 cupsdAddSelect(con
->http
.fd
, NULL
, (cupsd_selfunc_t
)cupsdWriteClient
, con
);
4221 * End of "$Id: client.c 7950 2008-09-17 00:21:59Z mike $".