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 * Include necessary headers...
23 #define _CUPS_NO_DEPRECATED
24 #define _HTTP_NO_PRIVATE
29 #endif /* __APPLE__ */
32 #endif /* HAVE_TCPD_H */
39 static int check_if_modified(cupsd_client_t
*con
,
40 struct stat
*filestats
);
41 static int compare_clients(cupsd_client_t
*a
, cupsd_client_t
*b
,
43 static char *get_file(cupsd_client_t
*con
, struct stat
*filestats
,
44 char *filename
, int len
);
45 static http_status_t
install_cupsd_conf(cupsd_client_t
*con
);
46 static int is_cgi(cupsd_client_t
*con
, const char *filename
,
47 struct stat
*filestats
, mime_type_t
*type
);
48 static int is_path_absolute(const char *path
);
49 static int pipe_command(cupsd_client_t
*con
, int infile
, int *outfile
,
50 char *command
, char *options
, int root
);
51 static int valid_host(cupsd_client_t
*con
);
52 static int write_file(cupsd_client_t
*con
, http_status_t code
,
53 char *filename
, char *type
,
54 struct stat
*filestats
);
55 static void write_pipe(cupsd_client_t
*con
);
59 * 'cupsdAcceptClient()' - Accept a new client.
63 cupsdAcceptClient(cupsd_listener_t
*lis
)/* I - Listener socket */
65 const char *hostname
; /* Hostname of client */
66 char name
[256]; /* Hostname of client */
67 int count
; /* Count of connections on a host */
68 cupsd_client_t
*con
, /* New client pointer */
69 *tempcon
; /* Temporary client pointer */
70 socklen_t addrlen
; /* Length of address */
71 http_addr_t temp
; /* Temporary address variable */
72 static time_t last_dos
= 0; /* Time of last DoS attack */
74 struct request_info wrap_req
; /* TCP wrappers request information */
75 #endif /* HAVE_TCPD_H */
78 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
79 "cupsdAcceptClient(lis=%p(%d)) Clients=%d",
80 lis
, lis
->fd
, cupsArrayCount(Clients
));
83 * Make sure we don't have a full set of clients already...
86 if (cupsArrayCount(Clients
) == MaxClients
)
90 * Get a pointer to the next available client...
94 Clients
= cupsArrayNew(NULL
, NULL
);
98 cupsdLogMessage(CUPSD_LOG_ERROR
,
99 "Unable to allocate memory for clients array!");
100 cupsdPauseListening();
105 ActiveClients
= cupsArrayNew((cups_array_func_t
)compare_clients
, NULL
);
109 cupsdLogMessage(CUPSD_LOG_ERROR
,
110 "Unable to allocate memory for active clients array!");
111 cupsdPauseListening();
115 if ((con
= calloc(1, sizeof(cupsd_client_t
))) == NULL
)
117 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to allocate memory for client!");
118 cupsdPauseListening();
123 * Accept the client and get the remote address...
126 con
->number
= ++ LastClientNumber
;
129 if ((con
->http
= httpAcceptConnection(lis
->fd
, 0)) == NULL
)
131 if (errno
== ENFILE
|| errno
== EMFILE
)
132 cupsdPauseListening();
134 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to accept client connection - %s.",
142 * Save the connected address and port number...
145 con
->clientaddr
= lis
->address
;
147 #if 0 /* ifdef AF_INET6 */
148 /* FIXME: I don't believe this is recommended any longer, and we specifically
149 * disable IPv4-over-IPv6 when we listen...
152 * Convert IPv4 over IPv6 addresses (::ffff:n.n.n.n) to IPv4 forms we
153 * can more easily use...
156 if (lis
->address
.addr
.sa_family
== AF_INET6
&&
157 httpGetAddress(con
->http
)->ipv6
.sin6_addr
.s6_addr32
[0] == 0 &&
158 httpGetAddress(con
->http
)->ipv6
.sin6_addr
.s6_addr32
[1] == 0 &&
159 ntohl(httpGetAddress(con
->http
)->ipv6
.sin6_addr
.s6_addr32
[2]) == 0xffff)
160 httpGetAddress(con
->http
)->ipv6
.sin6_addr
.s6_addr32
[2] = 0;
161 #endif /* AF_INET6 */
164 * Check the number of clients on the same address...
167 for (count
= 0, tempcon
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
169 tempcon
= (cupsd_client_t
*)cupsArrayNext(Clients
))
170 if (httpAddrEqual(httpGetAddress(tempcon
->http
), httpGetAddress(con
->http
)))
173 if (count
>= MaxClientsPerHost
)
177 if (count
>= MaxClientsPerHost
)
179 if ((time(NULL
) - last_dos
) >= 60)
181 last_dos
= time(NULL
);
182 cupsdLogMessage(CUPSD_LOG_WARN
,
183 "Possible DoS attack - more than %d clients connecting "
186 httpGetHostname(con
->http
, name
, sizeof(name
)));
189 httpClose(con
->http
);
195 * Get the hostname or format the IP address as needed...
199 hostname
= httpResolveHostname(con
->http
, NULL
, 0);
201 hostname
= httpGetHostname(con
->http
, NULL
, 0);
203 if (hostname
== NULL
&& HostNameLookups
== 2)
206 * Can't have an unresolved IP address with double-lookups enabled...
209 httpClose(con
->http
);
211 cupsdLogClient(con
, CUPSD_LOG_WARN
,
212 "Name lookup failed - connection from %s closed!",
213 httpGetHostname(con
->http
, NULL
, 0));
219 if (HostNameLookups
== 2)
222 * Do double lookups as needed...
225 http_addrlist_t
*addrlist
, /* List of addresses */
226 *addr
; /* Current address */
228 if ((addrlist
= httpAddrGetList(hostname
, AF_UNSPEC
, NULL
)) != NULL
)
231 * See if the hostname maps to the same IP address...
234 for (addr
= addrlist
; addr
; addr
= addr
->next
)
235 if (httpAddrEqual(httpGetAddress(con
->http
), &(addr
->addr
)))
241 httpAddrFreeList(addrlist
);
246 * Can't have a hostname that doesn't resolve to the same IP address
247 * with double-lookups enabled...
250 httpClose(con
->http
);
252 cupsdLogClient(con
, CUPSD_LOG_WARN
,
253 "IP lookup failed - connection from %s closed!",
254 httpGetHostname(con
->http
, NULL
, 0));
262 * See if the connection is denied by TCP wrappers...
265 request_init(&wrap_req
, RQ_DAEMON
, "cupsd", RQ_FILE
, httpGetFd(con
->http
),
269 if (!hosts_access(&wrap_req
))
271 httpClose(con
->http
);
273 cupsdLogClient(con
, CUPSD_LOG_WARN
,
274 "Connection from %s refused by /etc/hosts.allow and "
275 "/etc/hosts.deny rules.", httpGetHostname(con
->http
, NULL
, 0));
279 #endif /* HAVE_TCPD_H */
282 if (httpAddrFamily(httpGetAddress(con
->http
)) == AF_LOCAL
)
285 socklen_t peersize
; /* Size of peer credentials */
286 pid_t peerpid
; /* Peer process ID */
287 char peername
[256]; /* Name of process */
289 peersize
= sizeof(peerpid
);
290 if (!getsockopt(con
->number
, SOL_LOCAL
, LOCAL_PEERPID
, &peerpid
,
293 if (!proc_name(peerpid
, peername
, sizeof(peername
)))
294 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
295 "Accepted from %s (Domain ???[%d])",
296 httpGetHostname(con
->http
, NULL
, 0), (int)peerpid
);
298 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
299 "Accepted from %s (Domain %s[%d])",
300 httpGetHostname(con
->http
, NULL
, 0), name
, (int)peerpid
);
303 # endif /* __APPLE__ */
305 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Accepted from %s (Domain)",
306 httpGetHostname(con
->http
, NULL
, 0));
309 #endif /* AF_LOCAL */
310 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Accepted from %s:%d (IPv%d)",
311 httpGetHostname(con
->http
, NULL
, 0),
312 httpAddrPort(httpGetAddress(con
->http
)),
313 httpAddrFamily(httpGetAddress(con
->http
)) == AF_INET
? 4 : 6);
316 * Get the local address the client connected to...
319 addrlen
= sizeof(temp
);
320 if (getsockname(httpGetFd(con
->http
), (struct sockaddr
*)&temp
, &addrlen
))
322 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Unable to get local address - %s",
325 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
326 con
->serverport
= LocalPort
;
329 else if (httpAddrFamily(&temp
) == AF_LOCAL
)
331 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
332 con
->serverport
= LocalPort
;
334 #endif /* AF_LOCAL */
337 if (httpAddrLocalhost(&temp
))
338 strlcpy(con
->servername
, "localhost", sizeof(con
->servername
));
339 else if (HostNameLookups
)
340 httpAddrLookup(&temp
, con
->servername
, sizeof(con
->servername
));
342 httpAddrString(&temp
, con
->servername
, sizeof(con
->servername
));
344 con
->serverport
= httpAddrPort(&(lis
->address
));
348 * Add the connection to the array of active clients...
351 cupsArrayAdd(Clients
, con
);
354 * Add the socket to the server select.
357 cupsdAddSelect(httpGetFd(con
->http
), (cupsd_selfunc_t
)cupsdReadClient
, NULL
,
360 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for request.");
363 * Temporarily suspend accept()'s until we lose a client...
366 if (cupsArrayCount(Clients
) == MaxClients
)
367 cupsdPauseListening();
371 * See if we are connecting on a secure port...
374 if (lis
->encryption
== HTTP_ENCRYPTION_ALWAYS
)
377 * https connection; go secure...
380 if (!cupsdStartTLS(con
))
381 cupsdCloseClient(con
);
385 #endif /* HAVE_SSL */
390 * 'cupsdCloseAllClients()' - Close all remote clients immediately.
394 cupsdCloseAllClients(void)
396 cupsd_client_t
*con
; /* Current client */
399 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "cupsdCloseAllClients() Clients=%d",
400 cupsArrayCount(Clients
));
402 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
404 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
405 if (cupsdCloseClient(con
))
406 cupsdCloseClient(con
);
411 * 'cupsdCloseClient()' - Close a remote client.
414 int /* O - 1 if partial close, 0 if fully closed */
415 cupsdCloseClient(cupsd_client_t
*con
) /* I - Client to close */
417 int partial
; /* Do partial close for SSL? */
419 #elif defined(HAVE_GNUTLS)
420 # elif defined(HAVE_CDSASSL)
421 #endif /* HAVE_LIBSSL */
424 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing connection.");
427 * Flush pending writes before closing...
430 httpFlushWrite(con
->http
);
434 if (con
->pipe_pid
!= 0)
437 * Stop any CGI process...
440 cupsdEndProcess(con
->pipe_pid
, 1);
446 cupsdRemoveSelect(con
->file
);
453 * Close the socket and clear the file from the input set for select()...
456 if (httpGetFd(con
->http
) >= 0)
458 cupsArrayRemove(ActiveClients
, con
);
463 * Shutdown encryption as needed...
466 if (httpIsEncrypted(con
->http
))
468 #endif /* HAVE_SSL */
473 * Only do a partial close so that the encrypted client gets everything.
476 httpShutdown(con
->http
);
477 cupsdAddSelect(httpGetFd(con
->http
), (cupsd_selfunc_t
)cupsdReadClient
,
480 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for socket close.");
485 * Shut the socket down fully...
488 cupsdRemoveSelect(httpGetFd(con
->http
));
489 httpClose(con
->http
);
500 cupsdRemoveSelect(httpGetFd(con
->http
));
502 httpClose(con
->http
);
504 cupsdClearString(&con
->filename
);
505 cupsdClearString(&con
->command
);
506 cupsdClearString(&con
->options
);
507 cupsdClearString(&con
->query_string
);
511 ippDelete(con
->request
);
517 ippDelete(con
->response
);
518 con
->response
= NULL
;
523 cupsLangFree(con
->language
);
524 con
->language
= NULL
;
527 #ifdef HAVE_AUTHORIZATION_H
530 AuthorizationFree(con
->authref
, kAuthorizationFlagDefaults
);
533 #endif /* HAVE_AUTHORIZATION_H */
536 * Re-enable new client connections if we are going back under the
540 if (cupsArrayCount(Clients
) == MaxClients
)
541 cupsdResumeListening();
544 * Compact the list of clients as necessary...
547 cupsArrayRemove(Clients
, con
);
558 * 'cupsdFlushHeader()' - Flush the header fields to the client.
561 int /* I - Bytes written or -1 on error */
562 cupsdFlushHeader(cupsd_client_t
*con
) /* I - Client to flush to */
564 int bytes
= httpFlushWrite(con
->http
);
566 // TODO: Need to use httpSendResponse
567 con
->http
->data_encoding
= HTTP_ENCODING_LENGTH
;
575 * 'cupsdReadClient()' - Read data from a client.
579 cupsdReadClient(cupsd_client_t
*con
) /* I - Client to read from */
581 char line
[32768], /* Line from client... */
582 locale
[64], /* Locale */
583 *ptr
; /* Pointer into strings */
584 http_status_t status
; /* Transfer status */
585 ipp_state_t ipp_state
; /* State of IPP transfer */
586 int bytes
; /* Number of bytes to POST */
587 char *filename
; /* Name of file for GET/HEAD */
588 char buf
[1024]; /* Buffer for real filename */
589 struct stat filestats
; /* File information */
590 mime_type_t
*type
; /* MIME type of file */
591 cupsd_printer_t
*p
; /* Printer */
592 static unsigned request_id
= 0; /* Request ID for temp files */
595 status
= HTTP_STATUS_CONTINUE
;
597 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
602 "data_encoding=HTTP_ENCODING_%s, "
603 "data_remaining=" CUPS_LLFMT
", "
606 httpError(con
->http
), (int)httpGetReady(con
->http
),
607 httpStateString(httpGetState(con
->http
)),
608 httpIsChunked(con
->http
) ? "CHUNKED" : "LENGTH",
609 CUPS_LLCAST
httpGetRemaining(con
->http
),
611 con
->request
? ippStateString(ippGetState(con
->request
)) : "",
618 * Automatically check for a SSL/TLS handshake...
623 if (recv(httpGetFd(con
->http
), buf
, 1, MSG_PEEK
) == 1 &&
624 (!buf
[0] || !strchr("DGHOPT", buf
[0])))
627 * Encrypt this connection...
630 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
631 "Saw first byte %02X, auto-negotiating "
632 "SSL/TLS session.", buf
[0] & 255);
634 if (!cupsdStartTLS(con
))
635 cupsdCloseClient(con
);
640 #endif /* HAVE_SSL */
642 switch (httpGetState(con
->http
))
644 case HTTP_STATE_WAITING
:
646 * See if we've received a request line...
649 con
->operation
= httpReadRequest(con
->http
, con
->uri
, sizeof(con
->uri
));
650 if (con
->operation
== HTTP_STATE_ERROR
||
651 con
->operation
== HTTP_STATE_UNKNOWN_METHOD
||
652 con
->operation
== HTTP_STATE_UNKNOWN_VERSION
)
654 if (httpError(con
->http
))
655 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
656 "HTTP_STATE_WAITING Closing for error %d (%s)",
657 httpError(con
->http
), strerror(httpError(con
->http
)));
659 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
660 "HTTP_STATE_WAITING Closing on error: %s",
661 cupsLastErrorString());
663 cupsdCloseClient(con
);
668 * Ignore blank request lines...
671 if (con
->operation
== HTTP_STATE_WAITING
)
675 * Clear other state variables...
682 con
->username
[0] = '\0';
683 con
->password
[0] = '\0';
685 cupsdClearString(&con
->command
);
686 cupsdClearString(&con
->options
);
687 cupsdClearString(&con
->query_string
);
691 ippDelete(con
->request
);
697 ippDelete(con
->response
);
698 con
->response
= NULL
;
703 cupsLangFree(con
->language
);
704 con
->language
= NULL
;
710 #endif /* HAVE_GSSAPI */
713 * Handle full URLs in the request line...
716 if (strcmp(con
->uri
, "*"))
718 char scheme
[HTTP_MAX_URI
], /* Method/scheme */
719 userpass
[HTTP_MAX_URI
], /* Username:password */
720 hostname
[HTTP_MAX_URI
], /* Hostname */
721 resource
[HTTP_MAX_URI
]; /* Resource path */
722 int port
; /* Port number */
725 * Separate the URI into its components...
728 if (httpSeparateURI(HTTP_URI_CODING_MOST
, con
->uri
,
729 scheme
, sizeof(scheme
),
730 userpass
, sizeof(userpass
),
731 hostname
, sizeof(hostname
), &port
,
732 resource
, sizeof(resource
)) < HTTP_URI_STATUS_OK
)
734 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Bad URI \"%s\" in request.",
736 cupsdSendError(con
, HTTP_STATUS_METHOD_NOT_ALLOWED
, CUPSD_AUTH_NONE
);
737 cupsdCloseClient(con
);
742 * Only allow URIs with the servername, localhost, or an IP
746 if (strcmp(scheme
, "file") &&
747 _cups_strcasecmp(hostname
, ServerName
) &&
748 _cups_strcasecmp(hostname
, "localhost") &&
749 !cupsArrayFind(ServerAlias
, hostname
) &&
750 !isdigit(hostname
[0]) && hostname
[0] != '[')
753 * Nope, we don't do proxies...
756 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Bad URI \"%s\" in request.",
758 cupsdSendError(con
, HTTP_STATUS_METHOD_NOT_ALLOWED
, CUPSD_AUTH_NONE
);
759 cupsdCloseClient(con
);
764 * Copy the resource portion back into the URI; both resource and
765 * con->uri are HTTP_MAX_URI bytes in size...
768 strlcpy(con
->uri
, resource
, sizeof(con
->uri
));
772 * Process the request...
775 gettimeofday(&(con
->start
), NULL
);
777 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "%s %s HTTP/%d.%d",
778 httpStateString(con
->operation
) + 11, con
->uri
,
779 httpGetVersion(con
->http
) / 100,
780 httpGetVersion(con
->http
) % 100);
782 if (!cupsArrayFind(ActiveClients
, con
))
784 cupsArrayAdd(ActiveClients
, con
);
788 case HTTP_STATE_OPTIONS
:
789 case HTTP_STATE_DELETE
:
790 case HTTP_STATE_GET
:
791 case HTTP_STATE_HEAD
:
792 case HTTP_STATE_POST
:
793 case HTTP_STATE_PUT
:
794 case HTTP_STATE_TRACE
:
796 * Parse incoming parameters until the status changes...
799 while ((status
= httpUpdate(con
->http
)) == HTTP_STATUS_CONTINUE
)
800 if (!httpGetReady(con
->http
))
803 if (status
!= HTTP_STATUS_OK
&& status
!= HTTP_STATUS_CONTINUE
)
805 if (httpError(con
->http
) && httpError(con
->http
) != EPIPE
)
806 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
807 "Closing for error %d (%s) while reading headers.",
808 httpError(con
->http
), strerror(httpError(con
->http
)));
810 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
811 "Closing on EOF while reading headers.");
813 cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
);
814 cupsdCloseClient(con
);
820 if (!httpGetReady(con
->http
) && recv(httpGetFd(con
->http
), buf
, 1, MSG_PEEK
) < 1)
823 * Connection closed...
826 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing on EOF.");
827 cupsdCloseClient(con
);
830 break; /* Anti-compiler-warning-code */
834 * Handle new transfers...
837 if (status
== HTTP_STATUS_OK
)
839 if (httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
)[0])
842 * Figure out the locale from the Accept-Language and Content-Type
846 if ((ptr
= strchr(httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
),
850 if ((ptr
= strchr(httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
),
854 if ((ptr
= strstr(httpGetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
),
855 "charset=")) != NULL
)
858 * Combine language and charset, and trim any extra params in the
862 snprintf(locale
, sizeof(locale
), "%s.%s",
863 httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
), ptr
+ 8);
865 if ((ptr
= strchr(locale
, ',')) != NULL
)
869 snprintf(locale
, sizeof(locale
), "%s.UTF-8",
870 httpGetField(con
->http
, HTTP_FIELD_ACCEPT_LANGUAGE
));
872 con
->language
= cupsLangGet(locale
);
875 con
->language
= cupsLangGet(DefaultLocale
);
879 if (!_cups_strncasecmp(httpGetField(con
->http
, HTTP_FIELD_CONNECTION
),
880 "Keep-Alive", 10) && KeepAlive
)
881 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_ON
);
882 else if (!_cups_strncasecmp(httpGetField(con
->http
, HTTP_FIELD_CONNECTION
),
884 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
886 if (!httpGetField(con
->http
, HTTP_FIELD_HOST
)[0] &&
887 httpGetVersion(con
->http
) >= HTTP_VERSION_1_1
)
890 * HTTP/1.1 and higher require the "Host:" field...
893 if (!cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
))
895 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Missing Host: field in request.");
896 cupsdCloseClient(con
);
900 else if (!valid_host(con
))
903 * Access to localhost must use "localhost" or the corresponding IPv4
904 * or IPv6 values in the Host: field.
907 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
908 "Request from \"%s\" using invalid Host: field \"%s\".",
909 httpGetHostname(con
->http
, NULL
, 0), httpGetField(con
->http
, HTTP_FIELD_HOST
));
911 if (!cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
))
913 cupsdCloseClient(con
);
917 else if (con
->operation
== HTTP_STATE_OPTIONS
)
920 * Do OPTIONS command...
923 if (con
->best
&& con
->best
->type
!= CUPSD_AUTH_NONE
)
925 httpClearFields(con
->http
);
927 if (!cupsdSendHeader(con
, HTTP_STATUS_UNAUTHORIZED
, NULL
, CUPSD_AUTH_NONE
))
929 cupsdCloseClient(con
);
934 if (!_cups_strcasecmp(httpGetField(con
->http
, HTTP_FIELD_CONNECTION
), "Upgrade") &&
935 !httpIsEncrypted(con
->http
))
939 * Do encryption stuff...
942 httpClearFields(con
->http
);
944 if (!cupsdSendHeader(con
, HTTP_STATUS_SWITCHING_PROTOCOLS
, NULL
, CUPSD_AUTH_NONE
))
946 cupsdCloseClient(con
);
950 if (!cupsdStartTLS(con
))
952 cupsdCloseClient(con
);
956 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
958 cupsdCloseClient(con
);
961 #endif /* HAVE_SSL */
964 httpClearFields(con
->http
);
965 httpSetField(con
->http
, HTTP_FIELD_ALLOW
,
966 "GET, HEAD, OPTIONS, POST, PUT");
967 httpSetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
, "0");
969 if (!cupsdSendHeader(con
, HTTP_STATUS_OK
, NULL
, CUPSD_AUTH_NONE
))
971 cupsdCloseClient(con
);
975 else if (!is_path_absolute(con
->uri
))
978 * Protect against malicious users!
981 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
982 "Request for non-absolute resource \"%s\".", con
->uri
);
984 if (!cupsdSendError(con
, HTTP_STATUS_FORBIDDEN
, CUPSD_AUTH_NONE
))
986 cupsdCloseClient(con
);
992 if (!_cups_strcasecmp(httpGetField(con
->http
, HTTP_FIELD_CONNECTION
),
993 "Upgrade") && !httpIsEncrypted(con
->http
))
997 * Do encryption stuff...
1000 httpClearFields(con
->http
);
1002 if (!cupsdSendHeader(con
, HTTP_STATUS_SWITCHING_PROTOCOLS
, NULL
,
1005 cupsdCloseClient(con
);
1009 if (!cupsdStartTLS(con
))
1011 cupsdCloseClient(con
);
1015 if (!cupsdSendError(con
, HTTP_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
))
1017 cupsdCloseClient(con
);
1020 #endif /* HAVE_SSL */
1023 if ((status
= cupsdIsAuthorized(con
, NULL
)) != HTTP_STATUS_OK
)
1025 cupsdSendError(con
, status
, CUPSD_AUTH_NONE
);
1026 cupsdCloseClient(con
);
1030 if (httpGetExpect(con
->http
) &&
1031 (con
->operation
== HTTP_STATE_POST
|| con
->operation
== HTTP_STATE_PUT
))
1033 if (httpGetExpect(con
->http
) == HTTP_STATUS_CONTINUE
)
1036 * Send 100-continue header...
1039 if (httpWriteResponse(con
->http
, HTTP_STATUS_CONTINUE
))
1041 cupsdCloseClient(con
);
1048 * Send 417-expectation-failed header...
1051 httpClearFields(con
->http
);
1052 httpSetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
, "0");
1054 cupsdSendError(con
, HTTP_STATUS_EXPECTATION_FAILED
, CUPSD_AUTH_NONE
);
1055 cupsdCloseClient(con
);
1060 switch (httpGetState(con
->http
))
1062 case HTTP_STATE_GET_SEND
:
1063 if ((!strncmp(con
->uri
, "/ppd/", 5) ||
1064 !strncmp(con
->uri
, "/printers/", 10) ||
1065 !strncmp(con
->uri
, "/classes/", 9)) &&
1066 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1069 * Send PPD file - get the real printer name since printer
1070 * names are not case sensitive but filenames can be...
1073 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1075 if (!strncmp(con
->uri
, "/ppd/", 5))
1076 p
= cupsdFindPrinter(con
->uri
+ 5);
1077 else if (!strncmp(con
->uri
, "/printers/", 10))
1078 p
= cupsdFindPrinter(con
->uri
+ 10);
1081 p
= cupsdFindClass(con
->uri
+ 9);
1085 int i
; /* Looping var */
1087 for (i
= 0; i
< p
->num_printers
; i
++)
1089 if (!(p
->printers
[i
]->type
& CUPS_PRINTER_CLASS
))
1091 char ppdname
[1024];/* PPD filename */
1093 snprintf(ppdname
, sizeof(ppdname
), "%s/ppd/%s.ppd",
1094 ServerRoot
, p
->printers
[i
]->name
);
1095 if (!access(ppdname
, 0))
1103 if (i
>= p
->num_printers
)
1110 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1114 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1116 cupsdCloseClient(con
);
1123 else if ((!strncmp(con
->uri
, "/icons/", 7) ||
1124 !strncmp(con
->uri
, "/printers/", 10) ||
1125 !strncmp(con
->uri
, "/classes/", 9)) &&
1126 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".png"))
1129 * Send icon file - get the real queue name since queue names are
1130 * not case sensitive but filenames can be...
1133 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".png" */
1135 if (!strncmp(con
->uri
, "/icons/", 7))
1136 p
= cupsdFindPrinter(con
->uri
+ 7);
1137 else if (!strncmp(con
->uri
, "/printers/", 10))
1138 p
= cupsdFindPrinter(con
->uri
+ 10);
1141 p
= cupsdFindClass(con
->uri
+ 9);
1145 int i
; /* Looping var */
1147 for (i
= 0; i
< p
->num_printers
; i
++)
1149 if (!(p
->printers
[i
]->type
& CUPS_PRINTER_CLASS
))
1151 char ppdname
[1024];/* PPD filename */
1153 snprintf(ppdname
, sizeof(ppdname
), "%s/ppd/%s.ppd",
1154 ServerRoot
, p
->printers
[i
]->name
);
1155 if (!access(ppdname
, 0))
1163 if (i
>= p
->num_printers
)
1169 snprintf(con
->uri
, sizeof(con
->uri
), "/icons/%s.png", p
->name
);
1172 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1174 cupsdCloseClient(con
);
1181 else if (!WebInterface
)
1184 * Web interface is disabled. Show an appropriate message...
1187 if (!cupsdSendError(con
, HTTP_STATUS_CUPS_WEBIF_DISABLED
, CUPSD_AUTH_NONE
))
1189 cupsdCloseClient(con
);
1196 if ((!strncmp(con
->uri
, "/admin", 6) &&
1197 strncmp(con
->uri
, "/admin/conf/", 12) &&
1198 strncmp(con
->uri
, "/admin/log/", 11)) ||
1199 !strncmp(con
->uri
, "/printers", 9) ||
1200 !strncmp(con
->uri
, "/classes", 8) ||
1201 !strncmp(con
->uri
, "/help", 5) ||
1202 !strncmp(con
->uri
, "/jobs", 5))
1205 * Send CGI output...
1208 if (!strncmp(con
->uri
, "/admin", 6))
1210 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1213 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1215 else if (!strncmp(con
->uri
, "/printers", 9))
1217 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1220 if (con
->uri
[9] && con
->uri
[10])
1221 cupsdSetString(&con
->options
, con
->uri
+ 9);
1223 cupsdSetString(&con
->options
, NULL
);
1225 else if (!strncmp(con
->uri
, "/classes", 8))
1227 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1230 if (con
->uri
[8] && con
->uri
[9])
1231 cupsdSetString(&con
->options
, con
->uri
+ 8);
1233 cupsdSetString(&con
->options
, NULL
);
1235 else if (!strncmp(con
->uri
, "/jobs", 5))
1237 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1240 if (con
->uri
[5] && con
->uri
[6])
1241 cupsdSetString(&con
->options
, con
->uri
+ 5);
1243 cupsdSetString(&con
->options
, NULL
);
1247 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1250 if (con
->uri
[5] && con
->uri
[6])
1251 cupsdSetString(&con
->options
, con
->uri
+ 5);
1253 cupsdSetString(&con
->options
, NULL
);
1256 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1258 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1260 cupsdCloseClient(con
);
1265 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1267 if (httpGetVersion(con
->http
) <= HTTP_VERSION_1_0
)
1268 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
1270 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1271 (strchr(con
->uri
+ 12, '/') ||
1272 strlen(con
->uri
) == 12)) ||
1273 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1274 (strchr(con
->uri
+ 11, '/') ||
1275 strlen(con
->uri
) == 11)))
1278 * GET can only be done to configuration files directly under
1282 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1283 "Request for subdirectory \"%s\"!", con
->uri
);
1285 if (!cupsdSendError(con
, HTTP_STATUS_FORBIDDEN
, CUPSD_AUTH_NONE
))
1287 cupsdCloseClient(con
);
1299 if ((filename
= get_file(con
, &filestats
, buf
,
1300 sizeof(buf
))) == NULL
)
1302 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1304 cupsdCloseClient(con
);
1311 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1313 if (is_cgi(con
, filename
, &filestats
, type
))
1316 * Note: con->command and con->options were set by
1320 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
1322 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1324 cupsdCloseClient(con
);
1329 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1331 if (httpGetVersion(con
->http
) <= HTTP_VERSION_1_0
)
1332 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
1336 if (!check_if_modified(con
, &filestats
))
1338 if (!cupsdSendError(con
, HTTP_STATUS_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1340 cupsdCloseClient(con
);
1347 strlcpy(line
, "text/plain", sizeof(line
));
1349 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1351 if (!write_file(con
, HTTP_STATUS_OK
, filename
, line
, &filestats
))
1353 cupsdCloseClient(con
);
1360 case HTTP_STATE_POST_RECV
:
1362 * See if the POST request includes a Content-Length field, and if
1363 * so check the length against any limits that are set...
1366 if (httpGetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
)[0] &&
1367 MaxRequestSize
> 0 &&
1368 httpGetLength2(con
->http
) > MaxRequestSize
)
1371 * Request too large...
1374 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1376 cupsdCloseClient(con
);
1382 else if (httpGetLength2(con
->http
) < 0)
1385 * Negative content lengths are invalid!
1388 if (!cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1390 cupsdCloseClient(con
);
1398 * See what kind of POST request this is; for IPP requests the
1399 * content-type field will be "application/ipp"...
1402 if (!strcmp(httpGetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
),
1404 con
->request
= ippNew();
1405 else if (!WebInterface
)
1408 * Web interface is disabled. Show an appropriate message...
1411 if (!cupsdSendError(con
, HTTP_STATUS_CUPS_WEBIF_DISABLED
, CUPSD_AUTH_NONE
))
1413 cupsdCloseClient(con
);
1419 else if ((!strncmp(con
->uri
, "/admin", 6) &&
1420 strncmp(con
->uri
, "/admin/conf/", 12) &&
1421 strncmp(con
->uri
, "/admin/log/", 11)) ||
1422 !strncmp(con
->uri
, "/printers", 9) ||
1423 !strncmp(con
->uri
, "/classes", 8) ||
1424 !strncmp(con
->uri
, "/help", 5) ||
1425 !strncmp(con
->uri
, "/jobs", 5))
1431 if (!strncmp(con
->uri
, "/admin", 6))
1433 cupsdSetStringf(&con
->command
, "%s/cgi-bin/admin.cgi",
1436 cupsdSetString(&con
->options
, strchr(con
->uri
+ 6, '?'));
1438 else if (!strncmp(con
->uri
, "/printers", 9))
1440 cupsdSetStringf(&con
->command
, "%s/cgi-bin/printers.cgi",
1443 if (con
->uri
[9] && con
->uri
[10])
1444 cupsdSetString(&con
->options
, con
->uri
+ 9);
1446 cupsdSetString(&con
->options
, NULL
);
1448 else if (!strncmp(con
->uri
, "/classes", 8))
1450 cupsdSetStringf(&con
->command
, "%s/cgi-bin/classes.cgi",
1453 if (con
->uri
[8] && con
->uri
[9])
1454 cupsdSetString(&con
->options
, con
->uri
+ 8);
1456 cupsdSetString(&con
->options
, NULL
);
1458 else if (!strncmp(con
->uri
, "/jobs", 5))
1460 cupsdSetStringf(&con
->command
, "%s/cgi-bin/jobs.cgi",
1463 if (con
->uri
[5] && con
->uri
[6])
1464 cupsdSetString(&con
->options
, con
->uri
+ 5);
1466 cupsdSetString(&con
->options
, NULL
);
1470 cupsdSetStringf(&con
->command
, "%s/cgi-bin/help.cgi",
1473 if (con
->uri
[5] && con
->uri
[6])
1474 cupsdSetString(&con
->options
, con
->uri
+ 5);
1476 cupsdSetString(&con
->options
, NULL
);
1479 if (httpGetVersion(con
->http
) <= HTTP_VERSION_1_0
)
1480 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
1488 if ((filename
= get_file(con
, &filestats
, buf
,
1489 sizeof(buf
))) == NULL
)
1491 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1493 cupsdCloseClient(con
);
1500 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1502 if (!is_cgi(con
, filename
, &filestats
, type
))
1505 * Only POST to CGI's...
1508 if (!cupsdSendError(con
, HTTP_STATUS_UNAUTHORIZED
, CUPSD_AUTH_NONE
))
1510 cupsdCloseClient(con
);
1517 case HTTP_STATE_PUT_RECV
:
1519 * Validate the resource name...
1522 if (strcmp(con
->uri
, "/admin/conf/cupsd.conf"))
1525 * PUT can only be done to the cupsd.conf file...
1528 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1529 "Disallowed PUT request for \"%s\".", con
->uri
);
1531 if (!cupsdSendError(con
, HTTP_STATUS_FORBIDDEN
, CUPSD_AUTH_NONE
))
1533 cupsdCloseClient(con
);
1541 * See if the PUT request includes a Content-Length field, and if
1542 * so check the length against any limits that are set...
1545 if (httpGetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
)[0] &&
1546 MaxRequestSize
> 0 &&
1547 httpGetLength2(con
->http
) > MaxRequestSize
)
1550 * Request too large...
1553 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1555 cupsdCloseClient(con
);
1561 else if (httpGetLength2(con
->http
) < 0)
1564 * Negative content lengths are invalid!
1567 if (!cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
))
1569 cupsdCloseClient(con
);
1577 * Open a temporary file to hold the request...
1580 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
1582 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1586 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1587 "Unable to create request file \"%s\": %s",
1588 con
->filename
, strerror(errno
));
1590 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1592 cupsdCloseClient(con
);
1597 fchmod(con
->file
, 0640);
1598 fchown(con
->file
, RunUser
, Group
);
1599 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1602 case HTTP_STATE_DELETE
:
1603 case HTTP_STATE_TRACE
:
1604 cupsdSendError(con
, HTTP_STATUS_NOT_IMPLEMENTED
, CUPSD_AUTH_NONE
);
1605 cupsdCloseClient(con
);
1608 case HTTP_STATE_HEAD
:
1609 if (!strncmp(con
->uri
, "/printers/", 10) &&
1610 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".ppd"))
1613 * Send PPD file - get the real printer name since printer
1614 * names are not case sensitive but filenames can be...
1617 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1619 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1620 snprintf(con
->uri
, sizeof(con
->uri
), "/ppd/%s.ppd", p
->name
);
1623 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1625 cupsdCloseClient(con
);
1629 cupsdLogRequest(con
, HTTP_STATUS_NOT_FOUND
);
1633 else if (!strncmp(con
->uri
, "/printers/", 10) &&
1634 !strcmp(con
->uri
+ strlen(con
->uri
) - 4, ".png"))
1637 * Send PNG file - get the real printer name since printer
1638 * names are not case sensitive but filenames can be...
1641 con
->uri
[strlen(con
->uri
) - 4] = '\0'; /* Drop ".ppd" */
1643 if ((p
= cupsdFindPrinter(con
->uri
+ 10)) != NULL
)
1644 snprintf(con
->uri
, sizeof(con
->uri
), "/icons/%s.png", p
->name
);
1647 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
1649 cupsdCloseClient(con
);
1653 cupsdLogRequest(con
, HTTP_STATUS_NOT_FOUND
);
1657 else if (!WebInterface
)
1659 httpClearFields(con
->http
);
1661 if (!cupsdSendHeader(con
, HTTP_STATUS_OK
, NULL
, CUPSD_AUTH_NONE
))
1663 cupsdCloseClient(con
);
1667 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1671 if ((!strncmp(con
->uri
, "/admin", 6) &&
1672 strncmp(con
->uri
, "/admin/conf/", 12) &&
1673 strncmp(con
->uri
, "/admin/log/", 11)) ||
1674 !strncmp(con
->uri
, "/printers", 9) ||
1675 !strncmp(con
->uri
, "/classes", 8) ||
1676 !strncmp(con
->uri
, "/help", 5) ||
1677 !strncmp(con
->uri
, "/jobs", 5))
1683 httpClearFields(con
->http
);
1685 if (!cupsdSendHeader(con
, HTTP_STATUS_OK
, "text/html", CUPSD_AUTH_NONE
))
1687 cupsdCloseClient(con
);
1691 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1693 else if ((!strncmp(con
->uri
, "/admin/conf/", 12) &&
1694 (strchr(con
->uri
+ 12, '/') ||
1695 strlen(con
->uri
) == 12)) ||
1696 (!strncmp(con
->uri
, "/admin/log/", 11) &&
1697 (strchr(con
->uri
+ 11, '/') ||
1698 strlen(con
->uri
) == 11)))
1701 * HEAD can only be done to configuration files under
1705 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1706 "Request for subdirectory \"%s\".", con
->uri
);
1708 if (!cupsdSendError(con
, HTTP_STATUS_FORBIDDEN
, CUPSD_AUTH_NONE
))
1710 cupsdCloseClient(con
);
1714 cupsdLogRequest(con
, HTTP_STATUS_FORBIDDEN
);
1717 else if ((filename
= get_file(con
, &filestats
, buf
,
1718 sizeof(buf
))) == NULL
)
1720 httpClearFields(con
->http
);
1722 if (!cupsdSendHeader(con
, HTTP_STATUS_NOT_FOUND
, "text/html",
1725 cupsdCloseClient(con
);
1729 cupsdLogRequest(con
, HTTP_STATUS_NOT_FOUND
);
1731 else if (!check_if_modified(con
, &filestats
))
1733 if (!cupsdSendError(con
, HTTP_STATUS_NOT_MODIFIED
, CUPSD_AUTH_NONE
))
1735 cupsdCloseClient(con
);
1739 cupsdLogRequest(con
, HTTP_STATUS_NOT_MODIFIED
);
1747 type
= mimeFileType(MimeDatabase
, filename
, NULL
, NULL
);
1749 strlcpy(line
, "text/plain", sizeof(line
));
1751 snprintf(line
, sizeof(line
), "%s/%s", type
->super
, type
->type
);
1753 httpClearFields(con
->http
);
1755 httpSetField(con
->http
, HTTP_FIELD_LAST_MODIFIED
,
1756 httpGetDateString(filestats
.st_mtime
));
1757 httpSetLength(con
->http
, filestats
.st_size
);
1759 if (!cupsdSendHeader(con
, HTTP_STATUS_OK
, line
, CUPSD_AUTH_NONE
))
1761 cupsdCloseClient(con
);
1765 cupsdLogRequest(con
, HTTP_STATUS_OK
);
1770 break; /* Anti-compiler-warning-code */
1776 * Handle any incoming data...
1779 switch (httpGetState(con
->http
))
1781 case HTTP_STATE_PUT_RECV
:
1784 if ((bytes
= httpRead2(con
->http
, line
, sizeof(line
))) < 0)
1786 if (httpError(con
->http
) && httpError(con
->http
) != EPIPE
)
1787 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1788 "HTTP_STATE_PUT_RECV Closing for error %d (%s)",
1789 httpError(con
->http
), strerror(httpError(con
->http
)));
1791 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1792 "HTTP_STATE_PUT_RECV Closing on EOF.");
1794 cupsdCloseClient(con
);
1799 con
->bytes
+= bytes
;
1801 if (write(con
->file
, line
, bytes
) < bytes
)
1803 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1804 "Unable to write %d bytes to \"%s\": %s", bytes
,
1805 con
->filename
, strerror(errno
));
1809 unlink(con
->filename
);
1810 cupsdClearString(&con
->filename
);
1812 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1814 cupsdCloseClient(con
);
1820 while (httpGetState(con
->http
) == HTTP_STATE_PUT_RECV
&& httpGetReady(con
->http
));
1822 if (httpGetState(con
->http
) == HTTP_STATE_STATUS
)
1825 * End of file, see how big it is...
1828 fstat(con
->file
, &filestats
);
1833 if (filestats
.st_size
> MaxRequestSize
&&
1837 * Request is too big; remove it and send an error...
1840 unlink(con
->filename
);
1841 cupsdClearString(&con
->filename
);
1843 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1845 cupsdCloseClient(con
);
1851 * Install the configuration file...
1854 status
= install_cupsd_conf(con
);
1857 * Return the status to the client...
1860 if (!cupsdSendError(con
, status
, CUPSD_AUTH_NONE
))
1862 cupsdCloseClient(con
);
1868 case HTTP_STATE_POST_RECV
:
1871 if (con
->request
&& con
->file
< 0)
1874 * Grab any request data from the connection...
1877 if ((ipp_state
= ippRead(con
->http
, con
->request
)) == IPP_STATE_ERROR
)
1879 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "IPP read error: %s",
1880 cupsLastErrorString());
1882 cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
);
1883 cupsdCloseClient(con
);
1886 else if (ipp_state
!= IPP_STATE_DATA
)
1888 if (httpGetState(con
->http
) == HTTP_STATE_POST_SEND
)
1890 cupsdSendError(con
, HTTP_STATUS_BAD_REQUEST
, CUPSD_AUTH_NONE
);
1891 cupsdCloseClient(con
);
1895 if (httpGetReady(con
->http
))
1901 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "%d.%d %s %d",
1902 con
->request
->request
.op
.version
[0],
1903 con
->request
->request
.op
.version
[1],
1904 ippOpString(con
->request
->request
.op
.operation_id
),
1905 con
->request
->request
.op
.request_id
);
1906 con
->bytes
+= ippLength(con
->request
);
1910 if (con
->file
< 0 && httpGetState(con
->http
) != HTTP_STATE_POST_SEND
)
1913 * Create a file as needed for the request data...
1916 cupsdSetStringf(&con
->filename
, "%s/%08x", RequestRoot
,
1918 con
->file
= open(con
->filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0640);
1922 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1923 "Unable to create request file \"%s\": %s",
1924 con
->filename
, strerror(errno
));
1926 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
1928 cupsdCloseClient(con
);
1933 fchmod(con
->file
, 0640);
1934 fchown(con
->file
, RunUser
, Group
);
1935 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
1938 if (httpGetState(con
->http
) != HTTP_STATE_POST_SEND
)
1940 if (!httpWait(con
->http
, 0))
1942 else if ((bytes
= httpRead2(con
->http
, line
, sizeof(line
))) < 0)
1944 if (httpError(con
->http
) && httpError(con
->http
) != EPIPE
)
1945 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1946 "HTTP_STATE_POST_SEND Closing for error %d (%s)",
1947 httpError(con
->http
), strerror(httpError(con
->http
)));
1949 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1950 "HTTP_STATE_POST_SEND Closing on EOF.");
1952 cupsdCloseClient(con
);
1957 con
->bytes
+= bytes
;
1959 if (write(con
->file
, line
, bytes
) < bytes
)
1961 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
1962 "Unable to write %d bytes to \"%s\": %s",
1963 bytes
, con
->filename
, strerror(errno
));
1967 unlink(con
->filename
);
1968 cupsdClearString(&con
->filename
);
1970 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
,
1973 cupsdCloseClient(con
);
1978 else if (httpGetState(con
->http
) == HTTP_STATE_POST_RECV
)
1980 else if (httpGetState(con
->http
) != HTTP_STATE_POST_SEND
)
1982 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
1983 "Closing on unexpected state %s.",
1984 httpStateString(httpGetState(con
->http
)));
1985 cupsdCloseClient(con
);
1990 while (httpGetState(con
->http
) == HTTP_STATE_POST_RECV
&& httpGetReady(con
->http
));
1992 if (httpGetState(con
->http
) == HTTP_STATE_POST_SEND
)
1996 fstat(con
->file
, &filestats
);
2001 if (filestats
.st_size
> MaxRequestSize
&&
2005 * Request is too big; remove it and send an error...
2008 unlink(con
->filename
);
2009 cupsdClearString(&con
->filename
);
2014 * Delete any IPP request data...
2017 ippDelete(con
->request
);
2018 con
->request
= NULL
;
2021 if (!cupsdSendError(con
, HTTP_STATUS_REQUEST_TOO_LARGE
, CUPSD_AUTH_NONE
))
2023 cupsdCloseClient(con
);
2027 else if (filestats
.st_size
== 0)
2030 * Don't allow empty file...
2033 unlink(con
->filename
);
2034 cupsdClearString(&con
->filename
);
2039 if (!cupsdSendCommand(con
, con
->command
, con
->options
, 0))
2041 if (!cupsdSendError(con
, HTTP_STATUS_NOT_FOUND
, CUPSD_AUTH_NONE
))
2043 cupsdCloseClient(con
);
2048 cupsdLogRequest(con
, HTTP_STATUS_OK
);
2054 cupsdProcessIPPRequest(con
);
2058 unlink(con
->filename
);
2059 cupsdClearString(&con
->filename
);
2068 break; /* Anti-compiler-warning-code */
2071 if (httpGetState(con
->http
) == HTTP_STATE_WAITING
)
2073 if (!httpGetKeepAlive(con
->http
))
2075 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2076 "Closing because Keep-Alive is disabled.");
2077 cupsdCloseClient(con
);
2081 cupsArrayRemove(ActiveClients
, con
);
2082 cupsdSetBusyState();
2089 * 'cupsdSendCommand()' - Send output from a command via HTTP.
2092 int /* O - 1 on success, 0 on failure */
2094 cupsd_client_t
*con
, /* I - Client connection */
2095 char *command
, /* I - Command to run */
2096 char *options
, /* I - Command-line options */
2097 int root
) /* I - Run as root? */
2099 int fd
; /* Standard input file descriptor */
2104 fd
= open(con
->filename
, O_RDONLY
);
2108 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
2109 "Unable to open \"%s\" for reading: %s",
2110 con
->filename
? con
->filename
: "/dev/null",
2115 fcntl(fd
, F_SETFD
, fcntl(fd
, F_GETFD
) | FD_CLOEXEC
);
2120 con
->pipe_pid
= pipe_command(con
, fd
, &(con
->file
), command
, options
, root
);
2121 con
->pipe_status
= HTTP_STATUS_OK
;
2123 httpClearFields(con
->http
);
2128 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Started \"%s\" (pid=%d, file=%d)",
2129 command
, con
->pipe_pid
, con
->file
);
2131 if (con
->pipe_pid
== 0)
2134 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
2136 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2138 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for CGI data.");
2140 con
->sent_header
= 0;
2141 con
->file_ready
= 0;
2142 con
->got_fields
= 0;
2143 con
->header_used
= 0;
2150 * 'cupsdSendError()' - Send an error message via HTTP.
2153 int /* O - 1 if successful, 0 otherwise */
2154 cupsdSendError(cupsd_client_t
*con
, /* I - Connection */
2155 http_status_t code
, /* I - Error code */
2156 int auth_type
)/* I - Authentication type */
2158 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "cupsdSendError code=%d, auth_type=%d",
2163 * Force client to upgrade for authentication if that is how the
2164 * server is configured...
2167 if (code
== HTTP_STATUS_UNAUTHORIZED
&&
2168 DefaultEncryption
== HTTP_ENCRYPTION_REQUIRED
&&
2169 _cups_strcasecmp(httpGetHostname(con
->http
, NULL
, 0), "localhost") &&
2170 !httpIsEncrypted(con
->http
))
2172 code
= HTTP_STATUS_UPGRADE_REQUIRED
;
2174 #endif /* HAVE_SSL */
2177 * Put the request in the access_log file...
2180 cupsdLogRequest(con
, code
);
2183 * To work around bugs in some proxies, don't use Keep-Alive for some
2186 * Kerberos authentication doesn't work without Keep-Alive, so
2187 * never disable it in that case.
2190 httpClearFields(con
->http
);
2192 if (code
>= HTTP_STATUS_BAD_REQUEST
&& con
->type
!= CUPSD_AUTH_NEGOTIATE
)
2193 httpSetKeepAlive(con
->http
, HTTP_KEEPALIVE_OFF
);
2195 if (httpGetVersion(con
->http
) >= HTTP_VERSION_1_1
&&
2196 httpGetKeepAlive(con
->http
) == HTTP_KEEPALIVE_OFF
)
2197 httpSetField(con
->http
, HTTP_FIELD_CONNECTION
, "close");
2199 if (code
>= HTTP_STATUS_BAD_REQUEST
)
2202 * Send a human-readable error message.
2205 char message
[4096], /* Message for user */
2206 urltext
[1024], /* URL redirection text */
2207 redirect
[1024]; /* Redirection link */
2208 const char *text
; /* Status-specific text */
2213 if (code
== HTTP_STATUS_UNAUTHORIZED
)
2214 text
= _cupsLangString(con
->language
,
2215 _("Enter your username and password or the "
2216 "root username and password to access this "
2217 "page. If you are using Kerberos authentication, "
2218 "make sure you have a valid Kerberos ticket."));
2219 else if (code
== HTTP_STATUS_UPGRADE_REQUIRED
)
2223 snprintf(urltext
, sizeof(urltext
),
2224 _cupsLangString(con
->language
,
2225 _("You must access this page using the URL "
2226 "<A HREF=\"https://%s:%d%s\">"
2227 "https://%s:%d%s</A>.")),
2228 con
->servername
, con
->serverport
, con
->uri
,
2229 con
->servername
, con
->serverport
, con
->uri
);
2231 snprintf(redirect
, sizeof(redirect
),
2232 "<META HTTP-EQUIV=\"Refresh\" "
2233 "CONTENT=\"3;URL=https://%s:%d%s\">\n",
2234 con
->servername
, con
->serverport
, con
->uri
);
2236 else if (code
== HTTP_STATUS_CUPS_WEBIF_DISABLED
)
2237 text
= _cupsLangString(con
->language
,
2238 _("The web interface is currently disabled. Run "
2239 "\"cupsctl WebInterface=yes\" to enable it."));
2243 snprintf(message
, sizeof(message
),
2244 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" "
2245 "\"http://www.w3.org/TR/html4/loose.dtd\">\n"
2248 "\t<META HTTP-EQUIV=\"Content-Type\" "
2249 "CONTENT=\"text/html; charset=utf-8\">\n"
2250 "\t<TITLE>%s - " CUPS_SVERSION
"</TITLE>\n"
2251 "\t<LINK REL=\"STYLESHEET\" TYPE=\"text/css\" "
2252 "HREF=\"/cups.css\">\n"
2260 _httpStatus(con
->language
, code
), redirect
,
2261 _httpStatus(con
->language
, code
), text
);
2264 * Send an error message back to the client. If the error code is a
2265 * 400 or 500 series, make sure the message contains some text, too!
2268 httpSetLength(con
->http
, strlen(message
));
2270 if (!cupsdSendHeader(con
, code
, "text/html", auth_type
))
2273 if (httpPrintf(con
->http
, "%s", message
) < 0)
2278 httpSetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
, "0");
2280 if (!cupsdSendHeader(con
, code
, NULL
, auth_type
))
2289 * 'cupsdSendHeader()' - Send an HTTP request.
2292 int /* O - 1 on success, 0 on failure */
2294 cupsd_client_t
*con
, /* I - Client to send to */
2295 http_status_t code
, /* I - HTTP status code */
2296 char *type
, /* I - MIME type of document */
2297 int auth_type
) /* I - Type of authentication */
2299 char auth_str
[1024]; /* Authorization string */
2303 * Send the HTTP status header...
2306 if (code
== HTTP_STATUS_CUPS_WEBIF_DISABLED
)
2309 * Treat our special "web interface is disabled" status as "200 OK" for web
2313 code
= HTTP_STATUS_OK
;
2317 httpSetField(con
->http
, HTTP_FIELD_SERVER
, ServerHeader
);
2319 if (code
== HTTP_STATUS_METHOD_NOT_ALLOWED
)
2320 httpSetField(con
->http
, HTTP_FIELD_ALLOW
, "GET, HEAD, OPTIONS, POST, PUT");
2322 if (code
== HTTP_STATUS_UNAUTHORIZED
)
2324 if (auth_type
== CUPSD_AUTH_NONE
)
2326 if (!con
->best
|| con
->best
->type
<= CUPSD_AUTH_NONE
)
2327 auth_type
= cupsdDefaultAuthType();
2329 auth_type
= con
->best
->type
;
2334 if (auth_type
== CUPSD_AUTH_BASIC
|| auth_type
== CUPSD_AUTH_BASICDIGEST
)
2335 strlcpy(auth_str
, "Basic realm=\"CUPS\"", sizeof(auth_str
));
2336 else if (auth_type
== CUPSD_AUTH_DIGEST
)
2337 snprintf(auth_str
, sizeof(auth_str
), "Digest realm=\"CUPS\", nonce=\"%s\"",
2338 httpGetHostname(con
->http
, NULL
, 0));
2340 else if (auth_type
== CUPSD_AUTH_NEGOTIATE
)
2343 if (httpAddrFamily(httpGetAddress(con
->http
)) == AF_LOCAL
)
2344 strlcpy(auth_str
, "Basic realm=\"CUPS\"", sizeof(auth_str
));
2346 # endif /* AF_LOCAL */
2347 strlcpy(auth_str
, "Negotiate", sizeof(auth_str
));
2349 #endif /* HAVE_GSSAPI */
2351 if (con
->best
&& auth_type
!= CUPSD_AUTH_NEGOTIATE
&&
2352 !_cups_strcasecmp(httpGetHostname(con
->http
, NULL
, 0), "localhost"))
2355 * Add a "trc" (try root certification) parameter for local non-Kerberos
2356 * requests when the request requires system group membership - then the
2357 * client knows the root certificate can/should be used.
2359 * Also, for OS X we also look for @AUTHKEY and add an "authkey"
2360 * parameter as needed...
2363 char *name
, /* Current user name */
2364 *auth_key
; /* Auth key buffer */
2365 size_t auth_size
; /* Size of remaining buffer */
2367 auth_key
= auth_str
+ strlen(auth_str
);
2368 auth_size
= sizeof(auth_str
) - (auth_key
- auth_str
);
2370 for (name
= (char *)cupsArrayFirst(con
->best
->names
);
2372 name
= (char *)cupsArrayNext(con
->best
->names
))
2374 #ifdef HAVE_AUTHORIZATION_H
2375 if (!_cups_strncasecmp(name
, "@AUTHKEY(", 9))
2377 snprintf(auth_key
, auth_size
, ", authkey=\"%s\"", name
+ 9);
2378 /* end parenthesis is stripped in conf.c */
2382 #endif /* HAVE_AUTHORIZATION_H */
2383 if (!_cups_strcasecmp(name
, "@SYSTEM"))
2385 #ifdef HAVE_AUTHORIZATION_H
2386 if (SystemGroupAuthKey
)
2387 snprintf(auth_key
, auth_size
,
2389 SystemGroupAuthKey
);
2392 strlcpy(auth_key
, ", trc=\"y\"", auth_size
);
2393 #endif /* HAVE_AUTHORIZATION_H */
2401 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "WWW-Authenticate: %s", auth_str
);
2403 httpSetField(con
->http
, HTTP_FIELD_WWW_AUTHENTICATE
, auth_str
);
2407 if (con
->language
&& strcmp(con
->language
->language
, "C"))
2408 httpSetField(con
->http
, HTTP_FIELD_CONTENT_LANGUAGE
, con
->language
->language
);
2412 if (!strcmp(type
, "text/html"))
2413 httpSetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
, "text/html; charset=utf-8");
2415 httpSetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
, type
);
2418 return (!httpWriteResponse(con
->http
, code
));
2423 * 'cupsdUpdateCGI()' - Read status messages from CGI scripts and programs.
2427 cupsdUpdateCGI(void)
2429 char *ptr
, /* Pointer to end of line in buffer */
2430 message
[1024]; /* Pointer to message text */
2431 int loglevel
; /* Log level for message */
2434 while ((ptr
= cupsdStatBufUpdate(CGIStatusBuffer
, &loglevel
,
2435 message
, sizeof(message
))) != NULL
)
2437 if (loglevel
== CUPSD_LOG_INFO
)
2438 cupsdLogMessage(CUPSD_LOG_INFO
, "%s", message
);
2440 if (!strchr(CGIStatusBuffer
->buffer
, '\n'))
2444 if (ptr
== NULL
&& !CGIStatusBuffer
->bufused
)
2447 * Fatal error on pipe - should never happen!
2450 cupsdLogMessage(CUPSD_LOG_CRIT
,
2451 "cupsdUpdateCGI: error reading from CGI error pipe - %s",
2458 * 'cupsdWriteClient()' - Write data to a client as needed.
2462 cupsdWriteClient(cupsd_client_t
*con
) /* I - Client connection */
2464 int bytes
, /* Number of bytes written */
2465 field_col
; /* Current column */
2466 char *bufptr
, /* Pointer into buffer */
2467 *bufend
; /* Pointer to end of buffer */
2468 ipp_state_t ipp_state
; /* IPP state value */
2471 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "con->http=%p", con
->http
);
2472 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2477 "data_encoding=HTTP_ENCODING_%s, "
2478 "data_remaining=" CUPS_LLFMT
", "
2482 httpError(con
->http
), (int)httpGetReady(con
->http
),
2483 httpStateString(httpGetState(con
->http
)),
2484 httpIsChunked(con
->http
) ? "CHUNKED" : "LENGTH",
2485 CUPS_LLCAST
httpGetLength2(con
->http
),
2487 con
->response
? ippStateString(ippGetState(con
->request
)) : "",
2488 con
->pipe_pid
, con
->file
);
2490 if (httpGetState(con
->http
) != HTTP_STATE_GET_SEND
&&
2491 httpGetState(con
->http
) != HTTP_STATE_POST_SEND
)
2494 * If we get called in the wrong state, then something went wrong with the
2495 * connection and we need to shut it down...
2498 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing on unexpected HTTP state %s.",
2499 httpStateString(httpGetState(con
->http
)));
2500 cupsdCloseClient(con
);
2507 * Make sure we select on the CGI output...
2510 cupsdAddSelect(con
->file
, (cupsd_selfunc_t
)write_pipe
, NULL
, con
);
2512 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for CGI data.");
2514 if (!con
->file_ready
)
2517 * Try again later when there is CGI output available...
2520 cupsdRemoveSelect(httpGetFd(con
->http
));
2524 con
->file_ready
= 0;
2527 if (con
->response
&& con
->response
->state
!= IPP_STATE_DATA
)
2529 size_t wused
= httpGetPending(con
->http
); /* Previous write buffer use */
2534 * Write a single attribute or the IPP message header...
2537 ipp_state
= ippWrite(con
->http
, con
->response
);
2540 * If the write buffer has been flushed, stop buffering up attributes...
2543 if (httpGetPending(con
->http
) <= wused
)
2546 while (ipp_state
!= IPP_STATE_DATA
&& ipp_state
!= IPP_STATE_ERROR
);
2548 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2549 "Writing IPP response, ipp_state=%s, old "
2550 "wused=" CUPS_LLFMT
", new wused=" CUPS_LLFMT
,
2551 ippStateString(ipp_state
),
2552 CUPS_LLCAST wused
, CUPS_LLCAST
httpGetPending(con
->http
));
2554 if (httpGetPending(con
->http
) > 0)
2555 httpFlushWrite(con
->http
);
2557 bytes
= ipp_state
!= IPP_STATE_ERROR
&&
2558 (con
->file
>= 0 || ipp_state
!= IPP_STATE_DATA
);
2560 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2561 "bytes=%d, http_state=%d, data_remaining=" CUPS_LLFMT
,
2562 (int)bytes
, httpGetState(con
->http
),
2563 CUPS_LLCAST
httpGetLength2(con
->http
));
2565 else if ((bytes
= read(con
->file
, con
->header
+ con
->header_used
,
2566 sizeof(con
->header
) - con
->header_used
)) > 0)
2568 con
->header_used
+= bytes
;
2570 if (con
->pipe_pid
&& !con
->got_fields
)
2573 * Inspect the data for Content-Type and other fields.
2576 for (bufptr
= con
->header
, bufend
= con
->header
+ con
->header_used
,
2578 !con
->got_fields
&& bufptr
< bufend
;
2581 if (*bufptr
== '\n')
2584 * Send line to client...
2587 if (bufptr
> con
->header
&& bufptr
[-1] == '\r')
2591 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Script header: %s", con
->header
);
2593 if (!con
->sent_header
)
2596 * Handle redirection and CGI status codes...
2599 http_field_t field
; /* HTTP field */
2600 char *value
= strchr(con
->header
, ':');
2601 /* Value of field */
2606 while (isspace(*value
& 255))
2610 field
= httpFieldValue(con
->header
);
2612 if (field
!= HTTP_FIELD_UNKNOWN
&& value
)
2614 httpSetField(con
->http
, field
, value
);
2616 if (field
== HTTP_FIELD_LOCATION
)
2618 con
->pipe_status
= HTTP_STATUS_SEE_OTHER
;
2619 con
->sent_header
= 2;
2622 con
->sent_header
= 1;
2624 else if (!_cups_strcasecmp(con
->header
, "Status") && value
)
2626 con
->pipe_status
= (http_status_t
)atoi(value
);
2627 con
->sent_header
= 2;
2629 else if (!_cups_strcasecmp(con
->header
, "Set-Cookie") && value
)
2631 char *sep
= strchr(value
, ';');
2632 /* Separator between name=value and the rest */
2637 httpSetCookie(con
->http
, value
);
2638 con
->sent_header
= 1;
2646 con
->header_used
-= bufptr
- con
->header
;
2648 if (con
->header_used
> 0)
2649 memmove(con
->header
, bufptr
, con
->header_used
);
2651 bufptr
= con
->header
- 1;
2654 * See if the line was empty...
2659 con
->got_fields
= 1;
2661 if (httpGetVersion(con
->http
) == HTTP_VERSION_1_1
&&
2662 !httpGetField(con
->http
, HTTP_FIELD_CONTENT_LENGTH
)[0])
2663 httpSetLength(con
->http
, 0);
2665 if (!cupsdSendHeader(con
, con
->pipe_status
, NULL
, CUPSD_AUTH_NONE
))
2667 cupsdCloseClient(con
);
2674 else if (*bufptr
!= '\r')
2678 if (!con
->got_fields
)
2682 if (con
->header_used
> 0)
2684 if (httpWrite2(con
->http
, con
->header
, con
->header_used
) < 0)
2686 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing for error %d (%s)",
2687 httpError(con
->http
), strerror(httpError(con
->http
)));
2688 cupsdCloseClient(con
);
2692 if (httpIsChunked(con
->http
))
2693 httpFlushWrite(con
->http
);
2695 con
->bytes
+= con
->header_used
;
2697 if (httpGetState(con
->http
) == HTTP_STATE_WAITING
)
2700 bytes
= con
->header_used
;
2702 con
->header_used
= 0;
2707 (httpGetState(con
->http
) != HTTP_STATE_GET_SEND
&&
2708 httpGetState(con
->http
) != HTTP_STATE_POST_SEND
))
2710 if (!con
->sent_header
&& con
->pipe_pid
)
2711 cupsdSendError(con
, HTTP_STATUS_SERVER_ERROR
, CUPSD_AUTH_NONE
);
2714 cupsdLogRequest(con
, HTTP_STATUS_OK
);
2716 httpFlushWrite(con
->http
);
2718 if (httpIsChunked(con
->http
) && con
->sent_header
== 1)
2720 if (httpWrite2(con
->http
, "", 0) < 0)
2722 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Closing for error %d (%s)",
2723 httpError(con
->http
), strerror(httpError(con
->http
)));
2724 cupsdCloseClient(con
);
2730 cupsdAddSelect(httpGetFd(con
->http
), (cupsd_selfunc_t
)cupsdReadClient
, NULL
, con
);
2732 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Waiting for request.");
2736 cupsdRemoveSelect(con
->file
);
2739 cupsdEndProcess(con
->pipe_pid
, 0);
2748 unlink(con
->filename
);
2749 cupsdClearString(&con
->filename
);
2754 ippDelete(con
->request
);
2755 con
->request
= NULL
;
2760 ippDelete(con
->response
);
2761 con
->response
= NULL
;
2764 cupsdClearString(&con
->command
);
2765 cupsdClearString(&con
->options
);
2766 cupsdClearString(&con
->query_string
);
2768 if (!httpGetKeepAlive(con
->http
))
2770 cupsdLogClient(con
, CUPSD_LOG_DEBUG
,
2771 "Closing because Keep-Alive is disabled.");
2772 cupsdCloseClient(con
);
2777 cupsArrayRemove(ActiveClients
, con
);
2778 cupsdSetBusyState();
2785 * 'check_if_modified()' - Decode an "If-Modified-Since" line.
2788 static int /* O - 1 if modified since */
2790 cupsd_client_t
*con
, /* I - Client connection */
2791 struct stat
*filestats
) /* I - File information */
2793 const char *ptr
; /* Pointer into field */
2794 time_t date
; /* Time/date value */
2795 off_t size
; /* Size/length value */
2800 ptr
= httpGetField(con
->http
, HTTP_FIELD_IF_MODIFIED_SINCE
);
2805 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
2806 "check_if_modified "
2807 "filestats=%p(" CUPS_LLFMT
", %d)) If-Modified-Since=\"%s\"",
2808 filestats
, CUPS_LLCAST filestats
->st_size
,
2809 (int)filestats
->st_mtime
, ptr
);
2811 while (*ptr
!= '\0')
2813 while (isspace(*ptr
) || *ptr
== ';')
2816 if (_cups_strncasecmp(ptr
, "length=", 7) == 0)
2819 size
= strtoll(ptr
, NULL
, 10);
2821 while (isdigit(*ptr
))
2824 else if (isalpha(*ptr
))
2826 date
= httpGetDateTime(ptr
);
2827 while (*ptr
!= '\0' && *ptr
!= ';')
2834 return ((size
!= filestats
->st_size
&& size
!= 0) ||
2835 (date
< filestats
->st_mtime
&& date
!= 0) ||
2836 (size
== 0 && date
== 0));
2841 * 'compare_clients()' - Compare two client connections.
2844 static int /* O - Result of comparison */
2845 compare_clients(cupsd_client_t
*a
, /* I - First client */
2846 cupsd_client_t
*b
, /* I - Second client */
2847 void *data
) /* I - User data (not used) */
2861 * 'get_file()' - Get a filename and state info.
2864 static char * /* O - Real filename */
2865 get_file(cupsd_client_t
*con
, /* I - Client connection */
2866 struct stat
*filestats
, /* O - File information */
2867 char *filename
, /* IO - Filename buffer */
2868 int len
) /* I - Buffer length */
2870 int status
; /* Status of filesystem calls */
2871 char *ptr
; /* Pointer info filename */
2872 int plen
; /* Remaining length after pointer */
2873 char language
[7]; /* Language subdirectory, if any */
2877 * Figure out the real filename...
2882 if (!strncmp(con
->uri
, "/ppd/", 5) && !strchr(con
->uri
+ 5, '/'))
2883 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
);
2884 else if (!strncmp(con
->uri
, "/icons/", 7) && !strchr(con
->uri
+ 7, '/'))
2886 snprintf(filename
, len
, "%s/%s", CacheDir
, con
->uri
+ 7);
2887 if (access(filename
, F_OK
) < 0)
2888 snprintf(filename
, len
, "%s/images/generic.png", DocumentRoot
);
2890 else if (!strncmp(con
->uri
, "/rss/", 5) && !strchr(con
->uri
+ 5, '/'))
2891 snprintf(filename
, len
, "%s/rss/%s", CacheDir
, con
->uri
+ 5);
2892 else if (!strncmp(con
->uri
, "/admin/conf/", 12))
2893 snprintf(filename
, len
, "%s%s", ServerRoot
, con
->uri
+ 11);
2894 else if (!strncmp(con
->uri
, "/admin/log/", 11))
2896 if (!strncmp(con
->uri
+ 11, "access_log", 10) && AccessLog
[0] == '/')
2897 strlcpy(filename
, AccessLog
, len
);
2898 else if (!strncmp(con
->uri
+ 11, "error_log", 9) && ErrorLog
[0] == '/')
2899 strlcpy(filename
, ErrorLog
, len
);
2900 else if (!strncmp(con
->uri
+ 11, "page_log", 8) && PageLog
[0] == '/')
2901 strlcpy(filename
, PageLog
, len
);
2905 else if (con
->language
)
2907 snprintf(language
, sizeof(language
), "/%s", con
->language
->language
);
2908 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
2911 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
2913 if ((ptr
= strchr(filename
, '?')) != NULL
)
2917 * Grab the status for this language; if there isn't a language-specific file
2918 * then fallback to the default one...
2921 if ((status
= stat(filename
, filestats
)) != 0 && language
[0] &&
2922 strncmp(con
->uri
, "/icons/", 7) &&
2923 strncmp(con
->uri
, "/ppd/", 5) &&
2924 strncmp(con
->uri
, "/rss/", 5) &&
2925 strncmp(con
->uri
, "/admin/conf/", 12) &&
2926 strncmp(con
->uri
, "/admin/log/", 11))
2929 * Drop the country code...
2933 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
2935 if ((ptr
= strchr(filename
, '?')) != NULL
)
2938 if ((status
= stat(filename
, filestats
)) != 0)
2941 * Drop the language prefix and try the root directory...
2945 snprintf(filename
, len
, "%s%s", DocumentRoot
, con
->uri
);
2947 if ((ptr
= strchr(filename
, '?')) != NULL
)
2950 status
= stat(filename
, filestats
);
2955 * If we're found a directory, get the index.html file instead...
2958 if (!status
&& S_ISDIR(filestats
->st_mode
))
2961 * Make sure the URI ends with a slash...
2964 if (con
->uri
[strlen(con
->uri
) - 1] != '/')
2965 strlcat(con
->uri
, "/", sizeof(con
->uri
));
2968 * Find the directory index file, trying every language...
2973 if (status
&& language
[0])
2976 * Try a different language subset...
2980 language
[0] = '\0'; /* Strip country code */
2982 language
[0] = '\0'; /* Strip language */
2986 * Look for the index file...
2989 snprintf(filename
, len
, "%s%s%s", DocumentRoot
, language
, con
->uri
);
2991 if ((ptr
= strchr(filename
, '?')) != NULL
)
2994 ptr
= filename
+ strlen(filename
);
2995 plen
= len
- (ptr
- filename
);
2997 strlcpy(ptr
, "index.html", plen
);
2998 status
= stat(filename
, filestats
);
3003 strlcpy(ptr
, "index.class", plen
);
3004 status
= stat(filename
, filestats
);
3006 #endif /* HAVE_JAVA */
3011 strlcpy(ptr
, "index.pl", plen
);
3012 status
= stat(filename
, filestats
);
3014 #endif /* HAVE_PERL */
3019 strlcpy(ptr
, "index.php", plen
);
3020 status
= stat(filename
, filestats
);
3022 #endif /* HAVE_PHP */
3027 strlcpy(ptr
, "index.pyc", plen
);
3028 status
= stat(filename
, filestats
);
3033 strlcpy(ptr
, "index.py", plen
);
3034 status
= stat(filename
, filestats
);
3036 #endif /* HAVE_PYTHON */
3039 while (status
&& language
[0]);
3042 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3043 "get_file filestats=%p, filename=%p, len=%d, "
3044 "returning \"%s\".", filestats
, filename
, len
,
3045 status
? "(null)" : filename
);
3055 * 'install_cupsd_conf()' - Install a configuration file.
3058 static http_status_t
/* O - Status */
3059 install_cupsd_conf(cupsd_client_t
*con
) /* I - Connection */
3061 char filename
[1024]; /* Configuration filename */
3062 cups_file_t
*in
, /* Input file */
3063 *out
; /* Output file */
3064 char buffer
[16384]; /* Copy buffer */
3065 ssize_t bytes
; /* Number of bytes */
3069 * Open the request file...
3072 if ((in
= cupsFileOpen(con
->filename
, "rb")) == NULL
)
3074 cupsdLogClient(con
, CUPSD_LOG_ERROR
, "Unable to open request file \"%s\": %s",
3075 con
->filename
, strerror(errno
));
3076 return (HTTP_STATUS_SERVER_ERROR
);
3080 * Open the new config file...
3083 if ((out
= cupsdCreateConfFile(ConfigurationFile
, ConfigFilePerm
)) == NULL
)
3086 return (HTTP_STATUS_SERVER_ERROR
);
3089 cupsdLogClient(con
, CUPSD_LOG_INFO
, "Installing config file \"%s\"...",
3093 * Copy from the request to the new config file...
3096 while ((bytes
= cupsFileRead(in
, buffer
, sizeof(buffer
))) > 0)
3097 if (cupsFileWrite(out
, buffer
, bytes
) < bytes
)
3099 cupsdLogClient(con
, CUPSD_LOG_ERROR
,
3100 "Unable to copy to config file \"%s\": %s",
3101 ConfigurationFile
, strerror(errno
));
3106 snprintf(filename
, sizeof(filename
), "%s.N", ConfigurationFile
);
3107 cupsdUnlinkOrRemoveFile(filename
);
3109 return (HTTP_STATUS_SERVER_ERROR
);
3113 * Close the files...
3118 if (cupsdCloseCreatedConfFile(out
, ConfigurationFile
))
3119 return (HTTP_STATUS_SERVER_ERROR
);
3122 * Remove the request file...
3125 cupsdUnlinkOrRemoveFile(con
->filename
);
3126 cupsdClearString(&con
->filename
);
3129 * Set the NeedReload flag...
3132 NeedReload
= RELOAD_CUPSD
;
3133 ReloadTime
= time(NULL
);
3136 * Return that the file was created successfully...
3139 return (HTTP_STATUS_CREATED
);
3144 * 'is_cgi()' - Is the resource a CGI script/program?
3147 static int /* O - 1 = CGI, 0 = file */
3148 is_cgi(cupsd_client_t
*con
, /* I - Client connection */
3149 const char *filename
, /* I - Real filename */
3150 struct stat
*filestats
, /* I - File information */
3151 mime_type_t
*type
) /* I - MIME type */
3153 const char *options
; /* Options on URL */
3157 * Get the options, if any...
3160 if ((options
= strchr(con
->uri
, '?')) != NULL
)
3163 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", options
);
3167 * Check for known types...
3170 if (!type
|| _cups_strcasecmp(type
->super
, "application"))
3172 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3173 "is_cgi filename=\"%s\", filestats=%p, "
3174 "type=%s/%s, returning 0", filename
,
3175 filestats
, type
? type
->super
: "unknown",
3176 type
? type
->type
: "unknown");
3180 if (!_cups_strcasecmp(type
->type
, "x-httpd-cgi") &&
3181 (filestats
->st_mode
& 0111))
3184 * "application/x-httpd-cgi" is a CGI script.
3187 cupsdSetString(&con
->command
, filename
);
3190 cupsdSetStringf(&con
->options
, " %s", options
);
3192 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3193 "is_cgi filename=\"%s\", filestats=%p, "
3194 "type=%s/%s, returning 1", filename
,
3195 filestats
, type
->super
, type
->type
);
3199 else if (!_cups_strcasecmp(type
->type
, "x-httpd-java"))
3202 * "application/x-httpd-java" is a Java servlet.
3205 cupsdSetString(&con
->command
, CUPS_JAVA
);
3208 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3210 cupsdSetStringf(&con
->options
, " %s", filename
);
3212 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3213 "is_cgi filename=\"%s\", filestats=%p, "
3214 "type=%s/%s, returning 1", filename
,
3215 filestats
, type
->super
, type
->type
);
3218 #endif /* HAVE_JAVA */
3220 else if (!_cups_strcasecmp(type
->type
, "x-httpd-perl"))
3223 * "application/x-httpd-perl" is a Perl page.
3226 cupsdSetString(&con
->command
, CUPS_PERL
);
3229 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3231 cupsdSetStringf(&con
->options
, " %s", filename
);
3233 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3234 "is_cgi filename=\"%s\", filestats=%p, "
3235 "type=%s/%s, returning 1", filename
,
3236 filestats
, type
->super
, type
->type
);
3239 #endif /* HAVE_PERL */
3241 else if (!_cups_strcasecmp(type
->type
, "x-httpd-php"))
3244 * "application/x-httpd-php" is a PHP page.
3247 cupsdSetString(&con
->command
, CUPS_PHP
);
3250 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3252 cupsdSetStringf(&con
->options
, " %s", filename
);
3254 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3255 "is_cgi filename=\"%s\", filestats=%p, "
3256 "type=%s/%s, returning 1", filename
,
3257 filestats
, type
->super
, type
->type
);
3260 #endif /* HAVE_PHP */
3262 else if (!_cups_strcasecmp(type
->type
, "x-httpd-python"))
3265 * "application/x-httpd-python" is a Python page.
3268 cupsdSetString(&con
->command
, CUPS_PYTHON
);
3271 cupsdSetStringf(&con
->options
, " %s %s", filename
, options
);
3273 cupsdSetStringf(&con
->options
, " %s", filename
);
3275 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3276 "is_cgi filename=\"%s\", filestats=%p, "
3277 "type=%s/%s, returning 1", filename
,
3278 filestats
, type
->super
, type
->type
);
3281 #endif /* HAVE_PYTHON */
3283 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3284 "is_cgi filename=\"%s\", filestats=%p, "
3285 "type=%s/%s, returning 0", filename
,
3286 filestats
, type
->super
, type
->type
);
3292 * 'is_path_absolute()' - Is a path absolute and free of relative elements (i.e. "..").
3295 static int /* O - 0 if relative, 1 if absolute */
3296 is_path_absolute(const char *path
) /* I - Input path */
3299 * Check for a leading slash...
3306 * Check for "/.." in the path...
3309 while ((path
= strstr(path
, "/..")) != NULL
)
3311 if (!path
[3] || path
[3] == '/')
3318 * If we haven't found any relative paths, return 1 indicating an
3327 * 'pipe_command()' - Pipe the output of a command to the remote client.
3330 static int /* O - Process ID */
3331 pipe_command(cupsd_client_t
*con
, /* I - Client connection */
3332 int infile
, /* I - Standard input for command */
3333 int *outfile
, /* O - Standard output for command */
3334 char *command
, /* I - Command to run */
3335 char *options
, /* I - Options for command */
3336 int root
) /* I - Run as root? */
3338 int i
; /* Looping var */
3339 int pid
; /* Process ID */
3340 char *commptr
, /* Command string pointer */
3341 commch
; /* Command string character */
3342 char *uriptr
; /* URI string pointer */
3343 int fds
[2]; /* Pipe FDs */
3344 int argc
; /* Number of arguments */
3345 int envc
; /* Number of environment variables */
3346 char argbuf
[10240], /* Argument buffer */
3347 *argv
[100], /* Argument strings */
3348 *envp
[MAX_ENV
+ 20]; /* Environment variables */
3349 char auth_type
[256], /* AUTH_TYPE environment variable */
3350 content_length
[1024], /* CONTENT_LENGTH environment variable */
3351 content_type
[1024], /* CONTENT_TYPE environment variable */
3352 http_cookie
[32768], /* HTTP_COOKIE environment variable */
3353 http_referer
[1024], /* HTTP_REFERER environment variable */
3354 http_user_agent
[1024], /* HTTP_USER_AGENT environment variable */
3355 lang
[1024], /* LANG environment variable */
3356 path_info
[1024], /* PATH_INFO environment variable */
3357 remote_addr
[1024], /* REMOTE_ADDR environment variable */
3358 remote_host
[1024], /* REMOTE_HOST environment variable */
3359 remote_user
[1024], /* REMOTE_USER environment variable */
3360 script_filename
[1024], /* SCRIPT_FILENAME environment variable */
3361 script_name
[1024], /* SCRIPT_NAME environment variable */
3362 server_name
[1024], /* SERVER_NAME environment variable */
3363 server_port
[1024]; /* SERVER_PORT environment variable */
3364 ipp_attribute_t
*attr
; /* attributes-natural-language attribute */
3368 * Parse a copy of the options string, which is of the form:
3370 * argument+argument+argument
3371 * ?argument+argument+argument
3372 * param=value¶m=value
3373 * ?param=value¶m=value
3374 * /name?argument+argument+argument
3375 * /name?param=value¶m=value
3377 * If the string contains an "=" character after the initial name,
3378 * then we treat it as a HTTP GET form request and make a copy of
3379 * the remaining string for the environment variable.
3381 * The string is always parsed out as command-line arguments, to
3382 * be consistent with Apache...
3385 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3386 "pipe_command infile=%d, outfile=%p, "
3387 "command=\"%s\", options=\"%s\", root=%d",
3388 infile
, outfile
, command
,
3389 options
? options
: "(null)", root
);
3396 if (*commptr
== ' ')
3398 strlcpy(argbuf
, commptr
, sizeof(argbuf
));
3403 if (argbuf
[0] == '/')
3406 * Found some trailing path information, set PATH_INFO...
3409 if ((commptr
= strchr(argbuf
, '?')) == NULL
)
3410 commptr
= argbuf
+ strlen(argbuf
);
3414 snprintf(path_info
, sizeof(path_info
), "PATH_INFO=%s", argbuf
);
3420 path_info
[0] = '\0';
3422 if (*commptr
== ' ')
3426 if (*commptr
== '?' && con
->operation
== HTTP_STATE_GET
&& !con
->query_string
)
3429 cupsdSetStringf(&(con
->query_string
), "QUERY_STRING=%s", commptr
);
3436 argv
[argc
++] = commptr
;
3438 for (; *commptr
&& argc
< 99; commptr
++)
3441 * Break arguments whenever we see a + or space...
3444 if (*commptr
== ' ' || *commptr
== '+')
3446 while (*commptr
== ' ' || *commptr
== '+')
3450 * If we don't have a blank string, save it as another argument...
3455 argv
[argc
] = commptr
;
3461 else if (*commptr
== '%' && isxdigit(commptr
[1] & 255) &&
3462 isxdigit(commptr
[2] & 255))
3465 * Convert the %xx notation to the individual character.
3468 if (commptr
[1] >= '0' && commptr
[1] <= '9')
3469 *commptr
= (commptr
[1] - '0') << 4;
3471 *commptr
= (tolower(commptr
[1]) - 'a' + 10) << 4;
3473 if (commptr
[2] >= '0' && commptr
[2] <= '9')
3474 *commptr
|= commptr
[2] - '0';
3476 *commptr
|= tolower(commptr
[2]) - 'a' + 10;
3478 _cups_strcpy(commptr
+ 1, commptr
+ 3);
3481 * Check for a %00 and break if that is the case...
3493 * Setup the environment variables as needed...
3496 if (con
->username
[0])
3498 snprintf(auth_type
, sizeof(auth_type
), "AUTH_TYPE=%s",
3499 httpGetField(con
->http
, HTTP_FIELD_AUTHORIZATION
));
3501 if ((uriptr
= strchr(auth_type
+ 10, ' ')) != NULL
)
3505 auth_type
[0] = '\0';
3508 (attr
= ippFindAttribute(con
->request
, "attributes-natural-language",
3509 IPP_TAG_LANGUAGE
)) != NULL
)
3511 switch (strlen(attr
->values
[0].string
.text
))
3515 * This is an unknown or badly formatted language code; use
3516 * the POSIX locale...
3519 strlcpy(lang
, "LANG=C", sizeof(lang
));
3524 * Just the language code (ll)...
3527 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8",
3528 attr
->values
[0].string
.text
);
3533 * Language and country code (ll-cc)...
3536 snprintf(lang
, sizeof(lang
), "LANG=%c%c_%c%c.UTF8",
3537 attr
->values
[0].string
.text
[0],
3538 attr
->values
[0].string
.text
[1],
3539 toupper(attr
->values
[0].string
.text
[3] & 255),
3540 toupper(attr
->values
[0].string
.text
[4] & 255));
3544 else if (con
->language
)
3545 snprintf(lang
, sizeof(lang
), "LANG=%s.UTF8", con
->language
->language
);
3547 strlcpy(lang
, "LANG=C", sizeof(lang
));
3549 strlcpy(remote_addr
, "REMOTE_ADDR=", sizeof(remote_addr
));
3550 httpAddrString(httpGetAddress(con
->http
), remote_addr
+ 12,
3551 sizeof(remote_addr
) - 12);
3553 snprintf(remote_host
, sizeof(remote_host
), "REMOTE_HOST=%s",
3554 httpGetHostname(con
->http
, NULL
, 0));
3556 snprintf(script_name
, sizeof(script_name
), "SCRIPT_NAME=%s", con
->uri
);
3557 if ((uriptr
= strchr(script_name
, '?')) != NULL
)
3560 snprintf(script_filename
, sizeof(script_filename
), "SCRIPT_FILENAME=%s%s",
3561 DocumentRoot
, script_name
+ 12);
3563 sprintf(server_port
, "SERVER_PORT=%d", con
->serverport
);
3565 if (httpGetField(con
->http
, HTTP_FIELD_HOST
)[0])
3567 char *nameptr
; /* Pointer to ":port" */
3569 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
3570 httpGetField(con
->http
, HTTP_FIELD_HOST
));
3571 if ((nameptr
= strrchr(server_name
, ':')) != NULL
&& !strchr(nameptr
, ']'))
3572 *nameptr
= '\0'; /* Strip trailing ":port" */
3575 snprintf(server_name
, sizeof(server_name
), "SERVER_NAME=%s",
3578 envc
= cupsdLoadEnv(envp
, (int)(sizeof(envp
) / sizeof(envp
[0])));
3581 envp
[envc
++] = auth_type
;
3583 envp
[envc
++] = lang
;
3584 envp
[envc
++] = "REDIRECT_STATUS=1";
3585 envp
[envc
++] = "GATEWAY_INTERFACE=CGI/1.1";
3586 envp
[envc
++] = server_name
;
3587 envp
[envc
++] = server_port
;
3588 envp
[envc
++] = remote_addr
;
3589 envp
[envc
++] = remote_host
;
3590 envp
[envc
++] = script_name
;
3591 envp
[envc
++] = script_filename
;
3594 envp
[envc
++] = path_info
;
3596 if (con
->username
[0])
3598 snprintf(remote_user
, sizeof(remote_user
), "REMOTE_USER=%s", con
->username
);
3600 envp
[envc
++] = remote_user
;
3603 if (httpGetVersion(con
->http
) == HTTP_VERSION_1_1
)
3604 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.1";
3605 else if (httpGetVersion(con
->http
) == HTTP_VERSION_1_0
)
3606 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/1.0";
3608 envp
[envc
++] = "SERVER_PROTOCOL=HTTP/0.9";
3610 if (httpGetCookie(con
->http
))
3612 snprintf(http_cookie
, sizeof(http_cookie
), "HTTP_COOKIE=%s",
3613 httpGetCookie(con
->http
));
3614 envp
[envc
++] = http_cookie
;
3617 if (httpGetField(con
->http
, HTTP_FIELD_USER_AGENT
)[0])
3619 snprintf(http_user_agent
, sizeof(http_user_agent
), "HTTP_USER_AGENT=%s",
3620 httpGetField(con
->http
, HTTP_FIELD_USER_AGENT
));
3621 envp
[envc
++] = http_user_agent
;
3624 if (httpGetField(con
->http
, HTTP_FIELD_REFERER
)[0])
3626 snprintf(http_referer
, sizeof(http_referer
), "HTTP_REFERER=%s",
3627 httpGetField(con
->http
, HTTP_FIELD_REFERER
));
3628 envp
[envc
++] = http_referer
;
3631 if (con
->operation
== HTTP_STATE_GET
)
3633 envp
[envc
++] = "REQUEST_METHOD=GET";
3635 if (con
->query_string
)
3638 * Add GET form variables after ?...
3641 envp
[envc
++] = con
->query_string
;
3644 envp
[envc
++] = "QUERY_STRING=";
3648 sprintf(content_length
, "CONTENT_LENGTH=" CUPS_LLFMT
,
3649 CUPS_LLCAST con
->bytes
);
3650 snprintf(content_type
, sizeof(content_type
), "CONTENT_TYPE=%s",
3651 httpGetField(con
->http
, HTTP_FIELD_CONTENT_TYPE
));
3653 envp
[envc
++] = "REQUEST_METHOD=POST";
3654 envp
[envc
++] = content_length
;
3655 envp
[envc
++] = content_type
;
3659 * Tell the CGI if we are using encryption...
3662 if (httpIsEncrypted(con
->http
))
3663 envp
[envc
++] = "HTTPS=ON";
3666 * Terminate the environment array...
3671 if (LogLevel
>= CUPSD_LOG_DEBUG
)
3673 for (i
= 0; i
< argc
; i
++)
3674 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3675 "[CGI] argv[%d] = \"%s\"", i
, argv
[i
]);
3676 for (i
= 0; i
< envc
; i
++)
3677 cupsdLogMessage(CUPSD_LOG_DEBUG
,
3678 "[CGI] envp[%d] = \"%s\"", i
, envp
[i
]);
3682 * Create a pipe for the output...
3685 if (cupsdOpenPipe(fds
))
3687 cupsdLogMessage(CUPSD_LOG_ERROR
, "[CGI] Unable to create pipe for %s - %s",
3688 argv
[0], strerror(errno
));
3693 * Then execute the command...
3696 if (cupsdStartProcess(command
, argv
, envp
, infile
, fds
[1], CGIPipes
[1],
3697 -1, -1, root
, DefaultProfile
, NULL
, &pid
) < 0)
3700 * Error - can't fork!
3703 cupsdLogMessage(CUPSD_LOG_ERROR
, "[CGI] Unable to start %s - %s", argv
[0],
3706 cupsdClosePipe(fds
);
3712 * Fork successful - return the PID...
3715 if (con
->username
[0])
3716 cupsdAddCert(pid
, con
->username
, con
->type
);
3718 cupsdLogMessage(CUPSD_LOG_DEBUG
, "[CGI] Started %s (PID %d)", command
, pid
);
3729 * 'valid_host()' - Is the Host: field valid?
3732 static int /* O - 1 if valid, 0 if not */
3733 valid_host(cupsd_client_t
*con
) /* I - Client connection */
3735 cupsd_alias_t
*a
; /* Current alias */
3736 cupsd_netif_t
*netif
; /* Current network interface */
3737 const char *end
; /* End character */
3738 char *ptr
; /* Pointer into host value */
3742 * Copy the Host: header for later use...
3745 strlcpy(con
->clientname
, httpGetField(con
->http
, HTTP_FIELD_HOST
),
3746 sizeof(con
->clientname
));
3747 if ((ptr
= strrchr(con
->clientname
, ':')) != NULL
&& !strchr(ptr
, ']'))
3750 con
->clientport
= atoi(ptr
);
3753 con
->clientport
= con
->serverport
;
3759 if (httpAddrLocalhost(httpGetAddress(con
->http
)))
3762 * Only allow "localhost" or the equivalent IPv4 or IPv6 numerical
3763 * addresses when accessing CUPS via the loopback interface...
3766 return (!_cups_strcasecmp(con
->clientname
, "localhost") ||
3767 !_cups_strcasecmp(con
->clientname
, "localhost.") ||
3769 !_cups_strcasecmp(con
->clientname
, "localhost.localdomain") ||
3770 #endif /* __linux */
3771 !strcmp(con
->clientname
, "127.0.0.1") ||
3772 !strcmp(con
->clientname
, "[::1]"));
3775 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
3777 * Check if the hostname is something.local (Bonjour); if so, allow it.
3780 if ((end
= strrchr(con
->clientname
, '.')) != NULL
&& end
> con
->clientname
&&
3784 * "." on end, work back to second-to-last "."...
3787 for (end
--; end
> con
->clientname
&& *end
!= '.'; end
--);
3790 if (end
&& (!_cups_strcasecmp(end
, ".local") ||
3791 !_cups_strcasecmp(end
, ".local.")))
3793 #endif /* HAVE_DNSSD || HAVE_AVAHI */
3796 * Check if the hostname is an IP address...
3799 if (isdigit(con
->clientname
[0] & 255) || con
->clientname
[0] == '[')
3802 * Possible IPv4/IPv6 address...
3805 http_addrlist_t
*addrlist
; /* List of addresses */
3808 if ((addrlist
= httpAddrGetList(con
->clientname
, AF_UNSPEC
, NULL
)) != NULL
)
3811 * Good IPv4/IPv6 address...
3814 httpAddrFreeList(addrlist
);
3820 * Check for (alias) name matches...
3823 for (a
= (cupsd_alias_t
*)cupsArrayFirst(ServerAlias
);
3825 a
= (cupsd_alias_t
*)cupsArrayNext(ServerAlias
))
3828 * "ServerAlias *" allows all host values through...
3831 if (!strcmp(a
->name
, "*"))
3834 if (!_cups_strncasecmp(con
->clientname
, a
->name
, a
->namelen
))
3837 * Prefix matches; check the character at the end - it must be "." or nul.
3840 end
= con
->clientname
+ a
->namelen
;
3842 if (!*end
|| (*end
== '.' && !end
[1]))
3847 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
3848 for (a
= (cupsd_alias_t
*)cupsArrayFirst(DNSSDAlias
);
3850 a
= (cupsd_alias_t
*)cupsArrayNext(DNSSDAlias
))
3853 * "ServerAlias *" allows all host values through...
3856 if (!strcmp(a
->name
, "*"))
3859 if (!_cups_strncasecmp(con
->clientname
, a
->name
, a
->namelen
))
3862 * Prefix matches; check the character at the end - it must be "." or nul.
3865 end
= con
->clientname
+ a
->namelen
;
3867 if (!*end
|| (*end
== '.' && !end
[1]))
3871 #endif /* HAVE_DNSSD || HAVE_AVAHI */
3874 * Check for interface hostname matches...
3877 for (netif
= (cupsd_netif_t
*)cupsArrayFirst(NetIFList
);
3879 netif
= (cupsd_netif_t
*)cupsArrayNext(NetIFList
))
3881 if (!_cups_strncasecmp(con
->clientname
, netif
->hostname
, netif
->hostlen
))
3884 * Prefix matches; check the character at the end - it must be "." or nul.
3887 end
= con
->clientname
+ netif
->hostlen
;
3889 if (!*end
|| (*end
== '.' && !end
[1]))
3899 * 'write_file()' - Send a file via HTTP.
3902 static int /* O - 0 on failure, 1 on success */
3903 write_file(cupsd_client_t
*con
, /* I - Client connection */
3904 http_status_t code
, /* I - HTTP status */
3905 char *filename
, /* I - Filename */
3906 char *type
, /* I - File type */
3907 struct stat
*filestats
) /* O - File information */
3909 con
->file
= open(filename
, O_RDONLY
);
3911 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
,
3912 "write_file code=%d, filename=\"%s\" (%d), "
3913 "type=\"%s\", filestats=%p",
3914 code
, filename
, con
->file
, type
? type
: "(null)", filestats
);
3919 fcntl(con
->file
, F_SETFD
, fcntl(con
->file
, F_GETFD
) | FD_CLOEXEC
);
3923 httpClearFields(con
->http
);
3925 httpSetLength(con
->http
, filestats
->st_size
);
3927 httpSetField(con
->http
, HTTP_FIELD_LAST_MODIFIED
,
3928 httpGetDateString(filestats
->st_mtime
));
3930 if (!cupsdSendHeader(con
, code
, type
, CUPSD_AUTH_NONE
))
3933 cupsdAddSelect(httpGetFd(con
->http
), (cupsd_selfunc_t
)cupsdReadClient
,
3934 (cupsd_selfunc_t
)cupsdWriteClient
, con
);
3936 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "Sending file.");
3943 * 'write_pipe()' - Flag that data is available on the CGI pipe.
3947 write_pipe(cupsd_client_t
*con
) /* I - Client connection */
3949 cupsdLogClient(con
, CUPSD_LOG_DEBUG2
, "write_pipe CGI output on fd %d",
3952 con
->file_ready
= 1;
3954 cupsdRemoveSelect(con
->file
);
3955 cupsdAddSelect(httpGetFd(con
->http
), NULL
, (cupsd_selfunc_t
)cupsdWriteClient
, con
);
3957 cupsdLogClient(con
, CUPSD_LOG_DEBUG
, "CGI data ready to be sent.");