4 * Client routines for the CUPS scheduler.
6 * Copyright 2007-2013 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 /* __APPLE__ */
57 #endif /* HAVE_TCPD_H */
64 static const char * const http_states
[] =
65 { /* HTTP state strings */
70 "HTTP_STATE_GET_SEND",
73 "HTTP_STATE_POST_RECV",
74 "HTTP_STATE_POST_SEND",
76 "HTTP_STATE_PUT_RECV",
81 "HTTP_STATE_UNKNOWN_METHOD",
82 "HTTP_STATE_UNKNOWN_VERSION"
84 static const char * const ipp_states
[] =
85 { /* IPP state strings */
97 static int check_if_modified(cupsd_client_t
*con
,
98 struct stat
*filestats
);
99 static int compare_clients(cupsd_client_t
*a
, cupsd_client_t
*b
,
101 static int data_ready(cupsd_client_t
*con
);
102 static char *get_file(cupsd_client_t
*con
, struct stat
*filestats
,
103 char *filename
, int len
);
104 static http_status_t
install_cupsd_conf(cupsd_client_t
*con
);
105 static int is_cgi(cupsd_client_t
*con
, const char *filename
,
106 struct stat
*filestats
, mime_type_t
*type
);
107 static int is_path_absolute(const char *path
);
108 static int pipe_command(cupsd_client_t
*con
, int infile
, int *outfile
,
109 char *command
, char *options
, int root
);
110 static int valid_host(cupsd_client_t
*con
);
111 static int write_file(cupsd_client_t
*con
, http_status_t code
,
112 char *filename
, char *type
,
113 struct stat
*filestats
);
114 static void write_pipe(cupsd_client_t
*con
);
118 * 'cupsdAcceptClient()' - Accept a new client.
122 cupsdAcceptClient(cupsd_listener_t
*lis
)/* I - Listener socket */
124 char name
[256]; /* Hostname of client */
125 int count
; /* Count of connections on a host */
126 // int val; /* Parameter value */
127 cupsd_client_t
*con
, /* New client pointer */
128 *tempcon
; /* Temporary client pointer */
129 // http_addrlist_t *addrlist, /* List of adddresses for host */
130 // *addr; /* Current address */
131 socklen_t addrlen
; /* Length of address */
132 // char *hostname; /* Hostname for address */
133 http_addr_t temp
; /* Temporary address variable */
134 static time_t last_dos
= 0; /* Time of last DoS attack */
136 struct request_info wrap_req
; /* TCP wrappers request information */
137 #endif /* HAVE_TCPD_H */
140 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
141 "cupsdAcceptClient(lis=%p(%d)) Clients=%d",
142 lis
, lis
->fd
, cupsArrayCount(Clients
));
145 * Make sure we don't have a full set of clients already...
148 if (cupsArrayCount(Clients
) == MaxClients
)
152 * Get a pointer to the next available client...
156 Clients
= cupsArrayNew(NULL
, NULL
);
160 cupsdLogMessage(CUPSD_LOG_ERROR
,
161 "Unable to allocate memory for clients array!");
162 cupsdPauseListening();
167 ActiveClients
= cupsArrayNew((cups_array_func_t
)compare_clients
, NULL
);
171 cupsdLogMessage(CUPSD_LOG_ERROR
,
172 "Unable to allocate memory for active clients array!");
173 cupsdPauseListening();
177 if ((con
= calloc(1, sizeof(cupsd_client_t
))) == NULL
)
179 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to allocate memory for client!");
180 cupsdPauseListening();
185 * Accept the client and get the remote address...
188 con
->number
= ++ LastClientNumber
;
190 // con->http->activity = time(NULL);
191 // con->http->hostaddr = &(con->clientaddr);
192 // con->http->wait_value = 10000;
193 // con->http->mode = _HTTP_MODE_SERVER;
195 if ((con
->http
= httpAcceptConnection(lis
->fd
, 0)) == NULL
)
197 if (errno
== ENFILE
|| errno
== EMFILE
)
198 cupsdPauseListening();
200 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to accept client connection - %s.",
208 * Save the connected address and port number...
211 con
->clientaddr
= lis
->address
;
213 #if 0 /* ifdef AF_INET6 */
214 /* FIXME: I don't believe this is recommended any longer, and we specifically
215 * disable IPv4-over-IPv6 when we listen...
218 * Convert IPv4 over IPv6 addresses (::ffff:n.n.n.n) to IPv4 forms we
219 * can more easily use...
222 if (lis
->address
.addr
.sa_family
== AF_INET6
&&
223 con
->http
->hostaddr
->ipv6
.sin6_addr
.s6_addr32
[0] == 0 &&
224 con
->http
->hostaddr
->ipv6
.sin6_addr
.s6_addr32
[1] == 0 &&
225 ntohl(con
->http
->hostaddr
->ipv6
.sin6_addr
.s6_addr32
[2]) == 0xffff)
226 con
->http
->hostaddr
->ipv6
.sin6_addr
.s6_addr32
[2] = 0;
227 #endif /* AF_INET6 */
230 * Check the number of clients on the same address...
233 for (count
= 0, tempcon
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
235 tempcon
= (cupsd_client_t
*)cupsArrayNext(Clients
))
236 if (httpAddrEqual(httpGetAddress(tempcon
->http
), httpGetAddress(con
->http
)))
239 if (count
>= MaxClientsPerHost
)
243 if (count
>= MaxClientsPerHost
)
245 if ((time(NULL
) - last_dos
) >= 60)
247 last_dos
= time(NULL
);
248 cupsdLogMessage(CUPSD_LOG_WARN
,
249 "Possible DoS attack - more than %d clients connecting "
252 httpGetHostname(con
->http
, name
, sizeof(name
)));
255 httpClose(con
->http
);
260 #if 0 /* Decide if we keep this, and where to store the name */
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...
297 httpClose(con
->http
);
299 cupsdLogClient(con
, CUPSD_LOG_WARN
,
300 "Name lookup failed - connection from %s closed!",
301 con
->http
->hostname
);
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...
336 httpClose(con
->http
);
338 cupsdLogClient(con
, CUPSD_LOG_WARN
,
339 "IP lookup failed - connection from %s closed!",
340 con
->http
->hostname
);
349 * See if the connection is denied by TCP wrappers...
352 request_init(&wrap_req
, RQ_DAEMON
, "cupsd", RQ_FILE
, httpGetFd(con
->http
),
356 if (!hosts_access(&wrap_req
))
358 httpClose(con
->http
);
360 cupsdLogClient(con
, CUPSD_LOG_WARN
,
361 "Connection from %s refused by /etc/hosts.allow and "
362 "/etc/hosts.deny rules.", con
->http
->hostname
);
366 #endif /* HAVE_TCPD_H */
369 if (httpGetAddress(con
->http
)->addr
.sa_family
== AF_LOCAL
)
372 socklen_t peersize
; /* Size of peer credentials */
373 pid_t peerpid
; /* Peer process ID */
374 char peername
[256]; /* Name of process */
376 peersize
= sizeof(peerpid
);
377 if (!getsockopt(con
->number
, SOL_LOCAL
, LOCAL_PEERPID
, &peerpid
,
380 if (!proc_name(peerpid
, peername
, sizeof(peername
)))
381 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
382 "Accepted from %s (Domain ???[%d])",
383 con
->http
->hostname
, (int)peerpid
);
385 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
386 "Accepted from %s (Domain %s[%d])",
387 con
->http
->hostname
, name
, (int)peerpid
);
390 # endif /* __APPLE__ */
392 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Accepted from %s (Domain)",
393 con
->http
->hostname
);
396 #endif /* AF_LOCAL */
397 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Accepted from %s:%d (IPv%d)",
398 con
->http
->hostname
, httpAddrPort(con
->http
->hostaddr
),
399 _httpAddrFamily(con
->http
->hostaddr
) == AF_INET
? 4 : 6);
402 * Get the local address the client connected to...
405 addrlen
= sizeof(temp
);
406 if (getsockname(httpGetFd(con
->http
), (struct sockaddr
*)&temp
, &addrlen
))
408 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Unable to get local address - %s",
411 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
412 con
->serverport
= LocalPort
;
415 else if (_httpAddrFamily(&temp
) == AF_LOCAL
)
417 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
418 con
->serverport
= LocalPort
;
420 #endif /* AF_LOCAL */
423 if (httpAddrLocalhost(&temp
))
424 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
425 else if (HostNameLookups
)
426 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
428 httpAddrString(&temp
, con
->servername
, sizeof(con
->servername
));
430 con
->serverport
= httpAddrPort(&(lis
->address
));
434 * Add the connection to the array of active clients...
437 cupsArrayAdd(Clients
, con
);
440 * Add the socket to the server select.
443 cupsdAddSelect(httpGetFd(con
->http
), (cupsd_selfunc_t
)cupsdReadClient
, NULL
,
446 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for request.");
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 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing connection.");
515 * Flush pending writes before closing...
518 httpFlushWrite(con
->http
);
524 * Shutdown encryption as needed...
533 #endif /* HAVE_SSL */
535 if (con
->pipe_pid
!= 0)
538 * Stop any CGI process...
541 cupsdEndProcess(con
->pipe_pid
, 1);
547 cupsdRemoveSelect(con
->file
);
554 * Close the socket and clear the file from the input set for select()...
557 if (httpGetFd(con
->http
) >= 0)
559 cupsArrayRemove(ActiveClients
, con
);
565 * Only do a partial close so that the encrypted client gets everything.
568 shutdown(httpGetFd(con
->http
), 0);
569 cupsdAddSelect(httpGetFd(con
->http
), (cupsd_selfunc_t
)cupsdReadClient
,
572 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for socket close.");
577 * Shut the socket down fully...
580 cupsdRemoveSelect(httpGetFd(con
->http
));
581 httpClose(con
->http
);
592 httpClose(con
->http
);
594 cupsdClearString(&con
->filename
);
595 cupsdClearString(&con
->command
);
596 cupsdClearString(&con
->options
);
597 cupsdClearString(&con
->query_string
);
601 ippDelete(con
->request
);
607 ippDelete(con
->response
);
608 con
->response
= NULL
;
613 cupsLangFree(con
->language
);
614 con
->language
= NULL
;
617 #ifdef HAVE_AUTHORIZATION_H
620 AuthorizationFree(con
->authref
, kAuthorizationFlagDefaults
);
623 #endif /* HAVE_AUTHORIZATION_H */
626 * Re-enable new client connections if we are going back under the
630 if (cupsArrayCount(Clients
) == MaxClients
)
631 cupsdResumeListening();
634 * Compact the list of clients as necessary...
637 cupsArrayRemove(Clients
, con
);
647 * 'cupsdFlushHeader()' - Flush the header fields to the client.
650 int /* I - Bytes written or -1 on error */
651 cupsdFlushHeader(cupsd_client_t
*con
) /* I - Client to flush to */
653 int bytes
= httpFlushWrite(con
->http
);
655 // TODO: Need to use httpSendResponse
656 con
->http
->data_encoding
= HTTP_ENCODING_LENGTH
;
663 * 'cupsdReadClient()' - Read data from a client.
667 cupsdReadClient(cupsd_client_t
*con
) /* I - Client to read from */
669 char line
[32768], /* Line from client... */
670 operation
[64], /* Operation code from socket */
671 version
[64], /* HTTP version number string */
672 locale
[64], /* Locale */
673 *ptr
; /* Pointer into strings */
674 int major
, minor
; /* HTTP version numbers */
675 http_status_t status
; /* Transfer status */
676 ipp_state_t ipp_state
; /* State of IPP transfer */
677 int bytes
; /* Number of bytes to POST */
678 char *filename
; /* Name of file for GET/HEAD */
679 char buf
[1024]; /* Buffer for real filename */
680 struct stat filestats
; /* File information */
681 mime_type_t
*type
; /* MIME type of file */
682 cupsd_printer_t
*p
; /* Printer */
683 static unsigned request_id
= 0; /* Request ID for temp files */
686 status
= HTTP_CONTINUE
;
688 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
693 "data_encoding=HTTP_ENCODING_%s, "
694 "data_remaining=" CUPS_LLFMT
", "
697 con
->http
->error
, con
->http
->used
,
698 http_states
[con
->http
->state
+ 1],
699 con
->http
->data_encoding
== HTTP_ENCODING_CHUNKED
?
700 "CHUNKED" : "LENGTH",
701 CUPS_LLCAST con
->http
->data_remaining
,
703 con
->request
? ipp_states
[con
->request
->state
] : "",
710 * Automatically check for a SSL/TLS handshake...
715 if (recv(httpGetFd(con
->http
), buf
, 1, MSG_PEEK
) == 1 &&
716 (!buf
[0] || !strchr("DGHOPT", buf
[0])))
719 * Encrypt this connection...
722 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
723 "Saw first byte %02X, auto-negotiating "
724 "SSL/TLS session.", buf
[0] & 255);
726 if (!cupsdStartTLS(con
))
727 cupsdCloseClient(con
);
732 #endif /* HAVE_SSL */
734 switch (con
->http
->state
)
736 case HTTP_STATE_WAITING
:
738 * See if we've received a request line...
741 if (httpGets(line
, sizeof(line
) - 1, con
->http
) == NULL
)
743 if (con
->http
->error
&& con
->http
->error
!= EPIPE
)
744 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
745 "HTTP_STATE_WAITING Closing for error %d (%s)",
746 con
->http
->error
, strerror(con
->http
->error
));
748 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
749 "HTTP_STATE_WAITING Closing on EOF.");
751 cupsdCloseClient(con
);
756 * Ignore blank request lines...
763 * Clear other state variables...
766 httpClearFields(con
->http
);
768 con
->http
->activity
= time(NULL
);
769 con
->http
->version
= HTTP_1_0
;
770 con
->http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
771 con
->http
->data_encoding
= HTTP_ENCODING_LENGTH
;
772 con
->http
->data_remaining
= 0;
773 con
->http
->_data_remaining
= 0;
774 con
->operation
= HTTP_STATE_WAITING
;
779 con
->username
[0] = '\0';
780 con
->password
[0] = '\0';
783 cupsdClearString(&con
->command
);
784 cupsdClearString(&con
->options
);
785 cupsdClearString(&con
->query_string
);
789 ippDelete(con
->request
);
795 ippDelete(con
->response
);
796 con
->response
= NULL
;
801 cupsLangFree(con
->language
);
802 con
->language
= NULL
;
808 #endif /* HAVE_GSSAPI */
811 * Grab the request line...
814 switch (sscanf(line
, "%63s%1023s%63s", operation
, con
->uri
, version
))
819 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
820 "Bad request line \"%s\" from %s.",
821 _httpEncodeURI(buf
, line
, sizeof(buf
)),
822 con
->http
->hostname
);
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 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
834 "Bad request line \"%s\" from %s.",
835 _httpEncodeURI(buf
, line
, sizeof(buf
)),
836 con
->http
->hostname
);
837 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
838 cupsdCloseClient(con
);
844 con
->http
->version
= (http_version_t
)(major
* 100 + minor
);
845 if (con
->http
->version
== HTTP_1_1
&& KeepAlive
)
846 con
->http
->keep_alive
= HTTP_KEEPALIVE_ON
;
848 con
->http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
852 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
853 "Unsupported request line \"%s\" from %s.",
854 _httpEncodeURI(buf
, line
, sizeof(buf
)),
855 con
->http
->hostname
);
856 cupsdSendError(con
, HTTP_NOT_SUPPORTED
, CUPSD_AUTH_NONE
);
857 cupsdCloseClient(con
);
864 * Handle full URLs in the request line...
867 if (strcmp(con
->uri
, "*"))
869 char scheme
[HTTP_MAX_URI
], /* Method/scheme */
870 userpass
[HTTP_MAX_URI
], /* Username:password */
871 hostname
[HTTP_MAX_URI
], /* Hostname */
872 resource
[HTTP_MAX_URI
]; /* Resource path */
873 int port
; /* Port number */
877 * Separate the URI into its components...
880 httpSeparateURI(HTTP_URI_CODING_MOST
, con
->uri
,
881 scheme
, sizeof(scheme
),
882 userpass
, sizeof(userpass
),
883 hostname
, sizeof(hostname
), &port
,
884 resource
, sizeof(resource
));
887 * Only allow URIs with the servername, localhost, or an IP
891 if (strcmp(scheme
, "file") &&
892 _cups_strcasecmp(hostname
, ServerName
) &&
893 _cups_strcasecmp(hostname
, "localhost") &&
894 !isdigit(hostname
[0]) && hostname
[0] != '[')
897 * Nope, we don't do proxies...
900 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Bad URI \"%s\" in request.",
902 cupsdSendError(con
, HTTP_METHOD_NOT_ALLOWED
, CUPSD_AUTH_NONE
);
903 cupsdCloseClient(con
);
908 * Copy the resource portion back into the URI; both resource and
909 * con->uri are HTTP_MAX_URI bytes in size...
912 strlcpy(con
->uri
, resource
, sizeof(con
->uri
));
916 * Process the request...
919 if (!strcmp(operation
, "GET"))
920 con
->http
->state
= HTTP_STATE_GET
;
921 else if (!strcmp(operation
, "PUT"))
922 con
->http
->state
= HTTP_STATE_PUT
;
923 else if (!strcmp(operation
, "POST"))
924 con
->http
->state
= HTTP_STATE_POST
;
925 else if (!strcmp(operation
, "DELETE"))
926 con
->http
->state
= HTTP_STATE_DELETE
;
927 else if (!strcmp(operation
, "TRACE"))
928 con
->http
->state
= HTTP_STATE_TRACE
;
929 else if (!strcmp(operation
, "OPTIONS"))
930 con
->http
->state
= HTTP_STATE_OPTIONS
;
931 else if (!strcmp(operation
, "HEAD"))
932 con
->http
->state
= HTTP_STATE_HEAD
;
935 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Bad operation \"%s\".",
937 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
938 cupsdCloseClient(con
);
942 gettimeofday(&(con
->start
), NULL
);
943 con
->operation
= con
->http
->state
;
945 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "%s %s HTTP/%d.%d",
946 operation
, con
->uri
, con
->http
->version
/ 100,
947 con
->http
->version
% 100);
949 con
->http
->status
= HTTP_OK
;
951 if (!cupsArrayFind(ActiveClients
, con
))
953 cupsArrayAdd(ActiveClients
, con
);
957 case HTTP_STATE_OPTIONS
:
958 case HTTP_STATE_DELETE
:
959 case HTTP_STATE_GET
:
960 case HTTP_STATE_HEAD
:
961 case HTTP_STATE_POST
:
962 case HTTP_STATE_PUT
:
963 case HTTP_STATE_TRACE
:
965 * Parse incoming parameters until the status changes...
968 while ((status
= httpUpdate(con
->http
)) == HTTP_CONTINUE
)
969 if (!data_ready(con
))
972 if (status
!= HTTP_OK
&& status
!= HTTP_CONTINUE
)
974 if (con
->http
->error
&& con
->http
->error
!= EPIPE
)
975 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
976 "Closing for error %d (%s) while reading headers.",
977 con
->http
->error
, strerror(con
->http
->error
));
979 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
980 "Closing on EOF while reading headers.");
982 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
983 cupsdCloseClient(con
);
989 if (!data_ready(con
) && recv(httpGetFd(con
->http
), buf
, 1, MSG_PEEK
) < 1)
992 * Connection closed...
995 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing on EOF.");
996 cupsdCloseClient(con
);
999 break; /* Anti-compiler-warning-code */
1003 * Handle new transfers...
1006 if (status
== HTTP_OK
)
1008 if (con
->http
->fields
[HTTP_FIELD_ACCEPT_LANGUAGE
][0])
1011 * Figure out the locale from the Accept-Language and Content-Type
1015 if ((ptr
= strchr(con
->http
->fields
[HTTP_FIELD_ACCEPT_LANGUAGE
],
1019 if ((ptr
= strchr(con
->http
->fields
[HTTP_FIELD_ACCEPT_LANGUAGE
],
1023 if ((ptr
= strstr(con
->http
->fields
[HTTP_FIELD_CONTENT_TYPE
],
1024 "charset=")) != NULL
)
1027 * Combine language and charset, and trim any extra params in the
1031 snprintf(locale
, sizeof(locale
), "%s.%s",
1032 con
->http
->fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ptr
+ 8);
1034 if ((ptr
= strchr(locale
, ',')) != NULL
)
1038 snprintf(locale
, sizeof(locale
), "%s.UTF-8",
1039 con
->http
->fields
[HTTP_FIELD_ACCEPT_LANGUAGE
]);
1041 con
->language
= cupsLangGet(locale
);
1044 con
->language
= cupsLangGet(DefaultLocale
);
1046 cupsdAuthorize(con
);
1048 if (!_cups_strncasecmp(con
->http
->fields
[HTTP_FIELD_CONNECTION
],
1049 "Keep-Alive", 10) && KeepAlive
)
1050 con
->http
->keep_alive
= HTTP_KEEPALIVE_ON
;
1051 else if (!_cups_strncasecmp(con
->http
->fields
[HTTP_FIELD_CONNECTION
],
1053 con
->http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
1055 if (!con
->http
->fields
[HTTP_FIELD_HOST
][0] &&
1056 con
->http
->version
>= HTTP_1_1
)
1059 * HTTP/1.1 and higher require the "Host:" field...
1062 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1064 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Missing Host: field in request.");
1065 cupsdCloseClient(con
);
1069 else if (!valid_host(con
))
1072 * Access to localhost must use "localhost" or the corresponding IPv4
1073 * or IPv6 values in the Host: field.
1076 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1077 "Request from \"%s\" using invalid Host: field \"%s\".",
1078 con
->http
->hostname
, con
->http
->fields
[HTTP_FIELD_HOST
]);
1080 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1082 cupsdCloseClient(con
);
1086 else if (con
->operation
== HTTP_STATE_OPTIONS
)
1089 * Do OPTIONS command...
1092 if (con
->best
&& con
->best
->type
!= CUPSD_AUTH_NONE
)
1094 if (!cupsdSendHeader(con
, HTTP_UNAUTHORIZED
, NULL
, CUPSD_AUTH_NONE
))
1096 cupsdCloseClient(con
);
1101 if (!_cups_strcasecmp(con
->http
->fields
[HTTP_FIELD_CONNECTION
], "Upgrade") &&
1102 con
->http
->tls
== NULL
)
1106 * Do encryption stuff...
1109 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
, CUPSD_AUTH_NONE
))
1111 cupsdCloseClient(con
);
1115 httpPrintf(con
->http
, "Connection: Upgrade\r\n");
1116 httpPrintf(con
->http
, "Upgrade: TLS/1.2,TLS/1.1,TLS/1.0\r\n");
1117 httpPrintf(con
->http
, "Content-Length: 0\r\n");
1118 httpPrintf(con
->http
, "\r\n");
1120 if (cupsdFlushHeader(con
) < 0)
1122 cupsdCloseClient(con
);
1126 if (!cupsdStartTLS(con
))
1128 cupsdCloseClient(con
);
1132 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
1134 cupsdCloseClient(con
);
1137 #endif /* HAVE_SSL */
1140 if (!cupsdSendHeader(con
, HTTP_OK
, NULL
, CUPSD_AUTH_NONE
))
1142 cupsdCloseClient(con
);
1146 httpPrintf(con
->http
, "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n");
1147 httpPrintf(con
->http
, "Content-Length: 0\r\n");
1148 httpPrintf(con
->http
, "\r\n");
1150 if (cupsdFlushHeader(con
) < 0)
1152 cupsdCloseClient(con
);
1156 else if (!is_path_absolute(con
->uri
))
1159 * Protect against malicious users!
1162 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1163 "Request for non-absolute resource \"%s\".", con
->uri
);
1165 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1167 cupsdCloseClient(con
);
1173 if (!_cups_strcasecmp(con
->http
->fields
[HTTP_FIELD_CONNECTION
],
1174 "Upgrade") && con
->http
->tls
== NULL
)
1178 * Do encryption stuff...
1181 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
,
1184 cupsdCloseClient(con
);
1188 httpPrintf(con
->http
, "Connection: Upgrade\r\n");
1189 httpPrintf(con
->http
, "Upgrade: TLS/1.2,TLS/1.1,TLS/1.0\r\n");
1190 httpPrintf(con
->http
, "Content-Length: 0\r\n");
1191 httpPrintf(con
->http
, "\r\n");
1193 if (cupsdFlushHeader(con
) < 0)
1195 cupsdCloseClient(con
);
1199 if (!cupsdStartTLS(con
))
1201 cupsdCloseClient(con
);
1205 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
1207 cupsdCloseClient(con
);
1210 #endif /* HAVE_SSL */
1213 if ((status
= cupsdIsAuthorized(con
, NULL
)) != HTTP_OK
)
1215 cupsdSendError(con
, status
, CUPSD_AUTH_NONE
);
1216 cupsdCloseClient(con
);
1220 if (con
->http
->expect
&&
1221 (con
->operation
== HTTP_STATE_POST
|| con
->operation
== HTTP_STATE_PUT
))
1223 if (con
->http
->expect
== HTTP_CONTINUE
)
1226 * Send 100-continue header...
1229 if (!cupsdSendHeader(con
, HTTP_CONTINUE
, NULL
, CUPSD_AUTH_NONE
))
1231 cupsdCloseClient(con
);
1238 * Send 417-expectation-failed header...
1241 if (!cupsdSendHeader(con
, HTTP_EXPECTATION_FAILED
, NULL
,
1244 cupsdCloseClient(con
);
1248 httpPrintf(con
->http
, "Content-Length: 0\r\n");
1249 httpPrintf(con
->http
, "\r\n");
1251 if (cupsdFlushHeader(con
) < 0)
1253 cupsdCloseClient(con
);
1259 switch (con
->http
->state
)
1261 case HTTP_STATE_GET_SEND
:
1262 if ((!strncmp(con
->uri
, "/ppd/", 5) ||
1263 !strncmp(con
->uri
, "/printers/", 10) ||
1264 !strncmp(con
->uri
, "/classes/", 9)) &&
1265 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1268 * Send PPD file - get the real printer name since printer
1269 * names are not case sensitive but filenames can be...
1272 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1274 if (!strncmp(con
->uri
, "/ppd/", 5))
1275 p
= cupsdFindPrinter(con
->uri
+ 5);
1276 else if (!strncmp(con
->uri
, "/printers/", 10))
1277 p
= cupsdFindPrinter(con
->uri
+ 10);
1280 p
= cupsdFindClass(con
->uri
+ 9);
1284 int i
; /* Looping var */
1286 for (i
= 0; i
< p
->num_printers
; i
++)
1288 if (!(p
->printers
[i
]->type
& CUPS_PRINTER_CLASS
))
1290 char ppdname
[1024];/* PPD filename */
1292 snprintf(ppdname
, sizeof(ppdname
), "%s/ppd/%s.ppd",
1293 ServerRoot
, p
->printers
[i
]->name
);
1294 if (!access(ppdname
, 0))
1302 if (i
>= p
->num_printers
)
1309 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1313 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1315 cupsdCloseClient(con
);
1322 else if ((!strncmp(con
->uri
, "/icons/", 7) ||
1323 !strncmp(con
->uri
, "/printers/", 10) ||
1324 !strncmp(con
->uri
, "/classes/", 9)) &&
1325 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".png"))
1328 * Send icon file - get the real queue name since queue names are
1329 * not case sensitive but filenames can be...
1332 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".png" */
1334 if (!strncmp(con
->uri
, "/icons/", 7))
1335 p
= cupsdFindPrinter(con
->uri
+ 7);
1336 else if (!strncmp(con
->uri
, "/printers/", 10))
1337 p
= cupsdFindPrinter(con
->uri
+ 10);
1340 p
= cupsdFindClass(con
->uri
+ 9);
1344 int i
; /* Looping var */
1346 for (i
= 0; i
< p
->num_printers
; i
++)
1348 if (!(p
->printers
[i
]->type
& CUPS_PRINTER_CLASS
))
1350 char ppdname
[1024];/* PPD filename */
1352 snprintf(ppdname
, sizeof(ppdname
), "%s/ppd/%s.ppd",
1353 ServerRoot
, p
->printers
[i
]->name
);
1354 if (!access(ppdname
, 0))
1362 if (i
>= p
->num_printers
)
1368 snprintf(con
->uri
, sizeof(con
->uri
), "/icons/%s.png", p
->name
);
1371 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1373 cupsdCloseClient(con
);
1380 else if (!WebInterface
)
1383 * Web interface is disabled. Show an appropriate message...
1386 if (!cupsdSendError(con
, HTTP_WEBIF_DISABLED
, CUPSD_AUTH_NONE
))
1388 cupsdCloseClient(con
);
1395 if ((!strncmp(con
->uri
, "/admin", 6) &&
1396 strncmp(con
->uri
, "/admin/conf/", 12) &&
1397 strncmp(con
->uri
, "/admin/log/", 11)) ||
1398 !strncmp(con
->uri
, "/printers", 9) ||
1399 !strncmp(con
->uri
, "/classes", 8) ||
1400 !strncmp(con
->uri
, "/help", 5) ||
1401 !strncmp(con
->uri
, "/jobs", 5))
1404 * Send CGI output...
1407 if (!strncmp(con
->uri
, "/admin", 6))
1409 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1412 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1414 else if (!strncmp(con
->uri
, "/printers", 9))
1416 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1419 if (con
->uri
[9] && con
->uri
[10])
1420 cupsdSetString(&con
->options
, con
->uri
+ 9);
1422 cupsdSetString(&con
->options
, NULL
);
1424 else if (!strncmp(con
->uri
, "/classes", 8))
1426 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1429 if (con
->uri
[8] && con
->uri
[9])
1430 cupsdSetString(&con
->options
, con
->uri
+ 8);
1432 cupsdSetString(&con
->options
, NULL
);
1434 else if (!strncmp(con
->uri
, "/jobs", 5))
1436 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1439 if (con
->uri
[5] && con
->uri
[6])
1440 cupsdSetString(&con
->options
, con
->uri
+ 5);
1442 cupsdSetString(&con
->options
, NULL
);
1446 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1449 if (con
->uri
[5] && con
->uri
[6])
1450 cupsdSetString(&con
->options
, con
->uri
+ 5);
1452 cupsdSetString(&con
->options
, NULL
);
1455 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1457 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1459 cupsdCloseClient(con
);
1464 cupsdLogRequest(con
, HTTP_OK
);
1466 if (con
->http
->version
<= HTTP_1_0
)
1467 con
->http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
1469 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1470 (strchr(con
->uri
+ 12, '/') ||
1471 strlen(con
->uri
) == 12)) ||
1472 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1473 (strchr(con
->uri
+ 11, '/') ||
1474 strlen(con
->uri
) == 11)))
1477 * GET can only be done to configuration files directly under
1481 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1482 "Request for subdirectory \"%s\"!", con
->uri
);
1484 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1486 cupsdCloseClient(con
);
1498 if ((filename
= get_file(con
, &filestats
, buf
,
1499 sizeof(buf
))) == NULL
)
1501 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1503 cupsdCloseClient(con
);
1510 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1512 if (is_cgi(con
, filename
, &filestats
, type
))
1515 * Note: con->command and con->options were set by
1519 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1521 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1523 cupsdCloseClient(con
);
1528 cupsdLogRequest(con
, HTTP_OK
);
1530 if (con
->http
->version
<= HTTP_1_0
)
1531 con
->http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
1535 if (!check_if_modified(con
, &filestats
))
1537 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1539 cupsdCloseClient(con
);
1546 strlcpy(line
, "text/plain", sizeof(line
));
1548 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1550 if (!write_file(con
, HTTP_OK
, filename
, line
, &filestats
))
1552 cupsdCloseClient(con
);
1559 case HTTP_STATE_POST_RECV
:
1561 * See if the POST request includes a Content-Length field, and if
1562 * so check the length against any limits that are set...
1565 if (con
->http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1566 MaxRequestSize
> 0 &&
1567 con
->http
->data_remaining
> MaxRequestSize
)
1570 * Request too large...
1573 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1575 cupsdCloseClient(con
);
1581 else if (con
->http
->data_remaining
< 0 ||
1582 (!con
->http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1583 con
->http
->data_encoding
== HTTP_ENCODING_LENGTH
))
1586 * Negative content lengths are invalid!
1589 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1591 cupsdCloseClient(con
);
1599 * See what kind of POST request this is; for IPP requests the
1600 * content-type field will be "application/ipp"...
1603 if (!strcmp(con
->http
->fields
[HTTP_FIELD_CONTENT_TYPE
],
1605 con
->request
= ippNew();
1606 else if (!WebInterface
)
1609 * Web interface is disabled. Show an appropriate message...
1612 if (!cupsdSendError(con
, HTTP_WEBIF_DISABLED
, CUPSD_AUTH_NONE
))
1614 cupsdCloseClient(con
);
1620 else if ((!strncmp(con
->uri
, "/admin", 6) &&
1621 strncmp(con
->uri
, "/admin/conf/", 12) &&
1622 strncmp(con
->uri
, "/admin/log/", 11)) ||
1623 !strncmp(con
->uri
, "/printers", 9) ||
1624 !strncmp(con
->uri
, "/classes", 8) ||
1625 !strncmp(con
->uri
, "/help", 5) ||
1626 !strncmp(con
->uri
, "/jobs", 5))
1632 if (!strncmp(con
->uri
, "/admin", 6))
1634 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1637 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1639 else if (!strncmp(con
->uri
, "/printers", 9))
1641 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1644 if (con
->uri
[9] && con
->uri
[10])
1645 cupsdSetString(&con
->options
, con
->uri
+ 9);
1647 cupsdSetString(&con
->options
, NULL
);
1649 else if (!strncmp(con
->uri
, "/classes", 8))
1651 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1654 if (con
->uri
[8] && con
->uri
[9])
1655 cupsdSetString(&con
->options
, con
->uri
+ 8);
1657 cupsdSetString(&con
->options
, NULL
);
1659 else if (!strncmp(con
->uri
, "/jobs", 5))
1661 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1664 if (con
->uri
[5] && con
->uri
[6])
1665 cupsdSetString(&con
->options
, con
->uri
+ 5);
1667 cupsdSetString(&con
->options
, NULL
);
1671 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1674 if (con
->uri
[5] && con
->uri
[6])
1675 cupsdSetString(&con
->options
, con
->uri
+ 5);
1677 cupsdSetString(&con
->options
, NULL
);
1680 if (con
->http
->version
<= HTTP_1_0
)
1681 con
->http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
1689 if ((filename
= get_file(con
, &filestats
, buf
,
1690 sizeof(buf
))) == NULL
)
1692 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1694 cupsdCloseClient(con
);
1701 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1703 if (!is_cgi(con
, filename
, &filestats
, type
))
1706 * Only POST to CGI's...
1709 if (!cupsdSendError(con
, HTTP_UNAUTHORIZED
, CUPSD_AUTH_NONE
))
1711 cupsdCloseClient(con
);
1718 case HTTP_STATE_PUT_RECV
:
1720 * Validate the resource name...
1723 if (strcmp(con
->uri
, "/admin/conf/cupsd.conf"))
1726 * PUT can only be done to the cupsd.conf file...
1729 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1730 "Disallowed PUT request for \"%s\".", con
->uri
);
1732 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1734 cupsdCloseClient(con
);
1742 * See if the PUT request includes a Content-Length field, and if
1743 * so check the length against any limits that are set...
1746 if (con
->http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1747 MaxRequestSize
> 0 &&
1748 con
->http
->data_remaining
> MaxRequestSize
)
1751 * Request too large...
1754 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1756 cupsdCloseClient(con
);
1762 else if (con
->http
->data_remaining
< 0)
1765 * Negative content lengths are invalid!
1768 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1770 cupsdCloseClient(con
);
1778 * Open a temporary file to hold the request...
1781 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
1783 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1787 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1788 "Unable to create request file \"%s\": %s",
1789 con
->filename
, strerror(errno
));
1791 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1793 cupsdCloseClient(con
);
1798 fchmod(con
->file
, 0640);
1799 fchown(con
->file
, RunUser
, Group
);
1800 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1803 case HTTP_STATE_DELETE
:
1804 case HTTP_STATE_TRACE
:
1805 cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
);
1806 cupsdCloseClient(con
);
1809 case HTTP_STATE_HEAD
:
1810 if (!strncmp(con
->uri
, "/printers/", 10) &&
1811 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1814 * Send PPD file - get the real printer name since printer
1815 * names are not case sensitive but filenames can be...
1818 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1820 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1821 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1824 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1826 cupsdCloseClient(con
);
1833 else if (!strncmp(con
->uri
, "/printers/", 10) &&
1834 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".png"))
1837 * Send PNG file - get the real printer name since printer
1838 * names are not case sensitive but filenames can be...
1841 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1843 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1844 snprintf(con
->uri
, sizeof(con
->uri
), "/icons/%s.png", p
->name
);
1847 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1849 cupsdCloseClient(con
);
1856 else if (!WebInterface
)
1858 if (!cupsdSendHeader(con
, HTTP_OK
, NULL
, CUPSD_AUTH_NONE
))
1860 cupsdCloseClient(con
);
1864 if (httpPrintf(con
->http
, "\r\n") < 0)
1866 cupsdCloseClient(con
);
1870 if (cupsdFlushHeader(con
) < 0)
1872 cupsdCloseClient(con
);
1876 con
->http
->state
= HTTP_STATE_WAITING
;
1877 DEBUG_puts("cupsdReadClient: Set state to HTTP_STATE_WAITING "
1882 if ((!strncmp(con
->uri
, "/admin", 6) &&
1883 strncmp(con
->uri
, "/admin/conf/", 12) &&
1884 strncmp(con
->uri
, "/admin/log/", 11)) ||
1885 !strncmp(con
->uri
, "/printers", 9) ||
1886 !strncmp(con
->uri
, "/classes", 8) ||
1887 !strncmp(con
->uri
, "/help", 5) ||
1888 !strncmp(con
->uri
, "/jobs", 5))
1894 if (!cupsdSendHeader(con
, HTTP_OK
, "text/html", CUPSD_AUTH_NONE
))
1896 cupsdCloseClient(con
);
1900 if (httpPrintf(con
->http
, "\r\n") < 0)
1902 cupsdCloseClient(con
);
1906 if (cupsdFlushHeader(con
) < 0)
1908 cupsdCloseClient(con
);
1912 cupsdLogRequest(con
, HTTP_OK
);
1914 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1915 (strchr(con
->uri
+ 12, '/') ||
1916 strlen(con
->uri
) == 12)) ||
1917 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1918 (strchr(con
->uri
+ 11, '/') ||
1919 strlen(con
->uri
) == 11)))
1922 * HEAD can only be done to configuration files under
1926 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1927 "Request for subdirectory \"%s\".", con
->uri
);
1929 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1931 cupsdCloseClient(con
);
1937 else if ((filename
= get_file(con
, &filestats
, buf
,
1938 sizeof(buf
))) == NULL
)
1940 if (!cupsdSendHeader(con
, HTTP_NOT_FOUND
, "text/html",
1943 cupsdCloseClient(con
);
1947 cupsdLogRequest(con
, HTTP_NOT_FOUND
);
1949 else if (!check_if_modified(con
, &filestats
))
1951 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1953 cupsdCloseClient(con
);
1957 cupsdLogRequest(con
, HTTP_NOT_MODIFIED
);
1965 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1967 strlcpy(line
, "text/plain", sizeof(line
));
1969 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1971 if (!cupsdSendHeader(con
, HTTP_OK
, line
, CUPSD_AUTH_NONE
))
1973 cupsdCloseClient(con
);
1977 if (httpPrintf(con
->http
, "Last-Modified: %s\r\n",
1978 httpGetDateString(filestats
.st_mtime
)) < 0)
1980 cupsdCloseClient(con
);
1984 if (httpPrintf(con
->http
, "Content-Length: %lu\r\n",
1985 (unsigned long)filestats
.st_size
) < 0)
1987 cupsdCloseClient(con
);
1991 cupsdLogRequest(con
, HTTP_OK
);
1994 if (httpPrintf(con
->http
, "\r\n") < 0)
1996 cupsdCloseClient(con
);
2000 if (cupsdFlushHeader(con
) < 0)
2002 cupsdCloseClient(con
);
2006 con
->http
->state
= HTTP_STATE_WAITING
;
2007 DEBUG_puts("cupsdReadClient: Set state to HTTP_STATE_WAITING "
2012 break; /* Anti-compiler-warning-code */
2018 * Handle any incoming data...
2021 switch (con
->http
->state
)
2023 case HTTP_STATE_PUT_RECV
:
2026 if ((bytes
= httpRead2(con
->http
, line
, sizeof(line
))) < 0)
2028 if (con
->http
->error
&& con
->http
->error
!= EPIPE
)
2029 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2030 "HTTP_STATE_PUT_RECV Closing for error %d (%s)",
2031 con
->http
->error
, strerror(con
->http
->error
));
2033 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2034 "HTTP_STATE_PUT_RECV Closing on EOF.");
2036 cupsdCloseClient(con
);
2041 con
->bytes
+= bytes
;
2043 if (write(con
->file
, line
, bytes
) < bytes
)
2045 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
2046 "Unable to write %d bytes to \"%s\": %s", bytes
,
2047 con
->filename
, strerror(errno
));
2051 unlink(con
->filename
);
2052 cupsdClearString(&con
->filename
);
2054 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2056 cupsdCloseClient(con
);
2062 while (con
->http
->state
== HTTP_STATE_PUT_RECV
&& data_ready(con
));
2064 if (con
->http
->state
== HTTP_STATE_STATUS
)
2067 * End of file, see how big it is...
2070 fstat(con
->file
, &filestats
);
2075 if (filestats
.st_size
> MaxRequestSize
&&
2079 * Request is too big; remove it and send an error...
2082 unlink(con
->filename
);
2083 cupsdClearString(&con
->filename
);
2085 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2087 cupsdCloseClient(con
);
2093 * Install the configuration file...
2096 status
= install_cupsd_conf(con
);
2099 * Return the status to the client...
2102 if (!cupsdSendError(con
, status
, CUPSD_AUTH_NONE
))
2104 cupsdCloseClient(con
);
2110 case HTTP_STATE_POST_RECV
:
2113 if (con
->request
&& con
->file
< 0)
2116 * Grab any request data from the connection...
2119 if ((ipp_state
= ippRead(con
->http
, con
->request
)) == IPP_ERROR
)
2121 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "IPP read error: %s",
2122 cupsLastErrorString());
2124 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
2125 cupsdCloseClient(con
);
2128 else if (ipp_state
!= IPP_DATA
)
2130 if (con
->http
->state
== HTTP_STATE_POST_SEND
)
2132 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
2133 cupsdCloseClient(con
);
2137 if (data_ready(con
))
2143 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "%d.%d %s %d",
2144 con
->request
->request
.op
.version
[0],
2145 con
->request
->request
.op
.version
[1],
2146 ippOpString(con
->request
->request
.op
.operation_id
),
2147 con
->request
->request
.op
.request_id
);
2148 con
->bytes
+= ippLength(con
->request
);
2152 if (con
->file
< 0 && con
->http
->state
!= HTTP_STATE_POST_SEND
)
2155 * Create a file as needed for the request data...
2158 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
2160 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
2164 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
2165 "Unable to create request file \"%s\": %s",
2166 con
->filename
, strerror(errno
));
2168 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2170 cupsdCloseClient(con
);
2175 fchmod(con
->file
, 0640);
2176 fchown(con
->file
, RunUser
, Group
);
2177 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2180 if (con
->http
->state
!= HTTP_STATE_POST_SEND
)
2182 if (!httpWait(con
->http
, 0))
2184 else if ((bytes
= httpRead2(con
->http
, line
, sizeof(line
))) < 0)
2186 if (con
->http
->error
&& con
->http
->error
!= EPIPE
)
2187 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2188 "HTTP_STATE_POST_SEND Closing for error %d (%s)",
2189 con
->http
->error
, strerror(con
->http
->error
));
2191 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2192 "HTTP_STATE_POST_SEND Closing on EOF.");
2194 cupsdCloseClient(con
);
2199 con
->bytes
+= bytes
;
2201 if (write(con
->file
, line
, bytes
) < bytes
)
2203 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
2204 "Unable to write %d bytes to \"%s\": %s",
2205 bytes
, con
->filename
, strerror(errno
));
2209 unlink(con
->filename
);
2210 cupsdClearString(&con
->filename
);
2212 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
,
2215 cupsdCloseClient(con
);
2220 else if (con
->http
->state
== HTTP_STATE_POST_RECV
)
2222 else if (con
->http
->state
!= HTTP_STATE_POST_SEND
)
2224 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2225 "Closing on unexpected state %s.",
2226 http_states
[con
->http
->state
+ 1]);
2227 cupsdCloseClient(con
);
2232 while (con
->http
->state
== HTTP_STATE_POST_RECV
&& data_ready(con
));
2234 if (con
->http
->state
== HTTP_STATE_POST_SEND
)
2238 fstat(con
->file
, &filestats
);
2243 if (filestats
.st_size
> MaxRequestSize
&&
2247 * Request is too big; remove it and send an error...
2250 unlink(con
->filename
);
2251 cupsdClearString(&con
->filename
);
2256 * Delete any IPP request data...
2259 ippDelete(con
->request
);
2260 con
->request
= NULL
;
2263 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2265 cupsdCloseClient(con
);
2269 else if (filestats
.st_size
== 0)
2272 * Don't allow empty file...
2275 unlink(con
->filename
);
2276 cupsdClearString(&con
->filename
);
2281 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
2283 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
2285 cupsdCloseClient(con
);
2290 cupsdLogRequest(con
, HTTP_OK
);
2296 cupsdProcessIPPRequest(con
);
2300 unlink(con
->filename
);
2301 cupsdClearString(&con
->filename
);
2310 break; /* Anti-compiler-warning-code */
2313 if (con
->http
->state
== HTTP_STATE_WAITING
)
2315 if (!con
->http
->keep_alive
)
2317 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2318 "Closing because Keep-Alive is disabled.");
2319 cupsdCloseClient(con
);
2323 cupsArrayRemove(ActiveClients
, con
);
2324 cupsdSetBusyState();
2331 * 'cupsdSendCommand()' - Send output from a command via HTTP.
2334 int /* O - 1 on success, 0 on failure */
2336 cupsd_client_t
*con
, /* I - Client connection */
2337 char *command
, /* I - Command to run */
2338 char *options
, /* I - Command-line options */
2339 int root
) /* I - Run as root? */
2341 int fd
; /* Standard input file descriptor */
2346 fd
= open(con
->filename
, O_RDONLY
);
2350 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
2351 "Unable to open \"%s\" for reading: %s",
2352 con
->filename
? con
->filename
: "/dev/null",
2357 fcntl(fd
, F_SETFD
, fcntl(fd
, F_GETFD
) | FD_CLOEXEC
);
2362 con
->pipe_pid
= pipe_command(con
, fd
, &(con
->file
), command
, options
, root
);
2367 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Started \"%s\" (pid=%d, file=%d)",
2368 command
, con
->pipe_pid
, con
->file
);
2370 if (con
->pipe_pid
== 0)
2373 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2375 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2377 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for CGI data.");
2379 con
->sent_header
= 0;
2380 con
->file_ready
= 0;
2381 con
->got_fields
= 0;
2382 con
->header_used
= 0;
2389 * 'cupsdSendError()' - Send an error message via HTTP.
2392 int /* O - 1 if successful, 0 otherwise */
2393 cupsdSendError(cupsd_client_t
*con
, /* I - Connection */
2394 http_status_t code
, /* I - Error code */
2395 int auth_type
)/* I - Authentication type */
2397 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "cupsdSendError code=%d, auth_type=%d",
2402 * Force client to upgrade for authentication if that is how the
2403 * server is configured...
2406 if (code
== HTTP_UNAUTHORIZED
&&
2407 DefaultEncryption
== HTTP_ENCRYPT_REQUIRED
&&
2408 _cups_strcasecmp(con
->http
->hostname
, "localhost") &&
2411 code
= HTTP_UPGRADE_REQUIRED
;
2413 #endif /* HAVE_SSL */
2416 * Put the request in the access_log file...
2419 cupsdLogRequest(con
, code
);
2422 * To work around bugs in some proxies, don't use Keep-Alive for some
2425 * Kerberos authentication doesn't work without Keep-Alive, so
2426 * never disable it in that case.
2429 if (code
>= HTTP_BAD_REQUEST
&& con
->http
->auth_type
!= CUPSD_AUTH_NEGOTIATE
)
2430 con
->http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
2433 * Send an error message back to the client. If the error code is a
2434 * 400 or 500 series, make sure the message contains some text, too!
2437 if (!cupsdSendHeader(con
, code
, NULL
, auth_type
))
2441 if (code
== HTTP_UPGRADE_REQUIRED
)
2442 if (httpPrintf(con
->http
, "Connection: Upgrade\r\n") < 0)
2445 if (httpPrintf(con
->http
, "Upgrade: TLS/1.2,TLS/1.1,TLS/1.0\r\n") < 0)
2447 #endif /* HAVE_SSL */
2449 if (con
->http
->version
>= HTTP_1_1
&&
2450 con
->http
->keep_alive
== HTTP_KEEPALIVE_OFF
)
2452 if (httpPrintf(con
->http
, "Connection: close\r\n") < 0)
2456 if (code
>= HTTP_BAD_REQUEST
)
2459 * Send a human-readable error message.
2462 char message
[4096], /* Message for user */
2463 urltext
[1024], /* URL redirection text */
2464 redirect
[1024]; /* Redirection link */
2465 const char *text
; /* Status-specific text */
2470 if (code
== HTTP_UNAUTHORIZED
)
2471 text
= _cupsLangString(con
->language
,
2472 _("Enter your username and password or the "
2473 "root username and password to access this "
2474 "page. If you are using Kerberos authentication, "
2475 "make sure you have a valid Kerberos ticket."));
2476 else if (code
== HTTP_UPGRADE_REQUIRED
)
2480 snprintf(urltext
, sizeof(urltext
),
2481 _cupsLangString(con
->language
,
2482 _("You must access this page using the URL "
2483 "<A HREF=\"https://%s:%d%s\">"
2484 "https://%s:%d%s</A>.")),
2485 con
->servername
, con
->serverport
, con
->uri
,
2486 con
->servername
, con
->serverport
, con
->uri
);
2488 snprintf(redirect
, sizeof(redirect
),
2489 "<META HTTP-EQUIV=\"Refresh\" "
2490 "CONTENT=\"3;URL=https://%s:%d%s\">\n",
2491 con
->servername
, con
->serverport
, con
->uri
);
2493 else if (code
== HTTP_WEBIF_DISABLED
)
2494 text
= _cupsLangString(con
->language
,
2495 _("The web interface is currently disabled. Run "
2496 "\"cupsctl WebInterface=yes\" to enable it."));
2500 snprintf(message
, sizeof(message
),
2501 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" "
2502 "\"http://www.w3.org/TR/html4/loose.dtd\">\n"
2505 "\t<META HTTP-EQUIV=\"Content-Type\" "
2506 "CONTENT=\"text/html; charset=utf-8\">\n"
2507 "\t<TITLE>%s - " CUPS_SVERSION
"</TITLE>\n"
2508 "\t<LINK REL=\"STYLESHEET\" TYPE=\"text/css\" "
2509 "HREF=\"/cups.css\">\n"
2517 _httpStatus(con
->language
, code
), redirect
,
2518 _httpStatus(con
->language
, code
), text
);
2520 if (httpPrintf(con
->http
, "Content-Type: text/html; charset=utf-8\r\n") < 0)
2522 if (httpPrintf(con
->http
, "Content-Length: %d\r\n",
2523 (int)strlen(message
)) < 0)
2525 if (httpPrintf(con
->http
, "\r\n") < 0)
2527 if (httpPrintf(con
->http
, "%s", message
) < 0)
2530 else if (httpPrintf(con
->http
, "\r\n") < 0)
2533 if (cupsdFlushHeader(con
) < 0)
2536 con
->http
->state
= HTTP_STATE_WAITING
;
2538 DEBUG_puts("cupsdSendError: Set state to HTTP_STATE_WAITING.");
2545 * 'cupsdSendHeader()' - Send an HTTP request.
2548 int /* O - 1 on success, 0 on failure */
2550 cupsd_client_t
*con
, /* I - Client to send to */
2551 http_status_t code
, /* I - HTTP status code */
2552 char *type
, /* I - MIME type of document */
2553 int auth_type
) /* I - Type of authentication */
2555 char auth_str
[1024]; /* Authorization string */
2559 * Send the HTTP status header...
2562 if (code
== HTTP_CONTINUE
)
2565 * 100-continue doesn't send any headers...
2568 return (httpPrintf(con
->http
, "HTTP/%d.%d 100 Continue\r\n\r\n",
2569 con
->http
->version
/ 100, con
->http
->version
% 100) > 0);
2571 else if (code
== HTTP_WEBIF_DISABLED
)
2574 * Treat our special "web interface is disabled" status as "200 OK" for web
2581 httpFlushWrite(con
->http
);
2583 con
->http
->data_encoding
= HTTP_ENCODING_FIELDS
;
2585 if (httpPrintf(con
->http
, "HTTP/%d.%d %d %s\r\n", con
->http
->version
/ 100,
2586 con
->http
->version
% 100, code
, httpStatus(code
)) < 0)
2588 if (httpPrintf(con
->http
, "Date: %s\r\n", httpGetDateString(time(NULL
))) < 0)
2591 if (httpPrintf(con
->http
, "Server: %s\r\n", ServerHeader
) < 0)
2593 if (con
->http
->keep_alive
&& con
->http
->version
>= HTTP_1_0
)
2595 if (httpPrintf(con
->http
, "Connection: Keep-Alive\r\n") < 0)
2597 if (httpPrintf(con
->http
, "Keep-Alive: timeout=%d\r\n",
2598 KeepAliveTimeout
) < 0)
2601 if (code
== HTTP_METHOD_NOT_ALLOWED
)
2602 if (httpPrintf(con
->http
, "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n") < 0)
2605 if (code
== HTTP_UNAUTHORIZED
)
2607 if (auth_type
== CUPSD_AUTH_NONE
)
2609 if (!con
->best
|| con
->best
->type
<= CUPSD_AUTH_NONE
)
2610 auth_type
= cupsdDefaultAuthType();
2612 auth_type
= con
->best
->type
;
2617 if (auth_type
== CUPSD_AUTH_BASIC
|| auth_type
== CUPSD_AUTH_BASICDIGEST
)
2618 strlcpy(auth_str
, "Basic realm=\"CUPS\"", sizeof(auth_str
));
2619 else if (auth_type
== CUPSD_AUTH_DIGEST
)
2620 snprintf(auth_str
, sizeof(auth_str
), "Digest realm=\"CUPS\", nonce=\"%s\"",
2621 con
->http
->hostname
);
2623 else if (auth_type
== CUPSD_AUTH_NEGOTIATE
)
2626 if (_httpAddrFamily(con
->http
->hostaddr
) == AF_LOCAL
)
2627 strlcpy(auth_str
, "Basic realm=\"CUPS\"", sizeof(auth_str
));
2629 # endif /* AF_LOCAL */
2630 strlcpy(auth_str
, "Negotiate", sizeof(auth_str
));
2632 #endif /* HAVE_GSSAPI */
2634 if (con
->best
&& auth_type
!= CUPSD_AUTH_NEGOTIATE
&&
2635 !_cups_strcasecmp(con
->http
->hostname
, "localhost"))
2638 * Add a "trc" (try root certification) parameter for local non-Kerberos
2639 * requests when the request requires system group membership - then the
2640 * client knows the root certificate can/should be used.
2642 * Also, for OS X we also look for @AUTHKEY and add an "authkey"
2643 * parameter as needed...
2646 char *name
, /* Current user name */
2647 *auth_key
; /* Auth key buffer */
2648 size_t auth_size
; /* Size of remaining buffer */
2650 auth_key
= auth_str
+ strlen(auth_str
);
2651 auth_size
= sizeof(auth_str
) - (auth_key
- auth_str
);
2653 for (name
= (char *)cupsArrayFirst(con
->best
->names
);
2655 name
= (char *)cupsArrayNext(con
->best
->names
))
2657 #ifdef HAVE_AUTHORIZATION_H
2658 if (!_cups_strncasecmp(name
, "@AUTHKEY(", 9))
2660 snprintf(auth_key
, auth_size
, ", authkey=\"%s\"", name
+ 9);
2661 /* end parenthesis is stripped in conf.c */
2665 #endif /* HAVE_AUTHORIZATION_H */
2666 if (!_cups_strcasecmp(name
, "@SYSTEM"))
2668 #ifdef HAVE_AUTHORIZATION_H
2669 if (SystemGroupAuthKey
)
2670 snprintf(auth_key
, auth_size
,
2672 SystemGroupAuthKey
);
2675 strlcpy(auth_key
, ", trc=\"y\"", auth_size
);
2676 #endif /* HAVE_AUTHORIZATION_H */
2684 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "WWW-Authenticate: %s", auth_str
);
2686 if (httpPrintf(con
->http
, "WWW-Authenticate: %s\r\n", auth_str
) < 0)
2691 if (con
->language
&& strcmp(con
->language
->language
, "C"))
2693 if (httpPrintf(con
->http
, "Content-Language: %s\r\n",
2694 con
->language
->language
) < 0)
2700 if (!strcmp(type
, "text/html"))
2702 if (httpPrintf(con
->http
,
2703 "Content-Type: text/html; charset=utf-8\r\n") < 0)
2706 else if (httpPrintf(con
->http
, "Content-Type: %s\r\n", type
) < 0)
2715 * 'cupsdUpdateCGI()' - Read status messages from CGI scripts and programs.
2719 cupsdUpdateCGI(void)
2721 char *ptr
, /* Pointer to end of line in buffer */
2722 message
[1024]; /* Pointer to message text */
2723 int loglevel
; /* Log level for message */
2726 while ((ptr
= cupsdStatBufUpdate(CGIStatusBuffer
, &loglevel
,
2727 message
, sizeof(message
))) != NULL
)
2729 if (loglevel
== CUPSD_LOG_INFO
)
2730 cupsdLogMessage(CUPSD_LOG_INFO
, "%s", message
);
2732 if (!strchr(CGIStatusBuffer
->buffer
, '\n'))
2736 if (ptr
== NULL
&& !CGIStatusBuffer
->bufused
)
2739 * Fatal error on pipe - should never happen!
2742 cupsdLogMessage(CUPSD_LOG_CRIT
,
2743 "cupsdUpdateCGI: error reading from CGI error pipe - %s",
2750 * 'cupsdWriteClient()' - Write data to a client as needed.
2754 cupsdWriteClient(cupsd_client_t
*con
) /* I - Client connection */
2756 int bytes
, /* Number of bytes written */
2757 field_col
; /* Current column */
2758 char *bufptr
, /* Pointer into buffer */
2759 *bufend
; /* Pointer to end of buffer */
2760 ipp_state_t ipp_state
; /* IPP state value */
2763 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2768 "data_encoding=HTTP_ENCODING_%s, "
2769 "data_remaining=" CUPS_LLFMT
", "
2773 con
->http
->error
, con
->http
->used
,
2774 http_states
[con
->http
->state
+ 1],
2775 con
->http
->data_encoding
== HTTP_ENCODING_CHUNKED
?
2776 "CHUNKED" : "LENGTH",
2777 CUPS_LLCAST con
->http
->data_remaining
,
2779 con
->response
? ipp_states
[con
->response
->state
] : "",
2780 con
->pipe_pid
, con
->file
);
2782 if (con
->http
->state
!= HTTP_STATE_GET_SEND
&&
2783 con
->http
->state
!= HTTP_STATE_POST_SEND
)
2786 * If we get called in the wrong state, then something went wrong with the
2787 * connection and we need to shut it down...
2790 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing on unexpected HTTP state %s.",
2791 http_states
[con
->http
->state
+ 1]);
2792 cupsdCloseClient(con
);
2799 * Make sure we select on the CGI output...
2802 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2804 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for CGI data.");
2806 if (!con
->file_ready
)
2809 * Try again later when there is CGI output available...
2812 cupsdRemoveSelect(httpGetFd(con
->http
));
2816 con
->file_ready
= 0;
2819 if (con
->response
&& con
->response
->state
!= IPP_DATA
)
2821 int wused
= con
->http
->wused
; /* Previous write buffer use */
2826 * Write a single attribute or the IPP message header...
2829 ipp_state
= ippWrite(con
->http
, con
->response
);
2832 * If the write buffer has been flushed, stop buffering up attributes...
2835 if (con
->http
->wused
<= wused
)
2838 while (ipp_state
!= IPP_STATE_DATA
&& ipp_state
!= IPP_STATE_ERROR
);
2840 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2841 "Writing IPP response, ipp_state=%s, old "
2842 "wused=%d, new wused=%d",
2843 ipp_state
== IPP_STATE_ERROR
? "ERROR" :
2844 ipp_state
== IPP_STATE_IDLE
? "IDLE" :
2845 ipp_state
== IPP_STATE_HEADER
? "HEADER" :
2846 ipp_state
== IPP_STATE_ATTRIBUTE
? "ATTRIBUTE" : "DATA",
2847 wused
, con
->http
->wused
);
2849 if (con
->http
->wused
> 0)
2850 httpFlushWrite(con
->http
);
2852 bytes
= ipp_state
!= IPP_STATE_ERROR
&&
2853 (con
->file
>= 0 || ipp_state
!= IPP_STATE_DATA
);
2855 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2856 "bytes=%d, http_state=%d, data_remaining=" CUPS_LLFMT
,
2857 (int)bytes
, con
->http
->state
,
2858 CUPS_LLCAST con
->http
->data_remaining
);
2860 else if ((bytes
= read(con
->file
, con
->header
+ con
->header_used
,
2861 sizeof(con
->header
) - con
->header_used
)) > 0)
2863 con
->header_used
+= bytes
;
2865 if (con
->pipe_pid
&& !con
->got_fields
)
2868 * Inspect the data for Content-Type and other fields.
2871 for (bufptr
= con
->header
, bufend
= con
->header
+ con
->header_used
,
2873 !con
->got_fields
&& bufptr
< bufend
;
2876 if (*bufptr
== '\n')
2879 * Send line to client...
2882 if (bufptr
> con
->header
&& bufptr
[-1] == '\r')
2886 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Script header: %s", con
->header
);
2888 if (!con
->sent_header
)
2891 * Handle redirection and CGI status codes...
2894 if (!_cups_strncasecmp(con
->header
, "Location:", 9))
2896 if (!cupsdSendHeader(con
, HTTP_SEE_OTHER
, NULL
, CUPSD_AUTH_NONE
))
2898 cupsdCloseClient(con
);
2902 con
->sent_header
= 2;
2904 if (httpPrintf(con
->http
, "Content-Length: 0\r\n") < 0)
2907 else if (!_cups_strncasecmp(con
->header
, "Status:", 7))
2909 cupsdSendError(con
, (http_status_t
)atoi(con
->header
+ 7),
2911 con
->sent_header
= 2;
2915 if (!cupsdSendHeader(con
, HTTP_OK
, NULL
, CUPSD_AUTH_NONE
))
2917 cupsdCloseClient(con
);
2921 con
->sent_header
= 1;
2923 if (con
->http
->version
== HTTP_1_1
)
2925 if (httpPrintf(con
->http
, "Transfer-Encoding: chunked\r\n") < 0)
2931 if (_cups_strncasecmp(con
->header
, "Status:", 7))
2932 httpPrintf(con
->http
, "%s\r\n", con
->header
);
2938 con
->header_used
-= bufptr
- con
->header
;
2940 if (con
->header_used
> 0)
2941 memmove(con
->header
, bufptr
, con
->header_used
);
2943 bufptr
= con
->header
- 1;
2946 * See if the line was empty...
2951 con
->got_fields
= 1;
2953 if (cupsdFlushHeader(con
) < 0)
2955 cupsdCloseClient(con
);
2959 if (con
->http
->version
== HTTP_1_1
)
2960 con
->http
->data_encoding
= HTTP_ENCODING_CHUNKED
;
2965 else if (*bufptr
!= '\r')
2969 if (!con
->got_fields
)
2971 con
->http
->activity
= time(NULL
);
2976 if (con
->header_used
> 0)
2978 if (httpWrite2(con
->http
, con
->header
, con
->header_used
) < 0)
2980 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing for error %d (%s)",
2981 con
->http
->error
, strerror(con
->http
->error
));
2982 cupsdCloseClient(con
);
2986 if (con
->http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
2987 httpFlushWrite(con
->http
);
2989 con
->bytes
+= con
->header_used
;
2991 if (con
->http
->state
== HTTP_STATE_WAITING
)
2994 bytes
= con
->header_used
;
2996 con
->header_used
= 0;
3001 (con
->http
->state
!= HTTP_STATE_GET_SEND
&&
3002 con
->http
->state
!= HTTP_STATE_POST_SEND
))
3004 if (!con
->sent_header
&& con
->pipe_pid
)
3005 cupsdSendError(con
, HTTP_SERVER_ERROR
, CUPSD_AUTH_NONE
);
3008 cupsdLogRequest(con
, HTTP_OK
);
3010 httpFlushWrite(con
->http
);
3012 if (con
->http
->data_encoding
== HTTP_ENCODING_CHUNKED
&&
3013 con
->sent_header
== 1)
3015 if (httpWrite2(con
->http
, "", 0) < 0)
3017 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing for error %d (%s)",
3018 con
->http
->error
, strerror(con
->http
->error
));
3019 cupsdCloseClient(con
);
3025 con
->http
->state
= HTTP_STATE_WAITING
;
3027 cupsdAddSelect(httpGetFd(con
->http
), (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
3029 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for request.");
3033 cupsdRemoveSelect(con
->file
);
3036 cupsdEndProcess(con
->pipe_pid
, 0);
3045 unlink(con
->filename
);
3046 cupsdClearString(&con
->filename
);
3051 ippDelete(con
->request
);
3052 con
->request
= NULL
;
3057 ippDelete(con
->response
);
3058 con
->response
= NULL
;
3061 cupsdClearString(&con
->command
);
3062 cupsdClearString(&con
->options
);
3063 cupsdClearString(&con
->query_string
);
3065 if (!con
->http
->keep_alive
)
3067 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
3068 "Closing because Keep-Alive is disabled.");
3069 cupsdCloseClient(con
);
3074 cupsArrayRemove(ActiveClients
, con
);
3075 cupsdSetBusyState();
3079 con
->http
->activity
= time(NULL
);
3084 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
3087 static int /* O - 1 if modified since */
3089 cupsd_client_t
*con
, /* I - Client connection */
3090 struct stat
*filestats
) /* I - File information */
3092 char *ptr
; /* Pointer into field */
3093 time_t date
; /* Time/date value */
3094 off_t size
; /* Size/length value */
3099 ptr
= con
->http
->fields
[HTTP_FIELD_IF_MODIFIED_SINCE
];
3104 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3105 "check_if_modified "
3106 "filestats=%p(" CUPS_LLFMT
", %d)) If-Modified-Since=\"%s\"",
3107 filestats
, CUPS_LLCAST filestats
->st_size
,
3108 (int)filestats
->st_mtime
, ptr
);
3110 while (*ptr
!= '\0')
3112 while (isspace(*ptr
) || *ptr
== ';')
3115 if (_cups_strncasecmp(ptr
, "length=", 7) == 0)
3118 size
= strtoll(ptr
, NULL
, 10);
3120 while (isdigit(*ptr
))
3123 else if (isalpha(*ptr
))
3125 date
= httpGetDateTime(ptr
);
3126 while (*ptr
!= '\0' && *ptr
!= ';')
3133 return ((size
!= filestats
->st_size
&& size
!= 0) ||
3134 (date
< filestats
->st_mtime
&& date
!= 0) ||
3135 (size
== 0 && date
== 0));
3140 * 'compare_clients()' - Compare two client connections.
3143 static int /* O - Result of comparison */
3144 compare_clients(cupsd_client_t
*a
, /* I - First client */
3145 cupsd_client_t
*b
, /* I - Second client */
3146 void *data
) /* I - User data (not used) */
3160 * 'data_ready()' - Check whether data is available from a client.
3163 static int /* O - 1 if data is ready, 0 otherwise */
3164 data_ready(cupsd_client_t
*con
) /* I - Client */
3166 if (con
->http
->used
> 0)
3169 else if (con
->http
->tls
)
3172 if (SSL_pending((SSL
*)(con
->http
->tls
)))
3174 # elif defined(HAVE_GNUTLS)
3175 if (gnutls_record_check_pending(con
->http
->tls
))
3177 # elif defined(HAVE_CDSASSL)
3178 size_t bytes
; /* Bytes that are available */
3180 if (!SSLGetBufferedReadSize(con
->http
->tls
, &bytes
) && bytes
> 0)
3182 # endif /* HAVE_LIBSSL */
3184 #endif /* HAVE_SSL */
3191 * 'get_file()' - Get a filename and state info.
3194 static char * /* O - Real filename */
3195 get_file(cupsd_client_t
*con
, /* I - Client connection */
3196 struct stat
*filestats
, /* O - File information */
3197 char *filename
, /* IO - Filename buffer */
3198 int len
) /* I - Buffer length */
3200 int status
; /* Status of filesystem calls */
3201 char *ptr
; /* Pointer info filename */
3202 int plen
; /* Remaining length after pointer */
3203 char language
[7]; /* Language subdirectory, if any */
3207 * Figure out the real filename...
3212 if (!strncmp(con
->uri
, "/ppd/", 5) && !strchr(con
->uri
+ 5, '/'))
3213 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
);
3214 else if (!strncmp(con
->uri
, "/icons/", 7) && !strchr(con
->uri
+ 7, '/'))
3216 snprintf(filename
, len
, "%s/%s", CacheDir
, con
->uri
+ 7);
3217 if (access(filename
, F_OK
) < 0)
3218 snprintf(filename
, len
, "%s/images/generic.png", DocumentRoot
);
3220 else if (!strncmp(con
->uri
, "/rss/", 5) && !strchr(con
->uri
+ 5, '/'))
3221 snprintf(filename
, len
, "%s/rss/%s", CacheDir
, con
->uri
+ 5);
3222 else if (!strncmp(con
->uri
, "/admin/conf/", 12))
3223 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
+ 11);
3224 else if (!strncmp(con
->uri
, "/admin/log/", 11))
3226 if (!strncmp(con
->uri
+ 11, "access_log", 10) && AccessLog
[0] == '/')
3227 strlcpy(filename
, AccessLog
, len
);
3228 else if (!strncmp(con
->uri
+ 11, "error_log", 9) && ErrorLog
[0] == '/')
3229 strlcpy(filename
, ErrorLog
, len
);
3230 else if (!strncmp(con
->uri
+ 11, "page_log", 8) && PageLog
[0] == '/')
3231 strlcpy(filename
, PageLog
, len
);
3235 else if (con
->language
)
3237 snprintf(language
, sizeof(language
), "/%s", con
->language
->language
);
3238 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3241 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3243 if ((ptr
= strchr(filename
, '?')) != NULL
)
3247 * Grab the status for this language; if there isn't a language-specific file
3248 * then fallback to the default one...
3251 if ((status
= stat(filename
, filestats
)) != 0 && language
[0] &&
3252 strncmp(con
->uri
, "/icons/", 7) &&
3253 strncmp(con
->uri
, "/ppd/", 5) &&
3254 strncmp(con
->uri
, "/rss/", 5) &&
3255 strncmp(con
->uri
, "/admin/conf/", 12) &&
3256 strncmp(con
->uri
, "/admin/log/", 11))
3259 * Drop the country code...
3263 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3265 if ((ptr
= strchr(filename
, '?')) != NULL
)
3268 if ((status
= stat(filename
, filestats
)) != 0)
3271 * Drop the language prefix and try the root directory...
3275 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3277 if ((ptr
= strchr(filename
, '?')) != NULL
)
3280 status
= stat(filename
, filestats
);
3285 * If we're found a directory, get the index.html file instead...
3288 if (!status
&& S_ISDIR(filestats
->st_mode
))
3291 * Make sure the URI ends with a slash...
3294 if (con
->uri
[strlen(con
->uri
) - 1] != '/')
3295 strlcat(con
->uri
, "/", sizeof(con
->uri
));
3298 * Find the directory index file, trying every language...
3303 if (status
&& language
[0])
3306 * Try a different language subset...
3310 language
[0] = '\0'; /* Strip country code */
3312 language
[0] = '\0'; /* Strip language */
3316 * Look for the index file...
3319 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3321 if ((ptr
= strchr(filename
, '?')) != NULL
)
3324 ptr
= filename
+ strlen(filename
);
3325 plen
= len
- (ptr
- filename
);
3327 strlcpy(ptr
, "index.html", plen
);
3328 status
= stat(filename
, filestats
);
3333 strlcpy(ptr
, "index.class", plen
);
3334 status
= stat(filename
, filestats
);
3336 #endif /* HAVE_JAVA */
3341 strlcpy(ptr
, "index.pl", plen
);
3342 status
= stat(filename
, filestats
);
3344 #endif /* HAVE_PERL */
3349 strlcpy(ptr
, "index.php", plen
);
3350 status
= stat(filename
, filestats
);
3352 #endif /* HAVE_PHP */
3357 strlcpy(ptr
, "index.pyc", plen
);
3358 status
= stat(filename
, filestats
);
3363 strlcpy(ptr
, "index.py", plen
);
3364 status
= stat(filename
, filestats
);
3366 #endif /* HAVE_PYTHON */
3369 while (status
&& language
[0]);
3372 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3373 "get_file filestats=%p, filename=%p, len=%d, "
3374 "returning \"%s\".", filestats
, filename
, len
,
3375 status
? "(null)" : filename
);
3385 * 'install_cupsd_conf()' - Install a configuration file.
3388 static http_status_t
/* O - Status */
3389 install_cupsd_conf(cupsd_client_t
*con
) /* I - Connection */
3391 char filename
[1024]; /* Configuration filename */
3392 cups_file_t
*in
, /* Input file */
3393 *out
; /* Output file */
3394 char buffer
[16384]; /* Copy buffer */
3395 ssize_t bytes
; /* Number of bytes */
3399 * Open the request file...
3402 if ((in
= cupsFileOpen(con
->filename
, "rb")) == NULL
)
3404 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Unable to open request file \"%s\": %s",
3405 con
->filename
, strerror(errno
));
3406 return (HTTP_SERVER_ERROR
);
3410 * Open the new config file...
3413 if ((out
= cupsdCreateConfFile(ConfigurationFile
, ConfigFilePerm
)) == NULL
)
3416 return (HTTP_SERVER_ERROR
);
3419 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Installing config file \"%s\"...",
3423 * Copy from the request to the new config file...
3426 while ((bytes
= cupsFileRead(in
, buffer
, sizeof(buffer
))) > 0)
3427 if (cupsFileWrite(out
, buffer
, bytes
) < bytes
)
3429 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
3430 "Unable to copy to config file \"%s\": %s",
3431 ConfigurationFile
, strerror(errno
));
3436 snprintf(filename
, sizeof(filename
), "%s.N", ConfigurationFile
);
3437 cupsdUnlinkOrRemoveFile(filename
);
3439 return (HTTP_SERVER_ERROR
);
3443 * Close the files...
3448 if (cupsdCloseCreatedConfFile(out
, ConfigurationFile
))
3449 return (HTTP_SERVER_ERROR
);
3452 * Remove the request file...
3455 cupsdUnlinkOrRemoveFile(con
->filename
);
3456 cupsdClearString(&con
->filename
);
3459 * Set the NeedReload flag...
3462 NeedReload
= RELOAD_CUPSD
;
3463 ReloadTime
= time(NULL
);
3466 * Return that the file was created successfully...
3469 return (HTTP_CREATED
);
3474 * 'is_cgi()' - Is the resource a CGI script/program?
3477 static int /* O - 1 = CGI, 0 = file */
3478 is_cgi(cupsd_client_t
*con
, /* I - Client connection */
3479 const char *filename
, /* I - Real filename */
3480 struct stat
*filestats
, /* I - File information */
3481 mime_type_t
*type
) /* I - MIME type */
3483 const char *options
; /* Options on URL */
3487 * Get the options, if any...
3490 if ((options
= strchr(con
->uri
, '?')) != NULL
)
3493 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", options
);
3497 * Check for known types...
3500 if (!type
|| _cups_strcasecmp(type
->super
, "application"))
3502 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3503 "is_cgi filename=\"%s\", filestats=%p, "
3504 "type=%s/%s, returning 0", filename
,
3505 filestats
, type
? type
->super
: "unknown",
3506 type
? type
->type
: "unknown");
3510 if (!_cups_strcasecmp(type
->type
, "x-httpd-cgi") &&
3511 (filestats
->st_mode
& 0111))
3514 * "application/x-httpd-cgi" is a CGI script.
3517 cupsdSetString(&con
->command
, filename
);
3520 cupsdSetStringf(&con
->options
, " %s", options
);
3522 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3523 "is_cgi filename=\"%s\", filestats=%p, "
3524 "type=%s/%s, returning 1", filename
,
3525 filestats
, type
->super
, type
->type
);
3529 else if (!_cups_strcasecmp(type
->type
, "x-httpd-java"))
3532 * "application/x-httpd-java" is a Java servlet.
3535 cupsdSetString(&con
->command
, CUPS_JAVA
);
3538 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3540 cupsdSetStringf(&con
->options
, " %s", filename
);
3542 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3543 "is_cgi filename=\"%s\", filestats=%p, "
3544 "type=%s/%s, returning 1", filename
,
3545 filestats
, type
->super
, type
->type
);
3548 #endif /* HAVE_JAVA */
3550 else if (!_cups_strcasecmp(type
->type
, "x-httpd-perl"))
3553 * "application/x-httpd-perl" is a Perl page.
3556 cupsdSetString(&con
->command
, CUPS_PERL
);
3559 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3561 cupsdSetStringf(&con
->options
, " %s", filename
);
3563 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3564 "is_cgi filename=\"%s\", filestats=%p, "
3565 "type=%s/%s, returning 1", filename
,
3566 filestats
, type
->super
, type
->type
);
3569 #endif /* HAVE_PERL */
3571 else if (!_cups_strcasecmp(type
->type
, "x-httpd-php"))
3574 * "application/x-httpd-php" is a PHP page.
3577 cupsdSetString(&con
->command
, CUPS_PHP
);
3580 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3582 cupsdSetStringf(&con
->options
, " %s", filename
);
3584 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3585 "is_cgi filename=\"%s\", filestats=%p, "
3586 "type=%s/%s, returning 1", filename
,
3587 filestats
, type
->super
, type
->type
);
3590 #endif /* HAVE_PHP */
3592 else if (!_cups_strcasecmp(type
->type
, "x-httpd-python"))
3595 * "application/x-httpd-python" is a Python page.
3598 cupsdSetString(&con
->command
, CUPS_PYTHON
);
3601 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3603 cupsdSetStringf(&con
->options
, " %s", filename
);
3605 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3606 "is_cgi filename=\"%s\", filestats=%p, "
3607 "type=%s/%s, returning 1", filename
,
3608 filestats
, type
->super
, type
->type
);
3611 #endif /* HAVE_PYTHON */
3613 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3614 "is_cgi filename=\"%s\", filestats=%p, "
3615 "type=%s/%s, returning 0", filename
,
3616 filestats
, type
->super
, type
->type
);
3622 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
3625 static int /* O - 0 if relative, 1 if absolute */
3626 is_path_absolute(const char *path
) /* I - Input path */
3629 * Check for a leading slash...
3636 * Check for "/.." in the path...
3639 while ((path
= strstr(path
, "/..")) != NULL
)
3641 if (!path
[3] || path
[3] == '/')
3648 * If we haven't found any relative paths, return 1 indicating an
3657 * 'pipe_command()' - Pipe the output of a command to the remote client.
3660 static int /* O - Process ID */
3661 pipe_command(cupsd_client_t
*con
, /* I - Client connection */
3662 int infile
, /* I - Standard input for command */
3663 int *outfile
, /* O - Standard output for command */
3664 char *command
, /* I - Command to run */
3665 char *options
, /* I - Options for command */
3666 int root
) /* I - Run as root? */
3668 int i
; /* Looping var */
3669 int pid
; /* Process ID */
3670 char *commptr
, /* Command string pointer */
3671 commch
; /* Command string character */
3672 char *uriptr
; /* URI string pointer */
3673 int fds
[2]; /* Pipe FDs */
3674 int argc
; /* Number of arguments */
3675 int envc
; /* Number of environment variables */
3676 char argbuf
[10240], /* Argument buffer */
3677 *argv
[100], /* Argument strings */
3678 *envp
[MAX_ENV
+ 20]; /* Environment variables */
3679 char auth_type
[256], /* AUTH_TYPE environment variable */
3680 content_length
[1024], /* CONTENT_LENGTH environment variable */
3681 content_type
[1024], /* CONTENT_TYPE environment variable */
3682 http_cookie
[32768], /* HTTP_COOKIE environment variable */
3683 http_referer
[1024], /* HTTP_REFERER environment variable */
3684 http_user_agent
[1024], /* HTTP_USER_AGENT environment variable */
3685 lang
[1024], /* LANG environment variable */
3686 path_info
[1024], /* PATH_INFO environment variable */
3687 remote_addr
[1024], /* REMOTE_ADDR environment variable */
3688 remote_host
[1024], /* REMOTE_HOST environment variable */
3689 remote_user
[1024], /* REMOTE_USER environment variable */
3690 script_filename
[1024], /* SCRIPT_FILENAME environment variable */
3691 script_name
[1024], /* SCRIPT_NAME environment variable */
3692 server_name
[1024], /* SERVER_NAME environment variable */
3693 server_port
[1024]; /* SERVER_PORT environment variable */
3694 ipp_attribute_t
*attr
; /* attributes-natural-language attribute */
3698 * Parse a copy of the options string, which is of the form:
3700 * argument+argument+argument
3701 * ?argument+argument+argument
3702 * param=value¶m=value
3703 * ?param=value¶m=value
3704 * /name?argument+argument+argument
3705 * /name?param=value¶m=value
3707 * If the string contains an "=" character after the initial name,
3708 * then we treat it as a HTTP GET form request and make a copy of
3709 * the remaining string for the environment variable.
3711 * The string is always parsed out as command-line arguments, to
3712 * be consistent with Apache...
3715 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3716 "pipe_command infile=%d, outfile=%p, "
3717 "command=\"%s\", options=\"%s\", root=%d",
3718 infile
, outfile
, command
,
3719 options
? options
: "(null)", root
);
3726 if (*commptr
== ' ')
3728 strlcpy(argbuf
, commptr
, sizeof(argbuf
));
3733 if (argbuf
[0] == '/')
3736 * Found some trailing path information, set PATH_INFO...
3739 if ((commptr
= strchr(argbuf
, '?')) == NULL
)
3740 commptr
= argbuf
+ strlen(argbuf
);
3744 snprintf(path_info
, sizeof(path_info
), "PATH_INFO=%s", argbuf
);
3750 path_info
[0] = '\0';
3752 if (*commptr
== ' ')
3756 if (*commptr
== '?' && con
->operation
== HTTP_STATE_GET
&& !con
->query_string
)
3759 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", commptr
);
3766 argv
[argc
++] = commptr
;
3768 for (; *commptr
&& argc
< 99; commptr
++)
3771 * Break arguments whenever we see a + or space...
3774 if (*commptr
== ' ' || *commptr
== '+')
3776 while (*commptr
== ' ' || *commptr
== '+')
3780 * If we don't have a blank string, save it as another argument...
3785 argv
[argc
] = commptr
;
3791 else if (*commptr
== '%' && isxdigit(commptr
[1] & 255) &&
3792 isxdigit(commptr
[2] & 255))
3795 * Convert the %xx notation to the individual character.
3798 if (commptr
[1] >= '0' && commptr
[1] <= '9')
3799 *commptr
= (commptr
[1] - '0') << 4;
3801 *commptr
= (tolower(commptr
[1]) - 'a' + 10) << 4;
3803 if (commptr
[2] >= '0' && commptr
[2] <= '9')
3804 *commptr
|= commptr
[2] - '0';
3806 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
3808 _cups_strcpy(commptr
+ 1, commptr
+ 3);
3811 * Check for a %00 and break if that is the case...
3823 * Setup the environment variables as needed...
3826 if (con
->username
[0])
3828 snprintf(auth_type
, sizeof(auth_type
), "AUTH_TYPE=%s",
3829 httpGetField(con
->http
, HTTP_FIELD_AUTHORIZATION
));
3831 if ((uriptr
= strchr(auth_type
+ 10, ' ')) != NULL
)
3835 auth_type
[0] = '\0';
3838 (attr
= ippFindAttribute(con
->request
, "attributes-natural-language",
3839 IPP_TAG_LANGUAGE
)) != NULL
)
3841 switch (strlen(attr
->values
[0].string
.text
))
3845 * This is an unknown or badly formatted language code; use
3846 * the POSIX locale...
3849 strlcpy(lang
, "LANG=C", sizeof(lang
));
3854 * Just the language code (ll)...
3857 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8",
3858 attr
->values
[0].string
.text
);
3863 * Language and country code (ll-cc)...
3866 snprintf(lang
, sizeof(lang
), "LANG=%c%c_%c%c.UTF8",
3867 attr
->values
[0].string
.text
[0],
3868 attr
->values
[0].string
.text
[1],
3869 toupper(attr
->values
[0].string
.text
[3] & 255),
3870 toupper(attr
->values
[0].string
.text
[4] & 255));
3874 else if (con
->language
)
3875 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8", con
->language
->language
);
3877 strlcpy(lang
, "LANG=C", sizeof(lang
));
3879 strlcpy(remote_addr
, "REMOTE_ADDR=", sizeof(remote_addr
));
3880 httpAddrString(con
->http
->hostaddr
, remote_addr
+ 12,
3881 sizeof(remote_addr
) - 12);
3883 snprintf(remote_host
, sizeof(remote_host
), "REMOTE_HOST=%s",
3884 con
->http
->hostname
);
3886 snprintf(script_name
, sizeof(script_name
), "SCRIPT_NAME=%s", con
->uri
);
3887 if ((uriptr
= strchr(script_name
, '?')) != NULL
)
3890 snprintf(script_filename
, sizeof(script_filename
), "SCRIPT_FILENAME=%s%s",
3891 DocumentRoot
, script_name
+ 12);
3893 sprintf(server_port
, "SERVER_PORT=%d", con
->serverport
);
3895 if (con
->http
->fields
[HTTP_FIELD_HOST
][0])
3897 char *nameptr
; /* Pointer to ":port" */
3899 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
3900 con
->http
->fields
[HTTP_FIELD_HOST
]);
3901 if ((nameptr
= strrchr(server_name
, ':')) != NULL
&& !strchr(nameptr
, ']'))
3902 *nameptr
= '\0'; /* Strip trailing ":port" */
3905 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
3908 envc
= cupsdLoadEnv(envp
, (int)(sizeof(envp
) / sizeof(envp
[0])));
3911 envp
[envc
++] = auth_type
;
3913 envp
[envc
++] = lang
;
3914 envp
[envc
++] = "REDIRECT_STATUS=1";
3915 envp
[envc
++] = "GATEWAY_INTERFACE=CGI/1.1";
3916 envp
[envc
++] = server_name
;
3917 envp
[envc
++] = server_port
;
3918 envp
[envc
++] = remote_addr
;
3919 envp
[envc
++] = remote_host
;
3920 envp
[envc
++] = script_name
;
3921 envp
[envc
++] = script_filename
;
3924 envp
[envc
++] = path_info
;
3926 if (con
->username
[0])
3928 snprintf(remote_user
, sizeof(remote_user
), "REMOTE_USER=%s", con
->username
);
3930 envp
[envc
++] = remote_user
;
3933 if (con
->http
->version
== HTTP_1_1
)
3934 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.1";
3935 else if (con
->http
->version
== HTTP_1_0
)
3936 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.0";
3938 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/0.9";
3940 if (con
->http
->cookie
)
3942 snprintf(http_cookie
, sizeof(http_cookie
), "HTTP_COOKIE=%s",
3944 envp
[envc
++] = http_cookie
;
3947 if (con
->http
->fields
[HTTP_FIELD_USER_AGENT
][0])
3949 snprintf(http_user_agent
, sizeof(http_user_agent
), "HTTP_USER_AGENT=%s",
3950 con
->http
->fields
[HTTP_FIELD_USER_AGENT
]);
3951 envp
[envc
++] = http_user_agent
;
3954 if (con
->http
->fields
[HTTP_FIELD_REFERER
][0])
3956 snprintf(http_referer
, sizeof(http_referer
), "HTTP_REFERER=%s",
3957 con
->http
->fields
[HTTP_FIELD_REFERER
]);
3958 envp
[envc
++] = http_referer
;
3961 if (con
->operation
== HTTP_STATE_GET
)
3963 envp
[envc
++] = "REQUEST_METHOD=GET";
3965 if (con
->query_string
)
3968 * Add GET form variables after ?...
3971 envp
[envc
++] = con
->query_string
;
3974 envp
[envc
++] = "QUERY_STRING=";
3978 sprintf(content_length
, "CONTENT_LENGTH=" CUPS_LLFMT
,
3979 CUPS_LLCAST con
->bytes
);
3980 snprintf(content_type
, sizeof(content_type
), "CONTENT_TYPE=%s",
3981 con
->http
->fields
[HTTP_FIELD_CONTENT_TYPE
]);
3983 envp
[envc
++] = "REQUEST_METHOD=POST";
3984 envp
[envc
++] = content_length
;
3985 envp
[envc
++] = content_type
;
3989 * Tell the CGI if we are using encryption...
3993 envp
[envc
++] = "HTTPS=ON";
3996 * Terminate the environment array...
4001 if (LogLevel
>= CUPSD_LOG_DEBUG
)
4003 for (i
= 0; i
< argc
; i
++)
4004 cupsdLogMessage(CUPSD_LOG_DEBUG
,
4005 "[CGI] argv[%d] = \"%s\"", i
, argv
[i
]);
4006 for (i
= 0; i
< envc
; i
++)
4007 cupsdLogMessage(CUPSD_LOG_DEBUG
,
4008 "[CGI] envp[%d] = \"%s\"", i
, envp
[i
]);
4012 * Create a pipe for the output...
4015 if (cupsdOpenPipe(fds
))
4017 cupsdLogMessage(CUPSD_LOG_ERROR
, "[CGI] Unable to create pipe for %s - %s",
4018 argv
[0], strerror(errno
));
4023 * Then execute the command...
4026 if (cupsdStartProcess(command
, argv
, envp
, infile
, fds
[1], CGIPipes
[1],
4027 -1, -1, root
, DefaultProfile
, NULL
, &pid
) < 0)
4030 * Error - can't fork!
4033 cupsdLogMessage(CUPSD_LOG_ERROR
, "[CGI] Unable to start %s - %s", argv
[0],
4036 cupsdClosePipe(fds
);
4042 * Fork successful - return the PID...
4045 if (con
->username
[0])
4046 cupsdAddCert(pid
, con
->username
, con
->type
);
4048 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[CGI] Started %s (PID %d)", command
, pid
);
4059 * 'valid_host()' - Is the Host: field valid?
4062 static int /* O - 1 if valid, 0 if not */
4063 valid_host(cupsd_client_t
*con
) /* I - Client connection */
4065 cupsd_alias_t
*a
; /* Current alias */
4066 cupsd_netif_t
*netif
; /* Current network interface */
4067 const char *end
; /* End character */
4068 char *ptr
; /* Pointer into host value */
4072 * Copy the Host: header for later use...
4075 strlcpy(con
->clientname
, con
->http
->fields
[HTTP_FIELD_HOST
],
4076 sizeof(con
->clientname
));
4077 if ((ptr
= strrchr(con
->clientname
, ':')) != NULL
&& !strchr(ptr
, ']'))
4080 con
->clientport
= atoi(ptr
);
4083 con
->clientport
= con
->serverport
;
4089 if (httpAddrLocalhost(con
->http
->hostaddr
))
4092 * Only allow "localhost" or the equivalent IPv4 or IPv6 numerical
4093 * addresses when accessing CUPS via the loopback interface...
4096 return (!_cups_strcasecmp(con
->clientname
, "localhost") ||
4097 !_cups_strcasecmp(con
->clientname
, "localhost.") ||
4099 !_cups_strcasecmp(con
->clientname
, "localhost.localdomain") ||
4100 #endif /* __linux */
4101 !strcmp(con
->clientname
, "127.0.0.1") ||
4102 !strcmp(con
->clientname
, "[::1]"));
4105 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
4107 * Check if the hostname is something.local (Bonjour); if so, allow it.
4110 if ((end
= strrchr(con
->clientname
, '.')) != NULL
&& end
> con
->clientname
&&
4114 * "." on end, work back to second-to-last "."...
4117 for (end
--; end
> con
->clientname
&& *end
!= '.'; end
--);
4120 if (end
&& (!_cups_strcasecmp(end
, ".local") ||
4121 !_cups_strcasecmp(end
, ".local.")))
4123 #endif /* HAVE_DNSSD || HAVE_AVAHI */
4126 * Check if the hostname is an IP address...
4129 if (isdigit(con
->clientname
[0] & 255) || con
->clientname
[0] == '[')
4132 * Possible IPv4/IPv6 address...
4135 http_addrlist_t
*addrlist
; /* List of addresses */
4138 if ((addrlist
= httpAddrGetList(con
->clientname
, AF_UNSPEC
, NULL
)) != NULL
)
4141 * Good IPv4/IPv6 address...
4144 httpAddrFreeList(addrlist
);
4150 * Check for (alias) name matches...
4153 for (a
= (cupsd_alias_t
*)cupsArrayFirst(ServerAlias
);
4155 a
= (cupsd_alias_t
*)cupsArrayNext(ServerAlias
))
4158 * "ServerAlias *" allows all host values through...
4161 if (!strcmp(a
->name
, "*"))
4164 if (!_cups_strncasecmp(con
->clientname
, a
->name
, a
->namelen
))
4167 * Prefix matches; check the character at the end - it must be "." or nul.
4170 end
= con
->clientname
+ a
->namelen
;
4172 if (!*end
|| (*end
== '.' && !end
[1]))
4177 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
4178 for (a
= (cupsd_alias_t
*)cupsArrayFirst(DNSSDAlias
);
4180 a
= (cupsd_alias_t
*)cupsArrayNext(DNSSDAlias
))
4183 * "ServerAlias *" allows all host values through...
4186 if (!strcmp(a
->name
, "*"))
4189 if (!_cups_strncasecmp(con
->clientname
, a
->name
, a
->namelen
))
4192 * Prefix matches; check the character at the end - it must be "." or nul.
4195 end
= con
->clientname
+ a
->namelen
;
4197 if (!*end
|| (*end
== '.' && !end
[1]))
4201 #endif /* HAVE_DNSSD || HAVE_AVAHI */
4204 * Check for interface hostname matches...
4207 for (netif
= (cupsd_netif_t
*)cupsArrayFirst(NetIFList
);
4209 netif
= (cupsd_netif_t
*)cupsArrayNext(NetIFList
))
4211 if (!_cups_strncasecmp(con
->clientname
, netif
->hostname
, netif
->hostlen
))
4214 * Prefix matches; check the character at the end - it must be "." or nul.
4217 end
= con
->clientname
+ netif
->hostlen
;
4219 if (!*end
|| (*end
== '.' && !end
[1]))
4229 * 'write_file()' - Send a file via HTTP.
4232 static int /* O - 0 on failure, 1 on success */
4233 write_file(cupsd_client_t
*con
, /* I - Client connection */
4234 http_status_t code
, /* I - HTTP status */
4235 char *filename
, /* I - Filename */
4236 char *type
, /* I - File type */
4237 struct stat
*filestats
) /* O - File information */
4239 con
->file
= open(filename
, O_RDONLY
);
4241 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
4242 "write_file code=%d, filename=\"%s\" (%d), "
4243 "type=\"%s\", filestats=%p",
4244 code
, filename
, con
->file
, type
? type
: "(null)", filestats
);
4249 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
4253 if (!cupsdSendHeader(con
, code
, type
, CUPSD_AUTH_NONE
))
4256 if (httpPrintf(con
->http
, "Last-Modified: %s\r\n",
4257 httpGetDateString(filestats
->st_mtime
)) < 0)
4259 if (httpPrintf(con
->http
, "Content-Length: " CUPS_LLFMT
"\r\n",
4260 CUPS_LLCAST filestats
->st_size
) < 0)
4262 if (httpPrintf(con
->http
, "\r\n") < 0)
4265 if (cupsdFlushHeader(con
) < 0)
4268 con
->http
->data_encoding
= HTTP_ENCODING_LENGTH
;
4269 con
->http
->data_remaining
= filestats
->st_size
;
4271 if (con
->http
->data_remaining
<= INT_MAX
)
4272 con
->http
->_data_remaining
= con
->http
->data_remaining
;
4274 con
->http
->_data_remaining
= INT_MAX
;
4276 cupsdAddSelect(httpGetFd(con
->http
), (cupsd_selfunc_t
)cupsdReadClient
,
4277 (cupsd_selfunc_t
)cupsdWriteClient
, con
);
4279 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Sending file.");
4286 * 'write_pipe()' - Flag that data is available on the CGI pipe.
4290 write_pipe(cupsd_client_t
*con
) /* I - Client connection */
4292 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "write_pipe CGI output on fd %d",
4295 con
->file_ready
= 1;
4297 cupsdRemoveSelect(con
->file
);
4298 cupsdAddSelect(httpGetFd(con
->http
), NULL
, (cupsd_selfunc_t
)cupsdWriteClient
, con
);
4300 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "CGI data ready to be sent.");