4 * Client routines for the CUPS scheduler.
6 * Copyright 2007-2014 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 * Include necessary headers...
27 #endif /* __APPLE__ */
30 #endif /* HAVE_TCPD_H */
37 static const char * const http_states
[] =
38 { /* HTTP state strings */
43 "HTTP_STATE_GET_SEND",
46 "HTTP_STATE_POST_RECV",
47 "HTTP_STATE_POST_SEND",
49 "HTTP_STATE_PUT_RECV",
54 "HTTP_STATE_UNKNOWN_METHOD",
55 "HTTP_STATE_UNKNOWN_VERSION"
57 static const char * const ipp_states
[] =
58 { /* IPP state strings */
70 static int check_if_modified(cupsd_client_t
*con
,
71 struct stat
*filestats
);
72 static int compare_clients(cupsd_client_t
*a
, cupsd_client_t
*b
,
74 static int data_ready(cupsd_client_t
*con
);
75 static char *get_file(cupsd_client_t
*con
, struct stat
*filestats
,
76 char *filename
, int len
);
77 static http_status_t
install_cupsd_conf(cupsd_client_t
*con
);
78 static int is_cgi(cupsd_client_t
*con
, const char *filename
,
79 struct stat
*filestats
, mime_type_t
*type
);
80 static int is_path_absolute(const char *path
);
81 static int pipe_command(cupsd_client_t
*con
, int infile
, int *outfile
,
82 char *command
, char *options
, int root
);
83 static int valid_host(cupsd_client_t
*con
);
84 static int write_file(cupsd_client_t
*con
, http_status_t code
,
85 char *filename
, char *type
,
86 struct stat
*filestats
);
87 static void write_pipe(cupsd_client_t
*con
);
91 * 'cupsdAcceptClient()' - Accept a new client.
95 cupsdAcceptClient(cupsd_listener_t
*lis
)/* I - Listener socket */
97 int count
; /* Count of connections on a host */
98 int val
; /* Parameter value */
99 cupsd_client_t
*con
, /* New client pointer */
100 *tempcon
; /* Temporary client pointer */
101 http_addrlist_t
*addrlist
, /* List of adddresses for host */
102 *addr
; /* Current address */
103 socklen_t addrlen
; /* Length of address */
104 char *hostname
; /* Hostname for address */
105 http_addr_t temp
; /* Temporary address variable */
106 static time_t last_dos
= 0; /* Time of last DoS attack */
108 struct request_info wrap_req
; /* TCP wrappers request information */
109 #endif /* HAVE_TCPD_H */
112 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
113 "cupsdAcceptClient(lis=%p(%d)) Clients=%d",
114 lis
, lis
->fd
, cupsArrayCount(Clients
));
117 * Make sure we don't have a full set of clients already...
120 if (cupsArrayCount(Clients
) == MaxClients
)
124 * Get a pointer to the next available client...
128 Clients
= cupsArrayNew(NULL
, NULL
);
132 cupsdLogMessage(CUPSD_LOG_ERROR
,
133 "Unable to allocate memory for clients array!");
134 cupsdPauseListening();
139 ActiveClients
= cupsArrayNew((cups_array_func_t
)compare_clients
, NULL
);
143 cupsdLogMessage(CUPSD_LOG_ERROR
,
144 "Unable to allocate memory for active clients array!");
145 cupsdPauseListening();
149 if ((con
= calloc(1, sizeof(cupsd_client_t
))) == NULL
)
151 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to allocate memory for client!");
152 cupsdPauseListening();
157 con
->http
.activity
= time(NULL
);
158 con
->http
.hostaddr
= &(con
->clientaddr
);
159 con
->http
.wait_value
= 10000;
160 con
->http
.mode
= _HTTP_MODE_SERVER
;
163 * Accept the client and get the remote address...
166 addrlen
= sizeof(http_addr_t
);
168 if ((con
->http
.fd
= accept(lis
->fd
, (struct sockaddr
*)con
->http
.hostaddr
,
171 if (errno
== ENFILE
|| errno
== EMFILE
)
172 cupsdPauseListening();
174 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to accept client connection - %s.",
182 * Save the connected port number...
185 _httpAddrSetPort(con
->http
.hostaddr
, httpAddrPort(&(lis
->address
)));
189 * Convert IPv4 over IPv6 addresses (::ffff:n.n.n.n) to IPv4 forms we
190 * can more easily use...
193 if (lis
->address
.addr
.sa_family
== AF_INET6
&&
194 con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[0] == 0 &&
195 con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[1] == 0 &&
196 ntohl(con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[2]) == 0xffff)
197 con
->http
.hostaddr
->ipv6
.sin6_addr
.s6_addr32
[2] = 0;
198 #endif /* AF_INET6 */
201 * Check the number of clients on the same address...
204 for (count
= 0, tempcon
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
206 tempcon
= (cupsd_client_t
*)cupsArrayNext(Clients
))
207 if (httpAddrEqual(tempcon
->http
.hostaddr
, con
->http
.hostaddr
))
210 if (count
>= MaxClientsPerHost
)
214 if (count
>= MaxClientsPerHost
)
216 if ((time(NULL
) - last_dos
) >= 60)
218 last_dos
= time(NULL
);
219 cupsdLogMessage(CUPSD_LOG_WARN
,
220 "Possible DoS attack - more than %d clients connecting "
223 httpAddrString(con
->http
.hostaddr
, con
->http
.hostname
,
224 sizeof(con
->http
.hostname
)));
228 closesocket(con
->http
.fd
);
238 * Get the hostname or format the IP address as needed...
241 if (httpAddrLocalhost(con
->http
.hostaddr
))
244 * Map accesses from the loopback interface to "localhost"...
247 strlcpy(con
->http
.hostname
, "localhost", sizeof(con
->http
.hostname
));
248 hostname
= con
->http
.hostname
;
253 * Map accesses from the same host to the server name.
257 hostname
= httpAddrLookup(con
->http
.hostaddr
, con
->http
.hostname
,
258 sizeof(con
->http
.hostname
));
262 httpAddrString(con
->http
.hostaddr
, con
->http
.hostname
,
263 sizeof(con
->http
.hostname
));
267 if (hostname
== NULL
&& HostNameLookups
== 2)
270 * Can't have an unresolved IP address with double-lookups enabled...
274 closesocket(con
->http
.fd
);
279 cupsdLogMessage(CUPSD_LOG_WARN
,
280 "Name lookup failed - connection from %s closed!",
287 if (HostNameLookups
== 2)
290 * Do double lookups as needed...
293 if ((addrlist
= httpAddrGetList(con
->http
.hostname
, AF_UNSPEC
, NULL
))
297 * See if the hostname maps to the same IP address...
300 for (addr
= addrlist
; addr
; addr
= addr
->next
)
301 if (httpAddrEqual(con
->http
.hostaddr
, &(addr
->addr
)))
307 httpAddrFreeList(addrlist
);
312 * Can't have a hostname that doesn't resolve to the same IP address
313 * with double-lookups enabled...
317 closesocket(con
->http
.fd
);
322 cupsdLogMessage(CUPSD_LOG_WARN
,
323 "IP lookup failed - connection from %s closed!",
332 * See if the connection is denied by TCP wrappers...
335 request_init(&wrap_req
, RQ_DAEMON
, "cupsd", RQ_FILE
, con
->http
.fd
, NULL
);
338 if (!hosts_access(&wrap_req
))
341 closesocket(con
->http
.fd
);
346 cupsdLogMessage(CUPSD_LOG_WARN
,
347 "Connection from %s refused by /etc/hosts.allow and "
348 "/etc/hosts.deny rules.", con
->http
.hostname
);
352 #endif /* HAVE_TCPD_H */
355 if (con
->http
.hostaddr
->addr
.sa_family
== AF_LOCAL
)
358 socklen_t peersize
; /* Size of peer credentials */
359 pid_t peerpid
; /* Peer process ID */
360 char name
[256]; /* Name of process */
362 peersize
= sizeof(peerpid
);
363 if (!getsockopt(con
->http
.fd
, SOL_LOCAL
, LOCAL_PEERPID
, &peerpid
,
366 if (!proc_name(peerpid
, name
, sizeof(name
)))
367 cupsdLogMessage(CUPSD_LOG_DEBUG
,
368 "[Client %d] Accepted from %s (Domain ???[%d])",
369 con
->http
.fd
, con
->http
.hostname
, (int)peerpid
);
371 cupsdLogMessage(CUPSD_LOG_DEBUG
,
372 "[Client %d] Accepted from %s (Domain %s[%d])",
373 con
->http
.fd
, con
->http
.hostname
, name
, (int)peerpid
);
376 # endif /* __APPLE__ */
378 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[Client %d] Accepted from %s (Domain)",
379 con
->http
.fd
, con
->http
.hostname
);
382 #endif /* AF_LOCAL */
383 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[Client %d] Accepted from %s:%d (IPv%d)",
384 con
->http
.fd
, con
->http
.hostname
,
385 httpAddrPort(con
->http
.hostaddr
),
386 _httpAddrFamily(con
->http
.hostaddr
) == AF_INET
? 4 : 6);
389 * Get the local address the client connected to...
392 addrlen
= sizeof(temp
);
393 if (getsockname(con
->http
.fd
, (struct sockaddr
*)&temp
, &addrlen
))
395 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to get local address - %s",
398 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
399 con
->serverport
= LocalPort
;
402 else if (_httpAddrFamily(&temp
) == AF_LOCAL
)
404 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
405 con
->serverport
= LocalPort
;
407 #endif /* AF_LOCAL */
410 if (httpAddrLocalhost(&temp
))
411 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
412 else if (HostNameLookups
)
413 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
415 httpAddrString(&temp
, con
->servername
, sizeof(con
->servername
));
417 con
->serverport
= httpAddrPort(&(lis
->address
));
421 * Add the connection to the array of active clients...
424 cupsArrayAdd(Clients
, con
);
427 * Using TCP_NODELAY improves responsiveness, especially on systems with a slow
428 * loopback interface. Since we write large buffers when sending print files
429 * and requests there shouldn't be any performance penalty for this...
433 setsockopt(con
->http
.fd
, IPPROTO_TCP
, TCP_NODELAY
, &val
, sizeof(val
));
436 * Close this file on all execs...
439 fcntl(con
->http
.fd
, F_SETFD
, fcntl(con
->http
.fd
, F_GETFD
) | FD_CLOEXEC
);
442 * Add the socket to the server select.
445 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
447 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[Client %d] Waiting for request.",
451 * Temporarily suspend accept()'s until we lose a client...
454 if (cupsArrayCount(Clients
) == MaxClients
)
455 cupsdPauseListening();
459 * See if we are connecting on a secure port...
462 if (lis
->encryption
== HTTP_ENCRYPT_ALWAYS
)
465 * https connection; go secure...
468 con
->http
.encryption
= HTTP_ENCRYPT_ALWAYS
;
470 if (!cupsdStartTLS(con
))
471 cupsdCloseClient(con
);
475 #endif /* HAVE_SSL */
480 * 'cupsdCloseAllClients()' - Close all remote clients immediately.
484 cupsdCloseAllClients(void)
486 cupsd_client_t
*con
; /* Current client */
489 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdCloseAllClients() Clients=%d",
490 cupsArrayCount(Clients
));
492 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
494 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
495 if (cupsdCloseClient(con
))
496 cupsdCloseClient(con
);
501 * 'cupsdCloseClient()' - Close a remote client.
504 int /* O - 1 if partial close, 0 if fully closed */
505 cupsdCloseClient(cupsd_client_t
*con
) /* I - Client to close */
507 int partial
; /* Do partial close for SSL? */
509 #elif defined(HAVE_GNUTLS)
510 # elif defined(HAVE_CDSASSL)
511 #endif /* HAVE_LIBSSL */
514 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[Client %d] Closing connection.",
518 * Flush pending writes before closing...
521 httpFlushWrite(HTTP(con
));
527 * Shutdown encryption as needed...
536 #endif /* HAVE_SSL */
538 if (con
->pipe_pid
!= 0)
541 * Stop any CGI process...
544 cupsdEndProcess(con
->pipe_pid
, 1);
550 cupsdRemoveSelect(con
->file
);
557 * Close the socket and clear the file from the input set for select()...
560 if (con
->http
.fd
>= 0)
562 cupsArrayRemove(ActiveClients
, con
);
568 * Only do a partial close so that the encrypted client gets everything.
571 shutdown(con
->http
.fd
, 0);
572 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
574 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[Client %d] Waiting for socket close.",
580 * Shut the socket down fully...
583 cupsdRemoveSelect(con
->http
.fd
);
595 if (con
->http
.input_set
)
596 free(con
->http
.input_set
);
598 httpClearCookie(HTTP(con
));
599 httpClearFields(HTTP(con
));
601 cupsdClearString(&con
->filename
);
602 cupsdClearString(&con
->command
);
603 cupsdClearString(&con
->options
);
604 cupsdClearString(&con
->query_string
);
608 ippDelete(con
->request
);
614 ippDelete(con
->response
);
615 con
->response
= NULL
;
620 cupsLangFree(con
->language
);
621 con
->language
= NULL
;
624 #ifdef HAVE_AUTHORIZATION_H
627 AuthorizationFree(con
->authref
, kAuthorizationFlagDefaults
);
630 #endif /* HAVE_AUTHORIZATION_H */
633 * Re-enable new client connections if we are going back under the
637 if (cupsArrayCount(Clients
) == MaxClients
)
638 cupsdResumeListening();
641 * Compact the list of clients as necessary...
644 cupsArrayRemove(Clients
, con
);
654 * 'cupsdFlushHeader()' - Flush the header fields to the client.
657 int /* I - Bytes written or -1 on error */
658 cupsdFlushHeader(cupsd_client_t
*con
) /* I - Client to flush to */
660 int bytes
= httpFlushWrite(HTTP(con
));
662 con
->http
.data_encoding
= HTTP_ENCODING_LENGTH
;
669 * 'cupsdReadClient()' - Read data from a client.
673 cupsdReadClient(cupsd_client_t
*con
) /* I - Client to read from */
675 char line
[32768], /* Line from client... */
676 operation
[64], /* Operation code from socket */
677 version
[64], /* HTTP version number string */
678 locale
[64], /* Locale */
679 *ptr
; /* Pointer into strings */
680 int major
, minor
; /* HTTP version numbers */
681 http_status_t status
; /* Transfer status */
682 ipp_state_t ipp_state
; /* State of IPP transfer */
683 int bytes
; /* Number of bytes to POST */
684 char *filename
; /* Name of file for GET/HEAD */
685 char buf
[1024]; /* Buffer for real filename */
686 struct stat filestats
; /* File information */
687 mime_type_t
*type
; /* MIME type of file */
688 cupsd_printer_t
*p
; /* Printer */
689 static unsigned request_id
= 0; /* Request ID for temp files */
692 status
= HTTP_CONTINUE
;
694 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
695 "[Client %d] cupsdReadClient "
699 "data_encoding=HTTP_ENCODING_%s, "
700 "data_remaining=" CUPS_LLFMT
", "
703 con
->http
.fd
, con
->http
.error
, con
->http
.used
,
704 http_states
[con
->http
.state
+ 1],
705 con
->http
.data_encoding
== HTTP_ENCODING_CHUNKED
?
706 "CHUNKED" : "LENGTH",
707 CUPS_LLCAST con
->http
.data_remaining
,
709 con
->request
? ipp_states
[con
->request
->state
] : "",
716 * Automatically check for a SSL/TLS handshake...
721 if (recv(con
->http
.fd
, buf
, 1, MSG_PEEK
) == 1 &&
722 (!buf
[0] || !strchr("DGHOPT", buf
[0])))
725 * Encrypt this connection...
728 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
729 "[Client %d] Saw first byte %02X, auto-negotiating "
730 "SSL/TLS session.", con
->http
.fd
, buf
[0] & 255);
732 if (!cupsdStartTLS(con
))
733 cupsdCloseClient(con
);
738 #endif /* HAVE_SSL */
740 switch (con
->http
.state
)
742 case HTTP_STATE_WAITING
:
744 * See if we've received a request line...
747 if (httpGets(line
, sizeof(line
) - 1, HTTP(con
)) == NULL
)
749 if (con
->http
.error
&& con
->http
.error
!= EPIPE
)
750 cupsdLogMessage(CUPSD_LOG_DEBUG
,
751 "[Client %d] HTTP_STATE_WAITING Closing for error %d "
752 "(%s)", con
->http
.fd
, con
->http
.error
,
753 strerror(con
->http
.error
));
755 cupsdLogMessage(CUPSD_LOG_DEBUG
,
756 "[Client %d] HTTP_STATE_WAITING Closing on EOF",
759 cupsdCloseClient(con
);
764 * Ignore blank request lines...
771 * Clear other state variables...
774 httpClearFields(HTTP(con
));
776 con
->http
.activity
= time(NULL
);
777 con
->http
.version
= HTTP_1_0
;
778 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
779 con
->http
.data_encoding
= HTTP_ENCODING_LENGTH
;
780 con
->http
.data_remaining
= 0;
781 con
->http
._data_remaining
= 0;
782 con
->operation
= HTTP_STATE_WAITING
;
787 con
->username
[0] = '\0';
788 con
->password
[0] = '\0';
791 cupsdClearString(&con
->command
);
792 cupsdClearString(&con
->options
);
793 cupsdClearString(&con
->query_string
);
797 ippDelete(con
->request
);
803 ippDelete(con
->response
);
804 con
->response
= NULL
;
809 cupsLangFree(con
->language
);
810 con
->language
= NULL
;
816 #endif /* HAVE_GSSAPI */
819 * Grab the request line...
822 switch (sscanf(line
, "%63s%1023s%63s", operation
, con
->uri
, version
))
827 cupsdLogMessage(CUPSD_LOG_ERROR
,
828 "[Client %d] Bad request line \"%s\" from %s.",
830 _httpEncodeURI(buf
, line
, sizeof(buf
)),
832 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
833 cupsdCloseClient(con
);
837 con
->http
.version
= HTTP_0_9
;
840 if (sscanf(version
, "HTTP/%d.%d", &major
, &minor
) != 2)
842 cupsdLogMessage(CUPSD_LOG_ERROR
,
843 "[Client %d] Bad request line \"%s\" from %s.",
845 _httpEncodeURI(buf
, line
, sizeof(buf
)),
847 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
848 cupsdCloseClient(con
);
854 con
->http
.version
= (http_version_t
)(major
* 100 + minor
);
855 if (con
->http
.version
== HTTP_1_1
&& KeepAlive
)
856 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
858 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
862 cupsdLogMessage(CUPSD_LOG_ERROR
,
863 "[Client %d] Unsupported request line \"%s\" "
864 "from %s.", con
->http
.fd
,
865 _httpEncodeURI(buf
, line
, sizeof(buf
)),
867 cupsdSendError(con
, HTTP_NOT_SUPPORTED
, CUPSD_AUTH_NONE
);
868 cupsdCloseClient(con
);
875 * Handle full URLs in the request line...
878 if (strcmp(con
->uri
, "*"))
880 char scheme
[HTTP_MAX_URI
], /* Method/scheme */
881 userpass
[HTTP_MAX_URI
], /* Username:password */
882 hostname
[HTTP_MAX_URI
], /* Hostname */
883 resource
[HTTP_MAX_URI
]; /* Resource path */
884 int port
; /* Port number */
888 * Separate the URI into its components...
891 httpSeparateURI(HTTP_URI_CODING_MOST
, con
->uri
,
892 scheme
, sizeof(scheme
),
893 userpass
, sizeof(userpass
),
894 hostname
, sizeof(hostname
), &port
,
895 resource
, sizeof(resource
));
898 * Only allow URIs with the servername, localhost, or an IP
902 if (strcmp(scheme
, "file") &&
903 _cups_strcasecmp(hostname
, ServerName
) &&
904 _cups_strcasecmp(hostname
, "localhost") &&
905 !isdigit(hostname
[0]) && hostname
[0] != '[')
908 * Nope, we don't do proxies...
911 cupsdLogMessage(CUPSD_LOG_ERROR
,
912 "[Client %d] Bad URI \"%s\" in request.",
913 con
->http
.fd
, con
->uri
);
914 cupsdSendError(con
, HTTP_METHOD_NOT_ALLOWED
, CUPSD_AUTH_NONE
);
915 cupsdCloseClient(con
);
920 * Copy the resource portion back into the URI; both resource and
921 * con->uri are HTTP_MAX_URI bytes in size...
924 strlcpy(con
->uri
, resource
, sizeof(con
->uri
));
928 * Process the request...
931 if (!strcmp(operation
, "GET"))
932 con
->http
.state
= HTTP_STATE_GET
;
933 else if (!strcmp(operation
, "PUT"))
934 con
->http
.state
= HTTP_STATE_PUT
;
935 else if (!strcmp(operation
, "POST"))
936 con
->http
.state
= HTTP_STATE_POST
;
937 else if (!strcmp(operation
, "DELETE"))
938 con
->http
.state
= HTTP_STATE_DELETE
;
939 else if (!strcmp(operation
, "TRACE"))
940 con
->http
.state
= HTTP_STATE_TRACE
;
941 else if (!strcmp(operation
, "OPTIONS"))
942 con
->http
.state
= HTTP_STATE_OPTIONS
;
943 else if (!strcmp(operation
, "HEAD"))
944 con
->http
.state
= HTTP_STATE_HEAD
;
947 cupsdLogMessage(CUPSD_LOG_ERROR
,
948 "[Client %d] Bad operation \"%s\".", con
->http
.fd
,
950 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
951 cupsdCloseClient(con
);
955 gettimeofday(&(con
->start
), NULL
);
956 con
->operation
= con
->http
.state
;
958 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[Client %d] %s %s HTTP/%d.%d",
959 con
->http
.fd
, operation
, con
->uri
,
960 con
->http
.version
/ 100, con
->http
.version
% 100);
962 con
->http
.status
= HTTP_OK
;
964 if (!cupsArrayFind(ActiveClients
, con
))
966 cupsArrayAdd(ActiveClients
, con
);
970 case HTTP_STATE_OPTIONS
:
971 case HTTP_STATE_DELETE
:
972 case HTTP_STATE_GET
:
973 case HTTP_STATE_HEAD
:
974 case HTTP_STATE_POST
:
975 case HTTP_STATE_PUT
:
976 case HTTP_STATE_TRACE
:
978 * Parse incoming parameters until the status changes...
981 while ((status
= httpUpdate(HTTP(con
))) == HTTP_CONTINUE
)
982 if (!data_ready(con
))
985 if (status
!= HTTP_OK
&& status
!= HTTP_CONTINUE
)
987 if (con
->http
.error
&& con
->http
.error
!= EPIPE
)
988 cupsdLogMessage(CUPSD_LOG_DEBUG
,
989 "[Client %d] Closing for error %d (%s) while "
991 con
->http
.fd
, con
->http
.error
,
992 strerror(con
->http
.error
));
994 cupsdLogMessage(CUPSD_LOG_DEBUG
,
995 "[Client %d] Closing on EOF while reading headers.",
998 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
999 cupsdCloseClient(con
);
1005 if (!data_ready(con
) && recv(con
->http
.fd
, buf
, 1, MSG_PEEK
) < 1)
1008 * Connection closed...
1011 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1012 "[Client %d] Closing on EOF", con
->http
.fd
);
1013 cupsdCloseClient(con
);
1016 break; /* Anti-compiler-warning-code */
1020 * Handle new transfers...
1023 if (status
== HTTP_OK
)
1025 if (con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
][0])
1028 * Figure out the locale from the Accept-Language and Content-Type
1032 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
],
1036 if ((ptr
= strchr(con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
],
1040 if ((ptr
= strstr(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
],
1041 "charset=")) != NULL
)
1044 * Combine language and charset, and trim any extra params in the
1048 snprintf(locale
, sizeof(locale
), "%s.%s",
1049 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
], ptr
+ 8);
1051 if ((ptr
= strchr(locale
, ',')) != NULL
)
1055 snprintf(locale
, sizeof(locale
), "%s.UTF-8",
1056 con
->http
.fields
[HTTP_FIELD_ACCEPT_LANGUAGE
]);
1058 con
->language
= cupsLangGet(locale
);
1061 con
->language
= cupsLangGet(DefaultLocale
);
1063 cupsdAuthorize(con
);
1065 if (!_cups_strncasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
],
1066 "Keep-Alive", 10) && KeepAlive
)
1067 con
->http
.keep_alive
= HTTP_KEEPALIVE_ON
;
1068 else if (!_cups_strncasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
],
1070 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1072 if (!con
->http
.fields
[HTTP_FIELD_HOST
][0] &&
1073 con
->http
.version
>= HTTP_1_1
)
1076 * HTTP/1.1 and higher require the "Host:" field...
1079 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1081 cupsdLogMessage(CUPSD_LOG_ERROR
,
1082 "[Client %d] Missing Host: field in request.",
1084 cupsdCloseClient(con
);
1088 else if (!valid_host(con
))
1091 * Access to localhost must use "localhost" or the corresponding IPv4
1092 * or IPv6 values in the Host: field.
1095 cupsdLogMessage(CUPSD_LOG_ERROR
,
1096 "[Client %d] Request from \"%s\" using invalid Host: "
1097 "field \"%s\"", con
->http
.fd
, con
->http
.hostname
,
1098 con
->http
.fields
[HTTP_FIELD_HOST
]);
1100 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1102 cupsdCloseClient(con
);
1106 else if (con
->operation
== HTTP_STATE_OPTIONS
)
1109 * Do OPTIONS command...
1112 if (con
->best
&& con
->best
->type
!= CUPSD_AUTH_NONE
)
1114 if (!cupsdSendHeader(con
, HTTP_UNAUTHORIZED
, NULL
, CUPSD_AUTH_NONE
))
1116 cupsdCloseClient(con
);
1121 if (!_cups_strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
], "Upgrade") &&
1122 con
->http
.tls
== NULL
)
1126 * Do encryption stuff...
1129 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
, CUPSD_AUTH_NONE
))
1131 cupsdCloseClient(con
);
1135 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1136 httpPrintf(HTTP(con
), "Upgrade: TLS/1.2,TLS/1.1,TLS/1.0\r\n");
1137 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1138 httpPrintf(HTTP(con
), "\r\n");
1140 if (cupsdFlushHeader(con
) < 0)
1142 cupsdCloseClient(con
);
1146 if (!cupsdStartTLS(con
))
1148 cupsdCloseClient(con
);
1152 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
1154 cupsdCloseClient(con
);
1157 #endif /* HAVE_SSL */
1160 if (!cupsdSendHeader(con
, HTTP_OK
, NULL
, CUPSD_AUTH_NONE
))
1162 cupsdCloseClient(con
);
1166 httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n");
1167 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1168 httpPrintf(HTTP(con
), "\r\n");
1170 if (cupsdFlushHeader(con
) < 0)
1172 cupsdCloseClient(con
);
1176 else if (!is_path_absolute(con
->uri
))
1179 * Protect against malicious users!
1182 cupsdLogMessage(CUPSD_LOG_ERROR
,
1183 "[Client %d] Request for non-absolute resource \"%s\".",
1184 con
->http
.fd
, con
->uri
);
1186 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1188 cupsdCloseClient(con
);
1194 if (!_cups_strcasecmp(con
->http
.fields
[HTTP_FIELD_CONNECTION
],
1195 "Upgrade") && con
->http
.tls
== NULL
)
1199 * Do encryption stuff...
1202 if (!cupsdSendHeader(con
, HTTP_SWITCHING_PROTOCOLS
, NULL
,
1205 cupsdCloseClient(con
);
1209 httpPrintf(HTTP(con
), "Connection: Upgrade\r\n");
1210 httpPrintf(HTTP(con
), "Upgrade: TLS/1.2,TLS/1.1,TLS/1.0\r\n");
1211 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1212 httpPrintf(HTTP(con
), "\r\n");
1214 if (cupsdFlushHeader(con
) < 0)
1216 cupsdCloseClient(con
);
1220 if (!cupsdStartTLS(con
))
1222 cupsdCloseClient(con
);
1226 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
1228 cupsdCloseClient(con
);
1231 #endif /* HAVE_SSL */
1234 if ((status
= cupsdIsAuthorized(con
, NULL
)) != HTTP_OK
)
1236 cupsdSendError(con
, status
, CUPSD_AUTH_NONE
);
1237 cupsdCloseClient(con
);
1241 if (con
->http
.expect
&&
1242 (con
->operation
== HTTP_STATE_POST
|| con
->operation
== HTTP_STATE_PUT
))
1244 if (con
->http
.expect
== HTTP_CONTINUE
)
1247 * Send 100-continue header...
1250 if (!cupsdSendHeader(con
, HTTP_CONTINUE
, NULL
, CUPSD_AUTH_NONE
))
1252 cupsdCloseClient(con
);
1259 * Send 417-expectation-failed header...
1262 if (!cupsdSendHeader(con
, HTTP_EXPECTATION_FAILED
, NULL
,
1265 cupsdCloseClient(con
);
1269 httpPrintf(HTTP(con
), "Content-Length: 0\r\n");
1270 httpPrintf(HTTP(con
), "\r\n");
1272 if (cupsdFlushHeader(con
) < 0)
1274 cupsdCloseClient(con
);
1280 switch (con
->http
.state
)
1282 case HTTP_STATE_GET_SEND
:
1283 if ((!strncmp(con
->uri
, "/ppd/", 5) ||
1284 !strncmp(con
->uri
, "/printers/", 10) ||
1285 !strncmp(con
->uri
, "/classes/", 9)) &&
1286 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1289 * Send PPD file - get the real printer name since printer
1290 * names are not case sensitive but filenames can be...
1293 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1295 if (!strncmp(con
->uri
, "/ppd/", 5))
1296 p
= cupsdFindPrinter(con
->uri
+ 5);
1297 else if (!strncmp(con
->uri
, "/printers/", 10))
1298 p
= cupsdFindPrinter(con
->uri
+ 10);
1301 p
= cupsdFindClass(con
->uri
+ 9);
1305 int i
; /* Looping var */
1307 for (i
= 0; i
< p
->num_printers
; i
++)
1309 if (!(p
->printers
[i
]->type
& CUPS_PRINTER_CLASS
))
1311 char ppdname
[1024];/* PPD filename */
1313 snprintf(ppdname
, sizeof(ppdname
), "%s/ppd/%s.ppd",
1314 ServerRoot
, p
->printers
[i
]->name
);
1315 if (!access(ppdname
, 0))
1323 if (i
>= p
->num_printers
)
1330 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1334 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1336 cupsdCloseClient(con
);
1343 else if ((!strncmp(con
->uri
, "/icons/", 7) ||
1344 !strncmp(con
->uri
, "/printers/", 10) ||
1345 !strncmp(con
->uri
, "/classes/", 9)) &&
1346 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".png"))
1349 * Send icon file - get the real queue name since queue names are
1350 * not case sensitive but filenames can be...
1353 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".png" */
1355 if (!strncmp(con
->uri
, "/icons/", 7))
1356 p
= cupsdFindPrinter(con
->uri
+ 7);
1357 else if (!strncmp(con
->uri
, "/printers/", 10))
1358 p
= cupsdFindPrinter(con
->uri
+ 10);
1361 p
= cupsdFindClass(con
->uri
+ 9);
1365 int i
; /* Looping var */
1367 for (i
= 0; i
< p
->num_printers
; i
++)
1369 if (!(p
->printers
[i
]->type
& CUPS_PRINTER_CLASS
))
1371 char ppdname
[1024];/* PPD filename */
1373 snprintf(ppdname
, sizeof(ppdname
), "%s/ppd/%s.ppd",
1374 ServerRoot
, p
->printers
[i
]->name
);
1375 if (!access(ppdname
, 0))
1383 if (i
>= p
->num_printers
)
1389 snprintf(con
->uri
, sizeof(con
->uri
), "/icons/%s.png", p
->name
);
1392 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1394 cupsdCloseClient(con
);
1401 else if (!WebInterface
)
1404 * Web interface is disabled. Show an appropriate message...
1407 if (!cupsdSendError(con
, HTTP_WEBIF_DISABLED
, CUPSD_AUTH_NONE
))
1409 cupsdCloseClient(con
);
1416 if ((!strncmp(con
->uri
, "/admin", 6) &&
1417 strncmp(con
->uri
, "/admin/conf/", 12) &&
1418 strncmp(con
->uri
, "/admin/log/", 11)) ||
1419 !strncmp(con
->uri
, "/printers", 9) ||
1420 !strncmp(con
->uri
, "/classes", 8) ||
1421 !strncmp(con
->uri
, "/help", 5) ||
1422 !strncmp(con
->uri
, "/jobs", 5))
1425 * Send CGI output...
1428 if (!strncmp(con
->uri
, "/admin", 6))
1430 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1433 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1435 else if (!strncmp(con
->uri
, "/printers", 9))
1437 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1440 if (con
->uri
[9] && con
->uri
[10])
1441 cupsdSetString(&con
->options
, con
->uri
+ 9);
1443 cupsdSetString(&con
->options
, NULL
);
1445 else if (!strncmp(con
->uri
, "/classes", 8))
1447 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1450 if (con
->uri
[8] && con
->uri
[9])
1451 cupsdSetString(&con
->options
, con
->uri
+ 8);
1453 cupsdSetString(&con
->options
, NULL
);
1455 else if (!strncmp(con
->uri
, "/jobs", 5))
1457 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1460 if (con
->uri
[5] && con
->uri
[6])
1461 cupsdSetString(&con
->options
, con
->uri
+ 5);
1463 cupsdSetString(&con
->options
, NULL
);
1467 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1470 if (con
->uri
[5] && con
->uri
[6])
1471 cupsdSetString(&con
->options
, con
->uri
+ 5);
1473 cupsdSetString(&con
->options
, NULL
);
1476 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1478 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1480 cupsdCloseClient(con
);
1485 cupsdLogRequest(con
, HTTP_OK
);
1487 if (con
->http
.version
<= HTTP_1_0
)
1488 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1490 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1491 (strchr(con
->uri
+ 12, '/') ||
1492 strlen(con
->uri
) == 12)) ||
1493 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1494 (strchr(con
->uri
+ 11, '/') ||
1495 strlen(con
->uri
) == 11)))
1498 * GET can only be done to configuration files directly under
1502 cupsdLogMessage(CUPSD_LOG_ERROR
,
1503 "Request for subdirectory \"%s\"!", con
->uri
);
1505 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1507 cupsdCloseClient(con
);
1519 if ((filename
= get_file(con
, &filestats
, buf
,
1520 sizeof(buf
))) == NULL
)
1522 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1524 cupsdCloseClient(con
);
1531 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1533 if (is_cgi(con
, filename
, &filestats
, type
))
1536 * Note: con->command and con->options were set by
1540 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1542 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1544 cupsdCloseClient(con
);
1549 cupsdLogRequest(con
, HTTP_OK
);
1551 if (con
->http
.version
<= HTTP_1_0
)
1552 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1556 if (!check_if_modified(con
, &filestats
))
1558 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1560 cupsdCloseClient(con
);
1567 strlcpy(line
, "text/plain", sizeof(line
));
1569 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1571 if (!write_file(con
, HTTP_OK
, filename
, line
, &filestats
))
1573 cupsdCloseClient(con
);
1580 case HTTP_STATE_POST_RECV
:
1582 * See if the POST request includes a Content-Length field, and if
1583 * so check the length against any limits that are set...
1586 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1587 MaxRequestSize
> 0 &&
1588 con
->http
.data_remaining
> MaxRequestSize
)
1591 * Request too large...
1594 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1596 cupsdCloseClient(con
);
1602 else if (con
->http
.data_remaining
< 0 ||
1603 (!con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1604 con
->http
.data_encoding
== HTTP_ENCODING_LENGTH
))
1607 * Negative content lengths are invalid!
1610 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1612 cupsdCloseClient(con
);
1620 * See what kind of POST request this is; for IPP requests the
1621 * content-type field will be "application/ipp"...
1624 if (!strcmp(con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
],
1626 con
->request
= ippNew();
1627 else if (!WebInterface
)
1630 * Web interface is disabled. Show an appropriate message...
1633 if (!cupsdSendError(con
, HTTP_WEBIF_DISABLED
, CUPSD_AUTH_NONE
))
1635 cupsdCloseClient(con
);
1641 else if ((!strncmp(con
->uri
, "/admin", 6) &&
1642 strncmp(con
->uri
, "/admin/conf/", 12) &&
1643 strncmp(con
->uri
, "/admin/log/", 11)) ||
1644 !strncmp(con
->uri
, "/printers", 9) ||
1645 !strncmp(con
->uri
, "/classes", 8) ||
1646 !strncmp(con
->uri
, "/help", 5) ||
1647 !strncmp(con
->uri
, "/jobs", 5))
1653 if (!strncmp(con
->uri
, "/admin", 6))
1655 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1658 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1660 else if (!strncmp(con
->uri
, "/printers", 9))
1662 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1665 if (con
->uri
[9] && con
->uri
[10])
1666 cupsdSetString(&con
->options
, con
->uri
+ 9);
1668 cupsdSetString(&con
->options
, NULL
);
1670 else if (!strncmp(con
->uri
, "/classes", 8))
1672 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1675 if (con
->uri
[8] && con
->uri
[9])
1676 cupsdSetString(&con
->options
, con
->uri
+ 8);
1678 cupsdSetString(&con
->options
, NULL
);
1680 else if (!strncmp(con
->uri
, "/jobs", 5))
1682 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1685 if (con
->uri
[5] && con
->uri
[6])
1686 cupsdSetString(&con
->options
, con
->uri
+ 5);
1688 cupsdSetString(&con
->options
, NULL
);
1692 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1695 if (con
->uri
[5] && con
->uri
[6])
1696 cupsdSetString(&con
->options
, con
->uri
+ 5);
1698 cupsdSetString(&con
->options
, NULL
);
1701 if (con
->http
.version
<= HTTP_1_0
)
1702 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
1710 if ((filename
= get_file(con
, &filestats
, buf
,
1711 sizeof(buf
))) == NULL
)
1713 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1715 cupsdCloseClient(con
);
1722 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1724 if (!is_cgi(con
, filename
, &filestats
, type
))
1727 * Only POST to CGI's...
1730 if (!cupsdSendError(con
, HTTP_UNAUTHORIZED
, CUPSD_AUTH_NONE
))
1732 cupsdCloseClient(con
);
1739 case HTTP_STATE_PUT_RECV
:
1741 * Validate the resource name...
1744 if (strcmp(con
->uri
, "/admin/conf/cupsd.conf"))
1747 * PUT can only be done to the cupsd.conf file...
1750 cupsdLogMessage(CUPSD_LOG_ERROR
,
1751 "[Client %d] Disallowed PUT request for \"%s\".",
1752 con
->http
.fd
, con
->uri
);
1754 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1756 cupsdCloseClient(con
);
1764 * See if the PUT request includes a Content-Length field, and if
1765 * so check the length against any limits that are set...
1768 if (con
->http
.fields
[HTTP_FIELD_CONTENT_LENGTH
][0] &&
1769 MaxRequestSize
> 0 &&
1770 con
->http
.data_remaining
> MaxRequestSize
)
1773 * Request too large...
1776 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1778 cupsdCloseClient(con
);
1784 else if (con
->http
.data_remaining
< 0)
1787 * Negative content lengths are invalid!
1790 if (!cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1792 cupsdCloseClient(con
);
1800 * Open a temporary file to hold the request...
1803 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
1805 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1809 cupsdLogMessage(CUPSD_LOG_ERROR
,
1810 "[Client %d] Unable to create request file "
1811 "\"%s\": %s", con
->http
.fd
, con
->filename
,
1814 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1816 cupsdCloseClient(con
);
1821 fchmod(con
->file
, 0640);
1822 fchown(con
->file
, RunUser
, Group
);
1823 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1826 case HTTP_STATE_DELETE
:
1827 case HTTP_STATE_TRACE
:
1828 cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
);
1829 cupsdCloseClient(con
);
1832 case HTTP_STATE_HEAD
:
1833 if (!strncmp(con
->uri
, "/printers/", 10) &&
1834 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1837 * Send PPD 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
), "/ppd/%s.ppd", p
->name
);
1847 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1849 cupsdCloseClient(con
);
1856 else if (!strncmp(con
->uri
, "/printers/", 10) &&
1857 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".png"))
1860 * Send PNG file - get the real printer name since printer
1861 * names are not case sensitive but filenames can be...
1864 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1866 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1867 snprintf(con
->uri
, sizeof(con
->uri
), "/icons/%s.png", p
->name
);
1870 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
1872 cupsdCloseClient(con
);
1879 else if (!WebInterface
)
1881 if (!cupsdSendHeader(con
, HTTP_OK
, NULL
, CUPSD_AUTH_NONE
))
1883 cupsdCloseClient(con
);
1887 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1889 cupsdCloseClient(con
);
1893 if (cupsdFlushHeader(con
) < 0)
1895 cupsdCloseClient(con
);
1899 con
->http
.state
= HTTP_STATE_WAITING
;
1900 DEBUG_puts("cupsdReadClient: Set state to HTTP_STATE_WAITING "
1905 if ((!strncmp(con
->uri
, "/admin", 6) &&
1906 strncmp(con
->uri
, "/admin/conf/", 12) &&
1907 strncmp(con
->uri
, "/admin/log/", 11)) ||
1908 !strncmp(con
->uri
, "/printers", 9) ||
1909 !strncmp(con
->uri
, "/classes", 8) ||
1910 !strncmp(con
->uri
, "/help", 5) ||
1911 !strncmp(con
->uri
, "/jobs", 5))
1917 if (!cupsdSendHeader(con
, HTTP_OK
, "text/html", CUPSD_AUTH_NONE
))
1919 cupsdCloseClient(con
);
1923 if (httpPrintf(HTTP(con
), "\r\n") < 0)
1925 cupsdCloseClient(con
);
1929 if (cupsdFlushHeader(con
) < 0)
1931 cupsdCloseClient(con
);
1935 cupsdLogRequest(con
, HTTP_OK
);
1937 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1938 (strchr(con
->uri
+ 12, '/') ||
1939 strlen(con
->uri
) == 12)) ||
1940 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1941 (strchr(con
->uri
+ 11, '/') ||
1942 strlen(con
->uri
) == 11)))
1945 * HEAD can only be done to configuration files under
1949 cupsdLogMessage(CUPSD_LOG_ERROR
,
1950 "[Client %d] Request for subdirectory \"%s\".",
1951 con
->http
.fd
, con
->uri
);
1953 if (!cupsdSendError(con
, HTTP_FORBIDDEN
, CUPSD_AUTH_NONE
))
1955 cupsdCloseClient(con
);
1961 else if ((filename
= get_file(con
, &filestats
, buf
,
1962 sizeof(buf
))) == NULL
)
1964 if (!cupsdSendHeader(con
, HTTP_NOT_FOUND
, "text/html",
1967 cupsdCloseClient(con
);
1971 cupsdLogRequest(con
, HTTP_NOT_FOUND
);
1973 else if (!check_if_modified(con
, &filestats
))
1975 if (!cupsdSendError(con
, HTTP_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1977 cupsdCloseClient(con
);
1981 cupsdLogRequest(con
, HTTP_NOT_MODIFIED
);
1989 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1991 strlcpy(line
, "text/plain", sizeof(line
));
1993 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1995 if (!cupsdSendHeader(con
, HTTP_OK
, line
, CUPSD_AUTH_NONE
))
1997 cupsdCloseClient(con
);
2001 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
2002 httpGetDateString(filestats
.st_mtime
)) < 0)
2004 cupsdCloseClient(con
);
2008 if (httpPrintf(HTTP(con
), "Content-Length: %lu\r\n",
2009 (unsigned long)filestats
.st_size
) < 0)
2011 cupsdCloseClient(con
);
2015 cupsdLogRequest(con
, HTTP_OK
);
2018 if (httpPrintf(HTTP(con
), "\r\n") < 0)
2020 cupsdCloseClient(con
);
2024 if (cupsdFlushHeader(con
) < 0)
2026 cupsdCloseClient(con
);
2030 con
->http
.state
= HTTP_STATE_WAITING
;
2031 DEBUG_puts("cupsdReadClient: Set state to HTTP_STATE_WAITING "
2036 break; /* Anti-compiler-warning-code */
2042 * Handle any incoming data...
2045 switch (con
->http
.state
)
2047 case HTTP_STATE_PUT_RECV
:
2050 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
2052 if (con
->http
.error
&& con
->http
.error
!= EPIPE
)
2053 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2054 "[Client %d] HTTP_STATE_PUT_RECV Closing for error "
2055 "%d (%s)", con
->http
.fd
, con
->http
.error
,
2056 strerror(con
->http
.error
));
2058 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2059 "[Client %d] HTTP_STATE_PUT_RECV Closing on EOF",
2062 cupsdCloseClient(con
);
2067 con
->bytes
+= bytes
;
2069 if (write(con
->file
, line
, bytes
) < bytes
)
2071 cupsdLogMessage(CUPSD_LOG_ERROR
,
2072 "[Client %d] Unable to write %d bytes to "
2073 "\"%s\": %s", con
->http
.fd
, bytes
, con
->filename
,
2078 unlink(con
->filename
);
2079 cupsdClearString(&con
->filename
);
2081 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2083 cupsdCloseClient(con
);
2089 while (con
->http
.state
== HTTP_STATE_PUT_RECV
&& data_ready(con
));
2091 if (con
->http
.state
== HTTP_STATE_STATUS
)
2094 * End of file, see how big it is...
2097 fstat(con
->file
, &filestats
);
2102 if (filestats
.st_size
> MaxRequestSize
&&
2106 * Request is too big; remove it and send an error...
2109 unlink(con
->filename
);
2110 cupsdClearString(&con
->filename
);
2112 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2114 cupsdCloseClient(con
);
2120 * Install the configuration file...
2123 status
= install_cupsd_conf(con
);
2126 * Return the status to the client...
2129 if (!cupsdSendError(con
, status
, CUPSD_AUTH_NONE
))
2131 cupsdCloseClient(con
);
2137 case HTTP_STATE_POST_RECV
:
2140 if (con
->request
&& con
->file
< 0)
2143 * Grab any request data from the connection...
2146 if (!httpWait(HTTP(con
), 0))
2149 if ((ipp_state
= ippRead(&(con
->http
), con
->request
)) == IPP_ERROR
)
2151 cupsdLogMessage(CUPSD_LOG_ERROR
,
2152 "[Client %d] IPP read error: %s", con
->http
.fd
,
2153 cupsLastErrorString());
2155 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
2156 cupsdCloseClient(con
);
2159 else if (ipp_state
!= IPP_DATA
)
2161 if (con
->http
.state
== HTTP_STATE_POST_SEND
)
2163 cupsdSendError(con
, HTTP_BAD_REQUEST
, CUPSD_AUTH_NONE
);
2164 cupsdCloseClient(con
);
2168 if (data_ready(con
))
2174 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[Client %d] %d.%d %s %d",
2175 con
->http
.fd
, con
->request
->request
.op
.version
[0],
2176 con
->request
->request
.op
.version
[1],
2177 ippOpString(con
->request
->request
.op
.operation_id
),
2178 con
->request
->request
.op
.request_id
);
2179 con
->bytes
+= ippLength(con
->request
);
2183 if (con
->file
< 0 && con
->http
.state
!= HTTP_STATE_POST_SEND
)
2186 * Create a file as needed for the request data...
2189 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
2191 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
2195 cupsdLogMessage(CUPSD_LOG_ERROR
,
2196 "[Client %d] Unable to create request file "
2197 "\"%s\": %s", con
->http
.fd
, con
->filename
,
2200 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2202 cupsdCloseClient(con
);
2207 fchmod(con
->file
, 0640);
2208 fchown(con
->file
, RunUser
, Group
);
2209 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2212 if (con
->http
.state
!= HTTP_STATE_POST_SEND
)
2214 if (!httpWait(HTTP(con
), 0))
2217 if ((bytes
= httpRead2(HTTP(con
), line
, sizeof(line
))) < 0)
2219 if (con
->http
.error
&& con
->http
.error
!= EPIPE
)
2220 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2221 "[Client %d] HTTP_STATE_POST_SEND Closing for "
2222 "error %d (%s)", con
->http
.fd
, con
->http
.error
,
2223 strerror(con
->http
.error
));
2225 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2226 "[Client %d] HTTP_STATE_POST_SEND Closing on EOF",
2229 cupsdCloseClient(con
);
2234 con
->bytes
+= bytes
;
2236 if (write(con
->file
, line
, bytes
) < bytes
)
2238 cupsdLogMessage(CUPSD_LOG_ERROR
,
2239 "[Client %d] Unable to write %d bytes to "
2240 "\"%s\": %s", con
->http
.fd
, bytes
,
2241 con
->filename
, strerror(errno
));
2245 unlink(con
->filename
);
2246 cupsdClearString(&con
->filename
);
2248 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
,
2251 cupsdCloseClient(con
);
2256 else if (con
->http
.state
== HTTP_STATE_POST_RECV
)
2258 else if (con
->http
.state
!= HTTP_STATE_POST_SEND
)
2260 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2261 "[Client %d] Closing on unexpected state %s.",
2262 con
->http
.fd
, http_states
[con
->http
.state
+ 1]);
2263 cupsdCloseClient(con
);
2268 while (con
->http
.state
== HTTP_STATE_POST_RECV
&& data_ready(con
));
2270 if (con
->http
.state
== HTTP_STATE_POST_SEND
)
2274 fstat(con
->file
, &filestats
);
2279 if (filestats
.st_size
> MaxRequestSize
&&
2283 * Request is too big; remove it and send an error...
2286 unlink(con
->filename
);
2287 cupsdClearString(&con
->filename
);
2292 * Delete any IPP request data...
2295 ippDelete(con
->request
);
2296 con
->request
= NULL
;
2299 if (!cupsdSendError(con
, HTTP_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2301 cupsdCloseClient(con
);
2305 else if (filestats
.st_size
== 0)
2308 * Don't allow empty file...
2311 unlink(con
->filename
);
2312 cupsdClearString(&con
->filename
);
2317 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
2319 if (!cupsdSendError(con
, HTTP_NOT_FOUND
, CUPSD_AUTH_NONE
))
2321 cupsdCloseClient(con
);
2326 cupsdLogRequest(con
, HTTP_OK
);
2332 cupsdProcessIPPRequest(con
);
2336 unlink(con
->filename
);
2337 cupsdClearString(&con
->filename
);
2346 break; /* Anti-compiler-warning-code */
2349 if (con
->http
.state
== HTTP_STATE_WAITING
)
2351 if (!con
->http
.keep_alive
)
2353 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2354 "[Client %d] Closing because Keep-Alive disabled",
2356 cupsdCloseClient(con
);
2360 cupsArrayRemove(ActiveClients
, con
);
2361 cupsdSetBusyState();
2368 * 'cupsdSendCommand()' - Send output from a command via HTTP.
2371 int /* O - 1 on success, 0 on failure */
2373 cupsd_client_t
*con
, /* I - Client connection */
2374 char *command
, /* I - Command to run */
2375 char *options
, /* I - Command-line options */
2376 int root
) /* I - Run as root? */
2378 int fd
; /* Standard input file descriptor */
2383 fd
= open(con
->filename
, O_RDONLY
);
2387 cupsdLogMessage(CUPSD_LOG_ERROR
,
2388 "[Client %d] Unable to open \"%s\" for reading: %s",
2389 con
->http
.fd
, con
->filename
? con
->filename
: "/dev/null",
2394 fcntl(fd
, F_SETFD
, fcntl(fd
, F_GETFD
) | FD_CLOEXEC
);
2399 con
->pipe_pid
= pipe_command(con
, fd
, &(con
->file
), command
, options
, root
);
2404 cupsdLogMessage(CUPSD_LOG_INFO
, "[Client %d] Started \"%s\" (pid=%d)",
2405 con
->http
.fd
, command
, con
->pipe_pid
);
2407 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[Client %d] file=%d", con
->http
.fd
,
2410 if (con
->pipe_pid
== 0)
2413 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2415 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2417 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[Client %d] Waiting for CGI data.",
2420 con
->sent_header
= 0;
2421 con
->file_ready
= 0;
2422 con
->got_fields
= 0;
2423 con
->header_used
= 0;
2430 * 'cupsdSendError()' - Send an error message via HTTP.
2433 int /* O - 1 if successful, 0 otherwise */
2434 cupsdSendError(cupsd_client_t
*con
, /* I - Connection */
2435 http_status_t code
, /* I - Error code */
2436 int auth_type
)/* I - Authentication type */
2438 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
2439 "[Client %d] cupsdSendError code=%d, auth_type=%d",
2440 con
->http
.fd
, code
, auth_type
);
2444 * Force client to upgrade for authentication if that is how the
2445 * server is configured...
2448 if (code
== HTTP_UNAUTHORIZED
&&
2449 DefaultEncryption
== HTTP_ENCRYPT_REQUIRED
&&
2450 _cups_strcasecmp(con
->http
.hostname
, "localhost") &&
2453 code
= HTTP_UPGRADE_REQUIRED
;
2455 #endif /* HAVE_SSL */
2458 * Put the request in the access_log file...
2461 cupsdLogRequest(con
, code
);
2464 * To work around bugs in some proxies, don't use Keep-Alive for some
2467 * Kerberos authentication doesn't work without Keep-Alive, so
2468 * never disable it in that case.
2471 if (code
>= HTTP_BAD_REQUEST
&& con
->http
.auth_type
!= CUPSD_AUTH_NEGOTIATE
)
2472 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
2475 * Send an error message back to the client. If the error code is a
2476 * 400 or 500 series, make sure the message contains some text, too!
2479 if (!cupsdSendHeader(con
, code
, NULL
, auth_type
))
2483 if (code
== HTTP_UPGRADE_REQUIRED
)
2484 if (httpPrintf(HTTP(con
), "Connection: Upgrade\r\n") < 0)
2487 if (httpPrintf(HTTP(con
), "Upgrade: TLS/1.2,TLS/1.1,TLS/1.0\r\n") < 0)
2489 #endif /* HAVE_SSL */
2491 if (con
->http
.version
>= HTTP_1_1
&&
2492 con
->http
.keep_alive
== HTTP_KEEPALIVE_OFF
)
2494 if (httpPrintf(HTTP(con
), "Connection: close\r\n") < 0)
2498 if (code
>= HTTP_BAD_REQUEST
)
2501 * Send a human-readable error message.
2504 char message
[4096], /* Message for user */
2505 urltext
[1024], /* URL redirection text */
2506 redirect
[1024]; /* Redirection link */
2507 const char *text
; /* Status-specific text */
2512 if (code
== HTTP_UNAUTHORIZED
)
2513 text
= _cupsLangString(con
->language
,
2514 _("Enter your username and password or the "
2515 "root username and password to access this "
2516 "page. If you are using Kerberos authentication, "
2517 "make sure you have a valid Kerberos ticket."));
2518 else if (code
== HTTP_UPGRADE_REQUIRED
)
2522 snprintf(urltext
, sizeof(urltext
),
2523 _cupsLangString(con
->language
,
2524 _("You must access this page using the URL "
2525 "<A HREF=\"https://%s:%d%s\">"
2526 "https://%s:%d%s</A>.")),
2527 con
->servername
, con
->serverport
, con
->uri
,
2528 con
->servername
, con
->serverport
, con
->uri
);
2530 snprintf(redirect
, sizeof(redirect
),
2531 "<META HTTP-EQUIV=\"Refresh\" "
2532 "CONTENT=\"3;URL=https://%s:%d%s\">\n",
2533 con
->servername
, con
->serverport
, con
->uri
);
2535 else if (code
== HTTP_WEBIF_DISABLED
)
2536 text
= _cupsLangString(con
->language
,
2537 _("The web interface is currently disabled. Run "
2538 "\"cupsctl WebInterface=yes\" to enable it."));
2542 snprintf(message
, sizeof(message
),
2543 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" "
2544 "\"http://www.w3.org/TR/html4/loose.dtd\">\n"
2547 "\t<META HTTP-EQUIV=\"Content-Type\" "
2548 "CONTENT=\"text/html; charset=utf-8\">\n"
2549 "\t<TITLE>%s - " CUPS_SVERSION
"</TITLE>\n"
2550 "\t<LINK REL=\"STYLESHEET\" TYPE=\"text/css\" "
2551 "HREF=\"/cups.css\">\n"
2559 httpStatus(code
), redirect
, httpStatus(code
), text
);
2561 if (httpPrintf(HTTP(con
), "Content-Type: text/html; charset=utf-8\r\n") < 0)
2563 if (httpPrintf(HTTP(con
), "Content-Length: %d\r\n",
2564 (int)strlen(message
)) < 0)
2566 if (httpPrintf(HTTP(con
), "\r\n") < 0)
2568 if (httpPrintf(HTTP(con
), "%s", message
) < 0)
2571 else if (httpPrintf(HTTP(con
), "\r\n") < 0)
2574 if (cupsdFlushHeader(con
) < 0)
2577 con
->http
.state
= HTTP_STATE_WAITING
;
2579 DEBUG_puts("cupsdSendError: Set state to HTTP_STATE_WAITING.");
2586 * 'cupsdSendHeader()' - Send an HTTP request.
2589 int /* O - 1 on success, 0 on failure */
2591 cupsd_client_t
*con
, /* I - Client to send to */
2592 http_status_t code
, /* I - HTTP status code */
2593 char *type
, /* I - MIME type of document */
2594 int auth_type
) /* I - Type of authentication */
2596 char auth_str
[1024]; /* Authorization string */
2600 * Send the HTTP status header...
2603 if (code
== HTTP_CONTINUE
)
2606 * 100-continue doesn't send any headers...
2609 return (httpPrintf(HTTP(con
), "HTTP/%d.%d 100 Continue\r\n\r\n",
2610 con
->http
.version
/ 100, con
->http
.version
% 100) > 0);
2612 else if (code
== HTTP_WEBIF_DISABLED
)
2615 * Treat our special "web interface is disabled" status as "200 OK" for web
2622 httpFlushWrite(HTTP(con
));
2624 con
->http
.data_encoding
= HTTP_ENCODING_FIELDS
;
2626 if (httpPrintf(HTTP(con
), "HTTP/%d.%d %d %s\r\n", con
->http
.version
/ 100,
2627 con
->http
.version
% 100, code
, httpStatus(code
)) < 0)
2629 if (httpPrintf(HTTP(con
), "Date: %s\r\n", httpGetDateString(time(NULL
))) < 0)
2632 if (httpPrintf(HTTP(con
), "Server: %s\r\n", ServerHeader
) < 0)
2634 if (con
->http
.keep_alive
&& con
->http
.version
>= HTTP_1_0
)
2636 if (httpPrintf(HTTP(con
), "Connection: Keep-Alive\r\n") < 0)
2638 if (httpPrintf(HTTP(con
), "Keep-Alive: timeout=%d\r\n",
2639 KeepAliveTimeout
) < 0)
2642 if (code
== HTTP_METHOD_NOT_ALLOWED
)
2643 if (httpPrintf(HTTP(con
), "Allow: GET, HEAD, OPTIONS, POST, PUT\r\n") < 0)
2646 if (code
== HTTP_UNAUTHORIZED
)
2648 if (auth_type
== CUPSD_AUTH_NONE
)
2650 if (!con
->best
|| con
->best
->type
<= CUPSD_AUTH_NONE
)
2651 auth_type
= cupsdDefaultAuthType();
2653 auth_type
= con
->best
->type
;
2658 if (auth_type
== CUPSD_AUTH_BASIC
|| auth_type
== CUPSD_AUTH_BASICDIGEST
)
2659 strlcpy(auth_str
, "Basic realm=\"CUPS\"", sizeof(auth_str
));
2660 else if (auth_type
== CUPSD_AUTH_DIGEST
)
2661 snprintf(auth_str
, sizeof(auth_str
), "Digest realm=\"CUPS\", nonce=\"%s\"",
2662 con
->http
.hostname
);
2664 else if (auth_type
== CUPSD_AUTH_NEGOTIATE
)
2667 if (_httpAddrFamily(con
->http
.hostaddr
) == AF_LOCAL
)
2668 strlcpy(auth_str
, "Basic realm=\"CUPS\"", sizeof(auth_str
));
2670 # endif /* AF_LOCAL */
2671 strlcpy(auth_str
, "Negotiate", sizeof(auth_str
));
2673 #endif /* HAVE_GSSAPI */
2675 if (con
->best
&& auth_type
!= CUPSD_AUTH_NEGOTIATE
&&
2676 !_cups_strcasecmp(con
->http
.hostname
, "localhost"))
2679 * Add a "trc" (try root certification) parameter for local non-Kerberos
2680 * requests when the request requires system group membership - then the
2681 * client knows the root certificate can/should be used.
2683 * Also, for OS X we also look for @AUTHKEY and add an "authkey"
2684 * parameter as needed...
2687 char *name
, /* Current user name */
2688 *auth_key
; /* Auth key buffer */
2689 size_t auth_size
; /* Size of remaining buffer */
2691 auth_key
= auth_str
+ strlen(auth_str
);
2692 auth_size
= sizeof(auth_str
) - (auth_key
- auth_str
);
2694 for (name
= (char *)cupsArrayFirst(con
->best
->names
);
2696 name
= (char *)cupsArrayNext(con
->best
->names
))
2698 #ifdef HAVE_AUTHORIZATION_H
2699 if (!_cups_strncasecmp(name
, "@AUTHKEY(", 9))
2701 snprintf(auth_key
, auth_size
, ", authkey=\"%s\"", name
+ 9);
2702 /* end parenthesis is stripped in conf.c */
2706 #endif /* HAVE_AUTHORIZATION_H */
2707 if (!_cups_strcasecmp(name
, "@SYSTEM"))
2709 #ifdef HAVE_AUTHORIZATION_H
2710 if (SystemGroupAuthKey
)
2711 snprintf(auth_key
, auth_size
,
2713 SystemGroupAuthKey
);
2716 strlcpy(auth_key
, ", trc=\"y\"", auth_size
);
2717 #endif /* HAVE_AUTHORIZATION_H */
2725 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2726 "[Client %d] WWW-Authenticate: %s", con
->http
.fd
,
2729 if (httpPrintf(HTTP(con
), "WWW-Authenticate: %s\r\n", auth_str
) < 0)
2734 if (con
->language
&& strcmp(con
->language
->language
, "C"))
2736 if (httpPrintf(HTTP(con
), "Content-Language: %s\r\n",
2737 con
->language
->language
) < 0)
2743 if (!strcmp(type
, "text/html"))
2745 if (httpPrintf(HTTP(con
),
2746 "Content-Type: text/html; charset=utf-8\r\n") < 0)
2749 else if (httpPrintf(HTTP(con
), "Content-Type: %s\r\n", type
) < 0)
2758 * 'cupsdUpdateCGI()' - Read status messages from CGI scripts and programs.
2762 cupsdUpdateCGI(void)
2764 char *ptr
, /* Pointer to end of line in buffer */
2765 message
[1024]; /* Pointer to message text */
2766 int loglevel
; /* Log level for message */
2769 while ((ptr
= cupsdStatBufUpdate(CGIStatusBuffer
, &loglevel
,
2770 message
, sizeof(message
))) != NULL
)
2772 if (loglevel
== CUPSD_LOG_INFO
)
2773 cupsdLogMessage(CUPSD_LOG_INFO
, "%s", message
);
2775 if (!strchr(CGIStatusBuffer
->buffer
, '\n'))
2779 if (ptr
== NULL
&& !CGIStatusBuffer
->bufused
)
2782 * Fatal error on pipe - should never happen!
2785 cupsdLogMessage(CUPSD_LOG_CRIT
,
2786 "cupsdUpdateCGI: error reading from CGI error pipe - %s",
2793 * 'cupsdWriteClient()' - Write data to a client as needed.
2797 cupsdWriteClient(cupsd_client_t
*con
) /* I - Client connection */
2799 int bytes
, /* Number of bytes written */
2800 field_col
; /* Current column */
2801 char *bufptr
, /* Pointer into buffer */
2802 *bufend
; /* Pointer to end of buffer */
2803 ipp_state_t ipp_state
; /* IPP state value */
2806 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2807 "[Client %d] cupsdWriteClient "
2811 "data_encoding=HTTP_ENCODING_%s, "
2812 "data_remaining=" CUPS_LLFMT
", "
2816 con
->http
.fd
, con
->http
.error
, con
->http
.used
,
2817 http_states
[con
->http
.state
+ 1],
2818 con
->http
.data_encoding
== HTTP_ENCODING_CHUNKED
?
2819 "CHUNKED" : "LENGTH",
2820 CUPS_LLCAST con
->http
.data_remaining
,
2822 con
->response
? ipp_states
[con
->response
->state
] : "",
2823 con
->pipe_pid
, con
->file
);
2825 if (con
->http
.state
!= HTTP_STATE_GET_SEND
&&
2826 con
->http
.state
!= HTTP_STATE_POST_SEND
)
2829 * If we get called in the wrong state, then something went wrong with the
2830 * connection and we need to shut it down...
2833 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2834 "[Client %d] Closing on unexpected HTTP state %s.",
2835 con
->http
.fd
, http_states
[con
->http
.state
+ 1]);
2836 cupsdCloseClient(con
);
2843 * Make sure we select on the CGI output...
2846 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2848 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[Client %d] Waiting for CGI data.",
2851 if (!con
->file_ready
)
2854 * Try again later when there is CGI output available...
2857 cupsdRemoveSelect(con
->http
.fd
);
2861 con
->file_ready
= 0;
2864 bytes
= (ssize_t
)(sizeof(con
->header
) - (size_t)con
->header_used
);
2866 if (!con
->pipe_pid
&& bytes
> con
->http
.data_remaining
)
2869 * Limit GET bytes to original size of file (STR #3265)...
2872 bytes
= (ssize_t
)con
->http
.data_remaining
;
2875 if (con
->response
&& con
->response
->state
!= IPP_DATA
)
2877 int wused
= con
->http
.wused
; /* Previous write buffer use */
2882 * Write a single attribute or the IPP message header...
2885 ipp_state
= ippWrite(HTTP(con
), con
->response
);
2888 * If the write buffer has been flushed, stop buffering up attributes...
2891 if (con
->http
.wused
<= wused
)
2894 while (ipp_state
!= IPP_STATE_DATA
&& ipp_state
!= IPP_STATE_ERROR
);
2896 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2897 "[Client %d] Writing IPP response, ipp_state=%s, old "
2898 "wused=%d, new wused=%d", con
->http
.fd
,
2899 ipp_state
== IPP_STATE_ERROR
? "ERROR" :
2900 ipp_state
== IPP_STATE_IDLE
? "IDLE" :
2901 ipp_state
== IPP_STATE_HEADER
? "HEADER" :
2902 ipp_state
== IPP_STATE_ATTRIBUTE
? "ATTRIBUTE" : "DATA",
2903 wused
, con
->http
.wused
);
2905 if (con
->http
.wused
> 0)
2906 httpFlushWrite(HTTP(con
));
2908 bytes
= ipp_state
!= IPP_STATE_ERROR
&&
2909 (con
->file
>= 0 || ipp_state
!= IPP_STATE_DATA
);
2911 cupsdLogMessage(CUPSD_LOG_DEBUG
,
2912 "[Client %d] bytes=%d, http_state=%d, "
2913 "data_remaining=" CUPS_LLFMT
,
2914 con
->http
.fd
, (int)bytes
, con
->http
.state
,
2915 CUPS_LLCAST con
->http
.data_remaining
);
2917 else if ((bytes
= read(con
->file
, con
->header
+ con
->header_used
, (size_t)bytes
)) > 0)
2919 con
->header_used
+= bytes
;
2921 if (con
->pipe_pid
&& !con
->got_fields
)
2924 * Inspect the data for Content-Type and other fields.
2927 for (bufptr
= con
->header
, bufend
= con
->header
+ con
->header_used
,
2929 !con
->got_fields
&& bufptr
< bufend
;
2932 if (*bufptr
== '\n')
2935 * Send line to client...
2938 if (bufptr
> con
->header
&& bufptr
[-1] == '\r')
2942 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Script header: %s", con
->header
);
2944 if (!con
->sent_header
)
2947 * Handle redirection and CGI status codes...
2950 if (!_cups_strncasecmp(con
->header
, "Location:", 9))
2952 if (!cupsdSendHeader(con
, HTTP_SEE_OTHER
, NULL
, CUPSD_AUTH_NONE
))
2954 cupsdCloseClient(con
);
2958 con
->sent_header
= 2;
2960 if (httpPrintf(HTTP(con
), "Content-Length: 0\r\n") < 0)
2963 else if (!_cups_strncasecmp(con
->header
, "Status:", 7))
2965 cupsdSendError(con
, (http_status_t
)atoi(con
->header
+ 7),
2967 con
->sent_header
= 2;
2971 if (!cupsdSendHeader(con
, HTTP_OK
, NULL
, CUPSD_AUTH_NONE
))
2973 cupsdCloseClient(con
);
2977 con
->sent_header
= 1;
2979 if (con
->http
.version
== HTTP_1_1
)
2981 if (httpPrintf(HTTP(con
), "Transfer-Encoding: chunked\r\n") < 0)
2987 if (_cups_strncasecmp(con
->header
, "Status:", 7))
2988 httpPrintf(HTTP(con
), "%s\r\n", con
->header
);
2994 con
->header_used
-= bufptr
- con
->header
;
2996 if (con
->header_used
> 0)
2997 memmove(con
->header
, bufptr
, con
->header_used
);
2999 bufptr
= con
->header
- 1;
3002 * See if the line was empty...
3007 con
->got_fields
= 1;
3009 if (cupsdFlushHeader(con
) < 0)
3011 cupsdCloseClient(con
);
3015 if (con
->http
.version
== HTTP_1_1
)
3016 con
->http
.data_encoding
= HTTP_ENCODING_CHUNKED
;
3021 else if (*bufptr
!= '\r')
3025 if (!con
->got_fields
)
3027 con
->http
.activity
= time(NULL
);
3032 if (con
->header_used
> 0)
3034 if (httpWrite2(HTTP(con
), con
->header
, con
->header_used
) < 0)
3036 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3037 "[Client %d] Closing for error %d (%s)",
3038 con
->http
.fd
, con
->http
.error
,
3039 strerror(con
->http
.error
));
3040 cupsdCloseClient(con
);
3044 if (con
->http
.data_encoding
== HTTP_ENCODING_CHUNKED
)
3045 httpFlushWrite(HTTP(con
));
3047 con
->bytes
+= con
->header_used
;
3049 if (con
->http
.state
== HTTP_STATE_WAITING
)
3052 bytes
= con
->header_used
;
3054 con
->header_used
= 0;
3059 (con
->http
.state
!= HTTP_STATE_GET_SEND
&&
3060 con
->http
.state
!= HTTP_STATE_POST_SEND
))
3062 if (!con
->sent_header
&& con
->pipe_pid
)
3063 cupsdSendError(con
, HTTP_SERVER_ERROR
, CUPSD_AUTH_NONE
);
3066 cupsdLogRequest(con
, HTTP_OK
);
3068 httpFlushWrite(HTTP(con
));
3070 if (con
->http
.data_encoding
== HTTP_ENCODING_CHUNKED
&&
3071 con
->sent_header
== 1)
3073 if (httpWrite2(HTTP(con
), "", 0) < 0)
3075 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3076 "[Client %d] Closing for error %d (%s)",
3077 con
->http
.fd
, con
->http
.error
,
3078 strerror(con
->http
.error
));
3079 cupsdCloseClient(con
);
3085 con
->http
.state
= HTTP_STATE_WAITING
;
3087 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
3089 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[Client %d] Waiting for request.",
3094 cupsdRemoveSelect(con
->file
);
3097 cupsdEndProcess(con
->pipe_pid
, 0);
3106 unlink(con
->filename
);
3107 cupsdClearString(&con
->filename
);
3112 ippDelete(con
->request
);
3113 con
->request
= NULL
;
3118 ippDelete(con
->response
);
3119 con
->response
= NULL
;
3122 cupsdClearString(&con
->command
);
3123 cupsdClearString(&con
->options
);
3124 cupsdClearString(&con
->query_string
);
3126 if (!con
->http
.keep_alive
)
3128 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3129 "[Client %d] Closing because Keep-Alive disabled.",
3131 cupsdCloseClient(con
);
3136 cupsArrayRemove(ActiveClients
, con
);
3137 cupsdSetBusyState();
3141 con
->http
.activity
= time(NULL
);
3146 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
3149 static int /* O - 1 if modified since */
3151 cupsd_client_t
*con
, /* I - Client connection */
3152 struct stat
*filestats
) /* I - File information */
3154 char *ptr
; /* Pointer into field */
3155 time_t date
; /* Time/date value */
3156 off_t size
; /* Size/length value */
3161 ptr
= con
->http
.fields
[HTTP_FIELD_IF_MODIFIED_SINCE
];
3166 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3167 "[Client %d] check_if_modified "
3168 "filestats=%p(" CUPS_LLFMT
", %d)) If-Modified-Since=\"%s\"",
3169 con
->http
.fd
, filestats
, CUPS_LLCAST filestats
->st_size
,
3170 (int)filestats
->st_mtime
, ptr
);
3172 while (*ptr
!= '\0')
3174 while (isspace(*ptr
) || *ptr
== ';')
3177 if (_cups_strncasecmp(ptr
, "length=", 7) == 0)
3180 size
= strtoll(ptr
, NULL
, 10);
3182 while (isdigit(*ptr
))
3185 else if (isalpha(*ptr
))
3187 date
= httpGetDateTime(ptr
);
3188 while (*ptr
!= '\0' && *ptr
!= ';')
3195 return ((size
!= filestats
->st_size
&& size
!= 0) ||
3196 (date
< filestats
->st_mtime
&& date
!= 0) ||
3197 (size
== 0 && date
== 0));
3202 * 'compare_clients()' - Compare two client connections.
3205 static int /* O - Result of comparison */
3206 compare_clients(cupsd_client_t
*a
, /* I - First client */
3207 cupsd_client_t
*b
, /* I - Second client */
3208 void *data
) /* I - User data (not used) */
3222 * 'data_ready()' - Check whether data is available from a client.
3225 static int /* O - 1 if data is ready, 0 otherwise */
3226 data_ready(cupsd_client_t
*con
) /* I - Client */
3228 if (con
->http
.used
> 0)
3231 else if (con
->http
.tls
)
3234 if (SSL_pending((SSL
*)(con
->http
.tls
)))
3236 # elif defined(HAVE_GNUTLS)
3237 if (gnutls_record_check_pending(con
->http
.tls
))
3239 # elif defined(HAVE_CDSASSL)
3240 size_t bytes
; /* Bytes that are available */
3242 if (!SSLGetBufferedReadSize(con
->http
.tls
, &bytes
) && bytes
> 0)
3244 # endif /* HAVE_LIBSSL */
3246 #endif /* HAVE_SSL */
3253 * 'get_file()' - Get a filename and state info.
3256 static char * /* O - Real filename */
3257 get_file(cupsd_client_t
*con
, /* I - Client connection */
3258 struct stat
*filestats
, /* O - File information */
3259 char *filename
, /* IO - Filename buffer */
3260 int len
) /* I - Buffer length */
3262 int status
; /* Status of filesystem calls */
3263 char *ptr
; /* Pointer info filename */
3264 int plen
; /* Remaining length after pointer */
3265 char language
[7]; /* Language subdirectory, if any */
3269 * Figure out the real filename...
3274 if (!strncmp(con
->uri
, "/ppd/", 5) && !strchr(con
->uri
+ 5, '/'))
3275 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
);
3276 else if (!strncmp(con
->uri
, "/icons/", 7) && !strchr(con
->uri
+ 7, '/'))
3278 snprintf(filename
, len
, "%s/%s", CacheDir
, con
->uri
+ 7);
3279 if (access(filename
, F_OK
) < 0)
3280 snprintf(filename
, len
, "%s/images/generic.png", DocumentRoot
);
3282 else if (!strncmp(con
->uri
, "/rss/", 5) && !strchr(con
->uri
+ 5, '/'))
3283 snprintf(filename
, len
, "%s/rss/%s", CacheDir
, con
->uri
+ 5);
3284 else if (!strncmp(con
->uri
, "/admin/conf/", 12))
3285 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
+ 11);
3286 else if (!strncmp(con
->uri
, "/admin/log/", 11))
3288 if (!strncmp(con
->uri
+ 11, "access_log", 10) && AccessLog
[0] == '/')
3289 strlcpy(filename
, AccessLog
, len
);
3290 else if (!strncmp(con
->uri
+ 11, "error_log", 9) && ErrorLog
[0] == '/')
3291 strlcpy(filename
, ErrorLog
, len
);
3292 else if (!strncmp(con
->uri
+ 11, "page_log", 8) && PageLog
[0] == '/')
3293 strlcpy(filename
, PageLog
, len
);
3297 else if (con
->language
)
3299 snprintf(language
, sizeof(language
), "/%s", con
->language
->language
);
3300 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3303 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3305 if ((ptr
= strchr(filename
, '?')) != NULL
)
3309 * Grab the status for this language; if there isn't a language-specific file
3310 * then fallback to the default one...
3313 if ((status
= stat(filename
, filestats
)) != 0 && language
[0] &&
3314 strncmp(con
->uri
, "/icons/", 7) &&
3315 strncmp(con
->uri
, "/ppd/", 5) &&
3316 strncmp(con
->uri
, "/rss/", 5) &&
3317 strncmp(con
->uri
, "/admin/conf/", 12) &&
3318 strncmp(con
->uri
, "/admin/log/", 11))
3321 * Drop the country code...
3325 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3327 if ((ptr
= strchr(filename
, '?')) != NULL
)
3330 if ((status
= lstat(filename
, filestats
)) != 0)
3333 * Drop the language prefix and try the root directory...
3337 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
3339 if ((ptr
= strchr(filename
, '?')) != NULL
)
3342 status
= lstat(filename
, filestats
);
3347 * If we've found a symlink, 404 the sucker to avoid disclosing information.
3350 if (!status
&& S_ISLNK(filestats
->st_mode
))
3352 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Symlinks such as \"%s\" are not allowed.", filename
);
3357 * Similarly, if the file/directory does not have world read permissions, do
3358 * not allow access...
3361 if (!status
&& !(filestats
->st_mode
& S_IROTH
))
3363 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Files/directories such as \"%s\" must be world-readable.", filename
);
3368 * If we've found a directory, get the index.html file instead...
3371 if (!status
&& S_ISDIR(filestats
->st_mode
))
3374 * Make sure the URI ends with a slash...
3377 if (con
->uri
[strlen(con
->uri
) - 1] != '/')
3378 strlcat(con
->uri
, "/", sizeof(con
->uri
));
3381 * Find the directory index file, trying every language...
3386 if (status
&& language
[0])
3389 * Try a different language subset...
3393 language
[0] = '\0'; /* Strip country code */
3395 language
[0] = '\0'; /* Strip language */
3399 * Look for the index file...
3402 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
3404 if ((ptr
= strchr(filename
, '?')) != NULL
)
3407 ptr
= filename
+ strlen(filename
);
3408 plen
= len
- (ptr
- filename
);
3410 strlcpy(ptr
, "index.html", plen
);
3411 status
= stat(filename
, filestats
);
3416 strlcpy(ptr
, "index.class", plen
);
3417 status
= stat(filename
, filestats
);
3419 #endif /* HAVE_JAVA */
3424 strlcpy(ptr
, "index.pl", plen
);
3425 status
= stat(filename
, filestats
);
3427 #endif /* HAVE_PERL */
3432 strlcpy(ptr
, "index.php", plen
);
3433 status
= stat(filename
, filestats
);
3435 #endif /* HAVE_PHP */
3440 strlcpy(ptr
, "index.pyc", plen
);
3441 status
= stat(filename
, filestats
);
3446 strlcpy(ptr
, "index.py", plen
);
3447 status
= stat(filename
, filestats
);
3449 #endif /* HAVE_PYTHON */
3452 while (status
&& language
[0]);
3455 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3456 "[Client %d] get_file filestats=%p, filename=%p, len=%d, "
3457 "returning \"%s\".", con
->http
.fd
, filestats
, filename
, len
,
3458 status
? "(null)" : filename
);
3468 * 'install_cupsd_conf()' - Install a configuration file.
3471 static http_status_t
/* O - Status */
3472 install_cupsd_conf(cupsd_client_t
*con
) /* I - Connection */
3474 char filename
[1024]; /* Configuration filename */
3475 cups_file_t
*in
, /* Input file */
3476 *out
; /* Output file */
3477 char buffer
[16384]; /* Copy buffer */
3478 ssize_t bytes
; /* Number of bytes */
3482 * Open the request file...
3485 if ((in
= cupsFileOpen(con
->filename
, "rb")) == NULL
)
3487 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open request file \"%s\": %s",
3488 con
->filename
, strerror(errno
));
3489 return (HTTP_SERVER_ERROR
);
3493 * Open the new config file...
3496 if ((out
= cupsdCreateConfFile(ConfigurationFile
, ConfigFilePerm
)) == NULL
)
3499 return (HTTP_SERVER_ERROR
);
3502 cupsdLogMessage(CUPSD_LOG_INFO
, "Installing config file \"%s\"...",
3506 * Copy from the request to the new config file...
3509 while ((bytes
= cupsFileRead(in
, buffer
, sizeof(buffer
))) > 0)
3510 if (cupsFileWrite(out
, buffer
, bytes
) < bytes
)
3512 cupsdLogMessage(CUPSD_LOG_ERROR
,
3513 "Unable to copy to config file \"%s\": %s",
3514 ConfigurationFile
, strerror(errno
));
3519 snprintf(filename
, sizeof(filename
), "%s.N", ConfigurationFile
);
3520 cupsdUnlinkOrRemoveFile(filename
);
3522 return (HTTP_SERVER_ERROR
);
3526 * Close the files...
3531 if (cupsdCloseCreatedConfFile(out
, ConfigurationFile
))
3532 return (HTTP_SERVER_ERROR
);
3535 * Remove the request file...
3538 cupsdUnlinkOrRemoveFile(con
->filename
);
3539 cupsdClearString(&con
->filename
);
3542 * Set the NeedReload flag...
3545 NeedReload
= RELOAD_CUPSD
;
3546 ReloadTime
= time(NULL
);
3549 * Return that the file was created successfully...
3552 return (HTTP_CREATED
);
3557 * 'is_cgi()' - Is the resource a CGI script/program?
3560 static int /* O - 1 = CGI, 0 = file */
3561 is_cgi(cupsd_client_t
*con
, /* I - Client connection */
3562 const char *filename
, /* I - Real filename */
3563 struct stat
*filestats
, /* I - File information */
3564 mime_type_t
*type
) /* I - MIME type */
3566 const char *options
; /* Options on URL */
3570 * Get the options, if any...
3573 if ((options
= strchr(con
->uri
, '?')) != NULL
)
3576 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", options
);
3580 * Check for known types...
3583 if (!type
|| _cups_strcasecmp(type
->super
, "application"))
3585 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3586 "[Client %d] is_cgi filename=\"%s\", filestats=%p, "
3587 "type=%s/%s, returning 0", con
->http
.fd
, filename
,
3588 filestats
, type
? type
->super
: "unknown",
3589 type
? type
->type
: "unknown");
3593 if (!_cups_strcasecmp(type
->type
, "x-httpd-cgi") &&
3594 (filestats
->st_mode
& 0111))
3597 * "application/x-httpd-cgi" is a CGI script.
3600 cupsdSetString(&con
->command
, filename
);
3603 cupsdSetStringf(&con
->options
, " %s", options
);
3605 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3606 "[Client %d] is_cgi filename=\"%s\", filestats=%p, "
3607 "type=%s/%s, returning 1", con
->http
.fd
, filename
,
3608 filestats
, type
->super
, type
->type
);
3612 else if (!_cups_strcasecmp(type
->type
, "x-httpd-java"))
3615 * "application/x-httpd-java" is a Java servlet.
3618 cupsdSetString(&con
->command
, CUPS_JAVA
);
3621 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3623 cupsdSetStringf(&con
->options
, " %s", filename
);
3625 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3626 "[Client %d] is_cgi filename=\"%s\", filestats=%p, "
3627 "type=%s/%s, returning 1", con
->http
.fd
, filename
,
3628 filestats
, type
->super
, type
->type
);
3631 #endif /* HAVE_JAVA */
3633 else if (!_cups_strcasecmp(type
->type
, "x-httpd-perl"))
3636 * "application/x-httpd-perl" is a Perl page.
3639 cupsdSetString(&con
->command
, CUPS_PERL
);
3642 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3644 cupsdSetStringf(&con
->options
, " %s", filename
);
3646 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3647 "[Client %d] is_cgi filename=\"%s\", filestats=%p, "
3648 "type=%s/%s, returning 1", con
->http
.fd
, filename
,
3649 filestats
, type
->super
, type
->type
);
3652 #endif /* HAVE_PERL */
3654 else if (!_cups_strcasecmp(type
->type
, "x-httpd-php"))
3657 * "application/x-httpd-php" is a PHP page.
3660 cupsdSetString(&con
->command
, CUPS_PHP
);
3663 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3665 cupsdSetStringf(&con
->options
, " %s", filename
);
3667 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3668 "[Client %d] is_cgi filename=\"%s\", filestats=%p, "
3669 "type=%s/%s, returning 1", con
->http
.fd
, filename
,
3670 filestats
, type
->super
, type
->type
);
3673 #endif /* HAVE_PHP */
3675 else if (!_cups_strcasecmp(type
->type
, "x-httpd-python"))
3678 * "application/x-httpd-python" is a Python page.
3681 cupsdSetString(&con
->command
, CUPS_PYTHON
);
3684 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3686 cupsdSetStringf(&con
->options
, " %s", filename
);
3688 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3689 "[Client %d] is_cgi filename=\"%s\", filestats=%p, "
3690 "type=%s/%s, returning 1", con
->http
.fd
, filename
,
3691 filestats
, type
->super
, type
->type
);
3694 #endif /* HAVE_PYTHON */
3696 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3697 "[Client %d] is_cgi filename=\"%s\", filestats=%p, "
3698 "type=%s/%s, returning 0", con
->http
.fd
, filename
,
3699 filestats
, type
->super
, type
->type
);
3705 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
3708 static int /* O - 0 if relative, 1 if absolute */
3709 is_path_absolute(const char *path
) /* I - Input path */
3712 * Check for a leading slash...
3719 * Check for "<" or quotes in the path and reject since this is probably
3720 * someone trying to inject HTML...
3723 if (strchr(path
, '<') != NULL
|| strchr(path
, '\"') != NULL
|| strchr(path
, '\'') != NULL
)
3727 * Check for "/.." in the path...
3730 while ((path
= strstr(path
, "/..")) != NULL
)
3732 if (!path
[3] || path
[3] == '/')
3739 * If we haven't found any relative paths, return 1 indicating an
3748 * 'pipe_command()' - Pipe the output of a command to the remote client.
3751 static int /* O - Process ID */
3752 pipe_command(cupsd_client_t
*con
, /* I - Client connection */
3753 int infile
, /* I - Standard input for command */
3754 int *outfile
, /* O - Standard output for command */
3755 char *command
, /* I - Command to run */
3756 char *options
, /* I - Options for command */
3757 int root
) /* I - Run as root? */
3759 int i
; /* Looping var */
3760 int pid
; /* Process ID */
3761 char *commptr
, /* Command string pointer */
3762 commch
; /* Command string character */
3763 char *uriptr
; /* URI string pointer */
3764 int fds
[2]; /* Pipe FDs */
3765 int argc
; /* Number of arguments */
3766 int envc
; /* Number of environment variables */
3767 char argbuf
[10240], /* Argument buffer */
3768 *argv
[100], /* Argument strings */
3769 *envp
[MAX_ENV
+ 20]; /* Environment variables */
3770 char auth_type
[256], /* AUTH_TYPE environment variable */
3771 content_length
[1024], /* CONTENT_LENGTH environment variable */
3772 content_type
[1024], /* CONTENT_TYPE environment variable */
3773 http_cookie
[32768], /* HTTP_COOKIE environment variable */
3774 http_referer
[1024], /* HTTP_REFERER environment variable */
3775 http_user_agent
[1024], /* HTTP_USER_AGENT environment variable */
3776 lang
[1024], /* LANG environment variable */
3777 path_info
[1024], /* PATH_INFO environment variable */
3778 remote_addr
[1024], /* REMOTE_ADDR environment variable */
3779 remote_host
[1024], /* REMOTE_HOST environment variable */
3780 remote_user
[1024], /* REMOTE_USER environment variable */
3781 script_filename
[1024], /* SCRIPT_FILENAME environment variable */
3782 script_name
[1024], /* SCRIPT_NAME environment variable */
3783 server_name
[1024], /* SERVER_NAME environment variable */
3784 server_port
[1024]; /* SERVER_PORT environment variable */
3785 ipp_attribute_t
*attr
; /* attributes-natural-language attribute */
3789 * Parse a copy of the options string, which is of the form:
3791 * argument+argument+argument
3792 * ?argument+argument+argument
3793 * param=value¶m=value
3794 * ?param=value¶m=value
3795 * /name?argument+argument+argument
3796 * /name?param=value¶m=value
3798 * If the string contains an "=" character after the initial name,
3799 * then we treat it as a HTTP GET form request and make a copy of
3800 * the remaining string for the environment variable.
3802 * The string is always parsed out as command-line arguments, to
3803 * be consistent with Apache...
3806 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
3807 "[Client %d] pipe_command infile=%d, outfile=%p, "
3808 "command=\"%s\", options=\"%s\", root=%d",
3809 con
->http
.fd
, infile
, outfile
, command
,
3810 options
? options
: "(null)", root
);
3817 if (*commptr
== ' ')
3819 strlcpy(argbuf
, commptr
, sizeof(argbuf
));
3824 if (argbuf
[0] == '/')
3827 * Found some trailing path information, set PATH_INFO...
3830 if ((commptr
= strchr(argbuf
, '?')) == NULL
)
3831 commptr
= argbuf
+ strlen(argbuf
);
3835 snprintf(path_info
, sizeof(path_info
), "PATH_INFO=%s", argbuf
);
3841 path_info
[0] = '\0';
3843 if (*commptr
== ' ')
3847 if (*commptr
== '?' && con
->operation
== HTTP_STATE_GET
&& !con
->query_string
)
3850 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", commptr
);
3857 argv
[argc
++] = commptr
;
3859 for (; *commptr
&& argc
< 99; commptr
++)
3862 * Break arguments whenever we see a + or space...
3865 if (*commptr
== ' ' || *commptr
== '+')
3867 while (*commptr
== ' ' || *commptr
== '+')
3871 * If we don't have a blank string, save it as another argument...
3876 argv
[argc
] = commptr
;
3882 else if (*commptr
== '%' && isxdigit(commptr
[1] & 255) &&
3883 isxdigit(commptr
[2] & 255))
3886 * Convert the %xx notation to the individual character.
3889 if (commptr
[1] >= '0' && commptr
[1] <= '9')
3890 *commptr
= (commptr
[1] - '0') << 4;
3892 *commptr
= (tolower(commptr
[1]) - 'a' + 10) << 4;
3894 if (commptr
[2] >= '0' && commptr
[2] <= '9')
3895 *commptr
|= commptr
[2] - '0';
3897 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
3899 _cups_strcpy(commptr
+ 1, commptr
+ 3);
3902 * Check for a %00 and break if that is the case...
3914 * Setup the environment variables as needed...
3917 if (con
->username
[0])
3919 snprintf(auth_type
, sizeof(auth_type
), "AUTH_TYPE=%s",
3920 httpGetField(HTTP(con
), HTTP_FIELD_AUTHORIZATION
));
3922 if ((uriptr
= strchr(auth_type
+ 10, ' ')) != NULL
)
3926 auth_type
[0] = '\0';
3929 (attr
= ippFindAttribute(con
->request
, "attributes-natural-language",
3930 IPP_TAG_LANGUAGE
)) != NULL
)
3932 switch (strlen(attr
->values
[0].string
.text
))
3936 * This is an unknown or badly formatted language code; use
3937 * the POSIX locale...
3940 strlcpy(lang
, "LANG=C", sizeof(lang
));
3945 * Just the language code (ll)...
3948 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8",
3949 attr
->values
[0].string
.text
);
3954 * Language and country code (ll-cc)...
3957 snprintf(lang
, sizeof(lang
), "LANG=%c%c_%c%c.UTF8",
3958 attr
->values
[0].string
.text
[0],
3959 attr
->values
[0].string
.text
[1],
3960 toupper(attr
->values
[0].string
.text
[3] & 255),
3961 toupper(attr
->values
[0].string
.text
[4] & 255));
3965 else if (con
->language
)
3966 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8", con
->language
->language
);
3968 strlcpy(lang
, "LANG=C", sizeof(lang
));
3970 strlcpy(remote_addr
, "REMOTE_ADDR=", sizeof(remote_addr
));
3971 httpAddrString(con
->http
.hostaddr
, remote_addr
+ 12,
3972 sizeof(remote_addr
) - 12);
3974 snprintf(remote_host
, sizeof(remote_host
), "REMOTE_HOST=%s",
3975 con
->http
.hostname
);
3977 snprintf(script_name
, sizeof(script_name
), "SCRIPT_NAME=%s", con
->uri
);
3978 if ((uriptr
= strchr(script_name
, '?')) != NULL
)
3981 snprintf(script_filename
, sizeof(script_filename
), "SCRIPT_FILENAME=%s%s",
3982 DocumentRoot
, script_name
+ 12);
3984 sprintf(server_port
, "SERVER_PORT=%d", con
->serverport
);
3986 if (con
->http
.fields
[HTTP_FIELD_HOST
][0])
3988 char *nameptr
; /* Pointer to ":port" */
3990 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
3991 con
->http
.fields
[HTTP_FIELD_HOST
]);
3992 if ((nameptr
= strrchr(server_name
, ':')) != NULL
&& !strchr(nameptr
, ']'))
3993 *nameptr
= '\0'; /* Strip trailing ":port" */
3996 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
3999 envc
= cupsdLoadEnv(envp
, (int)(sizeof(envp
) / sizeof(envp
[0])));
4002 envp
[envc
++] = auth_type
;
4004 envp
[envc
++] = lang
;
4005 envp
[envc
++] = "REDIRECT_STATUS=1";
4006 envp
[envc
++] = "GATEWAY_INTERFACE=CGI/1.1";
4007 envp
[envc
++] = server_name
;
4008 envp
[envc
++] = server_port
;
4009 envp
[envc
++] = remote_addr
;
4010 envp
[envc
++] = remote_host
;
4011 envp
[envc
++] = script_name
;
4012 envp
[envc
++] = script_filename
;
4015 envp
[envc
++] = path_info
;
4017 if (con
->username
[0])
4019 snprintf(remote_user
, sizeof(remote_user
), "REMOTE_USER=%s", con
->username
);
4021 envp
[envc
++] = remote_user
;
4024 if (con
->http
.version
== HTTP_1_1
)
4025 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.1";
4026 else if (con
->http
.version
== HTTP_1_0
)
4027 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.0";
4029 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/0.9";
4031 if (con
->http
.cookie
)
4033 snprintf(http_cookie
, sizeof(http_cookie
), "HTTP_COOKIE=%s",
4035 envp
[envc
++] = http_cookie
;
4038 if (con
->http
.fields
[HTTP_FIELD_USER_AGENT
][0])
4040 snprintf(http_user_agent
, sizeof(http_user_agent
), "HTTP_USER_AGENT=%s",
4041 con
->http
.fields
[HTTP_FIELD_USER_AGENT
]);
4042 envp
[envc
++] = http_user_agent
;
4045 if (con
->http
.fields
[HTTP_FIELD_REFERER
][0])
4047 snprintf(http_referer
, sizeof(http_referer
), "HTTP_REFERER=%s",
4048 con
->http
.fields
[HTTP_FIELD_REFERER
]);
4049 envp
[envc
++] = http_referer
;
4052 if (con
->operation
== HTTP_STATE_GET
)
4054 envp
[envc
++] = "REQUEST_METHOD=GET";
4056 if (con
->query_string
)
4059 * Add GET form variables after ?...
4062 envp
[envc
++] = con
->query_string
;
4065 envp
[envc
++] = "QUERY_STRING=";
4069 sprintf(content_length
, "CONTENT_LENGTH=" CUPS_LLFMT
,
4070 CUPS_LLCAST con
->bytes
);
4071 snprintf(content_type
, sizeof(content_type
), "CONTENT_TYPE=%s",
4072 con
->http
.fields
[HTTP_FIELD_CONTENT_TYPE
]);
4074 envp
[envc
++] = "REQUEST_METHOD=POST";
4075 envp
[envc
++] = content_length
;
4076 envp
[envc
++] = content_type
;
4080 * Tell the CGI if we are using encryption...
4084 envp
[envc
++] = "HTTPS=ON";
4087 * Terminate the environment array...
4092 if (LogLevel
>= CUPSD_LOG_DEBUG
)
4094 for (i
= 0; i
< argc
; i
++)
4095 cupsdLogMessage(CUPSD_LOG_DEBUG
,
4096 "[CGI] argv[%d] = \"%s\"", i
, argv
[i
]);
4097 for (i
= 0; i
< envc
; i
++)
4098 cupsdLogMessage(CUPSD_LOG_DEBUG
,
4099 "[CGI] envp[%d] = \"%s\"", i
, envp
[i
]);
4103 * Create a pipe for the output...
4106 if (cupsdOpenPipe(fds
))
4108 cupsdLogMessage(CUPSD_LOG_ERROR
, "[CGI] Unable to create pipe for %s - %s",
4109 argv
[0], strerror(errno
));
4114 * Then execute the command...
4117 if (cupsdStartProcess(command
, argv
, envp
, infile
, fds
[1], CGIPipes
[1],
4118 -1, -1, root
, DefaultProfile
, NULL
, &pid
) < 0)
4121 * Error - can't fork!
4124 cupsdLogMessage(CUPSD_LOG_ERROR
, "[CGI] Unable to start %s - %s", argv
[0],
4127 cupsdClosePipe(fds
);
4133 * Fork successful - return the PID...
4136 if (con
->username
[0])
4137 cupsdAddCert(pid
, con
->username
, con
->type
);
4139 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[CGI] Started %s (PID %d)", command
, pid
);
4150 * 'valid_host()' - Is the Host: field valid?
4153 static int /* O - 1 if valid, 0 if not */
4154 valid_host(cupsd_client_t
*con
) /* I - Client connection */
4156 cupsd_alias_t
*a
; /* Current alias */
4157 cupsd_netif_t
*netif
; /* Current network interface */
4158 const char *end
; /* End character */
4159 char *ptr
; /* Pointer into host value */
4163 * Copy the Host: header for later use...
4166 strlcpy(con
->clientname
, con
->http
.fields
[HTTP_FIELD_HOST
],
4167 sizeof(con
->clientname
));
4168 if ((ptr
= strrchr(con
->clientname
, ':')) != NULL
&& !strchr(ptr
, ']'))
4171 con
->clientport
= atoi(ptr
);
4174 con
->clientport
= con
->serverport
;
4180 if (httpAddrLocalhost(con
->http
.hostaddr
))
4183 * Only allow "localhost" or the equivalent IPv4 or IPv6 numerical
4184 * addresses when accessing CUPS via the loopback interface...
4187 return (!_cups_strcasecmp(con
->clientname
, "localhost") ||
4188 !_cups_strcasecmp(con
->clientname
, "localhost.") ||
4190 !_cups_strcasecmp(con
->clientname
, "localhost.localdomain") ||
4191 #endif /* __linux */
4192 !strcmp(con
->clientname
, "127.0.0.1") ||
4193 !strcmp(con
->clientname
, "[::1]"));
4196 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
4198 * Check if the hostname is something.local (Bonjour); if so, allow it.
4201 if ((end
= strrchr(con
->clientname
, '.')) != NULL
&& end
> con
->clientname
&&
4205 * "." on end, work back to second-to-last "."...
4208 for (end
--; end
> con
->clientname
&& *end
!= '.'; end
--);
4211 if (end
&& (!_cups_strcasecmp(end
, ".local") ||
4212 !_cups_strcasecmp(end
, ".local.")))
4214 #endif /* HAVE_DNSSD || HAVE_AVAHI */
4217 * Check if the hostname is an IP address...
4220 if (isdigit(con
->clientname
[0] & 255) || con
->clientname
[0] == '[')
4223 * Possible IPv4/IPv6 address...
4226 http_addrlist_t
*addrlist
; /* List of addresses */
4229 if ((addrlist
= httpAddrGetList(con
->clientname
, AF_UNSPEC
, NULL
)) != NULL
)
4232 * Good IPv4/IPv6 address...
4235 httpAddrFreeList(addrlist
);
4241 * Check for (alias) name matches...
4244 for (a
= (cupsd_alias_t
*)cupsArrayFirst(ServerAlias
);
4246 a
= (cupsd_alias_t
*)cupsArrayNext(ServerAlias
))
4249 * "ServerAlias *" allows all host values through...
4252 if (!strcmp(a
->name
, "*"))
4255 if (!_cups_strncasecmp(con
->clientname
, a
->name
, a
->namelen
))
4258 * Prefix matches; check the character at the end - it must be "." or nul.
4261 end
= con
->clientname
+ a
->namelen
;
4263 if (!*end
|| (*end
== '.' && !end
[1]))
4268 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
4269 for (a
= (cupsd_alias_t
*)cupsArrayFirst(DNSSDAlias
);
4271 a
= (cupsd_alias_t
*)cupsArrayNext(DNSSDAlias
))
4274 * "ServerAlias *" allows all host values through...
4277 if (!strcmp(a
->name
, "*"))
4280 if (!_cups_strncasecmp(con
->clientname
, a
->name
, a
->namelen
))
4283 * Prefix matches; check the character at the end - it must be "." or nul.
4286 end
= con
->clientname
+ a
->namelen
;
4288 if (!*end
|| (*end
== '.' && !end
[1]))
4292 #endif /* HAVE_DNSSD || HAVE_AVAHI */
4295 * Check for interface hostname matches...
4298 for (netif
= (cupsd_netif_t
*)cupsArrayFirst(NetIFList
);
4300 netif
= (cupsd_netif_t
*)cupsArrayNext(NetIFList
))
4302 if (!_cups_strncasecmp(con
->clientname
, netif
->hostname
, netif
->hostlen
))
4305 * Prefix matches; check the character at the end - it must be "." or nul.
4308 end
= con
->clientname
+ netif
->hostlen
;
4310 if (!*end
|| (*end
== '.' && !end
[1]))
4320 * 'write_file()' - Send a file via HTTP.
4323 static int /* O - 0 on failure, 1 on success */
4324 write_file(cupsd_client_t
*con
, /* I - Client connection */
4325 http_status_t code
, /* I - HTTP status */
4326 char *filename
, /* I - Filename */
4327 char *type
, /* I - File type */
4328 struct stat
*filestats
) /* O - File information */
4330 con
->file
= open(filename
, O_RDONLY
);
4332 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4333 "[Client %d] write_file code=%d, filename=\"%s\" (%d), "
4334 "type=\"%s\", filestats=%p", con
->http
.fd
,
4335 code
, filename
, con
->file
, type
? type
: "(null)", filestats
);
4340 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
4344 if (!cupsdSendHeader(con
, code
, type
, CUPSD_AUTH_NONE
))
4347 if (httpPrintf(HTTP(con
), "Last-Modified: %s\r\n",
4348 httpGetDateString(filestats
->st_mtime
)) < 0)
4350 if (httpPrintf(HTTP(con
), "Content-Length: " CUPS_LLFMT
"\r\n",
4351 CUPS_LLCAST filestats
->st_size
) < 0)
4353 if (httpPrintf(HTTP(con
), "\r\n") < 0)
4356 if (cupsdFlushHeader(con
) < 0)
4359 con
->http
.data_encoding
= HTTP_ENCODING_LENGTH
;
4360 con
->http
.data_remaining
= filestats
->st_size
;
4362 if (con
->http
.data_remaining
<= INT_MAX
)
4363 con
->http
._data_remaining
= con
->http
.data_remaining
;
4365 con
->http
._data_remaining
= INT_MAX
;
4367 cupsdAddSelect(con
->http
.fd
, (cupsd_selfunc_t
)cupsdReadClient
,
4368 (cupsd_selfunc_t
)cupsdWriteClient
, con
);
4370 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[Client %d] Sending file.", con
->http
.fd
);
4377 * 'write_pipe()' - Flag that data is available on the CGI pipe.
4381 write_pipe(cupsd_client_t
*con
) /* I - Client connection */
4383 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
4384 "[Client %d] write_pipe CGI output on fd %d",
4385 con
->http
.fd
, con
->file
);
4387 con
->file_ready
= 1;
4389 cupsdRemoveSelect(con
->file
);
4390 cupsdAddSelect(con
->http
.fd
, NULL
, (cupsd_selfunc_t
)cupsdWriteClient
, con
);
4392 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[Client %d] CGI data ready to be sent.",