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
)
2583 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
+ 1],
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
+ 1]);
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_cupsd_conf()' - Install a configuration file.
3307 static http_status_t
/* O - Status */
3308 install_cupsd_conf(cupsd_client_t
*con
) /* I - Connection */
3310 char filename
[1024]; /* Configuration filename */
3311 cups_file_t
*in
, /* Input file */
3312 *out
; /* Output file */
3313 char buffer
[16384]; /* Copy buffer */
3314 ssize_t bytes
; /* Number of bytes */
3318 * Open the request file...
3321 if ((in
= cupsFileOpen(con
->filename
, "rb")) == NULL
)
3323 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open request file \"%s\": %s",
3324 con
->filename
, strerror(errno
));
3325 return (HTTP_SERVER_ERROR
);
3329 * Open the new config file...
3332 snprintf(filename
, sizeof(filename
), "%s/cupsd.conf", ServerRoot
);
3333 if ((out
= cupsdCreateConfFile(filename
, ConfigFilePerm
)) == NULL
)
3336 return (HTTP_SERVER_ERROR
);
3339 cupsdLogMessage(CUPSD_LOG_INFO
, "Installing config file \"%s\"...", filename
);
3342 * Copy from the request to the new config file...
3345 while ((bytes
= cupsFileRead(in
, buffer
, sizeof(buffer
))) > 0)
3346 if (cupsFileWrite(out
, buffer
, bytes
) < bytes
)
3348 cupsdLogMessage(CUPSD_LOG_ERROR
,
3349 "Unable to copy to config file \"%s\": %s",
3350 filename
, strerror(errno
));
3355 snprintf(filename
, sizeof(filename
), "%s%s.N", ServerRoot
, con
->uri
+ 11);
3356 cupsdRemoveFile(filename
);
3358 return (HTTP_SERVER_ERROR
);
3362 * Close the files...
3367 if (cupsdCloseCreatedConfFile(out
, filename
))
3368 return (HTTP_SERVER_ERROR
);
3371 * Remove the request file...
3374 cupsdRemoveFile(con
->filename
);
3375 cupsdClearString(&con
->filename
);
3378 * Set the NeedReload flag...
3381 NeedReload
= RELOAD_CUPSD
;
3382 ReloadTime
= time(NULL
);
3385 * Return that the file was created successfully...
3388 return (HTTP_CREATED
);
3393 * 'is_cgi()' - Is the resource a CGI script/program?
3396 static int /* O - 1 = CGI, 0 = file */
3397 is_cgi(cupsd_client_t
*con
, /* I - Client connection */
3398 const char *filename
, /* I - Real filename */
3399 struct stat
*filestats
, /* I - File information */
3400 mime_type_t
*type
) /* I - MIME type */
3402 const char *options
; /* Options on URL */
3406 * Get the options, if any...
3409 if ((options
= strchr(con
->uri
, '?')) != NULL
)
3412 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", options
);
3416 * Check for known types...
3419 if (!type
|| _cups_strcasecmp(type
->super
, "application"))
3421 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3422 "[Client %d] is_cgi filename=\"%s\", filestats=%p, "
3423 "type=%s/%s, returning 0", con
->http
.fd
, filename
,
3424 filestats
, type
? type
->super
: "unknown",
3425 type
? type
->type
: "unknown");
3429 if (!_cups_strcasecmp(type
->type
, "x-httpd-cgi") &&
3430 (filestats
->st_mode
& 0111))
3433 * "application/x-httpd-cgi" is a CGI script.
3436 cupsdSetString(&con
->command
, filename
);
3439 cupsdSetStringf(&con
->options
, " %s", options
);
3441 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3442 "[Client %d] is_cgi filename=\"%s\", filestats=%p, "
3443 "type=%s/%s, returning 1", con
->http
.fd
, filename
,
3444 filestats
, type
->super
, type
->type
);
3448 else if (!_cups_strcasecmp(type
->type
, "x-httpd-java"))
3451 * "application/x-httpd-java" is a Java servlet.
3454 cupsdSetString(&con
->command
, CUPS_JAVA
);
3457 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3459 cupsdSetStringf(&con
->options
, " %s", filename
);
3461 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3462 "[Client %d] is_cgi filename=\"%s\", filestats=%p, "
3463 "type=%s/%s, returning 1", con
->http
.fd
, filename
,
3464 filestats
, type
->super
, type
->type
);
3467 #endif /* HAVE_JAVA */
3469 else if (!_cups_strcasecmp(type
->type
, "x-httpd-perl"))
3472 * "application/x-httpd-perl" is a Perl page.
3475 cupsdSetString(&con
->command
, CUPS_PERL
);
3478 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3480 cupsdSetStringf(&con
->options
, " %s", filename
);
3482 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3483 "[Client %d] is_cgi filename=\"%s\", filestats=%p, "
3484 "type=%s/%s, returning 1", con
->http
.fd
, filename
,
3485 filestats
, type
->super
, type
->type
);
3488 #endif /* HAVE_PERL */
3490 else if (!_cups_strcasecmp(type
->type
, "x-httpd-php"))
3493 * "application/x-httpd-php" is a PHP page.
3496 cupsdSetString(&con
->command
, CUPS_PHP
);
3499 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3501 cupsdSetStringf(&con
->options
, " %s", filename
);
3503 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3504 "[Client %d] is_cgi filename=\"%s\", filestats=%p, "
3505 "type=%s/%s, returning 1", con
->http
.fd
, filename
,
3506 filestats
, type
->super
, type
->type
);
3509 #endif /* HAVE_PHP */
3511 else if (!_cups_strcasecmp(type
->type
, "x-httpd-python"))
3514 * "application/x-httpd-python" is a Python page.
3517 cupsdSetString(&con
->command
, CUPS_PYTHON
);
3520 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3522 cupsdSetStringf(&con
->options
, " %s", filename
);
3524 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3525 "[Client %d] is_cgi filename=\"%s\", filestats=%p, "
3526 "type=%s/%s, returning 1", con
->http
.fd
, filename
,
3527 filestats
, type
->super
, type
->type
);
3530 #endif /* HAVE_PYTHON */
3532 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3533 "[Client %d] is_cgi filename=\"%s\", filestats=%p, "
3534 "type=%s/%s, returning 0", con
->http
.fd
, filename
,
3535 filestats
, type
->super
, type
->type
);
3541 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
3544 static int /* O - 0 if relative, 1 if absolute */
3545 is_path_absolute(const char *path
) /* I - Input path */
3548 * Check for a leading slash...
3555 * Check for "/.." in the path...
3558 while ((path
= strstr(path
, "/..")) != NULL
)
3560 if (!path
[3] || path
[3] == '/')
3567 * If we haven't found any relative paths, return 1 indicating an
3576 * 'pipe_command()' - Pipe the output of a command to the remote client.
3579 static int /* O - Process ID */
3580 pipe_command(cupsd_client_t
*con
, /* I - Client connection */
3581 int infile
, /* I - Standard input for command */
3582 int *outfile
, /* O - Standard output for command */
3583 char *command
, /* I - Command to run */
3584 char *options
, /* I - Options for command */
3585 int root
) /* I - Run as root? */
3587 int i
; /* Looping var */
3588 int pid
; /* Process ID */
3589 char *commptr
, /* Command string pointer */
3590 commch
; /* Command string character */
3591 char *uriptr
; /* URI string pointer */
3592 int fds
[2]; /* Pipe FDs */
3593 int argc
; /* Number of arguments */
3594 int envc
; /* Number of environment variables */
3595 char argbuf
[10240], /* Argument buffer */
3596 *argv
[100], /* Argument strings */
3597 *envp
[MAX_ENV
+ 20]; /* Environment variables */
3598 char auth_type
[256], /* AUTH_TYPE environment variable */
3599 content_length
[1024], /* CONTENT_LENGTH environment variable */
3600 content_type
[1024], /* CONTENT_TYPE environment variable */
3601 http_cookie
[32768], /* HTTP_COOKIE environment variable */
3602 http_referer
[1024], /* HTTP_REFERER environment variable */
3603 http_user_agent
[1024], /* HTTP_USER_AGENT environment variable */
3604 lang
[1024], /* LANG environment variable */
3605 path_info
[1024], /* PATH_INFO environment variable */
3606 remote_addr
[1024], /* REMOTE_ADDR environment variable */
3607 remote_host
[1024], /* REMOTE_HOST environment variable */
3608 remote_user
[1024], /* REMOTE_USER environment variable */
3609 script_filename
[1024], /* SCRIPT_FILENAME environment variable */
3610 script_name
[1024], /* SCRIPT_NAME environment variable */
3611 server_name
[1024], /* SERVER_NAME environment variable */
3612 server_port
[1024]; /* SERVER_PORT environment variable */
3613 ipp_attribute_t
*attr
; /* attributes-natural-language attribute */
3617 * Parse a copy of the options string, which is of the form:
3619 * argument+argument+argument
3620 * ?argument+argument+argument
3621 * param=value¶m=value
3622 * ?param=value¶m=value
3623 * /name?argument+argument+argument
3624 * /name?param=value¶m=value
3626 * If the string contains an "=" character after the initial name,
3627 * then we treat it as a HTTP GET form request and make a copy of
3628 * the remaining string for the environment variable.
3630 * The string is always parsed out as command-line arguments, to
3631 * be consistent with Apache...
3634 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3635 "[Client %d] pipe_command infile=%d, outfile=%p, "
3636 "command=\"%s\", options=\"%s\", root=%d",
3637 con
->http
.fd
, infile
, outfile
, command
,
3638 options
? options
: "(null)", root
);
3645 if (*commptr
== ' ')
3647 strlcpy(argbuf
, commptr
, sizeof(argbuf
));
3652 if (argbuf
[0] == '/')
3655 * Found some trailing path information, set PATH_INFO...
3658 if ((commptr
= strchr(argbuf
, '?')) == NULL
)
3659 commptr
= argbuf
+ strlen(argbuf
);
3663 snprintf(path_info
, sizeof(path_info
), "PATH_INFO=%s", argbuf
);
3669 path_info
[0] = '\0';
3671 if (*commptr
== ' ')
3675 if (*commptr
== '?' && con
->operation
== HTTP_GET
&& !con
->query_string
)
3678 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", commptr
);
3685 argv
[argc
++] = commptr
;
3687 for (; *commptr
&& argc
< 99; commptr
++)
3690 * Break arguments whenever we see a + or space...
3693 if (*commptr
== ' ' || *commptr
== '+')
3695 while (*commptr
== ' ' || *commptr
== '+')
3699 * If we don't have a blank string, save it as another argument...
3704 argv
[argc
] = commptr
;
3710 else if (*commptr
== '%' && isxdigit(commptr
[1] & 255) &&
3711 isxdigit(commptr
[2] & 255))
3714 * Convert the %xx notation to the individual character.
3717 if (commptr
[1] >= '0' && commptr
[1] <= '9')
3718 *commptr
= (commptr
[1] - '0') << 4;
3720 *commptr
= (tolower(commptr
[1]) - 'a' + 10) << 4;
3722 if (commptr
[2] >= '0' && commptr
[2] <= '9')
3723 *commptr
|= commptr
[2] - '0';
3725 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
3727 _cups_strcpy(commptr
+ 1, commptr
+ 3);
3730 * Check for a %00 and break if that is the case...
3742 * Setup the environment variables as needed...
3745 if (con
->username
[0])
3747 snprintf(auth_type
, sizeof(auth_type
), "AUTH_TYPE=%s",
3748 httpGetField(HTTP(con
), HTTP_FIELD_AUTHORIZATION
));
3750 if ((uriptr
= strchr(auth_type
+ 10, ' ')) != NULL
)
3754 auth_type
[0] = '\0';
3757 (attr
= ippFindAttribute(con
->request
, "attributes-natural-language",
3758 IPP_TAG_LANGUAGE
)) != NULL
)
3760 switch (strlen(attr
->values
[0].string
.text
))
3764 * This is an unknown or badly formatted language code; use
3765 * the POSIX locale...
3768 strlcpy(lang
, "LANG=C", sizeof(lang
));
3773 * Just the language code (ll)...
3776 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8",
3777 attr
->values
[0].string
.text
);
3782 * Language and country code (ll-cc)...
3785 snprintf(lang
, sizeof(lang
), "LANG=%c%c_%c%c.UTF8",
3786 attr
->values
[0].string
.text
[0],
3787 attr
->values
[0].string
.text
[1],
3788 toupper(attr
->values
[0].string
.text
[3] & 255),
3789 toupper(attr
->values
[0].string
.text
[4] & 255));
3793 else if (con
->language
)
3794 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8", con
->language
->language
);
3796 strlcpy(lang
, "LANG=C", sizeof(lang
));
3798 strlcpy(remote_addr
, "REMOTE_ADDR=", sizeof(remote_addr
));
3799 httpAddrString(con
->http
.hostaddr
, remote_addr
+ 12,
3800 sizeof(remote_addr
) - 12);
3802 snprintf(remote_host
, sizeof(remote_host
), "REMOTE_HOST=%s",
3803 con
->http
.hostname
);
3805 snprintf(script_name
, sizeof(script_name
), "SCRIPT_NAME=%s", con
->uri
);
3806 if ((uriptr
= strchr(script_name
, '?')) != NULL
)
3809 snprintf(script_filename
, sizeof(script_filename
), "SCRIPT_FILENAME=%s%s",
3810 DocumentRoot
, script_name
+ 12);
3812 sprintf(server_port
, "SERVER_PORT=%d", con
->serverport
);
3814 if (con
->http
.fields
[HTTP_FIELD_HOST
][0])
3816 char *nameptr
; /* Pointer to ":port" */
3818 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
3819 con
->http
.fields
[HTTP_FIELD_HOST
]);
3820 if ((nameptr
= strrchr(server_name
, ':')) != NULL
&& !strchr(nameptr
, ']'))
3821 *nameptr
= '\0'; /* Strip trailing ":port" */
3824 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
3827 envc
= cupsdLoadEnv(envp
, (int)(sizeof(envp
) / sizeof(envp
[0])));
3830 envp
[envc
++] = auth_type
;
3832 envp
[envc
++] = lang
;
3833 envp
[envc
++] = "REDIRECT_STATUS=1";
3834 envp
[envc
++] = "GATEWAY_INTERFACE=CGI/1.1";
3835 envp
[envc
++] = server_name
;
3836 envp
[envc
++] = server_port
;
3837 envp
[envc
++] = remote_addr
;
3838 envp
[envc
++] = remote_host
;
3839 envp
[envc
++] = script_name
;
3840 envp
[envc
++] = script_filename
;
3843 envp
[envc
++] = path_info
;
3845 if (con
->username
[0])
3847 snprintf(remote_user
, sizeof(remote_user
), "REMOTE_USER=%s", con
->username
);
3849 envp
[envc
++] = remote_user
;
3852 if (con
->http
.version
== HTTP_1_1
)
3853 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.1";
3854 else if (con
->http
.version
== HTTP_1_0
)
3855 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.0";
3857 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/0.9";
3859 if (con
->http
.cookie
)
3861 snprintf(http_cookie
, sizeof(http_cookie
), "HTTP_COOKIE=%s",
3863 envp
[envc
++] = http_cookie
;
3866 if (con
->http
.fields
[HTTP_FIELD_USER_AGENT
][0])
3868 snprintf(http_user_agent
, sizeof(http_user_agent
), "HTTP_USER_AGENT=%s",
3869 con
->http
.fields
[HTTP_FIELD_USER_AGENT
]);
3870 envp
[envc
++] = http_user_agent
;
3873 if (con
->http
.fields
[HTTP_FIELD_REFERER
][0])
3875 snprintf(http_referer
, sizeof(http_referer
), "HTTP_REFERER=%s",
3876 con
->http
.fields
[HTTP_FIELD_REFERER
]);
3877 envp
[envc
++] = http_referer
;
3880 if (con
->operation
== HTTP_GET
)
3882 envp
[envc
++] = "REQUEST_METHOD=GET";
3884 if (con
->query_string
)
3887 * Add GET form variables after ?...
3890 envp
[envc
++] = con
->query_string
;
3893 envp
[envc
++] = "QUERY_STRING=";
3897 sprintf(content_length
, "CONTENT_LENGTH=" CUPS_LLFMT
,
3898 CUPS_LLCAST con
->bytes
);
3899 snprintf(content_type
, sizeof(content_type
), "CONTENT_TYPE=%s",
3900 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
3902 envp
[envc
++] = "REQUEST_METHOD=POST";
3903 envp
[envc
++] = content_length
;
3904 envp
[envc
++] = content_type
;
3908 * Tell the CGI if we are using encryption...
3912 envp
[envc
++] = "HTTPS=ON";
3915 * Terminate the environment array...
3920 if (LogLevel
>= CUPSD_LOG_DEBUG
)
3922 for (i
= 0; i
< argc
; i
++)
3923 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3924 "[CGI] argv[%d] = \"%s\"", i
, argv
[i
]);
3925 for (i
= 0; i
< envc
; i
++)
3926 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3927 "[CGI] envp[%d] = \"%s\"", i
, envp
[i
]);
3931 * Create a pipe for the output...
3934 if (cupsdOpenPipe(fds
))
3936 cupsdLogMessage(CUPSD_LOG_ERROR
, "[CGI] Unable to create pipe for %s - %s",
3937 argv
[0], strerror(errno
));
3942 * Then execute the command...
3945 if (cupsdStartProcess(command
, argv
, envp
, infile
, fds
[1], CGIPipes
[1],
3946 -1, -1, root
, DefaultProfile
, NULL
, &pid
) < 0)
3949 * Error - can't fork!
3952 cupsdLogMessage(CUPSD_LOG_ERROR
, "[CGI] Unable to start %s - %s", argv
[0],
3955 cupsdClosePipe(fds
);
3961 * Fork successful - return the PID...
3964 if (con
->username
[0])
3965 cupsdAddCert(pid
, con
->username
, con
->type
);
3967 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[CGI] Started %s (PID %d)", command
, pid
);
3978 * 'valid_host()' - Is the Host: field valid?
3981 static int /* O - 1 if valid, 0 if not */
3982 valid_host(cupsd_client_t
*con
) /* I - Client connection */
3984 cupsd_alias_t
*a
; /* Current alias */
3985 cupsd_netif_t
*netif
; /* Current network interface */
3986 const char *host
, /* Host field */
3987 *end
; /* End character */
3990 host
= con
->http
.fields
[HTTP_FIELD_HOST
];
3992 if (httpAddrLocalhost(con
->http
.hostaddr
))
3995 * Only allow "localhost" or the equivalent IPv4 or IPv6 numerical
3996 * addresses when accessing CUPS via the loopback interface...
3999 return (!_cups_strcasecmp(host
, "localhost") ||
4000 !_cups_strncasecmp(host
, "localhost:", 10) ||
4001 !_cups_strcasecmp(host
, "localhost.") ||
4002 !_cups_strncasecmp(host
, "localhost.:", 11) ||
4004 !_cups_strcasecmp(host
, "localhost.localdomain") ||
4005 !_cups_strncasecmp(host
, "localhost.localdomain:", 22) ||
4006 #endif /* __linux */
4007 !strcmp(host
, "127.0.0.1") ||
4008 !strncmp(host
, "127.0.0.1:", 10) ||
4009 !strcmp(host
, "[::1]") ||
4010 !strncmp(host
, "[::1]:", 6));
4013 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
4015 * Check if the hostname is something.local (Bonjour); if so, allow it.
4018 if ((end
= strrchr(host
, '.')) != NULL
&& end
> host
&&
4019 (!end
[1] || end
[1] == ':'))
4022 * "." on end, work back to second-to-last "."...
4024 for (end
--; end
> host
&& *end
!= '.'; end
--);
4027 if (end
&& (!_cups_strcasecmp(end
, ".local") ||
4028 !_cups_strncasecmp(end
, ".local:", 7) ||
4029 !_cups_strcasecmp(end
, ".local.") ||
4030 !_cups_strncasecmp(end
, ".local.:", 8)))
4032 #endif /* HAVE_DNSSD || HAVE_AVAHI */
4035 * Check if the hostname is an IP address...
4038 if (isdigit(*host
& 255) || *host
== '[')
4041 * Possible IPv4/IPv6 address...
4044 char temp
[1024], /* Temporary string */
4045 *ptr
; /* Pointer into temporary string */
4046 http_addrlist_t
*addrlist
; /* List of addresses */
4049 strlcpy(temp
, host
, sizeof(temp
));
4050 if ((ptr
= strrchr(temp
, ':')) != NULL
&& !strchr(ptr
, ']'))
4051 *ptr
= '\0'; /* Strip :port from host value */
4053 if ((addrlist
= httpAddrGetList(temp
, AF_UNSPEC
, NULL
)) != NULL
)
4056 * Good IPv4/IPv6 address...
4059 httpAddrFreeList(addrlist
);
4065 * Check for (alias) name matches...
4068 for (a
= (cupsd_alias_t
*)cupsArrayFirst(ServerAlias
);
4070 a
= (cupsd_alias_t
*)cupsArrayNext(ServerAlias
))
4073 * "ServerAlias *" allows all host values through...
4076 if (!strcmp(a
->name
, "*"))
4079 if (!_cups_strncasecmp(host
, a
->name
, a
->namelen
))
4082 * Prefix matches; check the character at the end - it must be ":", ".",
4086 end
= host
+ a
->namelen
;
4088 if (!*end
|| *end
== ':' || (*end
== '.' && (!end
[1] || end
[1] == ':')))
4093 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
4094 for (a
= (cupsd_alias_t
*)cupsArrayFirst(DNSSDAlias
);
4096 a
= (cupsd_alias_t
*)cupsArrayNext(DNSSDAlias
))
4099 * "ServerAlias *" allows all host values through...
4102 if (!strcmp(a
->name
, "*"))
4105 if (!_cups_strncasecmp(host
, a
->name
, a
->namelen
))
4108 * Prefix matches; check the character at the end - it must be ":", ".",
4112 end
= host
+ a
->namelen
;
4114 if (!*end
|| *end
== ':' || (*end
== '.' && (!end
[1] || end
[1] == ':')))
4118 #endif /* HAVE_DNSSD || HAVE_AVAHI */
4121 * Check for interface hostname matches...
4124 for (netif
= (cupsd_netif_t
*)cupsArrayFirst(NetIFList
);
4126 netif
= (cupsd_netif_t
*)cupsArrayNext(NetIFList
))
4128 if (!_cups_strncasecmp(host
, netif
->hostname
, netif
->hostlen
))
4131 * Prefix matches; check the character at the end - it must be ":", ".",
4135 end
= host
+ netif
->hostlen
;
4137 if (!*end
|| *end
== ':' || (*end
== '.' && (!end
[1] || end
[1] == ':')))
4147 * 'write_file()' - Send a file via HTTP.
4150 static int /* O - 0 on failure, 1 on success */
4151 write_file(cupsd_client_t
*con
, /* I - Client connection */
4152 http_status_t code
, /* I - HTTP status */
4153 char *filename
, /* I - Filename */
4154 char *type
, /* I - File type */
4155 struct stat
*filestats
) /* O - File information */
4157 con
->file
= open(filename
, O_RDONLY
);
4159 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4160 "[Client %d] write_file code=%d, filename=\"%s\" (%d), "
4161 "type=\"%s\", filestats=%p", con
->http
.fd
,
4162 code
, filename
, con
->file
, type
? type
: "(null)", filestats
);
4167 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
4171 if (!cupsdSendHeader(con
, code
, type
, CUPSD_AUTH_NONE
))
4174 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
4175 httpGetDateString(filestats
->st_mtime
)) < 0)
4177 if (httpPrintf(HTTP(con
), "Content-Length: " CUPS_LLFMT
"\r\n",
4178 CUPS_LLCAST filestats
->st_size
) < 0)
4180 if (httpPrintf(HTTP(con
), "\r\n") < 0)
4183 if (cupsdFlushHeader(con
) < 0)
4186 con
->http
.data_encoding
= HTTP_ENCODE_LENGTH
;
4187 con
->http
.data_remaining
= filestats
->st_size
;
4189 if (con
->http
.data_remaining
<= INT_MAX
)
4190 con
->http
._data_remaining
= con
->http
.data_remaining
;
4192 con
->http
._data_remaining
= INT_MAX
;
4194 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
,
4195 (cupsd_selfunc_t
)cupsdWriteClient
, con
);
4202 * 'write_pipe()' - Flag that data is available on the CGI pipe.
4206 write_pipe(cupsd_client_t
*con
) /* I - Client connection */
4208 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4209 "[Client %d] write_pipe CGI output on fd %d",
4210 con
->http
.fd
, con
->file
);
4212 con
->file_ready
= 1;
4214 cupsdRemoveSelect(con
->file
);
4215 cupsdAddSelect(con
->http
.fd
, NULL
, (cupsd_selfunc_t
)cupsdWriteClient
, con
);
4220 * End of "$Id: client.c 7950 2008-09-17 00:21:59Z mike $".